blob: c94fc81708a146630a34b5a35b2c85641a4cc179 [file] [log] [blame]
Glenn Moloney7fa322a2020-09-24 15:37:04 +10001/*
2 * This file is part of the MicroPython project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2017-2020 Nick Moore
7 * Copyright (c) 2018 shawwwn <shawwwn1@gmail.com>
8 * Copyright (c) 2020-2021 Glenn Moloney @glenn20
9 *
10 * Permission is hereby granted, free of charge, to any person obtaining a copy
11 * of this software and associated documentation files (the "Software"), to deal
12 * in the Software without restriction, including without limitation the rights
13 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 * copies of the Software, and to permit persons to whom the Software is
15 * furnished to do so, subject to the following conditions:
16 *
17 * The above copyright notice and this permission notice shall be included in
18 * all copies or substantial portions of the Software.
19 *
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 * THE SOFTWARE.
27 */
28
29
30#include <stdio.h>
31#include <stdint.h>
32#include <string.h>
33
34#include "esp_log.h"
35#include "esp_now.h"
36#include "esp_wifi.h"
37#include "esp_wifi_types.h"
38
39#include "py/runtime.h"
40#include "py/mphal.h"
41#include "py/mperrno.h"
42#include "py/obj.h"
43#include "py/objstr.h"
44#include "py/objarray.h"
45#include "py/stream.h"
46#include "py/binary.h"
47#include "py/ringbuf.h"
48
49#include "mpconfigport.h"
50#include "mphalport.h"
51#include "modnetwork.h"
52#include "modespnow.h"
53
54#ifndef MICROPY_ESPNOW_RSSI
55// Include code to track rssi of peers
56#define MICROPY_ESPNOW_RSSI 1
57#endif
58#ifndef MICROPY_ESPNOW_EXTRA_PEER_METHODS
59// Include mod_peer(),get_peer(),peer_count()
60#define MICROPY_ESPNOW_EXTRA_PEER_METHODS 1
61#endif
62
63// Relies on gcc Variadic Macros and Statement Expressions
64#define NEW_TUPLE(...) \
65 ({mp_obj_t _z[] = {__VA_ARGS__}; mp_obj_new_tuple(MP_ARRAY_SIZE(_z), _z); })
66
67static const uint8_t ESPNOW_MAGIC = 0x99;
68
69// ESPNow packet format for the receive buffer.
70// Use this for peeking at the header of the next packet in the buffer.
71typedef struct {
72 uint8_t magic; // = ESPNOW_MAGIC
73 uint8_t msg_len; // Length of the message
74 #if MICROPY_ESPNOW_RSSI
75 uint32_t time_ms; // Timestamp (ms) when packet is received
76 int8_t rssi; // RSSI value (dBm) (-127 to 0)
77 #endif // MICROPY_ESPNOW_RSSI
78} __attribute__((packed)) espnow_hdr_t;
79
80typedef struct {
81 espnow_hdr_t hdr; // The header
82 uint8_t peer[6]; // Peer address
83 uint8_t msg[0]; // Message is up to 250 bytes
84} __attribute__((packed)) espnow_pkt_t;
85
86// The maximum length of an espnow packet (bytes)
87static const size_t MAX_PACKET_LEN = (
88 (sizeof(espnow_pkt_t) + ESP_NOW_MAX_DATA_LEN));
89
90// Enough for 2 full-size packets: 2 * (6 + 7 + 250) = 526 bytes
91// Will allocate an additional 7 bytes for buffer overhead
92static const size_t DEFAULT_RECV_BUFFER_SIZE = (2 * MAX_PACKET_LEN);
93
94// Default timeout (millisec) to wait for incoming ESPNow messages (5 minutes).
95static const size_t DEFAULT_RECV_TIMEOUT_MS = (5 * 60 * 1000);
96
97// Time to wait (millisec) for responses from sent packets: (2 seconds).
98static const size_t DEFAULT_SEND_TIMEOUT_MS = (2 * 1000);
99
100// Number of milliseconds to wait for pending responses to sent packets.
101// This is a fallback which should never be reached.
102static const mp_uint_t PENDING_RESPONSES_TIMEOUT_MS = 100;
103static const mp_uint_t PENDING_RESPONSES_BUSY_POLL_MS = 10;
104
105// The data structure for the espnow_singleton.
106typedef struct _esp_espnow_obj_t {
107 mp_obj_base_t base;
108
109 ringbuf_t *recv_buffer; // A buffer for received packets
110 size_t recv_buffer_size; // The size of the recv_buffer
111 mp_int_t recv_timeout_ms; // Timeout for recv()
112 volatile size_t rx_packets; // # of received packets
113 size_t dropped_rx_pkts; // # of dropped packets (buffer full)
114 size_t tx_packets; // # of sent packets
115 volatile size_t tx_responses; // # of sent packet responses received
116 volatile size_t tx_failures; // # of sent packet responses failed
117 size_t peer_count; // Cache the # of peers for send(sync=True)
118 mp_obj_t recv_cb; // Callback when a packet is received
119 mp_obj_t recv_cb_arg; // Argument passed to callback
120 #if MICROPY_ESPNOW_RSSI
121 mp_obj_t peers_table; // A dictionary of discovered peers
122 #endif // MICROPY_ESPNOW_RSSI
123} esp_espnow_obj_t;
124
125const mp_obj_type_t esp_espnow_type;
126
127// ### Initialisation and Config functions
128//
129
130// Return a pointer to the ESPNow module singleton
131// If state == INITIALISED check the device has been initialised.
132// Raises OSError if not initialised and state == INITIALISED.
133static esp_espnow_obj_t *_get_singleton() {
134 return MP_STATE_PORT(espnow_singleton);
135}
136
137static esp_espnow_obj_t *_get_singleton_initialised() {
138 esp_espnow_obj_t *self = _get_singleton();
139 // assert(self);
140 if (self->recv_buffer == NULL) {
141 // Throw an espnow not initialised error
142 check_esp_err(ESP_ERR_ESPNOW_NOT_INIT);
143 }
144 return self;
145}
146
147// Allocate and initialise the ESPNow module as a singleton.
148// Returns the initialised espnow_singleton.
149STATIC mp_obj_t espnow_make_new(const mp_obj_type_t *type, size_t n_args,
150 size_t n_kw, const mp_obj_t *all_args) {
151
152 // The espnow_singleton must be defined in MICROPY_PORT_ROOT_POINTERS
153 // (see mpconfigport.h) to prevent memory allocated here from being
154 // garbage collected.
155 // NOTE: on soft reset the espnow_singleton MUST be set to NULL and the
156 // ESP-NOW functions de-initialised (see main.c).
157 esp_espnow_obj_t *self = MP_STATE_PORT(espnow_singleton);
158 if (self != NULL) {
159 return self;
160 }
161 self = m_new_obj(esp_espnow_obj_t);
162 self->base.type = &esp_espnow_type;
163 self->recv_buffer_size = DEFAULT_RECV_BUFFER_SIZE;
164 self->recv_timeout_ms = DEFAULT_RECV_TIMEOUT_MS;
165 self->recv_buffer = NULL; // Buffer is allocated in espnow_init()
166 self->recv_cb = mp_const_none;
167 #if MICROPY_ESPNOW_RSSI
168 self->peers_table = mp_obj_new_dict(0);
169 // Prevent user code modifying the dict
170 mp_obj_dict_get_map(self->peers_table)->is_fixed = 1;
171 #endif // MICROPY_ESPNOW_RSSI
172
173 // Set the global singleton pointer for the espnow protocol.
174 MP_STATE_PORT(espnow_singleton) = self;
175
176 return self;
177}
178
179// Forward declare the send and recv ESPNow callbacks
180STATIC void send_cb(const uint8_t *mac_addr, esp_now_send_status_t status);
181
Damien Georgee4650122023-05-09 09:52:54 +1000182STATIC void recv_cb(const esp_now_recv_info_t *recv_info, const uint8_t *msg, int msg_len);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000183
184// ESPNow.init(): Initialise the data buffers and ESP-NOW functions.
185// Initialise the Espressif ESPNOW software stack, register callbacks and
186// allocate the recv data buffers.
187// Returns None.
188static mp_obj_t espnow_init(mp_obj_t _) {
189 esp_espnow_obj_t *self = _get_singleton();
190 if (self->recv_buffer == NULL) { // Already initialised
191 self->recv_buffer = m_new_obj(ringbuf_t);
192 ringbuf_alloc(self->recv_buffer, self->recv_buffer_size);
193
194 esp_initialise_wifi(); // Call the wifi init code in network_wlan.c
195 check_esp_err(esp_now_init());
196 check_esp_err(esp_now_register_recv_cb(recv_cb));
197 check_esp_err(esp_now_register_send_cb(send_cb));
198 }
199 return mp_const_none;
200}
201
202// ESPNow.deinit(): De-initialise the ESPNOW software stack, disable callbacks
203// and deallocate the recv data buffers.
204// Note: this function is called from main.c:mp_task() to cleanup before soft
205// reset, so cannot be declared STATIC and must guard against self == NULL;.
206mp_obj_t espnow_deinit(mp_obj_t _) {
207 esp_espnow_obj_t *self = _get_singleton();
208 if (self != NULL && self->recv_buffer != NULL) {
209 check_esp_err(esp_now_unregister_recv_cb());
210 check_esp_err(esp_now_unregister_send_cb());
211 check_esp_err(esp_now_deinit());
212 self->recv_buffer->buf = NULL;
213 self->recv_buffer = NULL;
214 self->peer_count = 0; // esp_now_deinit() removes all peers.
215 self->tx_packets = self->tx_responses;
216 }
217 return mp_const_none;
218}
219
220STATIC mp_obj_t espnow_active(size_t n_args, const mp_obj_t *args) {
221 esp_espnow_obj_t *self = _get_singleton();
222 if (n_args > 1) {
223 if (mp_obj_is_true(args[1])) {
224 espnow_init(self);
225 } else {
226 espnow_deinit(self);
227 }
228 }
229 return self->recv_buffer != NULL ? mp_const_true : mp_const_false;
230}
231STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(espnow_active_obj, 1, 2, espnow_active);
232
233// ESPNow.config(['param'|param=value, ..])
234// Get or set configuration values. Supported config params:
235// buffer: size of buffer for rx packets (default=514 bytes)
236// timeout: Default read timeout (default=300,000 milliseconds)
237STATIC mp_obj_t espnow_config(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
238 esp_espnow_obj_t *self = _get_singleton();
Glenn Moloneyfd277702023-06-09 13:09:46 +1000239 enum { ARG_get, ARG_rxbuf, ARG_timeout_ms, ARG_rate };
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000240 static const mp_arg_t allowed_args[] = {
241 { MP_QSTR_, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
Glenn Moloneyfd277702023-06-09 13:09:46 +1000242 { MP_QSTR_rxbuf, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000243 { MP_QSTR_timeout_ms, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = INT_MIN} },
244 { MP_QSTR_rate, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
245 };
246 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
247 mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
248 MP_ARRAY_SIZE(allowed_args), allowed_args, args);
249
Glenn Moloneyfd277702023-06-09 13:09:46 +1000250 if (args[ARG_rxbuf].u_int >= 0) {
251 self->recv_buffer_size = args[ARG_rxbuf].u_int;
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000252 }
253 if (args[ARG_timeout_ms].u_int != INT_MIN) {
254 self->recv_timeout_ms = args[ARG_timeout_ms].u_int;
255 }
256 if (args[ARG_rate].u_int >= 0) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000257 esp_initialise_wifi(); // Call the wifi init code in network_wlan.c
258 check_esp_err(esp_wifi_config_espnow_rate(ESP_IF_WIFI_STA, args[ARG_rate].u_int));
259 check_esp_err(esp_wifi_config_espnow_rate(ESP_IF_WIFI_AP, args[ARG_rate].u_int));
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000260 }
261 if (args[ARG_get].u_obj == MP_OBJ_NULL) {
262 return mp_const_none;
263 }
264#define QS(x) (uintptr_t)MP_OBJ_NEW_QSTR(x)
265 // Return the value of the requested parameter
266 uintptr_t name = (uintptr_t)args[ARG_get].u_obj;
Glenn Moloneyfd277702023-06-09 13:09:46 +1000267 if (name == QS(MP_QSTR_rxbuf)) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000268 return mp_obj_new_int(self->recv_buffer_size);
269 } else if (name == QS(MP_QSTR_timeout_ms)) {
270 return mp_obj_new_int(self->recv_timeout_ms);
271 } else {
272 mp_raise_ValueError(MP_ERROR_TEXT("unknown config param"));
273 }
274#undef QS
275
276 return mp_const_none;
277}
278STATIC MP_DEFINE_CONST_FUN_OBJ_KW(espnow_config_obj, 1, espnow_config);
279
280// ESPNow.irq(recv_cb)
281// Set callback function to be invoked when a message is received.
282STATIC mp_obj_t espnow_irq(size_t n_args, const mp_obj_t *args) {
283 esp_espnow_obj_t *self = _get_singleton();
284 mp_obj_t recv_cb = args[1];
285 if (recv_cb != mp_const_none && !mp_obj_is_callable(recv_cb)) {
286 mp_raise_ValueError(MP_ERROR_TEXT("invalid handler"));
287 }
288 self->recv_cb = recv_cb;
289 self->recv_cb_arg = (n_args > 2) ? args[2] : mp_const_none;
290 return mp_const_none;
291}
292STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(espnow_irq_obj, 2, 3, espnow_irq);
293
294// ESPnow.stats(): Provide some useful stats.
295// Returns a tuple of:
296// (tx_pkts, tx_responses, tx_failures, rx_pkts, dropped_rx_pkts)
297STATIC mp_obj_t espnow_stats(mp_obj_t _) {
298 const esp_espnow_obj_t *self = _get_singleton();
299 return NEW_TUPLE(
300 mp_obj_new_int(self->tx_packets),
301 mp_obj_new_int(self->tx_responses),
302 mp_obj_new_int(self->tx_failures),
303 mp_obj_new_int(self->rx_packets),
304 mp_obj_new_int(self->dropped_rx_pkts));
305}
306STATIC MP_DEFINE_CONST_FUN_OBJ_1(espnow_stats_obj, espnow_stats);
307
308#if MICROPY_ESPNOW_RSSI
309// ### Maintaining the peer table and reading RSSI values
310//
311// We maintain a peers table for several reasons, to:
312// - support monitoring the RSSI values for all peers; and
313// - to return unique bytestrings for each peer which supports more efficient
314// application memory usage and peer handling.
315
316// Get the RSSI value from the wifi packet header
317static inline int8_t _get_rssi_from_wifi_pkt(const uint8_t *msg) {
318 // Warning: Secret magic to get the rssi from the wifi packet header
319 // See espnow.c:espnow_recv_cb() at https://github.com/espressif/esp-now/
320 // In the wifi packet the msg comes after a wifi_promiscuous_pkt_t
321 // and a espnow_frame_format_t.
322 // Backtrack to get a pointer to the wifi_promiscuous_pkt_t.
323 static const size_t sizeof_espnow_frame_format = 39;
324 wifi_promiscuous_pkt_t *wifi_pkt =
325 (wifi_promiscuous_pkt_t *)(msg - sizeof_espnow_frame_format -
326 sizeof(wifi_promiscuous_pkt_t));
327
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000328 return wifi_pkt->rx_ctrl.rssi;
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000329}
330
331// Lookup a peer in the peers table and return a reference to the item in the
332// peers_table. Add peer to the table if it is not found (may alloc memory).
333// Will not return NULL.
334static mp_map_elem_t *_lookup_add_peer(esp_espnow_obj_t *self, const uint8_t *peer) {
335 // We do not want to allocate any new memory in the case that the peer
336 // already exists in the peers_table (which is almost all the time).
337 // So, we use a byte string on the stack and look that up in the dict.
338 mp_map_t *map = mp_obj_dict_get_map(self->peers_table);
339 mp_obj_str_t peer_obj = {{&mp_type_bytes}, 0, ESP_NOW_ETH_ALEN, peer};
340 mp_map_elem_t *item = mp_map_lookup(map, &peer_obj, MP_MAP_LOOKUP);
341 if (item == NULL) {
342 // If not found, add the peer using a new bytestring
343 map->is_fixed = 0; // Allow to modify the dict
344 mp_obj_t new_peer = mp_obj_new_bytes(peer, ESP_NOW_ETH_ALEN);
345 item = mp_map_lookup(map, new_peer, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
346 item->value = mp_obj_new_list(2, NULL);
347 map->is_fixed = 1; // Relock the dict
348 }
349 return item;
350}
351
352// Update the peers table with the new rssi value from a received pkt and
353// return a reference to the item in the peers_table.
354static mp_map_elem_t *_update_rssi(const uint8_t *peer, int8_t rssi, uint32_t time_ms) {
355 esp_espnow_obj_t *self = _get_singleton_initialised();
356 // Lookup the peer in the device table
357 mp_map_elem_t *item = _lookup_add_peer(self, peer);
358 mp_obj_list_t *list = MP_OBJ_TO_PTR(item->value);
359 list->items[0] = MP_OBJ_NEW_SMALL_INT(rssi);
360 list->items[1] = mp_obj_new_int(time_ms);
361 return item;
362}
363#endif // MICROPY_ESPNOW_RSSI
364
365// Return C pointer to byte memory string/bytes/bytearray in obj.
366// Raise ValueError if the length does not match expected len.
367static uint8_t *_get_bytes_len_rw(mp_obj_t obj, size_t len, mp_uint_t rw) {
368 mp_buffer_info_t bufinfo;
369 mp_get_buffer_raise(obj, &bufinfo, rw);
370 if (bufinfo.len != len) {
371 mp_raise_ValueError(MP_ERROR_TEXT("invalid buffer length"));
372 }
373 return (uint8_t *)bufinfo.buf;
374}
375
376static uint8_t *_get_bytes_len(mp_obj_t obj, size_t len) {
377 return _get_bytes_len_rw(obj, len, MP_BUFFER_READ);
378}
379
380static uint8_t *_get_bytes_len_w(mp_obj_t obj, size_t len) {
381 return _get_bytes_len_rw(obj, len, MP_BUFFER_WRITE);
382}
383
384// Return C pointer to the MAC address.
385// Raise ValueError if mac_addr is wrong type or is not 6 bytes long.
386static const uint8_t *_get_peer(mp_obj_t mac_addr) {
387 return mp_obj_is_true(mac_addr)
388 ? _get_bytes_len(mac_addr, ESP_NOW_ETH_ALEN) : NULL;
389}
390
391// Copy data from the ring buffer - wait if buffer is empty up to timeout_ms
392// 0: Success
393// -1: Not enough data available to complete read (try again later)
394// -2: Requested read is larger than buffer - will never succeed
395static int ringbuf_get_bytes_wait(ringbuf_t *r, uint8_t *data, size_t len, mp_int_t timeout_ms) {
396 mp_uint_t start = mp_hal_ticks_ms();
397 int status = 0;
398 while (((status = ringbuf_get_bytes(r, data, len)) == -1)
399 && (timeout_ms < 0 || (mp_uint_t)(mp_hal_ticks_ms() - start) < (mp_uint_t)timeout_ms)) {
400 MICROPY_EVENT_POLL_HOOK;
401 }
402 return status;
403}
404
405// ESPNow.recvinto(buffers[, timeout_ms]):
406// Waits for an espnow message and copies the peer_addr and message into
407// the buffers list.
408// Arguments:
409// buffers: (Optional) list of bytearrays to store return values.
410// timeout_ms: (Optional) timeout in milliseconds (or None).
411// Buffers should be a list: [bytearray(6), bytearray(250)]
412// If buffers is 4 elements long, the rssi and timestamp values will be
413// loaded into the 3rd and 4th elements.
414// Default timeout is set with ESPNow.config(timeout=milliseconds).
415// Return (None, None) on timeout.
416STATIC mp_obj_t espnow_recvinto(size_t n_args, const mp_obj_t *args) {
417 esp_espnow_obj_t *self = _get_singleton_initialised();
418
419 mp_int_t timeout_ms = ((n_args > 2 && args[2] != mp_const_none)
420 ? mp_obj_get_int(args[2]) : self->recv_timeout_ms);
421
422 mp_obj_list_t *list = MP_OBJ_TO_PTR(args[1]);
423 if (!mp_obj_is_type(list, &mp_type_list) || list->len < 2) {
424 mp_raise_ValueError(MP_ERROR_TEXT("ESPNow.recvinto(): Invalid argument"));
425 }
426 mp_obj_array_t *msg = MP_OBJ_TO_PTR(list->items[1]);
427 if (mp_obj_is_type(msg, &mp_type_bytearray)) {
428 msg->len += msg->free; // Make all the space in msg array available
429 msg->free = 0;
430 }
431 #if MICROPY_ESPNOW_RSSI
432 uint8_t peer_buf[ESP_NOW_ETH_ALEN];
433 #else
434 uint8_t *peer_buf = _get_bytes_len_w(list->items[0], ESP_NOW_ETH_ALEN);
435 #endif // MICROPY_ESPNOW_RSSI
436 uint8_t *msg_buf = _get_bytes_len_w(msg, ESP_NOW_MAX_DATA_LEN);
437
438 // Read the packet header from the incoming buffer
439 espnow_hdr_t hdr;
440 if (ringbuf_get_bytes_wait(self->recv_buffer, (uint8_t *)&hdr, sizeof(hdr), timeout_ms) < 0) {
441 return MP_OBJ_NEW_SMALL_INT(0); // Timeout waiting for packet
442 }
443 int msg_len = hdr.msg_len;
444
445 // Check the message packet header format and read the message data
446 if (hdr.magic != ESPNOW_MAGIC
447 || msg_len > ESP_NOW_MAX_DATA_LEN
448 || ringbuf_get_bytes(self->recv_buffer, peer_buf, ESP_NOW_ETH_ALEN) < 0
449 || ringbuf_get_bytes(self->recv_buffer, msg_buf, msg_len) < 0) {
450 mp_raise_ValueError(MP_ERROR_TEXT("ESPNow.recv(): buffer error"));
451 }
452 if (mp_obj_is_type(msg, &mp_type_bytearray)) {
453 // Set the length of the message bytearray.
454 size_t size = msg->len + msg->free;
455 msg->len = msg_len;
456 msg->free = size - msg_len;
457 }
458
459 #if MICROPY_ESPNOW_RSSI
460 // Update rssi value in the peer device table
461 mp_map_elem_t *entry = _update_rssi(peer_buf, hdr.rssi, hdr.time_ms);
462 list->items[0] = entry->key; // Set first element of list to peer
463 if (list->len >= 4) {
464 list->items[2] = MP_OBJ_NEW_SMALL_INT(hdr.rssi);
465 list->items[3] = mp_obj_new_int(hdr.time_ms);
466 }
467 #endif // MICROPY_ESPNOW_RSSI
468
469 return MP_OBJ_NEW_SMALL_INT(msg_len);
470}
471STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(espnow_recvinto_obj, 2, 3, espnow_recvinto);
472
473// Test if data is available to read from the buffers
474STATIC mp_obj_t espnow_any(const mp_obj_t _) {
475 esp_espnow_obj_t *self = _get_singleton_initialised();
476
477 return ringbuf_avail(self->recv_buffer) ? mp_const_true : mp_const_false;
478}
479STATIC MP_DEFINE_CONST_FUN_OBJ_1(espnow_any_obj, espnow_any);
480
481// Used by espnow_send() for sends() with sync==True.
482// Wait till all pending sent packet responses have been received.
483// ie. self->tx_responses == self->tx_packets.
484static void _wait_for_pending_responses(esp_espnow_obj_t *self) {
485 mp_uint_t start = mp_hal_ticks_ms();
486 mp_uint_t t;
487 while (self->tx_responses < self->tx_packets) {
488 if ((t = mp_hal_ticks_ms() - start) > PENDING_RESPONSES_TIMEOUT_MS) {
489 mp_raise_OSError(MP_ETIMEDOUT);
490 }
491 if (t > PENDING_RESPONSES_BUSY_POLL_MS) {
492 // After 10ms of busy waiting give other tasks a look in.
493 MICROPY_EVENT_POLL_HOOK;
494 }
495 }
496}
497
498// ESPNow.send(peer_addr, message, [sync (=true), size])
499// ESPNow.send(message)
500// Send a message to the peer's mac address. Optionally wait for a response.
501// If peer_addr == None or any non-true value, send to all registered peers.
502// If sync == True, wait for response after sending.
503// If size is provided it should be the number of bytes in message to send().
504// Returns:
505// True if sync==False and message sent successfully.
506// True if sync==True and message is received successfully by all recipients
507// False if sync==True and message is not received by at least one recipient
508// Raises: EAGAIN if the internal espnow buffers are full.
509STATIC mp_obj_t espnow_send(size_t n_args, const mp_obj_t *args) {
510 esp_espnow_obj_t *self = _get_singleton_initialised();
511 // Check the various combinations of input arguments
512 const uint8_t *peer = (n_args > 2) ? _get_peer(args[1]) : NULL;
513 mp_obj_t msg = (n_args > 2) ? args[2] : (n_args == 2) ? args[1] : MP_OBJ_NULL;
514 bool sync = n_args <= 3 || args[3] == mp_const_none || mp_obj_is_true(args[3]);
515
516 // Get a pointer to the data buffer of the message
517 mp_buffer_info_t message;
518 mp_get_buffer_raise(msg, &message, MP_BUFFER_READ);
519
520 if (sync) {
521 // Flush out any pending responses.
522 // If the last call was sync==False there may be outstanding responses
523 // still to be received (possible many if we just had a burst of
524 // unsync send()s). We need to wait for all pending responses if this
525 // call has sync=True.
526 _wait_for_pending_responses(self);
527 }
528 int saved_failures = self->tx_failures;
529 // Send the packet - try, try again if internal esp-now buffers are full.
530 esp_err_t err;
531 mp_uint_t start = mp_hal_ticks_ms();
532 while ((ESP_ERR_ESPNOW_NO_MEM == (err = esp_now_send(peer, message.buf, message.len)))
533 && (mp_uint_t)(mp_hal_ticks_ms() - start) < (mp_uint_t)DEFAULT_SEND_TIMEOUT_MS) {
534 MICROPY_EVENT_POLL_HOOK;
535 }
536 check_esp_err(err); // Will raise OSError if e != ESP_OK
537 // Increment the sent packet count. If peer_addr==NULL msg will be
538 // sent to all peers EXCEPT any broadcast or multicast addresses.
539 self->tx_packets += ((peer == NULL) ? self->peer_count : 1);
540 if (sync) {
541 // Wait for and tally all the expected responses from peers
542 _wait_for_pending_responses(self);
543 }
544 // Return False if sync and any peers did not respond.
545 return mp_obj_new_bool(!(sync && self->tx_failures != saved_failures));
546}
547STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(espnow_send_obj, 2, 4, espnow_send);
548
549// ### The ESP_Now send and recv callback routines
550//
551
552// Callback triggered when a sent packet is acknowledged by the peer (or not).
553// Just count the number of responses and number of failures.
554// These are used in the send() logic.
555STATIC void send_cb(const uint8_t *mac_addr, esp_now_send_status_t status) {
556 esp_espnow_obj_t *self = _get_singleton();
557 self->tx_responses++;
558 if (status != ESP_NOW_SEND_SUCCESS) {
559 self->tx_failures++;
560 }
561}
562
563// Callback triggered when an ESP-Now packet is received.
564// Write the peer MAC address and the message into the recv_buffer as an
565// ESPNow packet.
566// If the buffer is full, drop the message and increment the dropped count.
567// Schedules the user callback if one has been registered (ESPNow.config()).
Damien Georgee4650122023-05-09 09:52:54 +1000568STATIC void recv_cb(const esp_now_recv_info_t *recv_info, const uint8_t *msg, int msg_len) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000569 esp_espnow_obj_t *self = _get_singleton();
570 ringbuf_t *buf = self->recv_buffer;
571 // TODO: Test this works with ">".
572 if (sizeof(espnow_pkt_t) + msg_len >= ringbuf_free(buf)) {
573 self->dropped_rx_pkts++;
574 return;
575 }
576 espnow_hdr_t header;
577 header.magic = ESPNOW_MAGIC;
578 header.msg_len = msg_len;
579 #if MICROPY_ESPNOW_RSSI
580 header.rssi = _get_rssi_from_wifi_pkt(msg);
581 header.time_ms = mp_hal_ticks_ms();
582 #endif // MICROPY_ESPNOW_RSSI
583
584 ringbuf_put_bytes(buf, (uint8_t *)&header, sizeof(header));
Damien Georgee4650122023-05-09 09:52:54 +1000585 ringbuf_put_bytes(buf, recv_info->src_addr, ESP_NOW_ETH_ALEN);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000586 ringbuf_put_bytes(buf, msg, msg_len);
587 self->rx_packets++;
588 if (self->recv_cb != mp_const_none) {
589 mp_sched_schedule(self->recv_cb, self->recv_cb_arg);
590 }
591}
592
593// ### Peer Management Functions
594//
595
596// Set the ESP-NOW Primary Master Key (pmk) (for encrypted communications).
597// Raise OSError if ESP-NOW functions are not initialised.
598// Raise ValueError if key is not a bytes-like object exactly 16 bytes long.
599STATIC mp_obj_t espnow_set_pmk(mp_obj_t _, mp_obj_t key) {
600 check_esp_err(esp_now_set_pmk(_get_bytes_len(key, ESP_NOW_KEY_LEN)));
601 return mp_const_none;
602}
603STATIC MP_DEFINE_CONST_FUN_OBJ_2(espnow_set_pmk_obj, espnow_set_pmk);
604
605// Common code for add_peer() and mod_peer() to process the args and kw_args:
606// Raise ValueError if the LMK is not a bytes-like object of exactly 16 bytes.
607// Raise TypeError if invalid keyword args or too many positional args.
608// Return true if all args parsed correctly.
609STATIC bool _update_peer_info(
610 esp_now_peer_info_t *peer, size_t n_args,
611 const mp_obj_t *pos_args, mp_map_t *kw_args) {
612
613 enum { ARG_lmk, ARG_channel, ARG_ifidx, ARG_encrypt };
614 static const mp_arg_t allowed_args[] = {
615 { MP_QSTR_lmk, MP_ARG_OBJ, {.u_obj = mp_const_none} },
616 { MP_QSTR_channel, MP_ARG_OBJ, {.u_obj = mp_const_none} },
617 { MP_QSTR_ifidx, MP_ARG_OBJ, {.u_obj = mp_const_none} },
618 { MP_QSTR_encrypt, MP_ARG_OBJ, {.u_obj = mp_const_none} },
619 };
620 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
621 mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
622 if (args[ARG_lmk].u_obj != mp_const_none) {
623 mp_obj_t obj = args[ARG_lmk].u_obj;
624 peer->encrypt = mp_obj_is_true(obj);
625 if (peer->encrypt) {
626 // Key must be 16 bytes in length.
627 memcpy(peer->lmk, _get_bytes_len(obj, ESP_NOW_KEY_LEN), ESP_NOW_KEY_LEN);
628 }
629 }
630 if (args[ARG_channel].u_obj != mp_const_none) {
631 peer->channel = mp_obj_get_int(args[ARG_channel].u_obj);
632 }
633 if (args[ARG_ifidx].u_obj != mp_const_none) {
634 peer->ifidx = mp_obj_get_int(args[ARG_ifidx].u_obj);
635 }
636 if (args[ARG_encrypt].u_obj != mp_const_none) {
637 peer->encrypt = mp_obj_is_true(args[ARG_encrypt].u_obj);
638 }
639 return true;
640}
641
642// Update the cached peer count in self->peer_count;
643// The peer_count ignores broadcast and multicast addresses and is used for the
644// send() logic and is updated from add_peer(), mod_peer() and del_peer().
645STATIC void _update_peer_count() {
646 esp_espnow_obj_t *self = _get_singleton_initialised();
647
648 esp_now_peer_info_t peer = {0};
649 bool from_head = true;
650 int count = 0;
651 // esp_now_fetch_peer() skips over any broadcast or multicast addresses
652 while (esp_now_fetch_peer(from_head, &peer) == ESP_OK) {
653 from_head = false;
654 if (++count >= ESP_NOW_MAX_TOTAL_PEER_NUM) {
655 break; // Should not happen
656 }
657 }
658 self->peer_count = count;
659}
660
661// ESPNow.add_peer(peer_mac, [lmk, [channel, [ifidx, [encrypt]]]]) or
662// ESPNow.add_peer(peer_mac, [lmk=b'0123456789abcdef'|b''|None|False],
663// [channel=1..11|0], [ifidx=0|1], [encrypt=True|False])
664// Positional args set to None will be left at defaults.
665// Raise OSError if ESPNow.init() has not been called.
666// Raise ValueError if mac or LMK are not bytes-like objects or wrong length.
667// Raise TypeError if invalid keyword args or too many positional args.
668// Return None.
669STATIC mp_obj_t espnow_add_peer(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
670 esp_now_peer_info_t peer = {0};
671 memcpy(peer.peer_addr, _get_peer(args[1]), ESP_NOW_ETH_ALEN);
672 _update_peer_info(&peer, n_args - 2, args + 2, kw_args);
673
674 check_esp_err(esp_now_add_peer(&peer));
675 _update_peer_count();
676
677 return mp_const_none;
678}
679STATIC MP_DEFINE_CONST_FUN_OBJ_KW(espnow_add_peer_obj, 2, espnow_add_peer);
680
681// ESPNow.del_peer(peer_mac): Unregister peer_mac.
682// Raise OSError if ESPNow.init() has not been called.
683// Raise ValueError if peer is not a bytes-like objects or wrong length.
684// Return None.
685STATIC mp_obj_t espnow_del_peer(mp_obj_t _, mp_obj_t peer) {
686 uint8_t peer_addr[ESP_NOW_ETH_ALEN];
687 memcpy(peer_addr, _get_peer(peer), ESP_NOW_ETH_ALEN);
688
689 check_esp_err(esp_now_del_peer(peer_addr));
690 _update_peer_count();
691
692 return mp_const_none;
693}
694STATIC MP_DEFINE_CONST_FUN_OBJ_2(espnow_del_peer_obj, espnow_del_peer);
695
696// Convert a peer_info struct to python tuple
697// Used by espnow_get_peer() and espnow_get_peers()
698static mp_obj_t _peer_info_to_tuple(const esp_now_peer_info_t *peer) {
699 return NEW_TUPLE(
700 mp_obj_new_bytes(peer->peer_addr, MP_ARRAY_SIZE(peer->peer_addr)),
701 mp_obj_new_bytes(peer->lmk, MP_ARRAY_SIZE(peer->lmk)),
702 mp_obj_new_int(peer->channel),
703 mp_obj_new_int(peer->ifidx),
704 (peer->encrypt) ? mp_const_true : mp_const_false);
705}
706
707// ESPNow.get_peers(): Fetch peer_info records for all registered ESPNow peers.
708// Raise OSError if ESPNow.init() has not been called.
709// Return a tuple of tuples:
710// ((peer_addr, lmk, channel, ifidx, encrypt),
711// (peer_addr, lmk, channel, ifidx, encrypt), ...)
712STATIC mp_obj_t espnow_get_peers(mp_obj_t _) {
713 esp_espnow_obj_t *self = _get_singleton_initialised();
714
715 // Build and initialise the peer info tuple.
716 mp_obj_tuple_t *peerinfo_tuple = mp_obj_new_tuple(self->peer_count, NULL);
717 esp_now_peer_info_t peer = {0};
718 for (int i = 0; i < peerinfo_tuple->len; i++) {
719 int status = esp_now_fetch_peer((i == 0), &peer);
720 peerinfo_tuple->items[i] =
721 (status == ESP_OK ? _peer_info_to_tuple(&peer) : mp_const_none);
722 }
723
724 return peerinfo_tuple;
725}
726STATIC MP_DEFINE_CONST_FUN_OBJ_1(espnow_get_peers_obj, espnow_get_peers);
727
728#if MICROPY_ESPNOW_EXTRA_PEER_METHODS
729// ESPNow.get_peer(peer_mac): Get the peer info for peer_mac as a tuple.
730// Raise OSError if ESPNow.init() has not been called.
731// Raise ValueError if mac or LMK are not bytes-like objects or wrong length.
732// Return a tuple of (peer_addr, lmk, channel, ifidx, encrypt).
733STATIC mp_obj_t espnow_get_peer(mp_obj_t _, mp_obj_t arg1) {
734 esp_now_peer_info_t peer = {0};
735 memcpy(peer.peer_addr, _get_peer(arg1), ESP_NOW_ETH_ALEN);
736
737 check_esp_err(esp_now_get_peer(peer.peer_addr, &peer));
738
739 return _peer_info_to_tuple(&peer);
740}
741STATIC MP_DEFINE_CONST_FUN_OBJ_2(espnow_get_peer_obj, espnow_get_peer);
742
743// ESPNow.mod_peer(peer_mac, [lmk, [channel, [ifidx, [encrypt]]]]) or
744// ESPNow.mod_peer(peer_mac, [lmk=b'0123456789abcdef'|b''|None|False],
745// [channel=1..11|0], [ifidx=0|1], [encrypt=True|False])
746// Positional args set to None will be left at current values.
747// Raise OSError if ESPNow.init() has not been called.
748// Raise ValueError if mac or LMK are not bytes-like objects or wrong length.
749// Raise TypeError if invalid keyword args or too many positional args.
750// Return None.
751STATIC mp_obj_t espnow_mod_peer(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
752 esp_now_peer_info_t peer = {0};
753 memcpy(peer.peer_addr, _get_peer(args[1]), ESP_NOW_ETH_ALEN);
754 check_esp_err(esp_now_get_peer(peer.peer_addr, &peer));
755
756 _update_peer_info(&peer, n_args - 2, args + 2, kw_args);
757
758 check_esp_err(esp_now_mod_peer(&peer));
759 _update_peer_count();
760
761 return mp_const_none;
762}
763STATIC MP_DEFINE_CONST_FUN_OBJ_KW(espnow_mod_peer_obj, 2, espnow_mod_peer);
764
765// ESPNow.espnow_peer_count(): Get the number of registered peers.
766// Raise OSError if ESPNow.init() has not been called.
767// Return a tuple of (num_total_peers, num_encrypted_peers).
768STATIC mp_obj_t espnow_peer_count(mp_obj_t _) {
769 esp_now_peer_num_t peer_num = {0};
770 check_esp_err(esp_now_get_peer_num(&peer_num));
771
772 return NEW_TUPLE(
773 mp_obj_new_int(peer_num.total_num),
774 mp_obj_new_int(peer_num.encrypt_num));
775}
776STATIC MP_DEFINE_CONST_FUN_OBJ_1(espnow_peer_count_obj, espnow_peer_count);
777#endif
778
779STATIC const mp_rom_map_elem_t esp_espnow_locals_dict_table[] = {
780 { MP_ROM_QSTR(MP_QSTR_active), MP_ROM_PTR(&espnow_active_obj) },
781 { MP_ROM_QSTR(MP_QSTR_config), MP_ROM_PTR(&espnow_config_obj) },
782 { MP_ROM_QSTR(MP_QSTR_irq), MP_ROM_PTR(&espnow_irq_obj) },
783 { MP_ROM_QSTR(MP_QSTR_stats), MP_ROM_PTR(&espnow_stats_obj) },
784
785 // Send and receive messages
786 { MP_ROM_QSTR(MP_QSTR_recvinto), MP_ROM_PTR(&espnow_recvinto_obj) },
787 { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&espnow_send_obj) },
788 { MP_ROM_QSTR(MP_QSTR_any), MP_ROM_PTR(&espnow_any_obj) },
789
790 // Peer management functions
791 { MP_ROM_QSTR(MP_QSTR_set_pmk), MP_ROM_PTR(&espnow_set_pmk_obj) },
792 { MP_ROM_QSTR(MP_QSTR_add_peer), MP_ROM_PTR(&espnow_add_peer_obj) },
793 { MP_ROM_QSTR(MP_QSTR_del_peer), MP_ROM_PTR(&espnow_del_peer_obj) },
794 { MP_ROM_QSTR(MP_QSTR_get_peers), MP_ROM_PTR(&espnow_get_peers_obj) },
795 #if MICROPY_ESPNOW_EXTRA_PEER_METHODS
796 { MP_ROM_QSTR(MP_QSTR_mod_peer), MP_ROM_PTR(&espnow_mod_peer_obj) },
797 { MP_ROM_QSTR(MP_QSTR_get_peer), MP_ROM_PTR(&espnow_get_peer_obj) },
798 { MP_ROM_QSTR(MP_QSTR_peer_count), MP_ROM_PTR(&espnow_peer_count_obj) },
799 #endif // MICROPY_ESPNOW_EXTRA_PEER_METHODS
800};
801STATIC MP_DEFINE_CONST_DICT(esp_espnow_locals_dict, esp_espnow_locals_dict_table);
802
803STATIC const mp_rom_map_elem_t espnow_globals_dict_table[] = {
804 { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR__espnow) },
805 { MP_ROM_QSTR(MP_QSTR_ESPNowBase), MP_ROM_PTR(&esp_espnow_type) },
806 { MP_ROM_QSTR(MP_QSTR_MAX_DATA_LEN), MP_ROM_INT(ESP_NOW_MAX_DATA_LEN)},
807 { MP_ROM_QSTR(MP_QSTR_ADDR_LEN), MP_ROM_INT(ESP_NOW_ETH_ALEN)},
808 { MP_ROM_QSTR(MP_QSTR_KEY_LEN), MP_ROM_INT(ESP_NOW_KEY_LEN)},
809 { MP_ROM_QSTR(MP_QSTR_MAX_TOTAL_PEER_NUM), MP_ROM_INT(ESP_NOW_MAX_TOTAL_PEER_NUM)},
810 { MP_ROM_QSTR(MP_QSTR_MAX_ENCRYPT_PEER_NUM), MP_ROM_INT(ESP_NOW_MAX_ENCRYPT_PEER_NUM)},
811};
812STATIC MP_DEFINE_CONST_DICT(espnow_globals_dict, espnow_globals_dict_table);
813
814// ### Dummy Buffer Protocol support
815// ...so asyncio can poll.ipoll() on this device
816
817// Support ioctl(MP_STREAM_POLL, ) for asyncio
818STATIC mp_uint_t espnow_stream_ioctl(
819 mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) {
820 if (request != MP_STREAM_POLL) {
821 *errcode = MP_EINVAL;
822 return MP_STREAM_ERROR;
823 }
824 esp_espnow_obj_t *self = _get_singleton();
825 return (self->recv_buffer == NULL) ? 0 : // If not initialised
826 arg ^ (
827 // If no data in the buffer, unset the Read ready flag
828 ((ringbuf_avail(self->recv_buffer) == 0) ? MP_STREAM_POLL_RD : 0) |
829 // If still waiting for responses, unset the Write ready flag
830 ((self->tx_responses < self->tx_packets) ? MP_STREAM_POLL_WR : 0));
831}
832
833STATIC const mp_stream_p_t espnow_stream_p = {
834 .ioctl = espnow_stream_ioctl,
835};
836
837#if MICROPY_ESPNOW_RSSI
838// Return reference to the dictionary of peers we have seen:
839// {peer1: (rssi, time_sec), peer2: (rssi, time_msec), ...}
840// where:
841// peerX is a byte string containing the 6-byte mac address of the peer,
842// rssi is the wifi signal strength from the last msg received
843// (in dBm from -127 to 0)
844// time_sec is the time in milliseconds since device last booted.
845STATIC void espnow_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
846 esp_espnow_obj_t *self = _get_singleton();
847 if (dest[0] != MP_OBJ_NULL) { // Only allow "Load" operation
848 return;
849 }
850 if (attr == MP_QSTR_peers_table) {
851 dest[0] = self->peers_table;
852 return;
853 }
854 dest[1] = MP_OBJ_SENTINEL; // Attribute not found
855}
856#endif // MICROPY_ESPNOW_RSSI
857
858MP_DEFINE_CONST_OBJ_TYPE(
859 esp_espnow_type,
860 MP_QSTR_ESPNowBase,
861 MP_TYPE_FLAG_NONE,
862 make_new, espnow_make_new,
863 #if MICROPY_ESPNOW_RSSI
864 attr, espnow_attr,
865 #endif // MICROPY_ESPNOW_RSSI
866 protocol, &espnow_stream_p,
867 locals_dict, &esp_espnow_locals_dict
868 );
869
870const mp_obj_module_t mp_module_espnow = {
871 .base = { &mp_type_module },
872 .globals = (mp_obj_dict_t *)&espnow_globals_dict,
873};
874
875MP_REGISTER_MODULE(MP_QSTR__espnow, mp_module_espnow);
876MP_REGISTER_ROOT_POINTER(struct _esp_espnow_obj_t *espnow_singleton);