stream_server.h 2.4 KB

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