stream_server.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* Copyright (C) 2020-2021 Oxan van Leeuwen
  2. *
  3. * This program is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation, either version 3 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  15. */
  16. #pragma once
  17. #include "esphome/core/version.h"
  18. #include "esphome/core/component.h"
  19. #include "esphome/components/uart/uart.h"
  20. // Provide VERSION_CODE for ESPHome versions lacking it, as existence checking doesn't work for function-like macros
  21. #ifndef VERSION_CODE
  22. #define VERSION_CODE(major, minor, patch) ((major) << 16 | (minor) << 8 | (patch))
  23. #endif
  24. #include <memory>
  25. #include <string>
  26. #include <vector>
  27. #include <Stream.h>
  28. #ifdef ARDUINO_ARCH_ESP8266
  29. #include <ESPAsyncTCP.h>
  30. #else
  31. // AsyncTCP.h includes parts of freertos, which require FreeRTOS.h header to be included first
  32. #include <freertos/FreeRTOS.h>
  33. #include <AsyncTCP.h>
  34. #endif
  35. #if ESPHOME_VERSION_CODE >= VERSION_CODE(2021, 10, 0)
  36. using SSStream = esphome::uart::UARTComponent;
  37. #else
  38. using SSStream = Stream;
  39. #endif
  40. class StreamServerComponent : public esphome::Component {
  41. public:
  42. StreamServerComponent() = default;
  43. explicit StreamServerComponent(SSStream *stream) : stream_{stream} {}
  44. void set_uart_parent(esphome::uart::UARTComponent *parent) { this->stream_ = parent; }
  45. void setup() override;
  46. void loop() override;
  47. void dump_config() override;
  48. void on_shutdown() override;
  49. float get_setup_priority() const override { return esphome::setup_priority::AFTER_WIFI; }
  50. void set_port(uint16_t port) { this->port_ = port; }
  51. protected:
  52. void cleanup();
  53. void read();
  54. void write();
  55. struct Client {
  56. Client(AsyncClient *client, std::vector<uint8_t> &recv_buf);
  57. ~Client();
  58. AsyncClient *tcp_client{nullptr};
  59. std::string identifier{};
  60. bool disconnected{false};
  61. };
  62. SSStream *stream_{nullptr};
  63. AsyncServer server_{0};
  64. uint16_t port_{6638};
  65. std::vector<uint8_t> recv_buf_{};
  66. std::vector<std::unique_ptr<Client>> clients_{};
  67. };