stream_server.cpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. #include "stream_server.h"
  2. #include "esphome/core/helpers.h"
  3. #include "esphome/core/log.h"
  4. #include "esphome/core/util.h"
  5. #include "esphome/core/version.h"
  6. #include "esphome/components/network/util.h"
  7. #include "esphome/components/socket/socket.h"
  8. static const char *TAG = "stream_server";
  9. using namespace esphome;
  10. void StreamServerComponent::setup() {
  11. ESP_LOGCONFIG(TAG, "Setting up stream server...");
  12. // The make_unique() wrapper doesn't like arrays, so initialize the unique_ptr directly.
  13. this->buf_ = std::unique_ptr<uint8_t[]>{new uint8_t[this->buf_size_]};
  14. struct sockaddr_storage bind_addr;
  15. #if ESPHOME_VERSION_CODE >= VERSION_CODE(2023, 4, 0)
  16. socklen_t bind_addrlen = socket::set_sockaddr_any(reinterpret_cast<struct sockaddr *>(&bind_addr), sizeof(bind_addr), this->port_);
  17. #else
  18. socklen_t bind_addrlen = socket::set_sockaddr_any(reinterpret_cast<struct sockaddr *>(&bind_addr), sizeof(bind_addr), htons(this->port_));
  19. #endif
  20. #if ESPHOME_VERSION_CODE >= VERSION_CODE(2026, 3, 0)
  21. this->socket_ = socket::socket_ip_loop_monitored(SOCK_STREAM, PF_INET).release();
  22. #else
  23. this->socket_ = socket::socket_ip(SOCK_STREAM, PF_INET);
  24. #endif
  25. this->socket_->setblocking(false);
  26. this->socket_->bind(reinterpret_cast<struct sockaddr *>(&bind_addr), bind_addrlen);
  27. this->socket_->listen(8);
  28. this->publish_sensor();
  29. }
  30. void StreamServerComponent::loop() {
  31. this->accept();
  32. this->read();
  33. this->flush();
  34. this->write();
  35. this->cleanup();
  36. }
  37. void StreamServerComponent::dump_config() {
  38. ESP_LOGCONFIG(TAG, "Stream Server:");
  39. #if ESPHOME_VERSION_CODE >= VERSION_CODE(2025, 11, 0)
  40. ESP_LOGCONFIG(TAG, " Address: %s:%u", esphome::network::get_use_address(), this->port_);
  41. #else
  42. ESP_LOGCONFIG(TAG, " Address: %s:%u", esphome::network::get_use_address().c_str(), this->port_);
  43. #endif
  44. #ifdef USE_BINARY_SENSOR
  45. LOG_BINARY_SENSOR(" ", "Connected:", this->connected_sensor_);
  46. #endif
  47. #ifdef USE_SENSOR
  48. LOG_SENSOR(" ", "Connection count:", this->connection_count_sensor_);
  49. #endif
  50. }
  51. void StreamServerComponent::on_shutdown() {
  52. #if ESPHOME_VERSION_CODE >= VERSION_CODE(2026, 3, 0)
  53. delete this->socket_;
  54. this->socket_ = nullptr;
  55. #endif
  56. for (const Client &client : this->clients_)
  57. client.socket->shutdown(SHUT_RDWR);
  58. }
  59. void StreamServerComponent::publish_sensor() {
  60. #ifdef USE_BINARY_SENSOR
  61. if (this->connected_sensor_)
  62. this->connected_sensor_->publish_state(this->clients_.size() > 0);
  63. #endif
  64. #ifdef USE_SENSOR
  65. if (this->connection_count_sensor_)
  66. this->connection_count_sensor_->publish_state(this->clients_.size());
  67. #endif
  68. }
  69. void StreamServerComponent::accept() {
  70. struct sockaddr_storage client_addr;
  71. socklen_t client_addrlen = sizeof(client_addr);
  72. std::unique_ptr<socket::Socket> socket = this->socket_->accept(reinterpret_cast<struct sockaddr *>(&client_addr), &client_addrlen);
  73. if (!socket)
  74. return;
  75. socket->setblocking(false);
  76. #if ESPHOME_VERSION_CODE >= VERSION_CODE(2026, 1, 0)
  77. std::string identifier = std::string{esphome::socket::SOCKADDR_STR_LEN, 0};
  78. auto identifier_span = std::span<char, esphome::socket::SOCKADDR_STR_LEN>(identifier.data(), identifier.size());
  79. identifier.resize(socket->getpeername_to(identifier_span));
  80. #else
  81. std::string identifier = socket->getpeername();
  82. #endif
  83. this->clients_.emplace_back(std::move(socket), identifier, this->buf_head_);
  84. ESP_LOGD(TAG, "New client connected from %s", identifier.c_str());
  85. this->publish_sensor();
  86. }
  87. void StreamServerComponent::cleanup() {
  88. auto discriminator = [](const Client &client) { return !client.disconnected; };
  89. auto last_client = std::partition(this->clients_.begin(), this->clients_.end(), discriminator);
  90. if (last_client != this->clients_.end()) {
  91. this->clients_.erase(last_client, this->clients_.end());
  92. this->publish_sensor();
  93. }
  94. }
  95. void StreamServerComponent::read() {
  96. size_t len = 0;
  97. int available;
  98. while ((available = this->stream_->available()) > 0) {
  99. size_t free = this->buf_size_ - (this->buf_head_ - this->buf_tail_);
  100. if (free == 0) {
  101. // Only overwrite if nothing has been added yet, otherwise give flush() a chance to empty the buffer first.
  102. if (len > 0)
  103. return;
  104. ESP_LOGE(TAG, "Incoming bytes available, but outgoing buffer is full: stream will be corrupted!");
  105. free = std::min<size_t>(available, this->buf_size_);
  106. this->buf_tail_ += free;
  107. for (Client &client : this->clients_) {
  108. if (client.position < this->buf_tail_) {
  109. ESP_LOGW(TAG, "Dropped %u pending bytes for client %s", this->buf_tail_ - client.position, client.identifier.c_str());
  110. client.position = this->buf_tail_;
  111. }
  112. }
  113. }
  114. // Fill all available contiguous space in the ring buffer.
  115. len = std::min<size_t>(available, std::min<size_t>(this->buf_ahead(this->buf_head_), free));
  116. this->stream_->read_array(&this->buf_[this->buf_index(this->buf_head_)], len);
  117. this->buf_head_ += len;
  118. }
  119. }
  120. void StreamServerComponent::flush() {
  121. ssize_t written;
  122. this->buf_tail_ = this->buf_head_;
  123. for (Client &client : this->clients_) {
  124. if (client.disconnected || client.position == this->buf_head_)
  125. continue;
  126. // Split the write into two parts: from the current position to the end of the ring buffer, and from the start
  127. // of the ring buffer until the head. The second part might be zero if no wraparound is necessary.
  128. struct iovec iov[2];
  129. iov[0].iov_base = &this->buf_[this->buf_index(client.position)];
  130. iov[0].iov_len = std::min(this->buf_head_ - client.position, this->buf_ahead(client.position));
  131. iov[1].iov_base = &this->buf_[0];
  132. iov[1].iov_len = this->buf_head_ - (client.position + iov[0].iov_len);
  133. if ((written = client.socket->writev(iov, 2)) > 0) {
  134. client.position += written;
  135. } else if (written == 0 || errno == ECONNRESET) {
  136. ESP_LOGD(TAG, "Client %s disconnected", client.identifier.c_str());
  137. client.disconnected = true;
  138. continue; // don't consider this client when calculating the tail position
  139. } else if (errno == EWOULDBLOCK || errno == EAGAIN) {
  140. // Expected if the (TCP) transmit buffer is full, nothing to do.
  141. } else {
  142. ESP_LOGE(TAG, "Failed to write to client %s with error %d!", client.identifier.c_str(), errno);
  143. }
  144. this->buf_tail_ = std::min(this->buf_tail_, client.position);
  145. }
  146. }
  147. void StreamServerComponent::write() {
  148. uint8_t buf[128];
  149. ssize_t read;
  150. for (Client &client : this->clients_) {
  151. if (client.disconnected)
  152. continue;
  153. while ((read = client.socket->read(&buf, sizeof(buf))) > 0)
  154. this->stream_->write_array(buf, read);
  155. if (read == 0 || errno == ECONNRESET) {
  156. ESP_LOGD(TAG, "Client %s disconnected", client.identifier.c_str());
  157. client.disconnected = true;
  158. } else if (errno == EWOULDBLOCK || errno == EAGAIN) {
  159. // Expected if the (TCP) receive buffer is empty, nothing to do.
  160. } else {
  161. ESP_LOGW(TAG, "Failed to read from client %s with error %d!", client.identifier.c_str(), errno);
  162. }
  163. }
  164. }
  165. StreamServerComponent::Client::Client(std::unique_ptr<esphome::socket::Socket> socket, std::string identifier, size_t position)
  166. : socket(std::move(socket)), identifier{identifier}, position{position} {}