stream_server.h 1.8 KB

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