stream_server.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #pragma once
  2. #include "esphome/core/version.h"
  3. #include "esphome/core/component.h"
  4. #include "esphome/components/socket/socket.h"
  5. #include "esphome/components/uart/uart.h"
  6. #ifdef USE_BINARY_SENSOR
  7. #include "esphome/components/binary_sensor/binary_sensor.h"
  8. #endif
  9. #ifdef USE_SENSOR
  10. #include "esphome/components/sensor/sensor.h"
  11. #endif
  12. #include <memory>
  13. #include <string>
  14. #include <vector>
  15. class StreamServerComponent : public esphome::Component {
  16. public:
  17. StreamServerComponent() = default;
  18. explicit StreamServerComponent(esphome::uart::UARTComponent *stream) : stream_{stream} {}
  19. void set_uart_parent(esphome::uart::UARTComponent *parent) { this->stream_ = parent; }
  20. void set_buffer_size(size_t size) { this->buf_size_ = size; }
  21. #ifdef USE_BINARY_SENSOR
  22. void set_connected_sensor(esphome::binary_sensor::BinarySensor *connected) { this->connected_sensor_ = connected; }
  23. #endif
  24. #ifdef USE_SENSOR
  25. void set_connection_count_sensor(esphome::sensor::Sensor *connection_count) { this->connection_count_sensor_ = connection_count; }
  26. #endif
  27. void setup() override;
  28. void loop() override;
  29. void dump_config() override;
  30. void on_shutdown() override;
  31. float get_setup_priority() const override { return esphome::setup_priority::AFTER_WIFI; }
  32. void set_port(uint16_t port) { this->port_ = port; }
  33. protected:
  34. void publish_sensor();
  35. void accept();
  36. void cleanup();
  37. void read();
  38. void flush();
  39. void write();
  40. size_t buf_index(size_t pos) { return pos & (this->buf_size_ - 1); }
  41. /// Return the number of consecutive elements that are ahead of @p pos in memory.
  42. size_t buf_ahead(size_t pos) { return (pos | (this->buf_size_ - 1)) - pos + 1; }
  43. struct Client {
  44. Client(std::unique_ptr<esphome::socket::Socket> socket, std::string identifier, size_t position);
  45. std::unique_ptr<esphome::socket::Socket> socket{nullptr};
  46. std::string identifier{};
  47. bool disconnected{false};
  48. size_t position{0};
  49. };
  50. esphome::uart::UARTComponent *stream_{nullptr};
  51. uint16_t port_;
  52. size_t buf_size_;
  53. #ifdef USE_BINARY_SENSOR
  54. esphome::binary_sensor::BinarySensor *connected_sensor_;
  55. #endif
  56. #ifdef USE_SENSOR
  57. esphome::sensor::Sensor *connection_count_sensor_;
  58. #endif
  59. std::unique_ptr<uint8_t[]> buf_{};
  60. size_t buf_head_{0};
  61. size_t buf_tail_{0};
  62. #if ESPHOME_VERSION_CODE >= VERSION_CODE(2026, 3, 0)
  63. esphome::socket::ListenSocket *socket_{nullptr};
  64. #else
  65. std::unique_ptr<esphome::socket::Socket> socket_{};
  66. #endif
  67. std::vector<Client> clients_{};
  68. };