stream_server.h 1.9 KB

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