ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
tcp_client_link.cpp
Go to the documentation of this file.
1#include "tcp_client_link.h"
2
3#if defined(USE_SOCKET_IMPL_LWIP_TCP) || defined(USE_SOCKET_IMPL_LWIP_SOCKETS) || defined(USE_SOCKET_IMPL_BSD_SOCKETS)
4
6#include "esphome/core/log.h"
7
8#include <algorithm>
9#include <cerrno>
10#include <cinttypes>
11#include <cstring>
12
13namespace esphome::socket {
14
15// After this long in SYN, the stack's own retries are cut short.
16static constexpr uint32_t CONNECT_TIMEOUT_MS = 10000;
17
18// Non-blocking options and TCP keepalive for a bridged stream socket.
19// Keepalive is best-effort: the raw lwIP implementation (ESP8266, RP2040)
20// rejects it, so a half-open link there is only detected by a failed write.
21static void set_stream_options(Socket *sock, const char *tag) {
22 int yes = 1;
23 // Fails only on an invalid descriptor, or on raw lwIP after a peer reset that the next read() reports.
24 sock->setblocking(false);
25 int err = sock->setsockopt(IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes));
26 err |= sock->setsockopt(SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes));
27#ifdef TCP_KEEPIDLE
28 int idle = 30;
29 int interval = 10;
30 int count = 3;
31 err |= sock->setsockopt(IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(idle));
32 err |= sock->setsockopt(IPPROTO_TCP, TCP_KEEPINTVL, &interval, sizeof(interval));
33 err |= sock->setsockopt(IPPROTO_TCP, TCP_KEEPCNT, &count, sizeof(count));
34#endif
35 if (err != 0) {
36 ESP_LOGV(tag, "Nodelay/keepalive not fully applied");
37 }
38}
39
40void TcpClientLink::begin(const char *tag) {
41 this->tag_ = tag;
42 // The first attempt must not wait out a full interval.
44}
45
47 if (this->sock_ == nullptr) {
48 this->try_connect_();
49 return;
50 }
51 int err = 0;
52 switch (poll_connect(*this->sock_, err)) {
54 // Give up before the stack's SYN retries do, so the interval stays honest
55 // and the next attempt resolves the host again.
56 if (App.get_loop_component_start_time() - this->last_attempt_ms_ >=
57 std::max(this->reconnect_interval_ms_, CONNECT_TIMEOUT_MS)) {
58 this->drop_(LOG_STR("Connect failed"), ETIMEDOUT);
59 }
60 return;
62 this->drop_(LOG_STR("Connect failed"), err);
63 return;
64 default:
65 break;
66 }
67 this->connected_ = true;
68 this->note_io();
69 ESP_LOGI(this->tag_, "Connected to %s:%u", this->host_.c_str(), this->port_);
70}
71
73 if (this->resolved_.consume_failure()) {
74 this->note_attempt();
75 return;
76 }
77 this->resolved_.start(this->host_.c_str(), this->port_, this->tag_);
78 if (!this->resolved_.ready()) {
79 return;
80 }
81 struct sockaddr_storage dest;
82 socklen_t dest_len =
83 this->resolved_.to_sockaddr(reinterpret_cast<struct sockaddr *>(&dest), sizeof(dest), this->port_);
84 if (dest_len == 0) {
85 this->note_attempt();
86 return;
87 }
88 this->sock_ = socket_loop_monitored(dest.ss_family, SOCK_STREAM, IPPROTO_TCP);
89 if (this->sock_ == nullptr) {
90 this->drop_(LOG_STR("Connect failed"), errno);
91 return;
92 }
93 set_stream_options(this->sock_.get(), this->tag_);
94 // Starts the pending-connect clock that poll() times out against.
95 this->note_attempt();
96 // An immediate success is reported by the next poll(); poll_connect() sees it writable.
97 if (this->sock_->connect(reinterpret_cast<struct sockaddr *>(&dest), dest_len) != 0 && errno != EINPROGRESS) {
98 this->drop_(LOG_STR("Connect failed"), errno);
99 }
100}
101
102void TcpClientLink::adopt(std::unique_ptr<Socket> sock) {
103 this->close();
104 set_stream_options(sock.get(), this->tag_);
105 this->sock_ = std::move(sock);
106 this->connected_ = true;
107 this->note_io();
108}
109
110ssize_t TcpClientLink::read(uint8_t *buf, size_t len) {
111 if (!this->connected_) {
112 return 0;
113 }
114 ssize_t count = this->sock_->read(buf, len);
115 if (count > 0) {
116 this->note_io();
117 return count;
118 }
119 if (count == 0 || (errno != EAGAIN && errno != EWOULDBLOCK)) {
120 this->drop_(LOG_STR("Connection lost"), count == 0 ? 0 : errno);
121 return -1;
122 }
123 return 0;
124}
125
126ssize_t TcpClientLink::write_(const uint8_t *buf, size_t len) {
127 if (!this->connected_ || len == 0) {
128 return 0;
129 }
130 ssize_t sent = this->sock_->write(buf, len);
131 if (sent >= 0) {
132 if (sent > 0) {
133 this->note_io();
134 }
135 return sent;
136 }
137 if (errno == EAGAIN || errno == EWOULDBLOCK) {
138 return 0;
139 }
140 this->drop_(LOG_STR("Connection lost"), errno);
141 return -1;
142}
143
144size_t TcpClientLink::queue(const uint8_t *data, size_t len) {
145 size_t room = this->tx_free();
146 if (len > room) {
147 len = room;
148 }
149 std::memcpy(this->tx_ + this->tx_len_, data, len);
150 this->tx_len_ += static_cast<uint16_t>(len);
151 return len;
152}
153
155 ssize_t sent = this->write_(this->tx_, this->tx_len_);
156 if (sent > 0) {
157 this->tx_len_ -= static_cast<uint16_t>(sent);
158 if (this->tx_len_ != 0) {
159 std::memmove(this->tx_, this->tx_ + sent, this->tx_len_);
160 }
161 }
162}
163
165 if (this->sock_ != nullptr) {
166 this->sock_->shutdown(SHUT_RDWR);
167 this->sock_->close();
168 this->sock_.reset();
169 }
170 this->connected_ = false;
171 this->tx_len_ = 0;
172 this->resolved_.forget();
173}
174
175void TcpClientLink::drop_(const LogString *what, int err) {
176 ESP_LOGW(this->tag_, "%s: %d", LOG_STR_ARG(what), err);
177 this->close();
178 this->note_attempt();
179}
180
183 // A configured close, not a failure.
184 ESP_LOGI(this->tag_, "Idle for %" PRIu32 "ms, closing", idle);
185 this->close();
186 this->note_attempt();
187}
188
189} // namespace esphome::socket
190
191#endif
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.
constexpr const char * c_str() const
Definition string_ref.h:78
void start(const char *host, uint16_t port, const char *tag)
Resolve host; tag names the failure log.
bool consume_failure()
Drop a failed lookup so the next start() tries again.
socklen_t to_sockaddr(struct sockaddr *dest, socklen_t destlen, uint16_t port) const
Write the stored address into dest. Returns 0 until ready() is true.
void forget()
Drop the stored address so the next start() resolves again.
unsigned count
Definition gif.cpp:51
uint32_t socklen_t
Definition headers.h:109
__int64 ssize_t
Definition httplib.h:178
ConnectPollResult poll_connect(Socket &sock, int &err_out)
Poll a connect() that returned EINPROGRESS.
Definition socket.h:223
BSDSocketImpl Socket
Definition socket.h:36
std::unique_ptr< Socket > socket_loop_monitored(int domain, int type, int protocol)
Create a socket and monitor it for data in the main loop.
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
sa_family_t ss_family
Definition headers.h:104