stream_server.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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/component.h"
  18. #include "esphome/components/uart/uart.h"
  19. #include <memory>
  20. #include <string>
  21. #include <vector>
  22. #ifdef ARDUINO_ARCH_ESP8266
  23. #include <ESPAsyncTCP.h>
  24. #else
  25. // AsyncTCP.h includes parts of freertos, which require FreeRTOS.h header to be included first
  26. #include <freertos/FreeRTOS.h>
  27. #include <AsyncTCP.h>
  28. #endif
  29. class StreamServerComponent : public esphome::Component {
  30. public:
  31. StreamServerComponent() = default;
  32. explicit StreamServerComponent(esphome::uart::UARTComponent *stream) : stream_{stream} {}
  33. void set_uart_parent(esphome::uart::UARTComponent *parent) { this->stream_ = parent; }
  34. void setup() override;
  35. void loop() override;
  36. void dump_config() override;
  37. void on_shutdown() override;
  38. float get_setup_priority() const override { return esphome::setup_priority::AFTER_WIFI; }
  39. void set_port(uint16_t port) { this->port_ = port; }
  40. protected:
  41. void cleanup();
  42. void read();
  43. void write();
  44. struct Client {
  45. Client(AsyncClient *client, std::vector<uint8_t> &recv_buf);
  46. ~Client();
  47. AsyncClient *tcp_client{nullptr};
  48. std::string identifier{};
  49. bool disconnected{false};
  50. };
  51. esphome::uart::UARTComponent *stream_{nullptr};
  52. AsyncServer server_{0};
  53. uint16_t port_{6638};
  54. std::vector<uint8_t> recv_buf_{};
  55. std::vector<std::unique_ptr<Client>> clients_{};
  56. };