stream_server.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* Copyright (C) 2020-2023 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/socket/socket.h"
  19. #include "esphome/components/uart/uart.h"
  20. #include <memory>
  21. #include <string>
  22. #include <vector>
  23. class StreamServerComponent : public esphome::Component {
  24. public:
  25. StreamServerComponent() = default;
  26. explicit StreamServerComponent(esphome::uart::UARTComponent *stream) : stream_{stream} {}
  27. void set_uart_parent(esphome::uart::UARTComponent *parent) { this->stream_ = parent; }
  28. void set_buffer_size(size_t size) { this->buf_size_ = size; }
  29. void setup() override;
  30. void loop() override;
  31. void dump_config() override;
  32. void on_shutdown() override;
  33. float get_setup_priority() const override { return esphome::setup_priority::AFTER_WIFI; }
  34. void set_port(uint16_t port) { this->port_ = port; }
  35. protected:
  36. void accept();
  37. void cleanup();
  38. void read();
  39. void flush();
  40. void write();
  41. size_t buf_index(size_t pos) { return pos & (this->buf_size_ - 1); }
  42. /// Return the number of consecutive elements that are ahead of @p pos in memory.
  43. size_t buf_ahead(size_t pos) { return (pos | (this->buf_size_ - 1)) - pos + 1; }
  44. struct Client {
  45. Client(std::unique_ptr<esphome::socket::Socket> socket, std::string identifier, size_t position);
  46. std::unique_ptr<esphome::socket::Socket> socket{nullptr};
  47. std::string identifier{};
  48. bool disconnected{false};
  49. size_t position{0};
  50. };
  51. esphome::uart::UARTComponent *stream_{nullptr};
  52. size_t buf_size_;
  53. std::unique_ptr<uint8_t[]> buf_{};
  54. size_t buf_head_{0};
  55. size_t buf_tail_{0};
  56. std::unique_ptr<esphome::socket::Socket> socket_{};
  57. uint16_t port_{6638};
  58. std::vector<Client> clients_{};
  59. };