stream_server.cpp 6.3 KB

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