stream_server.cpp 6.9 KB

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