ESPHome 2026.2.1
Loading...
Searching...
No Matches
espnow_component.cpp
Go to the documentation of this file.
1#include "espnow_component.h"
2
3#ifdef USE_ESP32
4
5#include "espnow_err.h"
6
10#include "esphome/core/log.h"
11
12#include <esp_event.h>
13#include <esp_mac.h>
14#include <esp_netif.h>
15#include <esp_now.h>
16#include <esp_random.h>
17#include <esp_wifi.h>
18#include <cstring>
19#include <memory>
20
21#ifdef USE_WIFI
23#endif
24
25namespace esphome::espnow {
26
27static constexpr const char *TAG = "espnow";
28
29static const esp_err_t CONFIG_ESPNOW_WAKE_WINDOW = 50;
30static const esp_err_t CONFIG_ESPNOW_WAKE_INTERVAL = 100;
31
32ESPNowComponent *global_esp_now = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
33
34static const LogString *espnow_error_to_str(esp_err_t error) {
35 switch (error) {
36 case ESP_ERR_ESPNOW_FAILED:
37 return LOG_STR("ESPNow is in fail mode");
38 case ESP_ERR_ESPNOW_OWN_ADDRESS:
39 return LOG_STR("Message to your self");
40 case ESP_ERR_ESPNOW_DATA_SIZE:
41 return LOG_STR("Data size to large");
42 case ESP_ERR_ESPNOW_PEER_NOT_SET:
43 return LOG_STR("Peer address not set");
44 case ESP_ERR_ESPNOW_PEER_NOT_PAIRED:
45 return LOG_STR("Peer address not paired");
46 case ESP_ERR_ESPNOW_NOT_INIT:
47 return LOG_STR("Not init");
48 case ESP_ERR_ESPNOW_ARG:
49 return LOG_STR("Invalid argument");
50 case ESP_ERR_ESPNOW_INTERNAL:
51 return LOG_STR("Internal Error");
52 case ESP_ERR_ESPNOW_NO_MEM:
53 return LOG_STR("Our of memory");
54 case ESP_ERR_ESPNOW_NOT_FOUND:
55 return LOG_STR("Peer not found");
56 case ESP_ERR_ESPNOW_IF:
57 return LOG_STR("Interface does not match");
58 case ESP_OK:
59 return LOG_STR("OK");
60 case ESP_NOW_SEND_FAIL:
61 return LOG_STR("Failed");
62 default:
63 return LOG_STR("Unknown Error");
64 }
65}
66
67#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
68void on_send_report(const esp_now_send_info_t *info, esp_now_send_status_t status)
69#else
70void on_send_report(const uint8_t *mac_addr, esp_now_send_status_t status)
71#endif
72{
73 // Allocate an event from the pool
75 if (packet == nullptr) {
76 // No events available - queue is full or we're out of memory
77 global_esp_now->receive_packet_queue_.increment_dropped_count();
78 return;
79 }
80
81// Load new packet data (replaces previous packet)
82#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
83 packet->load_sent_data(info->des_addr, status);
84#else
85 packet->load_sent_data(mac_addr, status);
86#endif
87
88 // Push the packet to the queue
90 // Push always because we're the only producer and the pool ensures we never exceed queue size
91
92 // Wake main loop immediately to process ESP-NOW send event instead of waiting for select() timeout
93#if defined(USE_SOCKET_SELECT_SUPPORT) && defined(USE_WAKE_LOOP_THREADSAFE)
95#endif
96}
97
98void on_data_received(const esp_now_recv_info_t *info, const uint8_t *data, int size) {
99 // Allocate an event from the pool
101 if (packet == nullptr) {
102 // No events available - queue is full or we're out of memory
103 global_esp_now->receive_packet_queue_.increment_dropped_count();
104 return;
105 }
106
107 // Load new packet data (replaces previous packet)
108 packet->load_received_data(info, data, size);
109
110 // Push the packet to the queue
112 // Push always because we're the only producer and the pool ensures we never exceed queue size
113
114 // Wake main loop immediately to process ESP-NOW receive event instead of waiting for select() timeout
115#if defined(USE_SOCKET_SELECT_SUPPORT) && defined(USE_WAKE_LOOP_THREADSAFE)
117#endif
118}
119
121
123 uint32_t version = 0;
124 esp_now_get_version(&version);
125
126 ESP_LOGCONFIG(TAG, "espnow:");
127 if (this->is_disabled()) {
128 ESP_LOGCONFIG(TAG, " Disabled");
129 return;
130 }
131 char own_addr_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
132 format_mac_addr_upper(this->own_address_, own_addr_buf);
133 ESP_LOGCONFIG(TAG,
134 " Own address: %s\n"
135 " Version: v%" PRIu32 "\n"
136 " Wi-Fi channel: %d",
137 own_addr_buf, version, this->wifi_channel_);
138#ifdef USE_WIFI
139 ESP_LOGCONFIG(TAG, " Wi-Fi enabled: %s", YESNO(this->is_wifi_enabled()));
140#endif
141}
142
144#ifdef USE_WIFI
146#else
147 return false;
148#endif
149}
150
152#ifndef USE_WIFI
153 // Initialize LwIP stack for wake_loop_threadsafe() socket support
154 // When WiFi component is present, it handles esp_netif_init()
155 ESP_ERROR_CHECK(esp_netif_init());
156#endif
157
158 if (this->enable_on_boot_) {
159 this->enable_();
160 } else {
162 }
163}
164
166 if (this->state_ == ESPNOW_STATE_ENABLED)
167 return;
168
169 ESP_LOGD(TAG, "Enabling");
170 this->state_ = ESPNOW_STATE_OFF;
171
172 this->enable_();
173}
174
176 if (!this->is_wifi_enabled()) {
177 esp_event_loop_create_default();
178
179 wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
180
181 ESP_ERROR_CHECK(esp_wifi_init(&cfg));
182 ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
183 ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
184 ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE));
185 ESP_ERROR_CHECK(esp_wifi_start());
186 ESP_ERROR_CHECK(esp_wifi_disconnect());
187
188 this->apply_wifi_channel();
189 }
190 this->get_wifi_channel();
191
192 esp_err_t err = esp_now_init();
193 if (err != ESP_OK) {
194 ESP_LOGE(TAG, "esp_now_init failed: %s", esp_err_to_name(err));
195 this->mark_failed();
196 return;
197 }
198
199 err = esp_now_register_recv_cb(on_data_received);
200 if (err != ESP_OK) {
201 ESP_LOGE(TAG, "esp_now_register_recv_cb failed: %s", esp_err_to_name(err));
202 this->mark_failed();
203 return;
204 }
205
206 err = esp_now_register_send_cb(on_send_report);
207 if (err != ESP_OK) {
208 ESP_LOGE(TAG, "esp_now_register_recv_cb failed: %s", esp_err_to_name(err));
209 this->mark_failed();
210 return;
211 }
212
213 esp_wifi_get_mac(WIFI_IF_STA, this->own_address_);
214
215#ifdef USE_DEEP_SLEEP
216 esp_now_set_wake_window(CONFIG_ESPNOW_WAKE_WINDOW);
217 esp_wifi_connectionless_module_set_wake_interval(CONFIG_ESPNOW_WAKE_INTERVAL);
218#endif
219
221
222 for (auto peer : this->peers_) {
223 this->add_peer(peer.address);
224 }
225}
226
228 if (this->state_ == ESPNOW_STATE_DISABLED)
229 return;
230
231 ESP_LOGD(TAG, "Disabling");
233
234 esp_now_unregister_recv_cb();
235 esp_now_unregister_send_cb();
236
237 esp_err_t err = esp_now_deinit();
238 if (err != ESP_OK) {
239 ESP_LOGE(TAG, "esp_now_deinit failed! 0x%x", err);
240 }
241}
242
244 if (this->state_ == ESPNOW_STATE_DISABLED) {
245 ESP_LOGE(TAG, "Cannot set channel when ESPNOW disabled");
246 this->mark_failed();
247 return;
248 }
249
250 if (this->is_wifi_enabled()) {
251 ESP_LOGE(TAG, "Cannot set channel when Wi-Fi enabled");
252 this->mark_failed();
253 return;
254 }
255
256 ESP_LOGI(TAG, "Channel set to %d.", this->wifi_channel_);
257 esp_wifi_set_promiscuous(true);
258 esp_wifi_set_channel(this->wifi_channel_, WIFI_SECOND_CHAN_NONE);
259 esp_wifi_set_promiscuous(false);
260}
261
263#ifdef USE_WIFI
264 if (wifi::global_wifi_component != nullptr && wifi::global_wifi_component->is_connected()) {
265 int32_t new_channel = wifi::global_wifi_component->get_wifi_channel();
266 if (new_channel != this->wifi_channel_) {
267 ESP_LOGI(TAG, "Wifi Channel is changed from %d to %d.", this->wifi_channel_, new_channel);
268 this->wifi_channel_ = new_channel;
269 }
270 }
271#endif
272 // Process received packets
273 ESPNowPacket *packet = this->receive_packet_queue_.pop();
274 while (packet != nullptr) {
275 switch (packet->type_) {
277 const ESPNowRecvInfo info = packet->get_receive_info();
278 if (!esp_now_is_peer_exist(info.src_addr)) {
279 bool handled = false;
280 for (auto *handler : this->unknown_peer_handlers_) {
281 if (handler->on_unknown_peer(info, packet->packet_.receive.data, packet->packet_.receive.size)) {
282 handled = true;
283 break; // If a handler returns true, stop processing further handlers
284 }
285 }
286 if (!handled && this->auto_add_peer_) {
287 this->add_peer(info.src_addr);
288 }
289 }
290 // Intentionally left as if instead of else in case the peer is added above
291 if (esp_now_is_peer_exist(info.src_addr)) {
292#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
293 char src_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
294 char dst_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
295 char hex_buf[format_hex_pretty_size(ESP_NOW_MAX_DATA_LEN)];
296 format_mac_addr_upper(info.src_addr, src_buf);
297 format_mac_addr_upper(info.des_addr, dst_buf);
298 ESP_LOGV(TAG, "<<< [%s -> %s] %s", src_buf, dst_buf,
299 format_hex_pretty_to(hex_buf, packet->packet_.receive.data, packet->packet_.receive.size));
300#endif
301 if (memcmp(info.des_addr, ESPNOW_BROADCAST_ADDR, ESP_NOW_ETH_ALEN) == 0) {
302 for (auto *handler : this->broadcasted_handlers_) {
303 if (handler->on_broadcasted(info, packet->packet_.receive.data, packet->packet_.receive.size))
304 break; // If a handler returns true, stop processing further handlers
305 }
306 } else {
307 for (auto *handler : this->received_handlers_) {
308 if (handler->on_received(info, packet->packet_.receive.data, packet->packet_.receive.size))
309 break; // If a handler returns true, stop processing further handlers
310 }
311 }
312 }
313 break;
314 }
315 case ESPNowPacket::SENT: {
316#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
317 char addr_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
318 format_mac_addr_upper(packet->packet_.sent.address, addr_buf);
319 ESP_LOGV(TAG, ">>> [%s] %s", addr_buf, LOG_STR_ARG(espnow_error_to_str(packet->packet_.sent.status)));
320#endif
321 if (this->current_send_packet_ != nullptr) {
322 this->current_send_packet_->callback_(packet->packet_.sent.status);
323 this->send_packet_pool_.release(this->current_send_packet_);
324 this->current_send_packet_ = nullptr; // Reset current packet after sending
325 }
326 break;
327 }
328 default:
329 break;
330 }
331 // Return the packet to the pool
332 this->receive_packet_pool_.release(packet);
333 packet = this->receive_packet_queue_.pop();
334 }
335
336 // Process sending packet queue
337 if (this->current_send_packet_ == nullptr) {
338 this->send_();
339 }
340
341 // Log dropped received packets periodically
342 uint16_t received_dropped = this->receive_packet_queue_.get_and_reset_dropped_count();
343 if (received_dropped > 0) {
344 ESP_LOGW(TAG, "Dropped %u received packets due to buffer overflow", received_dropped);
345 }
346
347 // Log dropped send packets periodically
348 uint16_t send_dropped = this->send_packet_queue_.get_and_reset_dropped_count();
349 if (send_dropped > 0) {
350 ESP_LOGW(TAG, "Dropped %u send packets due to buffer overflow", send_dropped);
351 }
352}
353
355 wifi_second_chan_t dummy;
356 esp_wifi_get_channel(&this->wifi_channel_, &dummy);
357 return this->wifi_channel_;
358}
359
360esp_err_t ESPNowComponent::send(const uint8_t *peer_address, const uint8_t *payload, size_t size,
361 const send_callback_t &callback) {
362 if (this->state_ != ESPNOW_STATE_ENABLED) {
363 return ESP_ERR_ESPNOW_NOT_INIT;
364 } else if (this->is_failed()) {
365 return ESP_ERR_ESPNOW_FAILED;
366 } else if (peer_address == 0ULL) {
367 return ESP_ERR_ESPNOW_PEER_NOT_SET;
368 } else if (memcmp(peer_address, this->own_address_, ESP_NOW_ETH_ALEN) == 0) {
369 return ESP_ERR_ESPNOW_OWN_ADDRESS;
370 } else if (size > ESP_NOW_MAX_DATA_LEN) {
371 return ESP_ERR_ESPNOW_DATA_SIZE;
372 } else if (!esp_now_is_peer_exist(peer_address)) {
373 if (memcmp(peer_address, ESPNOW_BROADCAST_ADDR, ESP_NOW_ETH_ALEN) == 0 || this->auto_add_peer_) {
374 esp_err_t err = this->add_peer(peer_address);
375 if (err != ESP_OK) {
376 return err;
377 }
378 } else {
379 return ESP_ERR_ESPNOW_PEER_NOT_PAIRED;
380 }
381 }
382 // Allocate a packet from the pool
383 ESPNowSendPacket *packet = this->send_packet_pool_.allocate();
384 if (packet == nullptr) {
385 this->send_packet_queue_.increment_dropped_count();
386 ESP_LOGE(TAG, "Failed to allocate send packet from pool");
387 this->status_momentary_warning("send-packet-pool-full");
388 return ESP_ERR_ESPNOW_NO_MEM;
389 }
390 // Load the packet data
391 packet->load_data(peer_address, payload, size, callback);
392 // Push the packet to the send queue
393 this->send_packet_queue_.push(packet);
394 return ESP_OK;
395}
396
398 ESPNowSendPacket *packet = this->send_packet_queue_.pop();
399 if (packet == nullptr) {
400 return; // No packets to send
401 }
402
403 this->current_send_packet_ = packet;
404 esp_err_t err = esp_now_send(packet->address_, packet->data_, packet->size_);
405 if (err != ESP_OK) {
406 char addr_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
407 format_mac_addr_upper(packet->address_, addr_buf);
408 ESP_LOGE(TAG, "Failed to send packet to %s - %s", addr_buf, LOG_STR_ARG(espnow_error_to_str(err)));
409 if (packet->callback_ != nullptr) {
410 packet->callback_(err);
411 }
412 this->status_momentary_warning("send-failed");
413 this->send_packet_pool_.release(packet);
414 this->current_send_packet_ = nullptr; // Reset current packet
415 return;
416 }
417}
418
419esp_err_t ESPNowComponent::add_peer(const uint8_t *peer) {
420 if (this->state_ != ESPNOW_STATE_ENABLED || this->is_failed()) {
421 return ESP_ERR_ESPNOW_NOT_INIT;
422 }
423
424 if (memcmp(peer, this->own_address_, ESP_NOW_ETH_ALEN) == 0) {
425 this->status_momentary_warning("peer-add-failed");
426 return ESP_ERR_INVALID_MAC;
427 }
428
429 if (!esp_now_is_peer_exist(peer)) {
430 esp_now_peer_info_t peer_info = {};
431 memset(&peer_info, 0, sizeof(esp_now_peer_info_t));
432 peer_info.ifidx = WIFI_IF_STA;
433 memcpy(peer_info.peer_addr, peer, ESP_NOW_ETH_ALEN);
434 esp_err_t err = esp_now_add_peer(&peer_info);
435
436 if (err != ESP_OK) {
437 char peer_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
438 format_mac_addr_upper(peer, peer_buf);
439 ESP_LOGE(TAG, "Failed to add peer %s - %s", peer_buf, LOG_STR_ARG(espnow_error_to_str(err)));
440 this->status_momentary_warning("peer-add-failed");
441 return err;
442 }
443 }
444 bool found = false;
445 for (auto &it : this->peers_) {
446 if (it == peer) {
447 found = true;
448 break;
449 }
450 }
451 if (!found) {
452 ESPNowPeer new_peer;
453 memcpy(new_peer.address, peer, ESP_NOW_ETH_ALEN);
454 this->peers_.push_back(new_peer);
455 }
456
457 return ESP_OK;
458}
459
460esp_err_t ESPNowComponent::del_peer(const uint8_t *peer) {
461 if (this->state_ != ESPNOW_STATE_ENABLED || this->is_failed()) {
462 return ESP_ERR_ESPNOW_NOT_INIT;
463 }
464 if (esp_now_is_peer_exist(peer)) {
465 esp_err_t err = esp_now_del_peer(peer);
466 if (err != ESP_OK) {
467 char peer_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
468 format_mac_addr_upper(peer, peer_buf);
469 ESP_LOGE(TAG, "Failed to delete peer %s - %s", peer_buf, LOG_STR_ARG(espnow_error_to_str(err)));
470 this->status_momentary_warning("peer-del-failed");
471 return err;
472 }
473 }
474 for (auto it = this->peers_.begin(); it != this->peers_.end(); ++it) {
475 if (*it == peer) {
476 this->peers_.erase(it);
477 break;
478 }
479 }
480 return ESP_OK;
481}
482
483} // namespace esphome::espnow
484
485#endif // USE_ESP32
void wake_loop_threadsafe()
Wake the main event loop from a FreeRTOS task Thread-safe, can be called from task context to immedia...
virtual void mark_failed()
Mark this component as failed.
bool is_failed() const
void status_momentary_warning(const char *name, uint32_t length=5000)
Set warning status flag and automatically clear it after a timeout.
esp_err_t send(const uint8_t *peer_address, const std::vector< uint8_t > &payload, const send_callback_t &callback=nullptr)
Queue a packet to be sent to a specific peer address.
LockFreeQueue< ESPNowSendPacket, MAX_ESP_NOW_SEND_QUEUE_SIZE > send_packet_queue_
void add_peer(peer_address_t address)
std::vector< ESPNowUnknownPeerHandler * > unknown_peer_handlers_
EventPool< ESPNowSendPacket, MAX_ESP_NOW_SEND_QUEUE_SIZE > send_packet_pool_
std::vector< ESPNowPeer > peers_
friend void on_send_report(const esp_now_send_info_t *info, esp_now_send_status_t status)
std::vector< ESPNowBroadcastedHandler * > broadcasted_handlers_
friend void on_data_received(const esp_now_recv_info_t *info, const uint8_t *data, int size)
EventPool< ESPNowPacket, MAX_ESP_NOW_RECEIVE_QUEUE_SIZE > receive_packet_pool_
esp_err_t del_peer(const uint8_t *peer)
std::vector< ESPNowReceivedPacketHandler * > received_handlers_
LockFreeQueue< ESPNowPacket, MAX_ESP_NOW_RECEIVE_QUEUE_SIZE > receive_packet_queue_
uint8_t own_address_[ESP_NOW_ETH_ALEN]
void load_sent_data(const uint8_t *mac_addr, esp_now_send_status_t status)
struct esphome::espnow::ESPNowPacket::@85::received_data receive
void load_received_data(const esp_now_recv_info_t *info, const uint8_t *data, int size)
union esphome::espnow::ESPNowPacket::@85 packet_
esp_now_packet_type_t type_
const ESPNowRecvInfo & get_receive_info() const
struct esphome::espnow::ESPNowPacket::@85::sent_data sent
void load_data(const uint8_t *peer_address, const uint8_t *payload, size_t size, const send_callback_t &callback)
uint8_t address_[ESP_NOW_ETH_ALEN]
uint8_t data_[ESP_NOW_MAX_DATA_LEN]
@ ESPNOW_STATE_ENABLED
ESPNOW is enabled.
@ ESPNOW_STATE_OFF
Nothing has been initialized yet.
@ ESPNOW_STATE_DISABLED
ESPNOW is disabled.
void on_send_report(const esp_now_send_info_t *info, esp_now_send_status_t status) void on_send_report(const uint8_t *mac_addr
void on_data_received(const esp_now_recv_info_t *info, const uint8_t *data, int size)
ESPNowComponent * global_esp_now
void esp_now_send_status_t status
std::function< void(esp_err_t)> send_callback_t
WiFiComponent * global_wifi_component
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:353
size_t size
Definition helpers.h:729
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:978
Application App
Global storage of Application pointer - only one Application can exist.
char * format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase, colon separators)
Definition helpers.h:1045
uint8_t address[ESP_NOW_ETH_ALEN]
uint8_t des_addr[ESP_NOW_ETH_ALEN]
Destination address of ESPNOW packet.
uint8_t src_addr[ESP_NOW_ETH_ALEN]
Source address of ESPNOW packet.