ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
tcp_uart.cpp
Go to the documentation of this file.
1#include "tcp_uart.h"
2
4#include "esphome/core/log.h"
5
6#include <algorithm>
7#include <cinttypes>
8#include <cstring>
9
11
12ESPHOME_LOG_TAG(TAG, "tcp_uart");
13
14static constexpr uint32_t DROP_LOG_INTERVAL_MS = 5000;
15#ifdef USE_TCP_UART_MAX_CONNECTIONS
16// Longer than a few Wi-Fi retransmissions, which can stall the send for seconds.
17static constexpr uint32_t TX_STALL_TIMEOUT_MS = 5000;
18#endif
19
20#ifdef USE_TCP_UART_MAX_CONNECTIONS
21void TcpUart::set_max_connections(uint8_t count) {
22 this->extra_.init(count - 1);
23 for (uint8_t i = 1; i < count; i++) {
24 this->extra_.emplace_back();
25 }
26}
27#endif
28
29void TcpUart::setup() {
30 this->link_.begin(TAG);
31#ifdef USE_TCP_UART_MAX_CONNECTIONS
32 for (auto &link : this->extra_) {
33 link.begin(TAG);
34 link.set_idle_timeout(this->link_.idle_timeout());
35 }
36#endif
37#ifdef USE_SOCKET_TCP_LISTENER
38 this->listener_.begin(TAG);
39#endif
40#ifdef USE_BINARY_SENSOR
41 PUBLISH_STATE(this->connected_binary_sensor_, false);
42#endif
43#ifdef USE_SENSOR
44 PUBLISH_STATE(this->disconnects_sensor_, 0);
45#endif
46}
47
48void TcpUart::dump_config() {
49 ESP_LOGCONFIG(TAG,
50 "TCP UART:\n"
51 " %s: %s:%u\n"
52 " Reconnect Interval: %" PRIu32 "ms\n"
53 " Timeout: %" PRIu32 "ms",
54 this->server_ ? LOG_STR_LITERAL("Listen") : LOG_STR_LITERAL("Host"),
55 this->server_ ? LOG_STR_LITERAL("*") : this->link_.host(), this->link_.port(),
56 this->link_.reconnect_interval(), this->link_.idle_timeout());
57#ifdef USE_TCP_UART_MAX_CONNECTIONS
58 if (!this->extra_.empty()) {
59 ESP_LOGCONFIG(TAG,
60 " Max Connections: %u\n"
61 " Turn Timeout: %ums",
62 this->slot_count_(), this->turn_timeout_ms_);
63 }
64#endif
65#ifdef USE_SOCKET_TCP_LISTENER
66 this->listener_.dump_config();
67#endif
68#ifdef USE_BINARY_SENSOR
69 LOG_BINARY_SENSOR(" ", "Connected", this->connected_binary_sensor_);
70#endif
71#ifdef USE_SENSOR
72 LOG_SENSOR(" ", "Disconnects", this->disconnects_sensor_);
73#endif
74}
75
76void TcpUart::on_shutdown() {
77 this->link_.close();
78#ifdef USE_TCP_UART_MAX_CONNECTIONS
79 for (auto &link : this->extra_) {
80 link.close();
81 }
82#endif
83#ifdef USE_SOCKET_TCP_LISTENER
84 this->listener_.close();
85#endif
86}
87
88bool TcpUart::is_connected() {
89#ifdef USE_TCP_UART_MAX_CONNECTIONS
90 for (auto &link : this->extra_) {
91 if (link.connected()) {
92 return true;
93 }
94 }
95#endif
96 return this->link_.connected();
97}
98
100#ifdef USE_BINARY_SENSOR
101 PUBLISH_STATE(this->connected_binary_sensor_, up);
102#endif
103}
104
106#ifdef USE_SENSOR
107 if (this->disconnects_sensor_ != nullptr) {
108 this->disconnects_++;
109 this->disconnects_sensor_->publish_state(this->disconnects_);
110 }
111#endif
112}
113
115 bool up = this->link_.connected();
116 this->link_was_up_ = up;
117 // Each session is a turn of its own.
118 this->turn_++;
119 // A hold belongs to the session that took it.
120 this->held_ = false;
121 if (up) {
122 // Unread bytes of the last session stay readable while down, never into the next one.
123 this->rx_start_ = this->rx_end_ = 0;
124 }
125 this->publish_connected_(up);
126 // Only edges get here, so down is the falling edge.
127 if (!up) {
128 this->count_disconnect_();
129 }
130}
131
132size_t TcpUart::read_socket_(Link &link, size_t limit) {
133 if (this->rx_start_ != 0) {
134 this->rx_end_ -= this->rx_start_;
135 std::memmove(this->rx_, this->rx_ + this->rx_start_, this->rx_end_);
136 this->rx_start_ = 0;
137 }
138 size_t room = std::min(RX_BUFFER_SIZE - this->rx_end_, limit);
139 if (room == 0) {
140 // Unread bytes are waiting on the consumer. The peer is not idle.
141 link.note_io();
142 return 0;
143 }
144 ssize_t count = link.read(this->rx_ + this->rx_end_, room);
145 if (count <= 0) {
146 // Nothing left in the socket, or the link dropped (-1, seen by the edge check on the next loop).
147 this->rx_pending_ = false;
148 return 0;
149 }
150 this->rx_end_ += static_cast<uint16_t>(count);
151 this->rx_pending_ = static_cast<size_t>(count) == room;
152 return static_cast<size_t>(count);
153}
154
155void TcpUart::loop() {
156#ifdef USE_TCP_UART_MAX_CONNECTIONS
157 if (!this->extra_.empty()) {
158 // Nothing to do with no client and none waiting.
159 bool waiting = this->listener_.poll_listen(this->link_, this->slot_count_());
160 if (waiting || this->up_mask_ != 0) {
161 this->loop_pool_(waiting);
162 }
163 return;
164 }
165#endif
166#ifdef USE_SOCKET_TCP_LISTENER
167 if (this->server_) {
168 // link_was_up_ holds the accept until the previous drop's edge has run,
169 // so the sensor sees the disconnect and the new session's edge clears RX.
170 this->listener_.poll(this->link_, !this->link_was_up_);
171 } else {
172 this->link_.poll();
173 }
174#else
175 this->link_.poll();
176#endif
177 if (this->link_.connected() != this->link_was_up_) {
178 this->sync_link_();
179 }
180 if (!this->link_was_up_) {
181 return;
182 }
183 if (this->rx_pending_ || this->link_.ready()) {
184 this->read_socket_(this->link_);
185 }
186 this->flush_link_(this->link_);
187 if (this->held_) {
188 // The peer waits for its reply.
189 this->link_.note_io();
190 }
191 this->link_.check_idle();
192}
193
194#ifdef USE_TCP_UART_MAX_CONNECTIONS
195void TcpUart::loop_pool_(bool waiting) {
197 const uint8_t count = this->slot_count_();
198 for (uint8_t i = 0; i < count; i++) {
199 if (this->slot_(i).connected() != ((this->up_mask_ & (1u << i)) != 0)) {
200 this->slot_edge_(i);
201 }
202 }
203 if (waiting) {
204 this->accept_slot_(now);
205 }
206 if (this->holder_ != NO_SLOT) {
207 // After release_turn() only the bytes already read are left to consume, and the rest of a request started in them.
208 const bool rest = this->rest_ != 0 && !this->held_ && this->available() == 0;
209 if ((!this->release_ || rest) && (this->rx_pending_ || this->slot_(this->holder_).ready())) {
210 this->read_holder_(now);
211 }
212 if (this->available() == 0 && !this->held_ &&
213 ((this->release_ && this->rest_ == 0) || now - this->last_traffic_ms_ >= this->turn_timeout_ms_)) {
214 this->end_turn_(now);
215 }
216 }
217 if (this->holder_ == NO_SLOT) {
218 this->pick_holder_(now);
219 }
220 for (uint8_t i = 0; i < count; i++) {
221 Link &link = this->slot_(i);
222 this->flush_link_(link);
223 // Bytes still waiting in its socket, for their turn or for room, are not a quiet peer. Nor is the holder's peer
224 // while its bytes wait on the consumer or a held turn waits for its reply.
225 const bool busy = (this->pending_mask_ & (1u << i)) != 0 ||
226 (i == this->holder_ && (this->rx_pending_ || this->held_ || this->available() != 0));
227 if (busy || link.ready()) {
228 link.note_io();
229 }
230 link.check_idle();
231 }
232}
233
234void TcpUart::slot_edge_(uint8_t i) {
235 const uint8_t bit = 1u << i;
236 const bool was_up = this->up_mask_ != 0;
237 if (this->slot_(i).connected()) {
238 this->up_mask_ |= bit;
239 } else {
240 this->up_mask_ &= ~bit;
241 this->pending_mask_ &= ~bit;
242 if (i == this->holder_) {
243 // Its unread bytes never reach another connection; the next turn goes round from it, as after end_turn_().
244 this->rx_start_ = this->rx_end_ = 0;
245 this->rx_pending_ = false;
246 this->last_holder_ = i;
247 this->holder_ = NO_SLOT;
248 }
249 if (i == this->tx_slot_) {
250 // The holder or the last holder closed: the turn that writes belong to is over.
251 this->tx_slot_ = NO_SLOT;
252 this->turn_++;
253 }
254 this->count_disconnect_();
255 }
256 if ((this->up_mask_ != 0) != was_up) {
257 this->publish_connected_(!was_up);
258 }
259}
260
262 auto sock = this->listener_.accept(this->link_);
263 if (sock == nullptr) {
264 return;
265 }
266 const uint8_t count = this->slot_count_();
267 uint8_t slot = NO_SLOT;
268 uint8_t quietest = NO_SLOT;
269 bool quietest_waits = false;
270 uint32_t quietest_idle = 0;
271 for (uint8_t i = 0; i < count; i++) {
272 Link &link = this->slot_(i);
273 if (!link.connected()) {
274 slot = i;
275 break;
276 }
277 if (i == this->holder_) {
278 continue;
279 }
280 // The last holder keeps its connection while its reply still sits in the shared TX buffer.
281 if (i == this->tx_slot_ && link.tx_free() != Link::TX_BUFFER_SIZE) {
282 continue;
283 }
284 // A connection with bytes waiting for its turn is not idle.
285 const bool waiting = (this->pending_mask_ & (1u << i)) != 0 || link.ready();
286 const uint32_t idle = now - link.last_io();
287 if (quietest == NO_SLOT || (quietest_waits && !waiting) || (waiting == quietest_waits && idle > quietest_idle)) {
288 quietest = i;
289 quietest_waits = waiting;
290 quietest_idle = idle;
291 }
292 }
293 if (slot == NO_SLOT) {
294 if (quietest == NO_SLOT) {
295 return;
296 }
297 // A full pool closes the quietest connection other than the holder and a last holder whose reply still sits in the
298 // shared TX buffer. Of the rest, one waiting for its turn is closed only when all of them wait; Modbus TCP
299 // [4.2.1.1] asks for the oldest unused one.
300 ESP_LOGI(TAG, "All %u connections in use, closing the quietest", count);
301 slot = quietest;
302 this->slot_(slot).close();
303 this->slot_edge_(slot);
304 }
305 this->slot_(slot).adopt(std::move(sock));
306 this->slot_edge_(slot);
307}
308
310 if (this->tx_slot_ != NO_SLOT && !this->tx_drained_(now)) {
311 return;
312 }
313 const uint8_t count = this->slot_count_();
314 for (uint8_t step = 1; step <= count; step++) {
315 const uint8_t i = (this->last_holder_ + step) % count;
316 Link &link = this->slot_(i);
317 const uint8_t bit = 1u << i;
318 if (!link.connected() || ((this->pending_mask_ & bit) == 0 && !link.ready())) {
319 continue;
320 }
321 this->holder_ = i;
322 this->held_ = false;
323 this->release_ = false;
324 this->rest_ = 0;
325 this->rx_start_ = this->rx_end_ = 0;
326 this->rx_pending_ = (this->pending_mask_ & bit) != 0;
327 this->pending_mask_ &= ~bit;
328 this->last_traffic_ms_ = now;
329 this->read_holder_(now);
330 if (this->available() == 0 && !this->rx_pending_) {
331 // A read that stopped exactly at the rest of a request marks bytes pending that may not be there: no empty turn.
332 this->holder_ = NO_SLOT;
333 continue;
334 }
335 this->tx_slot_ = i;
336 this->turn_++;
337 return;
338 }
339}
340
342 Link &link = this->slot_(this->tx_slot_);
343 if (this->flush_link_(link)) {
344 // Bytes that reach the last holder after the buffer emptied get a stall clock of their own.
345 this->tx_moved_ms_ = now;
346 return true;
347 }
348 const uint16_t room = static_cast<uint16_t>(link.tx_free());
349 if (room != this->tx_free_seen_) {
350 this->tx_free_seen_ = room;
351 this->tx_moved_ms_ = now;
352 return false;
353 }
354 if (now - this->tx_moved_ms_ < TX_STALL_TIMEOUT_MS) {
355 return false;
356 }
357 const uint8_t count = this->slot_count_();
358 for (uint8_t i = 0; i < count; i++) {
359 Link &other = this->slot_(i);
360 if (i == this->tx_slot_ || !other.connected() || ((this->pending_mask_ & (1u << i)) == 0 && !other.ready())) {
361 continue;
362 }
363 // Another client waits. The rest of this reply cannot go to another connection, so closing is the only way out.
364 ESP_LOGW(TAG, "Connection took no bytes for %" PRIu32 "ms while another waits, closing", now - this->tx_moved_ms_);
365 link.close();
366 this->slot_edge_(this->tx_slot_);
367 return true;
368 }
369 return false;
370}
371
373 // A released turn reads no more than the rest that release_turn() named.
374 const size_t count = this->read_socket_(this->slot_(this->holder_), this->release_ ? this->rest_ : RX_BUFFER_SIZE);
375 if (count != 0) {
376 this->last_traffic_ms_ = now;
377 if (this->release_) {
378 this->rest_ -= static_cast<uint16_t>(count);
379 }
380 }
381}
382
384 // The stall clock of the reply in the TX buffer starts with the turn's end.
385 this->tx_moved_ms_ = now;
386 // Bytes left in the socket keep their place for the next turn.
387 if (this->rx_pending_) {
388 this->pending_mask_ |= 1u << this->holder_;
389 this->rx_pending_ = false;
390 }
391 this->last_holder_ = this->holder_;
392 this->holder_ = NO_SLOT;
393 this->held_ = false;
394 this->release_ = false;
395 this->rest_ = 0;
396}
397#endif
398
399void TcpUart::write_array(const uint8_t *data, size_t len) {
400 Link *link = this->tx_link_();
401 size_t queued = link != nullptr ? this->queue_link_(*link, data, len) : 0;
402#ifdef USE_TCP_UART_MAX_CONNECTIONS
403 if (queued != 0 && this->holder_ != NO_SLOT) {
405 }
406#endif
407 if (queued < len) {
409 if (this->last_drop_log_ms_ == 0 || now - this->last_drop_log_ms_ >= DROP_LOG_INTERVAL_MS) {
410 // With clients open, writes find no connection before the first turn and after the last holder closed.
411 ESP_LOGW(TAG, "%s, dropped %u bytes",
412 link != nullptr && link->connected() ? LOG_STR_LITERAL("TX buffer full")
413 : this->is_connected() ? LOG_STR_LITERAL("No connection holds the turn")
414 : LOG_STR_LITERAL("Not connected"),
415 static_cast<unsigned>(len - queued));
416 this->last_drop_log_ms_ = now;
417 }
418 }
419}
420
421bool TcpUart::peek_byte(uint8_t *data) {
422 if (this->rx_start_ == this->rx_end_) {
423 return false;
424 }
425 *data = this->rx_[this->rx_start_];
426 return true;
427}
428
429bool TcpUart::read_array(uint8_t *data, size_t len) {
430 if (this->available() < len) {
431 return false;
432 }
433 std::memcpy(data, this->rx_ + this->rx_start_, len);
434 this->rx_start_ += static_cast<uint16_t>(len);
435 return true;
436}
437
438uart::UARTFlushResult TcpUart::flush() {
439 Link *link = this->tx_link_();
440 if (link == nullptr) {
442 }
443 bool emptied = this->flush_link_(*link);
444 if (!link->connected()) {
445 // A down link cannot have delivered anything, whether this flush dropped
446 // it or an earlier loop() write did.
448 }
450}
451
452} // namespace esphome::tcp_uart
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
std::unique_ptr< Socket > accept(TcpClientLinkBase &link)
Accepts a waiting connection that the allow list admits, or returns nullptr.
void begin(const char *tag)
Call from setup(); tag names the log lines.
void dump_config() const
One config line per allowed network.
bool poll_listen(TcpClientLinkBase &link, uint8_t backlog=1)
Opens the listen socket on link's port after its backoff; true when a connection waits.
void poll(TcpClientLinkBase &link, bool may_accept)
Server state machine; call every loop.
size_t queue_link_(Link &link, const uint8_t *data, size_t len)
Definition tcp_uart.h:111
socket::TcpClientLinkSharedTx Link
Definition tcp_uart.h:99
bool tx_drained_(uint32_t now)
True once the last holder's reply has left the shared TX buffer.
Definition tcp_uart.cpp:341
void loop_pool_(bool waiting)
Definition tcp_uart.cpp:195
void end_turn_(uint32_t now)
Definition tcp_uart.cpp:383
size_t read_socket_(Link &link, size_t limit=RX_BUFFER_SIZE)
Reads at most limit bytes and returns how many arrived.
Definition tcp_uart.cpp:132
void accept_slot_(uint32_t now)
Definition tcp_uart.cpp:261
void publish_connected_(bool up)
Definition tcp_uart.cpp:99
Link & slot_(uint8_t i)
Definition tcp_uart.h:129
Link * tx_link_()
The connection that writes go to, or nullptr.
Definition tcp_uart.h:118
static constexpr size_t RX_BUFFER_SIZE
Definition tcp_uart.h:142
bool flush_link_(Link &link)
Definition tcp_uart.h:112
static constexpr uint8_t NO_SLOT
Definition tcp_uart.h:127
uint8_t rx_[RX_BUFFER_SIZE]
Definition tcp_uart.h:185
void read_holder_(uint32_t now)
Definition tcp_uart.cpp:372
uint8_t slot_count_() const
Definition tcp_uart.h:130
void pick_holder_(uint32_t now)
Definition tcp_uart.cpp:309
void slot_edge_(uint8_t i)
Definition tcp_uart.cpp:234
FixedVector< Link > extra_
Definition tcp_uart.h:154
socket::TcpListener listener_
Definition tcp_uart.h:146
unsigned count
Definition gif.cpp:51
__int64 ssize_t
Definition httplib.h:178
ESPHOME_LOG_TAG(TAG, "tcp_uart")
UARTFlushResult
Result of a flush() call.
@ UART_FLUSH_RESULT_SUCCESS
Confirmed: all bytes left the TX FIFO.
@ UART_FLUSH_RESULT_FAILED
Confirmed: driver or hardware error.
@ UART_FLUSH_RESULT_TIMEOUT
Confirmed: timed out before TX completed.
const void size_t len
Definition hal.h:68
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t