stream_server.cpp 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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. }
  35. void StreamServerComponent::loop() {
  36. this->accept();
  37. this->read();
  38. this->flush();
  39. this->write();
  40. this->cleanup();
  41. }
  42. void StreamServerComponent::dump_config() {
  43. ESP_LOGCONFIG(TAG, "Stream Server:");
  44. ESP_LOGCONFIG(TAG, " Address: %s:%u", esphome::network::get_ip_address().str().c_str(), this->port_);
  45. }
  46. void StreamServerComponent::on_shutdown() {
  47. for (const Client &client : this->clients_)
  48. client.socket->shutdown(SHUT_RDWR);
  49. }
  50. void StreamServerComponent::accept() {
  51. struct sockaddr_storage client_addr;
  52. socklen_t client_addrlen = sizeof(client_addr);
  53. std::unique_ptr<socket::Socket> socket = this->socket_->accept(reinterpret_cast<struct sockaddr *>(&client_addr), &client_addrlen);
  54. if (!socket)
  55. return;
  56. socket->setblocking(false);
  57. std::string identifier = socket->getpeername();
  58. this->clients_.emplace_back(std::move(socket), identifier, this->buf_head_);
  59. ESP_LOGD(TAG, "New client connected from %s", identifier.c_str());
  60. }
  61. void StreamServerComponent::cleanup() {
  62. auto discriminator = [](const Client &client) { return !client.disconnected; };
  63. auto last_client = std::partition(this->clients_.begin(), this->clients_.end(), discriminator);
  64. this->clients_.erase(last_client, this->clients_.end());
  65. }
  66. void StreamServerComponent::read() {
  67. bool first_iteration = true;
  68. int available;
  69. while ((available = this->stream_->available()) > 0) {
  70. // Write until the tail is encountered, or wraparound of the ring buffer if that happens before.
  71. size_t max = std::min(this->buf_ahead(this->buf_head_), this->buf_tail_ + this->buf_size_ - this->buf_head_);
  72. if (max == 0) {
  73. // Only warn on the first iteration, the finite buffer size is also used as a throttling mechanism to avoid
  74. // blocking here for too long when a large amount of data comes in.
  75. if (first_iteration)
  76. ESP_LOGW(TAG, "Incoming bytes available in stream, but outgoing buffer is full!");
  77. break;
  78. }
  79. size_t len = std::min<size_t>(available, max);
  80. this->stream_->read_array(&this->buf_[this->buf_index(this->buf_head_)], len);
  81. this->buf_head_ += len;
  82. first_iteration = false;
  83. }
  84. }
  85. void StreamServerComponent::flush() {
  86. this->buf_tail_ = this->buf_head_;
  87. for (Client &client : this->clients_) {
  88. if (client.position == this->buf_head_)
  89. continue;
  90. // Split the write into two parts: from the current position to the end of the ring buffer, and from the start
  91. // of the ring buffer until the head. The second part might be zero if no wraparound is necessary.
  92. struct iovec iov[2];
  93. iov[0].iov_base = &this->buf_[this->buf_index(client.position)];
  94. iov[0].iov_len = std::min(this->buf_head_ - client.position, this->buf_ahead(client.position));
  95. iov[1].iov_base = &this->buf_[0];
  96. iov[1].iov_len = this->buf_head_ - (client.position + iov[0].iov_len);
  97. client.position += client.socket->writev(iov, 2);
  98. this->buf_tail_ = std::min(this->buf_tail_, client.position);
  99. }
  100. }
  101. void StreamServerComponent::write() {
  102. uint8_t buf[128];
  103. ssize_t len;
  104. for (Client &client : this->clients_) {
  105. while ((len = client.socket->read(&buf, sizeof(buf))) > 0)
  106. this->stream_->write_array(buf, len);
  107. if (len == 0) {
  108. ESP_LOGD(TAG, "Client %s disconnected", client.identifier.c_str());
  109. client.disconnected = true;
  110. continue;
  111. }
  112. }
  113. }
  114. StreamServerComponent::Client::Client(std::unique_ptr<esphome::socket::Socket> socket, std::string identifier, size_t position)
  115. : socket(std::move(socket)), identifier{identifier}, position{position} {}