stream_server.cpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. /* Copyright (C) 2020-2023 Oxan van Leeuwen
  2. *
  3. * This program is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation, either version 3 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  15. */
  16. #include "stream_server.h"
  17. #include "esphome/core/helpers.h"
  18. #include "esphome/core/log.h"
  19. #include "esphome/core/util.h"
  20. #include "esphome/components/network/util.h"
  21. #include "esphome/components/socket/socket.h"
  22. static const char *TAG = "stream_server";
  23. using namespace esphome;
  24. void StreamServerComponent::setup() {
  25. ESP_LOGCONFIG(TAG, "Setting up stream server...");
  26. // The make_unique() wrapper doesn't like arrays, so initialize the unique_ptr directly.
  27. this->buf_ = std::unique_ptr<uint8_t[]>{new uint8_t[this->buf_size_]};
  28. struct sockaddr_storage bind_addr;
  29. socklen_t bind_addrlen = socket::set_sockaddr_any(reinterpret_cast<struct sockaddr *>(&bind_addr), sizeof(bind_addr), htons(this->port_));
  30. this->socket_ = socket::socket_ip(SOCK_STREAM, PF_INET);
  31. this->socket_->setblocking(false);
  32. this->socket_->bind(reinterpret_cast<struct sockaddr *>(&bind_addr), bind_addrlen);
  33. this->socket_->listen(8);
  34. #ifdef USE_BINARY_SENSOR
  35. this->connected_sensor_->publish_state(false);
  36. #endif
  37. #ifdef USE_SENSOR
  38. this->connection_count_sensor_->publish_state(0);
  39. #endif
  40. }
  41. void StreamServerComponent::loop() {
  42. this->accept();
  43. this->read();
  44. this->flush();
  45. this->write();
  46. this->cleanup();
  47. }
  48. void StreamServerComponent::dump_config() {
  49. ESP_LOGCONFIG(TAG, "Stream Server:");
  50. ESP_LOGCONFIG(TAG, " Address: %s:%u", esphome::network::get_use_address().c_str(), this->port_);
  51. #ifdef USE_BINARY_SENSOR
  52. LOG_BINARY_SENSOR(" ", "Connected:", this->connected_sensor_);
  53. #endif
  54. #ifdef USE_SENSOR
  55. LOG_SENSOR(" ", "Connection count:", this->connection_count_sensor_);
  56. #endif
  57. }
  58. void StreamServerComponent::on_shutdown() {
  59. for (const Client &client : this->clients_)
  60. client.socket->shutdown(SHUT_RDWR);
  61. }
  62. void StreamServerComponent::publish_sensor() {
  63. #ifdef USE_BINARY_SENSOR
  64. if (this->connected_sensor_)
  65. this->connected_sensor_->publish_state(this->clients_.size() > 0);
  66. #endif
  67. #ifdef USE_SENSOR
  68. if (this->connection_count_sensor_)
  69. this->connection_count_sensor_->publish_state(this->clients_.size());
  70. #endif
  71. }
  72. void StreamServerComponent::accept() {
  73. struct sockaddr_storage client_addr;
  74. socklen_t client_addrlen = sizeof(client_addr);
  75. std::unique_ptr<socket::Socket> socket = this->socket_->accept(reinterpret_cast<struct sockaddr *>(&client_addr), &client_addrlen);
  76. if (!socket)
  77. return;
  78. socket->setblocking(false);
  79. std::string identifier = socket->getpeername();
  80. this->clients_.emplace_back(std::move(socket), identifier, this->buf_head_);
  81. ESP_LOGD(TAG, "New client connected from %s", identifier.c_str());
  82. this->publish_sensor();
  83. }
  84. void StreamServerComponent::cleanup() {
  85. auto discriminator = [](const Client &client) { return !client.disconnected; };
  86. auto last_client = std::partition(this->clients_.begin(), this->clients_.end(), discriminator);
  87. if (last_client != this->clients_.end()) {
  88. this->clients_.erase(last_client, this->clients_.end());
  89. this->publish_sensor();
  90. }
  91. }
  92. void StreamServerComponent::read() {
  93. size_t len = 0;
  94. int available;
  95. while ((available = this->stream_->available()) > 0) {
  96. size_t free = this->buf_size_ - (this->buf_head_ - this->buf_tail_);
  97. if (free == 0) {
  98. // Only overwrite if nothing has been added yet, otherwise give flush() a chance to empty the buffer first.
  99. if (len > 0)
  100. return;
  101. ESP_LOGE(TAG, "Incoming bytes available, but outgoing buffer is full: stream will be corrupted!");
  102. free = std::min<size_t>(available, this->buf_size_);
  103. this->buf_tail_ += free;
  104. for (Client &client : this->clients_) {
  105. if (client.position < this->buf_tail_) {
  106. ESP_LOGW(TAG, "Dropped %u pending bytes for client %s", this->buf_tail_ - client.position, client.identifier.c_str());
  107. client.position = this->buf_tail_;
  108. }
  109. }
  110. }
  111. // Fill all available contiguous space in the ring buffer.
  112. len = std::min<size_t>(available, std::min<size_t>(this->buf_ahead(this->buf_head_), free));
  113. this->stream_->read_array(&this->buf_[this->buf_index(this->buf_head_)], len);
  114. this->buf_head_ += len;
  115. }
  116. }
  117. void StreamServerComponent::flush() {
  118. this->buf_tail_ = this->buf_head_;
  119. for (Client &client : this->clients_) {
  120. if (client.position == this->buf_head_)
  121. continue;
  122. // Split the write into two parts: from the current position to the end of the ring buffer, and from the start
  123. // of the ring buffer until the head. The second part might be zero if no wraparound is necessary.
  124. struct iovec iov[2];
  125. iov[0].iov_base = &this->buf_[this->buf_index(client.position)];
  126. iov[0].iov_len = std::min(this->buf_head_ - client.position, this->buf_ahead(client.position));
  127. iov[1].iov_base = &this->buf_[0];
  128. iov[1].iov_len = this->buf_head_ - (client.position + iov[0].iov_len);
  129. client.position += client.socket->writev(iov, 2);
  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 len;
  136. for (Client &client : this->clients_) {
  137. while ((len = client.socket->read(&buf, sizeof(buf))) > 0)
  138. this->stream_->write_array(buf, len);
  139. if (len == 0) {
  140. ESP_LOGD(TAG, "Client %s disconnected", client.identifier.c_str());
  141. client.disconnected = true;
  142. continue;
  143. }
  144. }
  145. }
  146. StreamServerComponent::Client::Client(std::unique_ptr<esphome::socket::Socket> socket, std::string identifier, size_t position)
  147. : socket(std::move(socket)), identifier{identifier}, position{position} {}