stream_server.cpp 6.7 KB

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