ESPHome 2025.12.0-dev
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
9#include "esphome/core/log.h"
10
11#include <esp_event.h>
12#include <esp_mac.h>
13#include <esp_now.h>
14#include <esp_random.h>
15#include <esp_wifi.h>
16#include <cstring>
17#include <memory>
18
19#ifdef USE_WIFI
21#endif
22
23namespace esphome::espnow {
24
25static constexpr const char *TAG = "espnow";
26
27static const esp_err_t CONFIG_ESPNOW_WAKE_WINDOW = 50;
28static const esp_err_t CONFIG_ESPNOW_WAKE_INTERVAL = 100;
29
30ESPNowComponent *global_esp_now = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
31
32static const LogString *espnow_error_to_str(esp_err_t error) {
33 switch (error) {
34 case ESP_ERR_ESPNOW_FAILED:
35 return LOG_STR("ESPNow is in fail mode");
36 case ESP_ERR_ESPNOW_OWN_ADDRESS:
37 return LOG_STR("Message to your self");
38 case ESP_ERR_ESPNOW_DATA_SIZE:
39 return LOG_STR("Data size to large");
40 case ESP_ERR_ESPNOW_PEER_NOT_SET:
41 return LOG_STR("Peer address not set");
42 case ESP_ERR_ESPNOW_PEER_NOT_PAIRED:
43 return LOG_STR("Peer address not paired");
44 case ESP_ERR_ESPNOW_NOT_INIT:
45 return LOG_STR("Not init");
46 case ESP_ERR_ESPNOW_ARG:
47 return LOG_STR("Invalid argument");
48 case ESP_ERR_ESPNOW_INTERNAL:
49 return LOG_STR("Internal Error");
50 case ESP_ERR_ESPNOW_NO_MEM:
51 return LOG_STR("Our of memory");
52 case ESP_ERR_ESPNOW_NOT_FOUND:
53 return LOG_STR("Peer not found");
54 case ESP_ERR_ESPNOW_IF:
55 return LOG_STR("Interface does not match");
56 case ESP_OK:
57 return LOG_STR("OK");
58 case ESP_NOW_SEND_FAIL:
59 return LOG_STR("Failed");
60 default:
61 return LOG_STR("Unknown Error");
62 }
63}
64
65std::string peer_str(uint8_t *peer) {
66 if (peer == nullptr || peer[0] == 0) {
67 return "[Not Set]";
68 } else if (memcmp(peer, ESPNOW_BROADCAST_ADDR, ESP_NOW_ETH_ALEN) == 0) {
69 return "[Broadcast]";
70 } else if (memcmp(peer, ESPNOW_MULTICAST_ADDR, ESP_NOW_ETH_ALEN) == 0) {
71 return "[Multicast]";
72 } else {
73 return format_mac_address_pretty(peer);
74 }
75}
76
77#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
78void on_send_report(const esp_now_send_info_t *info, esp_now_send_status_t status)
79#else
80void on_send_report(const uint8_t *mac_addr, esp_now_send_status_t status)
81#endif
82{
83 // Allocate an event from the pool
85 if (packet == nullptr) {
86 // No events available - queue is full or we're out of memory
87 global_esp_now->receive_packet_queue_.increment_dropped_count();
88 return;
89 }
90
91// Load new packet data (replaces previous packet)
92#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
93 packet->load_sent_data(info->des_addr, status);
94#else
95 packet->load_sent_data(mac_addr, status);
96#endif
97
98 // Push the packet to the queue
100 // Push always because we're the only producer and the pool ensures we never exceed queue size
101
102 // Wake main loop immediately to process ESP-NOW send event instead of waiting for select() timeout
103#if defined(USE_SOCKET_SELECT_SUPPORT) && defined(USE_WAKE_LOOP_THREADSAFE)
105#endif
106}
107
108void on_data_received(const esp_now_recv_info_t *info, const uint8_t *data, int size) {
109 // Allocate an event from the pool
111 if (packet == nullptr) {
112 // No events available - queue is full or we're out of memory
113 global_esp_now->receive_packet_queue_.increment_dropped_count();
114 return;
115 }
116
117 // Load new packet data (replaces previous packet)
118 packet->load_received_data(info, data, size);
119
120 // Push the packet to the queue
122 // Push always because we're the only producer and the pool ensures we never exceed queue size
123
124 // Wake main loop immediately to process ESP-NOW receive event instead of waiting for select() timeout
125#if defined(USE_SOCKET_SELECT_SUPPORT) && defined(USE_WAKE_LOOP_THREADSAFE)
127#endif
128}
129
131
133 uint32_t version = 0;
134 esp_now_get_version(&version);
135
136 ESP_LOGCONFIG(TAG, "espnow:");
137 if (this->is_disabled()) {
138 ESP_LOGCONFIG(TAG, " Disabled");
139 return;
140 }
141 ESP_LOGCONFIG(TAG,
142 " Own address: %s\n"
143 " Version: v%" PRIu32 "\n"
144 " Wi-Fi channel: %d",
145 format_mac_address_pretty(this->own_address_).c_str(), version, this->wifi_channel_);
146#ifdef USE_WIFI
147 ESP_LOGCONFIG(TAG, " Wi-Fi enabled: %s", YESNO(this->is_wifi_enabled()));
148#endif
149}
150
152#ifdef USE_WIFI
154#else
155 return false;
156#endif
157}
158
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 ESP_LOGV(TAG, "<<< [%s -> %s] %s", format_mac_address_pretty(info.src_addr).c_str(),
297 format_hex_pretty(packet->packet_.receive.data, packet->packet_.receive.size).c_str());
298#endif
299 if (memcmp(info.des_addr, ESPNOW_BROADCAST_ADDR, ESP_NOW_ETH_ALEN) == 0) {
300 for (auto *handler : this->broadcasted_handlers_) {
301 if (handler->on_broadcasted(info, packet->packet_.receive.data, packet->packet_.receive.size))
302 break; // If a handler returns true, stop processing further handlers
303 }
304 } else {
305 for (auto *handler : this->received_handlers_) {
306 if (handler->on_received(info, packet->packet_.receive.data, packet->packet_.receive.size))
307 break; // If a handler returns true, stop processing further handlers
308 }
309 }
310 }
311 break;
312 }
313 case ESPNowPacket::SENT: {
314#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
315 ESP_LOGV(TAG, ">>> [%s] %s", format_mac_address_pretty(packet->packet_.sent.address).c_str(),
316 LOG_STR_ARG(espnow_error_to_str(packet->packet_.sent.status)));
317#endif
318 if (this->current_send_packet_ != nullptr) {
319 this->current_send_packet_->callback_(packet->packet_.sent.status);
320 this->send_packet_pool_.release(this->current_send_packet_);
321 this->current_send_packet_ = nullptr; // Reset current packet after sending
322 }
323 break;
324 }
325 default:
326 break;
327 }
328 // Return the packet to the pool
329 this->receive_packet_pool_.release(packet);
330 packet = this->receive_packet_queue_.pop();
331 }
332
333 // Process sending packet queue
334 if (this->current_send_packet_ == nullptr) {
335 this->send_();
336 }
337
338 // Log dropped received packets periodically
339 uint16_t received_dropped = this->receive_packet_queue_.get_and_reset_dropped_count();
340 if (received_dropped > 0) {
341 ESP_LOGW(TAG, "Dropped %u received packets due to buffer overflow", received_dropped);
342 }
343
344 // Log dropped send packets periodically
345 uint16_t send_dropped = this->send_packet_queue_.get_and_reset_dropped_count();
346 if (send_dropped > 0) {
347 ESP_LOGW(TAG, "Dropped %u send packets due to buffer overflow", send_dropped);
348 }
349}
350
352 wifi_second_chan_t dummy;
353 esp_wifi_get_channel(&this->wifi_channel_, &dummy);
354 return this->wifi_channel_;
355}
356
357esp_err_t ESPNowComponent::send(const uint8_t *peer_address, const uint8_t *payload, size_t size,
358 const send_callback_t &callback) {
359 if (this->state_ != ESPNOW_STATE_ENABLED) {
360 return ESP_ERR_ESPNOW_NOT_INIT;
361 } else if (this->is_failed()) {
362 return ESP_ERR_ESPNOW_FAILED;
363 } else if (peer_address == 0ULL) {
364 return ESP_ERR_ESPNOW_PEER_NOT_SET;
365 } else if (memcmp(peer_address, this->own_address_, ESP_NOW_ETH_ALEN) == 0) {
366 return ESP_ERR_ESPNOW_OWN_ADDRESS;
367 } else if (size > ESP_NOW_MAX_DATA_LEN) {
368 return ESP_ERR_ESPNOW_DATA_SIZE;
369 } else if (!esp_now_is_peer_exist(peer_address)) {
370 if (memcmp(peer_address, ESPNOW_BROADCAST_ADDR, ESP_NOW_ETH_ALEN) == 0 || this->auto_add_peer_) {
371 esp_err_t err = this->add_peer(peer_address);
372 if (err != ESP_OK) {
373 return err;
374 }
375 } else {
376 return ESP_ERR_ESPNOW_PEER_NOT_PAIRED;
377 }
378 }
379 // Allocate a packet from the pool
380 ESPNowSendPacket *packet = this->send_packet_pool_.allocate();
381 if (packet == nullptr) {
382 this->send_packet_queue_.increment_dropped_count();
383 ESP_LOGE(TAG, "Failed to allocate send packet from pool");
384 this->status_momentary_warning("send-packet-pool-full");
385 return ESP_ERR_ESPNOW_NO_MEM;
386 }
387 // Load the packet data
388 packet->load_data(peer_address, payload, size, callback);
389 // Push the packet to the send queue
390 this->send_packet_queue_.push(packet);
391 return ESP_OK;
392}
393
395 ESPNowSendPacket *packet = this->send_packet_queue_.pop();
396 if (packet == nullptr) {
397 return; // No packets to send
398 }
399
400 this->current_send_packet_ = packet;
401 esp_err_t err = esp_now_send(packet->address_, packet->data_, packet->size_);
402 if (err != ESP_OK) {
403 ESP_LOGE(TAG, "Failed to send packet to %s - %s", format_mac_address_pretty(packet->address_).c_str(),
404 LOG_STR_ARG(espnow_error_to_str(err)));
405 if (packet->callback_ != nullptr) {
406 packet->callback_(err);
407 }
408 this->status_momentary_warning("send-failed");
409 this->send_packet_pool_.release(packet);
410 this->current_send_packet_ = nullptr; // Reset current packet
411 return;
412 }
413}
414
415esp_err_t ESPNowComponent::add_peer(const uint8_t *peer) {
416 if (this->state_ != ESPNOW_STATE_ENABLED || this->is_failed()) {
417 return ESP_ERR_ESPNOW_NOT_INIT;
418 }
419
420 if (memcmp(peer, this->own_address_, ESP_NOW_ETH_ALEN) == 0) {
421 this->status_momentary_warning("peer-add-failed");
422 return ESP_ERR_INVALID_MAC;
423 }
424
425 if (!esp_now_is_peer_exist(peer)) {
426 esp_now_peer_info_t peer_info = {};
427 memset(&peer_info, 0, sizeof(esp_now_peer_info_t));
428 peer_info.ifidx = WIFI_IF_STA;
429 memcpy(peer_info.peer_addr, peer, ESP_NOW_ETH_ALEN);
430 esp_err_t err = esp_now_add_peer(&peer_info);
431
432 if (err != ESP_OK) {
433 ESP_LOGE(TAG, "Failed to add peer %s - %s", format_mac_address_pretty(peer).c_str(),
434 LOG_STR_ARG(espnow_error_to_str(err)));
435 this->status_momentary_warning("peer-add-failed");
436 return err;
437 }
438 }
439 bool found = false;
440 for (auto &it : this->peers_) {
441 if (it == peer) {
442 found = true;
443 break;
444 }
445 }
446 if (!found) {
447 ESPNowPeer new_peer;
448 memcpy(new_peer.address, peer, ESP_NOW_ETH_ALEN);
449 this->peers_.push_back(new_peer);
450 }
451
452 return ESP_OK;
453}
454
455esp_err_t ESPNowComponent::del_peer(const uint8_t *peer) {
456 if (this->state_ != ESPNOW_STATE_ENABLED || this->is_failed()) {
457 return ESP_ERR_ESPNOW_NOT_INIT;
458 }
459 if (esp_now_is_peer_exist(peer)) {
460 esp_err_t err = esp_now_del_peer(peer);
461 if (err != ESP_OK) {
462 ESP_LOGE(TAG, "Failed to delete peer %s - %s", format_mac_address_pretty(peer).c_str(),
463 LOG_STR_ARG(espnow_error_to_str(err)));
464 this->status_momentary_warning("peer-del-failed");
465 return err;
466 }
467 }
468 for (auto it = this->peers_.begin(); it != this->peers_.end(); ++it) {
469 if (*it == peer) {
470 this->peers_.erase(it);
471 break;
472 }
473 }
474 return ESP_OK;
475}
476
477} // namespace esphome::espnow
478
479#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 std::string &name, uint32_t length=5000)
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
std::string peer_str(uint8_t *peer)
WiFiComponent * global_wifi_component
std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length)
Format a byte array in pretty-printed, human-readable hex format.
Definition helpers.cpp:317
std::string format_mac_address_pretty(const uint8_t *mac)
Definition helpers.cpp:282
Application App
Global storage of Application pointer - only one Application can exist.
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.