ESPHome 2026.3.3
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 succeeds: pool is sized to queue capacity (SIZE-1), so if
91 // allocate() returned non-null, the queue cannot be full.
92
93 // Wake main loop immediately to process ESP-NOW send event instead of waiting for select() timeout
94#if defined(USE_SOCKET_SELECT_SUPPORT) && defined(USE_WAKE_LOOP_THREADSAFE)
96#endif
97}
98
99void on_data_received(const esp_now_recv_info_t *info, const uint8_t *data, int size) {
100 // Allocate an event from the pool
102 if (packet == nullptr) {
103 // No events available - queue is full or we're out of memory
104 global_esp_now->receive_packet_queue_.increment_dropped_count();
105 return;
106 }
107
108 // Load new packet data (replaces previous packet)
109 packet->load_received_data(info, data, size);
110
111 // Push the packet to the queue
113 // Push always succeeds: pool is sized to queue capacity (SIZE-1), so if
114 // allocate() returned non-null, the queue cannot be full.
115
116 // Wake main loop immediately to process ESP-NOW receive event instead of waiting for select() timeout
117#if defined(USE_SOCKET_SELECT_SUPPORT) && defined(USE_WAKE_LOOP_THREADSAFE)
119#endif
120}
121
123
125 uint32_t version = 0;
126 esp_now_get_version(&version);
127
128 ESP_LOGCONFIG(TAG, "espnow:");
129 if (this->is_disabled()) {
130 ESP_LOGCONFIG(TAG, " Disabled");
131 return;
132 }
133 char own_addr_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
134 format_mac_addr_upper(this->own_address_, own_addr_buf);
135 ESP_LOGCONFIG(TAG,
136 " Own address: %s\n"
137 " Version: v%" PRIu32 "\n"
138 " Wi-Fi channel: %d",
139 own_addr_buf, version, this->wifi_channel_);
140#ifdef USE_WIFI
141 ESP_LOGCONFIG(TAG, " Wi-Fi enabled: %s", YESNO(this->is_wifi_enabled()));
142#endif
143}
144
146#ifdef USE_WIFI
148#else
149 return false;
150#endif
151}
152
154#ifndef USE_WIFI
155 // Initialize LwIP stack for wake_loop_threadsafe() socket support
156 // When WiFi component is present, it handles esp_netif_init()
157 ESP_ERROR_CHECK(esp_netif_init());
158#endif
159
160 if (this->enable_on_boot_) {
161 this->enable_();
162 } else {
164 }
165}
166
168 if (this->state_ == ESPNOW_STATE_ENABLED)
169 return;
170
171 ESP_LOGD(TAG, "Enabling");
172 this->state_ = ESPNOW_STATE_OFF;
173
174 this->enable_();
175}
176
178 if (!this->is_wifi_enabled()) {
179 esp_event_loop_create_default();
180
181 wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
182
183 ESP_ERROR_CHECK(esp_wifi_init(&cfg));
184 ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
185 ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
186 ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE));
187 ESP_ERROR_CHECK(esp_wifi_start());
188 ESP_ERROR_CHECK(esp_wifi_disconnect());
189
190 this->apply_wifi_channel();
191 }
192 this->get_wifi_channel();
193
194 esp_err_t err = esp_now_init();
195 if (err != ESP_OK) {
196 ESP_LOGE(TAG, "esp_now_init failed: %s", esp_err_to_name(err));
197 this->mark_failed();
198 return;
199 }
200
201 err = esp_now_register_recv_cb(on_data_received);
202 if (err != ESP_OK) {
203 ESP_LOGE(TAG, "esp_now_register_recv_cb failed: %s", esp_err_to_name(err));
204 this->mark_failed();
205 return;
206 }
207
208 err = esp_now_register_send_cb(on_send_report);
209 if (err != ESP_OK) {
210 ESP_LOGE(TAG, "esp_now_register_recv_cb failed: %s", esp_err_to_name(err));
211 this->mark_failed();
212 return;
213 }
214
215 esp_wifi_get_mac(WIFI_IF_STA, this->own_address_);
216
217#ifdef USE_DEEP_SLEEP
218 esp_now_set_wake_window(CONFIG_ESPNOW_WAKE_WINDOW);
219 esp_wifi_connectionless_module_set_wake_interval(CONFIG_ESPNOW_WAKE_INTERVAL);
220#endif
221
223
224 for (auto peer : this->peers_) {
225 this->add_peer(peer.address);
226 }
227}
228
230 if (this->state_ == ESPNOW_STATE_DISABLED)
231 return;
232
233 ESP_LOGD(TAG, "Disabling");
235
236 esp_now_unregister_recv_cb();
237 esp_now_unregister_send_cb();
238
239 esp_err_t err = esp_now_deinit();
240 if (err != ESP_OK) {
241 ESP_LOGE(TAG, "esp_now_deinit failed! 0x%x", err);
242 }
243}
244
246 if (this->state_ == ESPNOW_STATE_DISABLED) {
247 ESP_LOGE(TAG, "Cannot set channel when ESPNOW disabled");
248 this->mark_failed();
249 return;
250 }
251
252 if (this->is_wifi_enabled()) {
253 ESP_LOGE(TAG, "Cannot set channel when Wi-Fi enabled");
254 this->mark_failed();
255 return;
256 }
257
258 ESP_LOGI(TAG, "Channel set to %d.", this->wifi_channel_);
259 esp_wifi_set_promiscuous(true);
260 esp_wifi_set_channel(this->wifi_channel_, WIFI_SECOND_CHAN_NONE);
261 esp_wifi_set_promiscuous(false);
262}
263
265#ifdef USE_WIFI
266 if (wifi::global_wifi_component != nullptr && wifi::global_wifi_component->is_connected()) {
267 int32_t new_channel = wifi::global_wifi_component->get_wifi_channel();
268 if (new_channel != this->wifi_channel_) {
269 ESP_LOGI(TAG, "Wifi Channel is changed from %d to %d.", this->wifi_channel_, new_channel);
270 this->wifi_channel_ = new_channel;
271 }
272 }
273#endif
274 // Process received packets
275 ESPNowPacket *packet = this->receive_packet_queue_.pop();
276 while (packet != nullptr) {
277 switch (packet->type_) {
279 const ESPNowRecvInfo info = packet->get_receive_info();
280 if (!esp_now_is_peer_exist(info.src_addr)) {
281 bool handled = false;
282 for (auto *handler : this->unknown_peer_handlers_) {
283 if (handler->on_unknown_peer(info, packet->packet_.receive.data, packet->packet_.receive.size)) {
284 handled = true;
285 break; // If a handler returns true, stop processing further handlers
286 }
287 }
288 if (!handled && this->auto_add_peer_) {
289 this->add_peer(info.src_addr);
290 }
291 }
292 // Intentionally left as if instead of else in case the peer is added above
293 if (esp_now_is_peer_exist(info.src_addr)) {
294#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
295 char src_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
296 char dst_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
297 char hex_buf[format_hex_pretty_size(ESP_NOW_MAX_DATA_LEN)];
298 format_mac_addr_upper(info.src_addr, src_buf);
299 format_mac_addr_upper(info.des_addr, dst_buf);
300 ESP_LOGV(TAG, "<<< [%s -> %s] %s", src_buf, dst_buf,
301 format_hex_pretty_to(hex_buf, packet->packet_.receive.data, packet->packet_.receive.size));
302#endif
303 if (memcmp(info.des_addr, ESPNOW_BROADCAST_ADDR, ESP_NOW_ETH_ALEN) == 0) {
304 for (auto *handler : this->broadcasted_handlers_) {
305 if (handler->on_broadcasted(info, packet->packet_.receive.data, packet->packet_.receive.size))
306 break; // If a handler returns true, stop processing further handlers
307 }
308 } else {
309 for (auto *handler : this->received_handlers_) {
310 if (handler->on_received(info, packet->packet_.receive.data, packet->packet_.receive.size))
311 break; // If a handler returns true, stop processing further handlers
312 }
313 }
314 }
315 break;
316 }
317 case ESPNowPacket::SENT: {
318#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
319 char addr_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
320 format_mac_addr_upper(packet->packet_.sent.address, addr_buf);
321 ESP_LOGV(TAG, ">>> [%s] %s", addr_buf, LOG_STR_ARG(espnow_error_to_str(packet->packet_.sent.status)));
322#endif
323 if (this->current_send_packet_ != nullptr) {
324 this->current_send_packet_->callback_(packet->packet_.sent.status);
325 this->send_packet_pool_.release(this->current_send_packet_);
326 this->current_send_packet_ = nullptr; // Reset current packet after sending
327 }
328 break;
329 }
330 default:
331 break;
332 }
333 // Return the packet to the pool
334 this->receive_packet_pool_.release(packet);
335 packet = this->receive_packet_queue_.pop();
336 }
337
338 // Process sending packet queue
339 if (this->current_send_packet_ == nullptr) {
340 this->send_();
341 }
342
343 // Log dropped received packets periodically
344 uint16_t received_dropped = this->receive_packet_queue_.get_and_reset_dropped_count();
345 if (received_dropped > 0) {
346 ESP_LOGW(TAG, "Dropped %u received packets due to buffer overflow", received_dropped);
347 }
348
349 // Log dropped send packets periodically
350 uint16_t send_dropped = this->send_packet_queue_.get_and_reset_dropped_count();
351 if (send_dropped > 0) {
352 ESP_LOGW(TAG, "Dropped %u send packets due to buffer overflow", send_dropped);
353 }
354}
355
357 wifi_second_chan_t dummy;
358 esp_wifi_get_channel(&this->wifi_channel_, &dummy);
359 return this->wifi_channel_;
360}
361
362esp_err_t ESPNowComponent::send(const uint8_t *peer_address, const uint8_t *payload, size_t size,
363 const send_callback_t &callback) {
364 if (this->state_ != ESPNOW_STATE_ENABLED) {
365 return ESP_ERR_ESPNOW_NOT_INIT;
366 } else if (this->is_failed()) {
367 return ESP_ERR_ESPNOW_FAILED;
368 } else if (peer_address == 0ULL) {
369 return ESP_ERR_ESPNOW_PEER_NOT_SET;
370 } else if (memcmp(peer_address, this->own_address_, ESP_NOW_ETH_ALEN) == 0) {
371 return ESP_ERR_ESPNOW_OWN_ADDRESS;
372 } else if (size > ESP_NOW_MAX_DATA_LEN) {
373 return ESP_ERR_ESPNOW_DATA_SIZE;
374 } else if (!esp_now_is_peer_exist(peer_address)) {
375 if (memcmp(peer_address, ESPNOW_BROADCAST_ADDR, ESP_NOW_ETH_ALEN) == 0 || this->auto_add_peer_) {
376 esp_err_t err = this->add_peer(peer_address);
377 if (err != ESP_OK) {
378 return err;
379 }
380 } else {
381 return ESP_ERR_ESPNOW_PEER_NOT_PAIRED;
382 }
383 }
384 // Allocate a packet from the pool
385 ESPNowSendPacket *packet = this->send_packet_pool_.allocate();
386 if (packet == nullptr) {
387 this->send_packet_queue_.increment_dropped_count();
388 ESP_LOGE(TAG, "Failed to allocate send packet from pool");
389 this->status_momentary_warning("send-packet-pool-full");
390 return ESP_ERR_ESPNOW_NO_MEM;
391 }
392 // Load the packet data
393 packet->load_data(peer_address, payload, size, callback);
394 // Push the packet to the send queue
395 this->send_packet_queue_.push(packet);
396 return ESP_OK;
397}
398
400 ESPNowSendPacket *packet = this->send_packet_queue_.pop();
401 if (packet == nullptr) {
402 return; // No packets to send
403 }
404
405 this->current_send_packet_ = packet;
406 esp_err_t err = esp_now_send(packet->address_, packet->data_, packet->size_);
407 if (err != ESP_OK) {
408 char addr_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
409 format_mac_addr_upper(packet->address_, addr_buf);
410 ESP_LOGE(TAG, "Failed to send packet to %s - %s", addr_buf, LOG_STR_ARG(espnow_error_to_str(err)));
411 if (packet->callback_ != nullptr) {
412 packet->callback_(err);
413 }
414 this->status_momentary_warning("send-failed");
415 this->send_packet_pool_.release(packet);
416 this->current_send_packet_ = nullptr; // Reset current packet
417 return;
418 }
419}
420
421esp_err_t ESPNowComponent::add_peer(const uint8_t *peer) {
422 if (this->state_ != ESPNOW_STATE_ENABLED || this->is_failed()) {
423 return ESP_ERR_ESPNOW_NOT_INIT;
424 }
425
426 if (memcmp(peer, this->own_address_, ESP_NOW_ETH_ALEN) == 0) {
427 this->status_momentary_warning("peer-add-failed");
428 return ESP_ERR_INVALID_MAC;
429 }
430
431 if (!esp_now_is_peer_exist(peer)) {
432 esp_now_peer_info_t peer_info = {};
433 memset(&peer_info, 0, sizeof(esp_now_peer_info_t));
434 peer_info.ifidx = WIFI_IF_STA;
435 memcpy(peer_info.peer_addr, peer, ESP_NOW_ETH_ALEN);
436 esp_err_t err = esp_now_add_peer(&peer_info);
437
438 if (err != ESP_OK) {
439 char peer_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
440 format_mac_addr_upper(peer, peer_buf);
441 ESP_LOGE(TAG, "Failed to add peer %s - %s", peer_buf, LOG_STR_ARG(espnow_error_to_str(err)));
442 this->status_momentary_warning("peer-add-failed");
443 return err;
444 }
445 }
446 bool found = false;
447 for (auto &it : this->peers_) {
448 if (it == peer) {
449 found = true;
450 break;
451 }
452 }
453 if (!found) {
454 ESPNowPeer new_peer;
455 memcpy(new_peer.address, peer, ESP_NOW_ETH_ALEN);
456 this->peers_.push_back(new_peer);
457 }
458
459 return ESP_OK;
460}
461
462esp_err_t ESPNowComponent::del_peer(const uint8_t *peer) {
463 if (this->state_ != ESPNOW_STATE_ENABLED || this->is_failed()) {
464 return ESP_ERR_ESPNOW_NOT_INIT;
465 }
466 if (esp_now_is_peer_exist(peer)) {
467 esp_err_t err = esp_now_del_peer(peer);
468 if (err != ESP_OK) {
469 char peer_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
470 format_mac_addr_upper(peer, peer_buf);
471 ESP_LOGE(TAG, "Failed to delete peer %s - %s", peer_buf, LOG_STR_ARG(espnow_error_to_str(err)));
472 this->status_momentary_warning("peer-del-failed");
473 return err;
474 }
475 }
476 for (auto it = this->peers_.begin(); it != this->peers_.end(); ++it) {
477 if (*it == peer) {
478 this->peers_.erase(it);
479 break;
480 }
481 }
482 return ESP_OK;
483}
484
485} // namespace esphome::espnow
486
487#endif // USE_ESP32
void wake_loop_threadsafe()
Wake the main event loop from another FreeRTOS task.
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:233
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_
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)
esp_err_t del_peer(const uint8_t *peer)
std::vector< ESPNowReceivedPacketHandler * > received_handlers_
EventPool< ESPNowPacket, MAX_ESP_NOW_RECEIVE_QUEUE_SIZE - 1 > receive_packet_pool_
LockFreeQueue< ESPNowPacket, MAX_ESP_NOW_RECEIVE_QUEUE_SIZE > receive_packet_queue_
EventPool< ESPNowSendPacket, MAX_ESP_NOW_SEND_QUEUE_SIZE - 1 > send_packet_pool_
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:929
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:1200
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:1267
static void uint32_t
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.