ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
udp_component.cpp
Go to the documentation of this file.
2#ifdef USE_NETWORK
3#include "esphome/core/log.h"
6#ifdef USE_UDP_OMR_SOURCE
8#endif
9#include "udp_component.h"
10
11namespace esphome::udp {
12
13ESPHOME_LOG_TAG(TAG, "udp");
14static constexpr uint32_t NETWORK_POLL_ID = 0;
15static constexpr uint32_t NETWORK_POLL_INTERVAL_MS = 1000;
16
18 size_t address_count = 0;
19 for (const char *const *it = this->addresses_; it != nullptr && *it != nullptr; it++)
20 address_count++;
21 this->sockaddrs_.init(address_count);
22 for (const char *const *it = this->addresses_; it != nullptr && *it != nullptr; it++) {
23 const char *address = *it;
24 SockaddrEntry entry{};
25 if (socket::set_sockaddr(&entry.sa, sizeof(entry), address, this->broadcast_port_) == 0) {
26 ESP_LOGW(TAG, "Invalid address %s", address);
27 // A dropped address silently receives nothing; surface the misconfiguration
28 this->status_set_warning(LOG_STR("invalid address"));
29 continue;
30 }
31 this->sockaddrs_.push_back(entry);
32 }
33 // set up broadcast socket
34 if (this->should_broadcast_) {
35#ifdef USE_UDP_IPV6_SEND
36 if (this->ipv4_send_)
37#endif
38 {
39 this->broadcast_socket_ = socket::socket_udp_send(AF_INET, IPPROTO_IP);
40 if (this->broadcast_socket_ == nullptr) {
41 this->status_set_error(LOG_STR("Could not create socket"));
42 this->mark_failed();
43 return;
44 }
45 int enable = 1;
46 auto err = this->broadcast_socket_->setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
47 if (err != 0) {
48 this->status_set_warning(LOG_STR("Socket unable to set reuseaddr"));
49 // we can still continue
50 }
51 err = this->broadcast_socket_->setsockopt(SOL_SOCKET, SO_BROADCAST, &enable, sizeof(int));
52 if (err != 0) {
53 this->status_set_warning(LOG_STR("Socket unable to set broadcast"));
54 }
55 }
56#ifdef USE_UDP_IPV6_SEND
57 if (this->ipv6_send_) {
58 this->send_socket_v6_ = socket::socket_udp_send(AF_INET6, IPPROTO_IP);
59 if (this->send_socket_v6_ == nullptr) {
60 this->status_set_error(LOG_STR("Could not create IPv6 socket"));
61 this->mark_failed();
62 return;
63 }
64 // Unicast needs no egress interface; multicast does
65 if (this->ipv6_multicast_)
67 }
68#endif
69 }
70#ifdef USE_UDP_OMR_SOURCE
71 // set_omr_source() asked for the bind; without a send socket there is nothing to bind
72 if (this->send_socket_v6_ == nullptr)
73 this->poll_pending_ &= ~POLL_SRC_BIND;
74#endif
75 // create listening socket if we either want to subscribe to providers, or need to listen
76 // for ping key broadcasts.
77 if (this->should_listen_) {
78 struct sockaddr_storage server{};
79 socklen_t server_len;
80 if (this->listen_address_ != nullptr) {
81 server_len =
82 socket::set_sockaddr((struct sockaddr *) &server, sizeof(server), this->listen_address_, this->listen_port_);
83 // A multicast join needs a socket of the group's address family
84 this->listen_socket_ = socket::socket_udp_loop_monitored(server.ss_family, IPPROTO_IP);
85 this->poll_pending_ |= POLL_JOIN;
86#ifdef USE_SOCKET_IPV6
87 // An IPv6 group binds after the join, which supplies the scope id link-local groups need
88 if (server.ss_family == AF_INET6)
89 this->poll_pending_ |= POLL_BIND;
90#endif
91 } else {
92#ifdef USE_SOCKET_IPV6
93 server_len = socket::set_sockaddr_any((struct sockaddr *) &server, sizeof(server), this->listen_port_);
94 this->listen_socket_ = socket::socket_udp_loop_monitored(AF_INET6, IPPROTO_IP);
95 // Clear IPV6_V6ONLY so IPv4 datagrams also arrive, as mapped addresses
96 int v6only = 0;
97 if (this->listen_socket_ != nullptr &&
98 this->listen_socket_->setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only)) != 0) {
99 ESP_LOGW(TAG, "Failed to clear IPV6_V6ONLY: errno %d", errno);
100 this->status_set_warning(LOG_STR("IPv4 datagrams may not be received"));
101 }
102#else
103 // Must stay IPv4: raw lwIP can have USE_NETWORK_IPV6 without IPv6 sockets
104 server_len = socket::set_sockaddr((struct sockaddr *) &server, sizeof(server), "0.0.0.0", this->listen_port_);
105 this->listen_socket_ = socket::socket_udp_loop_monitored(AF_INET, IPPROTO_IP);
106#endif
107 }
108 if (this->listen_socket_ == nullptr) {
109 this->status_set_error(LOG_STR("Could not create socket"));
110 this->mark_failed();
111 return;
112 }
113 auto err = this->listen_socket_->setblocking(false);
114 if (err < 0) {
115 ESP_LOGE(TAG, "Unable to set nonblocking: errno %d", errno);
116 this->status_set_error(LOG_STR("Unable to set nonblocking"));
117 this->mark_failed();
118 return;
119 }
120 int enable = 1;
121 err = this->listen_socket_->setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
122 if (err != 0) {
123 this->status_set_warning(LOG_STR("Socket unable to set reuseaddr"));
124 // we can still continue
125 }
126
127 if ((this->poll_pending_ & POLL_BIND) == 0) {
128 err = this->listen_socket_->bind((struct sockaddr *) &server, server_len);
129 if (err != 0) {
130 ESP_LOGE(TAG, "Socket unable to bind: errno %d", errno);
131 this->status_set_error(LOG_STR("Unable to bind socket"));
132 this->mark_failed();
133 return;
134 }
135 }
136 }
137 if (this->poll_pending_ != 0) {
138 // Joins and the IPv6 egress interface need the network up; RP2040 has no interface before then
139 this->set_interval(NETWORK_POLL_ID, NETWORK_POLL_INTERVAL_MS, [this]() {
140 if (network::is_connected() && this->network_poll_())
141 this->cancel_interval(NETWORK_POLL_ID);
142 });
143 }
144}
145
147 bool ok = true;
148 if (this->poll_pending_ & POLL_JOIN) {
149#ifdef USE_SOCKET_IPV6
150 uint32_t *if_index = &this->mcast_ifindex_;
151#else
152 uint32_t *if_index = nullptr;
153#endif
154 if (socket::join_multicast_group(this->listen_socket_.get(), this->listen_address_, if_index)) {
155 ESP_LOGD(TAG, "Joined multicast %s", this->listen_address_);
156 this->poll_pending_ &= ~POLL_JOIN;
157 this->poll_failed_ &= ~POLL_JOIN;
158 } else {
159 this->set_poll_warning_(POLL_JOIN, LOG_STR("Failed to join multicast group"), errno);
160 ok = false;
161 }
162 }
163#ifdef USE_SOCKET_IPV6
164 if (ok && (this->poll_pending_ & POLL_BIND)) {
165 struct sockaddr_storage server{};
166 socklen_t server_len =
167 socket::set_sockaddr((struct sockaddr *) &server, sizeof(server), this->listen_address_, this->listen_port_);
168 // POSIX bind() on a link-local group needs it; lwIP ignores it
169 reinterpret_cast<sockaddr_in6 *>(&server)->sin6_scope_id = this->mcast_ifindex_;
170 if (this->listen_socket_->bind((struct sockaddr *) &server, server_len) == 0) {
171 this->poll_pending_ &= ~POLL_BIND;
172 this->poll_failed_ &= ~POLL_BIND;
173 } else {
174 this->set_poll_warning_(POLL_BIND, LOG_STR("Unable to bind socket"), errno);
175 ok = false;
176 }
177 }
178#endif
179#ifdef USE_UDP_IPV6_SEND
180 // Only an IPv6 group's join supplies the index, so a failing IPv4 join must not hold back sends
181 const bool index_pending = (this->poll_pending_ & (POLL_JOIN | POLL_BIND)) == (POLL_JOIN | POLL_BIND);
182 if ((this->poll_pending_ & POLL_MCAST_IF) && !index_pending) {
183 // Index 0 picks the first eligible interface
184 if (socket::set_ipv6_multicast_if(this->send_socket_v6_.get(), this->mcast_ifindex_)) {
185 this->poll_pending_ &= ~POLL_MCAST_IF;
186 this->poll_failed_ &= ~POLL_MCAST_IF;
187 } else {
188 this->set_poll_warning_(POLL_MCAST_IF, LOG_STR("Failed to set IPv6 multicast interface"), errno);
189 ok = false;
190 }
191 }
192#endif
193#ifdef USE_UDP_OMR_SOURCE
194 if (this->poll_pending_ & POLL_SRC_BIND) {
195 // An unbound socket picks a mesh-local source that global destinations reject; bind the OMR address
197 auto omr = ot != nullptr ? ot->get_omr_address() : std::nullopt;
198 if (!omr.has_value()) {
199 // Nothing failed yet, so there is no errno to report
200 this->set_poll_warning_(POLL_SRC_BIND, LOG_STR("No routable IPv6 source address"), 0);
201 ok = false;
202 } else {
203 struct sockaddr_in6 src{};
204 src.sin6_family = AF_INET6;
205 memcpy(&src.sin6_addr, omr->mFields.m8, sizeof(src.sin6_addr));
206 if (this->send_socket_v6_->bind((struct sockaddr *) &src, sizeof(src)) == 0) {
207 this->poll_pending_ &= ~POLL_SRC_BIND;
208 this->poll_failed_ &= ~POLL_SRC_BIND;
209 } else {
210 this->set_poll_warning_(POLL_SRC_BIND, LOG_STR("Unable to bind the OMR source address"), errno);
211 ok = false;
212 }
213 }
214 }
215#endif
216 if (!ok)
217 return false;
218 if (this->poll_warning_) {
219 this->poll_warning_ = false;
220 this->status_clear_warning();
221 }
222 return true;
223}
224
225void UDPComponent::set_poll_warning_(PollStep step, const LogString *what, int err) {
226 // Log the first failure of each step only; the poll keeps retrying every second
227 if (this->poll_failed_ & step)
228 return;
229 this->poll_failed_ |= step;
230 if (err != 0) {
231 ESP_LOGW(TAG, "%s. Error %d", LOG_STR_ARG(what), err);
232 } else {
233 ESP_LOGW(TAG, "%s", LOG_STR_ARG(what));
234 }
235 // One warning bit: only a warning raised here is cleared on success, one from setup() stays
236 if (!this->status_has_warning()) {
237 this->status_set_warning(what);
238 this->poll_warning_ = true;
239 }
240}
241
243 if (!this->should_listen_) {
244 this->disable_loop();
245 return;
246 }
247 // One byte more than the largest packet, as a read cuts a longer datagram to fit and so cannot report it
248 std::array<uint8_t, MAX_PACKET_SIZE + 1> buf;
249 for (;;) {
250 if (!this->listen_socket_->ready())
251 break;
252 auto len = this->listen_socket_->read(buf.data(), buf.size());
253 if (len <= 0)
254 break;
255 size_t packet_len = static_cast<size_t>(len);
256 if (packet_len > MAX_PACKET_SIZE) {
257 ESP_LOGV(TAG, "Packet longer than %zu bytes dropped", MAX_PACKET_SIZE);
258 continue;
259 }
260 ESP_LOGV(TAG, "Received packet of length %zu", packet_len);
261 this->packet_listeners_.call(std::span<const uint8_t>(buf.data(), packet_len));
262 }
263}
264
266 ESP_LOGCONFIG(TAG,
267 "UDP:\n"
268 " Listen Port: %u\n"
269 " Broadcast Port: %u",
270 this->listen_port_, this->broadcast_port_);
271 for (const char *const *it = this->addresses_; it != nullptr && *it != nullptr; it++) {
272 const char *address = *it;
273 ESP_LOGCONFIG(TAG, " Address: %s", address);
274 }
275 if (this->listen_address_ != nullptr) {
276 ESP_LOGCONFIG(TAG, " Listen address: %s", this->listen_address_);
277 }
278 ESP_LOGCONFIG(TAG,
279 " Broadcasting: %s\n"
280 " Listening: %s",
281 YESNO(this->should_broadcast_), YESNO(this->should_listen_));
282}
283
284bool UDPComponent::send_packet(const uint8_t *data, size_t size) {
285 if (this->is_failed())
286 return false; // a send socket may be missing
287 bool sent = true;
288 for (const auto &entry : this->sockaddrs_) {
289#ifdef USE_UDP_IPV6_SEND
290 const bool v6 = entry.sa.sa_family == AF_INET6;
291 // Until the egress interface is set, a multicast packet would leave on the wrong one
292 if (v6 && (this->poll_pending_ & POLL_MCAST_IF) && entry.in6.sin6_addr.s6_addr[0] == 0xff) {
293 ESP_LOGV(TAG, "Egress interface not set yet, multicast packet dropped");
294 continue;
295 }
296#ifdef USE_UDP_OMR_SOURCE
297 // Zephyr registers the socket on its first sendto() and bind() then fails with EISCONN, so even
298 // mesh-scope destinations wait for the routable one
299 if (v6 && (this->poll_pending_ & POLL_SRC_BIND)) {
300 if ((this->poll_failed_ & POLL_SEND_HELD) == 0) {
302 ESP_LOGW(TAG, "IPv6 sends are held until a Thread border router provides an OMR address. "
303 "Put mesh-only destinations in a separate udp block to send them without waiting");
304 }
305 ESP_LOGV(TAG, "IPv6 source not bound yet, packet dropped");
306 continue;
307 }
308#endif
309 socket::UDPSendSocket *sock = v6 ? this->send_socket_v6_.get() : this->broadcast_socket_.get();
310 socklen_t sockaddr_size = v6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in);
311#else
312 socket::UDPSendSocket *sock = this->broadcast_socket_.get();
313 socklen_t sockaddr_size = sizeof(sockaddr_in);
314#endif
315 if (sock == nullptr) {
316 ESP_LOGW(TAG, "Broadcast socket not initialized");
317 return false;
318 }
319 auto result = sock->sendto(data, size, 0, &entry.sa, sockaddr_size);
320 if (result < 0) {
321 // lwIP refuses a packet with ENOMEM while the destination's ARP lookup is pending and its queue is full;
322 // the packet can be sent again later
323 if (errno == ENOMEM) {
324 ESP_LOGV(TAG, "sendto() out of memory");
325 } else {
326 ESP_LOGW(TAG, "sendto() error %d", errno);
327 }
328 sent = false;
329 }
330 }
331 return sent;
332}
333} // namespace esphome::udp
334
335#endif
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:287
bool cancel_interval(const char *name)
Cancel an interval function.
Definition component.cpp:92
bool status_has_warning() const
Definition component.h:293
void disable_loop()
Disable this component's loop.
void set_interval(const char *name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a const char* name.
Definition component.cpp:88
void status_clear_warning()
Definition component.h:309
ssize_t sendto(const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen)
std::unique_ptr< socket::UDPSendSocket > send_socket_v6_
FixedVector< SockaddrEntry > sockaddrs_
LazyCallbackManager< void(std::span< const uint8_t >)> packet_listeners_
bool network_poll_()
One pass of the network poll; true once nothing is left to do.
std::unique_ptr< socket::UDPSendSocket > broadcast_socket_
void set_poll_warning_(PollStep step, const LogString *what, int err)
err is the errno of the failed call, or 0 when no call failed.
const char *const * addresses_
std::unique_ptr< socket::UDPSocket > listen_socket_
bool send_packet(const uint8_t *data, size_t size)
Returns false if the packet could not be sent to every destination.
uint32_t socklen_t
Definition headers.h:109
ESPHOME_ALWAYS_INLINE bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.h:36
OpenThreadComponent * global_openthread_component
std::unique_ptr< UDPSendSocket > socket_udp_send(int domain, int protocol)
Create a send-only UDP socket (socket_udp_send), a UDP socket with receive support (socket_udp),...
socklen_t set_sockaddr(struct sockaddr *addr, socklen_t addrlen, const char *ip_address, uint16_t port)
Set a sockaddr to the specified address and port for the IP version used by socket_ip().
bool set_ipv6_multicast_if(Socket *sock, uint32_t if_index_in=0)
Configure the outgoing IPv6 multicast interface on the given socket.
bool join_multicast_group(UDPSocket *sock, const char *ip_address, uint32_t *if_index_out=nullptr)
Join a multicast group on the given socket.
socklen_t set_sockaddr_any(struct sockaddr *addr, socklen_t addrlen, uint16_t port)
Set a sockaddr to the any address and specified port for the IP version used by socket_ip().
std::unique_ptr< UDPSocket > socket_udp_loop_monitored(int domain, int protocol)
Definition socket.h:136
ESPHOME_LOG_TAG(TAG, "udp.packet_interface")
const void size_t len
Definition hal.h:68
uint16_t size
Definition helpers.cpp:34
const void * src
Definition hal.h:68
static void uint32_t