stream_server.cpp 6.5 KB

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