blob: 08836c0ad790ef32aba0e61919794a6bc0851056 [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
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000316// Lookup a peer in the peers table and return a reference to the item in the
317// peers_table. Add peer to the table if it is not found (may alloc memory).
318// Will not return NULL.
319static mp_map_elem_t *_lookup_add_peer(esp_espnow_obj_t *self, const uint8_t *peer) {
320 // We do not want to allocate any new memory in the case that the peer
321 // already exists in the peers_table (which is almost all the time).
322 // So, we use a byte string on the stack and look that up in the dict.
323 mp_map_t *map = mp_obj_dict_get_map(self->peers_table);
324 mp_obj_str_t peer_obj = {{&mp_type_bytes}, 0, ESP_NOW_ETH_ALEN, peer};
325 mp_map_elem_t *item = mp_map_lookup(map, &peer_obj, MP_MAP_LOOKUP);
326 if (item == NULL) {
327 // If not found, add the peer using a new bytestring
328 map->is_fixed = 0; // Allow to modify the dict
329 mp_obj_t new_peer = mp_obj_new_bytes(peer, ESP_NOW_ETH_ALEN);
330 item = mp_map_lookup(map, new_peer, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
331 item->value = mp_obj_new_list(2, NULL);
332 map->is_fixed = 1; // Relock the dict
333 }
334 return item;
335}
336
337// Update the peers table with the new rssi value from a received pkt and
338// return a reference to the item in the peers_table.
339static mp_map_elem_t *_update_rssi(const uint8_t *peer, int8_t rssi, uint32_t time_ms) {
340 esp_espnow_obj_t *self = _get_singleton_initialised();
341 // Lookup the peer in the device table
342 mp_map_elem_t *item = _lookup_add_peer(self, peer);
343 mp_obj_list_t *list = MP_OBJ_TO_PTR(item->value);
344 list->items[0] = MP_OBJ_NEW_SMALL_INT(rssi);
345 list->items[1] = mp_obj_new_int(time_ms);
346 return item;
347}
348#endif // MICROPY_ESPNOW_RSSI
349
350// Return C pointer to byte memory string/bytes/bytearray in obj.
351// Raise ValueError if the length does not match expected len.
352static uint8_t *_get_bytes_len_rw(mp_obj_t obj, size_t len, mp_uint_t rw) {
353 mp_buffer_info_t bufinfo;
354 mp_get_buffer_raise(obj, &bufinfo, rw);
355 if (bufinfo.len != len) {
356 mp_raise_ValueError(MP_ERROR_TEXT("invalid buffer length"));
357 }
358 return (uint8_t *)bufinfo.buf;
359}
360
361static uint8_t *_get_bytes_len(mp_obj_t obj, size_t len) {
362 return _get_bytes_len_rw(obj, len, MP_BUFFER_READ);
363}
364
365static uint8_t *_get_bytes_len_w(mp_obj_t obj, size_t len) {
366 return _get_bytes_len_rw(obj, len, MP_BUFFER_WRITE);
367}
368
369// Return C pointer to the MAC address.
370// Raise ValueError if mac_addr is wrong type or is not 6 bytes long.
371static const uint8_t *_get_peer(mp_obj_t mac_addr) {
372 return mp_obj_is_true(mac_addr)
373 ? _get_bytes_len(mac_addr, ESP_NOW_ETH_ALEN) : NULL;
374}
375
376// Copy data from the ring buffer - wait if buffer is empty up to timeout_ms
377// 0: Success
378// -1: Not enough data available to complete read (try again later)
379// -2: Requested read is larger than buffer - will never succeed
380static int ringbuf_get_bytes_wait(ringbuf_t *r, uint8_t *data, size_t len, mp_int_t timeout_ms) {
381 mp_uint_t start = mp_hal_ticks_ms();
382 int status = 0;
383 while (((status = ringbuf_get_bytes(r, data, len)) == -1)
384 && (timeout_ms < 0 || (mp_uint_t)(mp_hal_ticks_ms() - start) < (mp_uint_t)timeout_ms)) {
385 MICROPY_EVENT_POLL_HOOK;
386 }
387 return status;
388}
389
390// ESPNow.recvinto(buffers[, timeout_ms]):
391// Waits for an espnow message and copies the peer_addr and message into
392// the buffers list.
393// Arguments:
394// buffers: (Optional) list of bytearrays to store return values.
395// timeout_ms: (Optional) timeout in milliseconds (or None).
396// Buffers should be a list: [bytearray(6), bytearray(250)]
397// If buffers is 4 elements long, the rssi and timestamp values will be
398// loaded into the 3rd and 4th elements.
399// Default timeout is set with ESPNow.config(timeout=milliseconds).
400// Return (None, None) on timeout.
401STATIC mp_obj_t espnow_recvinto(size_t n_args, const mp_obj_t *args) {
402 esp_espnow_obj_t *self = _get_singleton_initialised();
403
404 mp_int_t timeout_ms = ((n_args > 2 && args[2] != mp_const_none)
405 ? mp_obj_get_int(args[2]) : self->recv_timeout_ms);
406
407 mp_obj_list_t *list = MP_OBJ_TO_PTR(args[1]);
408 if (!mp_obj_is_type(list, &mp_type_list) || list->len < 2) {
409 mp_raise_ValueError(MP_ERROR_TEXT("ESPNow.recvinto(): Invalid argument"));
410 }
411 mp_obj_array_t *msg = MP_OBJ_TO_PTR(list->items[1]);
412 if (mp_obj_is_type(msg, &mp_type_bytearray)) {
413 msg->len += msg->free; // Make all the space in msg array available
414 msg->free = 0;
415 }
416 #if MICROPY_ESPNOW_RSSI
417 uint8_t peer_buf[ESP_NOW_ETH_ALEN];
418 #else
419 uint8_t *peer_buf = _get_bytes_len_w(list->items[0], ESP_NOW_ETH_ALEN);
420 #endif // MICROPY_ESPNOW_RSSI
421 uint8_t *msg_buf = _get_bytes_len_w(msg, ESP_NOW_MAX_DATA_LEN);
422
423 // Read the packet header from the incoming buffer
424 espnow_hdr_t hdr;
425 if (ringbuf_get_bytes_wait(self->recv_buffer, (uint8_t *)&hdr, sizeof(hdr), timeout_ms) < 0) {
426 return MP_OBJ_NEW_SMALL_INT(0); // Timeout waiting for packet
427 }
428 int msg_len = hdr.msg_len;
429
430 // Check the message packet header format and read the message data
431 if (hdr.magic != ESPNOW_MAGIC
432 || msg_len > ESP_NOW_MAX_DATA_LEN
433 || ringbuf_get_bytes(self->recv_buffer, peer_buf, ESP_NOW_ETH_ALEN) < 0
434 || ringbuf_get_bytes(self->recv_buffer, msg_buf, msg_len) < 0) {
435 mp_raise_ValueError(MP_ERROR_TEXT("ESPNow.recv(): buffer error"));
436 }
437 if (mp_obj_is_type(msg, &mp_type_bytearray)) {
438 // Set the length of the message bytearray.
439 size_t size = msg->len + msg->free;
440 msg->len = msg_len;
441 msg->free = size - msg_len;
442 }
443
444 #if MICROPY_ESPNOW_RSSI
445 // Update rssi value in the peer device table
446 mp_map_elem_t *entry = _update_rssi(peer_buf, hdr.rssi, hdr.time_ms);
447 list->items[0] = entry->key; // Set first element of list to peer
448 if (list->len >= 4) {
449 list->items[2] = MP_OBJ_NEW_SMALL_INT(hdr.rssi);
450 list->items[3] = mp_obj_new_int(hdr.time_ms);
451 }
452 #endif // MICROPY_ESPNOW_RSSI
453
454 return MP_OBJ_NEW_SMALL_INT(msg_len);
455}
456STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(espnow_recvinto_obj, 2, 3, espnow_recvinto);
457
458// Test if data is available to read from the buffers
459STATIC mp_obj_t espnow_any(const mp_obj_t _) {
460 esp_espnow_obj_t *self = _get_singleton_initialised();
461
462 return ringbuf_avail(self->recv_buffer) ? mp_const_true : mp_const_false;
463}
464STATIC MP_DEFINE_CONST_FUN_OBJ_1(espnow_any_obj, espnow_any);
465
466// Used by espnow_send() for sends() with sync==True.
467// Wait till all pending sent packet responses have been received.
468// ie. self->tx_responses == self->tx_packets.
469static void _wait_for_pending_responses(esp_espnow_obj_t *self) {
470 mp_uint_t start = mp_hal_ticks_ms();
471 mp_uint_t t;
472 while (self->tx_responses < self->tx_packets) {
473 if ((t = mp_hal_ticks_ms() - start) > PENDING_RESPONSES_TIMEOUT_MS) {
474 mp_raise_OSError(MP_ETIMEDOUT);
475 }
476 if (t > PENDING_RESPONSES_BUSY_POLL_MS) {
477 // After 10ms of busy waiting give other tasks a look in.
478 MICROPY_EVENT_POLL_HOOK;
479 }
480 }
481}
482
483// ESPNow.send(peer_addr, message, [sync (=true), size])
484// ESPNow.send(message)
485// Send a message to the peer's mac address. Optionally wait for a response.
486// If peer_addr == None or any non-true value, send to all registered peers.
487// If sync == True, wait for response after sending.
488// If size is provided it should be the number of bytes in message to send().
489// Returns:
490// True if sync==False and message sent successfully.
491// True if sync==True and message is received successfully by all recipients
492// False if sync==True and message is not received by at least one recipient
493// Raises: EAGAIN if the internal espnow buffers are full.
494STATIC mp_obj_t espnow_send(size_t n_args, const mp_obj_t *args) {
495 esp_espnow_obj_t *self = _get_singleton_initialised();
496 // Check the various combinations of input arguments
497 const uint8_t *peer = (n_args > 2) ? _get_peer(args[1]) : NULL;
498 mp_obj_t msg = (n_args > 2) ? args[2] : (n_args == 2) ? args[1] : MP_OBJ_NULL;
499 bool sync = n_args <= 3 || args[3] == mp_const_none || mp_obj_is_true(args[3]);
500
501 // Get a pointer to the data buffer of the message
502 mp_buffer_info_t message;
503 mp_get_buffer_raise(msg, &message, MP_BUFFER_READ);
504
505 if (sync) {
506 // Flush out any pending responses.
507 // If the last call was sync==False there may be outstanding responses
508 // still to be received (possible many if we just had a burst of
509 // unsync send()s). We need to wait for all pending responses if this
510 // call has sync=True.
511 _wait_for_pending_responses(self);
512 }
513 int saved_failures = self->tx_failures;
514 // Send the packet - try, try again if internal esp-now buffers are full.
515 esp_err_t err;
516 mp_uint_t start = mp_hal_ticks_ms();
517 while ((ESP_ERR_ESPNOW_NO_MEM == (err = esp_now_send(peer, message.buf, message.len)))
518 && (mp_uint_t)(mp_hal_ticks_ms() - start) < (mp_uint_t)DEFAULT_SEND_TIMEOUT_MS) {
519 MICROPY_EVENT_POLL_HOOK;
520 }
521 check_esp_err(err); // Will raise OSError if e != ESP_OK
522 // Increment the sent packet count. If peer_addr==NULL msg will be
523 // sent to all peers EXCEPT any broadcast or multicast addresses.
524 self->tx_packets += ((peer == NULL) ? self->peer_count : 1);
525 if (sync) {
526 // Wait for and tally all the expected responses from peers
527 _wait_for_pending_responses(self);
528 }
529 // Return False if sync and any peers did not respond.
530 return mp_obj_new_bool(!(sync && self->tx_failures != saved_failures));
531}
532STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(espnow_send_obj, 2, 4, espnow_send);
533
534// ### The ESP_Now send and recv callback routines
535//
536
537// Callback triggered when a sent packet is acknowledged by the peer (or not).
538// Just count the number of responses and number of failures.
539// These are used in the send() logic.
540STATIC void send_cb(const uint8_t *mac_addr, esp_now_send_status_t status) {
541 esp_espnow_obj_t *self = _get_singleton();
542 self->tx_responses++;
543 if (status != ESP_NOW_SEND_SUCCESS) {
544 self->tx_failures++;
545 }
546}
547
548// Callback triggered when an ESP-Now packet is received.
549// Write the peer MAC address and the message into the recv_buffer as an
550// ESPNow packet.
551// If the buffer is full, drop the message and increment the dropped count.
552// Schedules the user callback if one has been registered (ESPNow.config()).
Damien Georgee4650122023-05-09 09:52:54 +1000553STATIC 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 +1000554 esp_espnow_obj_t *self = _get_singleton();
555 ringbuf_t *buf = self->recv_buffer;
556 // TODO: Test this works with ">".
557 if (sizeof(espnow_pkt_t) + msg_len >= ringbuf_free(buf)) {
558 self->dropped_rx_pkts++;
559 return;
560 }
561 espnow_hdr_t header;
562 header.magic = ESPNOW_MAGIC;
563 header.msg_len = msg_len;
564 #if MICROPY_ESPNOW_RSSI
Glenn Moloney2cc37112023-05-25 10:40:50 +1000565 header.rssi = recv_info->rx_ctrl->rssi;
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000566 header.time_ms = mp_hal_ticks_ms();
567 #endif // MICROPY_ESPNOW_RSSI
568
569 ringbuf_put_bytes(buf, (uint8_t *)&header, sizeof(header));
Damien Georgee4650122023-05-09 09:52:54 +1000570 ringbuf_put_bytes(buf, recv_info->src_addr, ESP_NOW_ETH_ALEN);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000571 ringbuf_put_bytes(buf, msg, msg_len);
572 self->rx_packets++;
573 if (self->recv_cb != mp_const_none) {
574 mp_sched_schedule(self->recv_cb, self->recv_cb_arg);
575 }
576}
577
578// ### Peer Management Functions
579//
580
581// Set the ESP-NOW Primary Master Key (pmk) (for encrypted communications).
582// Raise OSError if ESP-NOW functions are not initialised.
583// Raise ValueError if key is not a bytes-like object exactly 16 bytes long.
584STATIC mp_obj_t espnow_set_pmk(mp_obj_t _, mp_obj_t key) {
585 check_esp_err(esp_now_set_pmk(_get_bytes_len(key, ESP_NOW_KEY_LEN)));
586 return mp_const_none;
587}
588STATIC MP_DEFINE_CONST_FUN_OBJ_2(espnow_set_pmk_obj, espnow_set_pmk);
589
590// Common code for add_peer() and mod_peer() to process the args and kw_args:
591// Raise ValueError if the LMK is not a bytes-like object of exactly 16 bytes.
592// Raise TypeError if invalid keyword args or too many positional args.
593// Return true if all args parsed correctly.
594STATIC bool _update_peer_info(
595 esp_now_peer_info_t *peer, size_t n_args,
596 const mp_obj_t *pos_args, mp_map_t *kw_args) {
597
598 enum { ARG_lmk, ARG_channel, ARG_ifidx, ARG_encrypt };
599 static const mp_arg_t allowed_args[] = {
600 { MP_QSTR_lmk, MP_ARG_OBJ, {.u_obj = mp_const_none} },
601 { MP_QSTR_channel, MP_ARG_OBJ, {.u_obj = mp_const_none} },
602 { MP_QSTR_ifidx, MP_ARG_OBJ, {.u_obj = mp_const_none} },
603 { MP_QSTR_encrypt, MP_ARG_OBJ, {.u_obj = mp_const_none} },
604 };
605 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
606 mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
607 if (args[ARG_lmk].u_obj != mp_const_none) {
608 mp_obj_t obj = args[ARG_lmk].u_obj;
609 peer->encrypt = mp_obj_is_true(obj);
610 if (peer->encrypt) {
611 // Key must be 16 bytes in length.
612 memcpy(peer->lmk, _get_bytes_len(obj, ESP_NOW_KEY_LEN), ESP_NOW_KEY_LEN);
613 }
614 }
615 if (args[ARG_channel].u_obj != mp_const_none) {
616 peer->channel = mp_obj_get_int(args[ARG_channel].u_obj);
617 }
618 if (args[ARG_ifidx].u_obj != mp_const_none) {
619 peer->ifidx = mp_obj_get_int(args[ARG_ifidx].u_obj);
620 }
621 if (args[ARG_encrypt].u_obj != mp_const_none) {
622 peer->encrypt = mp_obj_is_true(args[ARG_encrypt].u_obj);
623 }
624 return true;
625}
626
627// Update the cached peer count in self->peer_count;
628// The peer_count ignores broadcast and multicast addresses and is used for the
629// send() logic and is updated from add_peer(), mod_peer() and del_peer().
630STATIC void _update_peer_count() {
631 esp_espnow_obj_t *self = _get_singleton_initialised();
632
633 esp_now_peer_info_t peer = {0};
634 bool from_head = true;
635 int count = 0;
636 // esp_now_fetch_peer() skips over any broadcast or multicast addresses
637 while (esp_now_fetch_peer(from_head, &peer) == ESP_OK) {
638 from_head = false;
639 if (++count >= ESP_NOW_MAX_TOTAL_PEER_NUM) {
640 break; // Should not happen
641 }
642 }
643 self->peer_count = count;
644}
645
646// ESPNow.add_peer(peer_mac, [lmk, [channel, [ifidx, [encrypt]]]]) or
647// ESPNow.add_peer(peer_mac, [lmk=b'0123456789abcdef'|b''|None|False],
648// [channel=1..11|0], [ifidx=0|1], [encrypt=True|False])
649// Positional args set to None will be left at defaults.
650// Raise OSError if ESPNow.init() has not been called.
651// Raise ValueError if mac or LMK are not bytes-like objects or wrong length.
652// Raise TypeError if invalid keyword args or too many positional args.
653// Return None.
654STATIC mp_obj_t espnow_add_peer(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
655 esp_now_peer_info_t peer = {0};
656 memcpy(peer.peer_addr, _get_peer(args[1]), ESP_NOW_ETH_ALEN);
657 _update_peer_info(&peer, n_args - 2, args + 2, kw_args);
658
659 check_esp_err(esp_now_add_peer(&peer));
660 _update_peer_count();
661
662 return mp_const_none;
663}
664STATIC MP_DEFINE_CONST_FUN_OBJ_KW(espnow_add_peer_obj, 2, espnow_add_peer);
665
666// ESPNow.del_peer(peer_mac): Unregister peer_mac.
667// Raise OSError if ESPNow.init() has not been called.
668// Raise ValueError if peer is not a bytes-like objects or wrong length.
669// Return None.
670STATIC mp_obj_t espnow_del_peer(mp_obj_t _, mp_obj_t peer) {
671 uint8_t peer_addr[ESP_NOW_ETH_ALEN];
672 memcpy(peer_addr, _get_peer(peer), ESP_NOW_ETH_ALEN);
673
674 check_esp_err(esp_now_del_peer(peer_addr));
675 _update_peer_count();
676
677 return mp_const_none;
678}
679STATIC MP_DEFINE_CONST_FUN_OBJ_2(espnow_del_peer_obj, espnow_del_peer);
680
681// Convert a peer_info struct to python tuple
682// Used by espnow_get_peer() and espnow_get_peers()
683static mp_obj_t _peer_info_to_tuple(const esp_now_peer_info_t *peer) {
684 return NEW_TUPLE(
685 mp_obj_new_bytes(peer->peer_addr, MP_ARRAY_SIZE(peer->peer_addr)),
686 mp_obj_new_bytes(peer->lmk, MP_ARRAY_SIZE(peer->lmk)),
687 mp_obj_new_int(peer->channel),
688 mp_obj_new_int(peer->ifidx),
689 (peer->encrypt) ? mp_const_true : mp_const_false);
690}
691
692// ESPNow.get_peers(): Fetch peer_info records for all registered ESPNow peers.
693// Raise OSError if ESPNow.init() has not been called.
694// Return a tuple of tuples:
695// ((peer_addr, lmk, channel, ifidx, encrypt),
696// (peer_addr, lmk, channel, ifidx, encrypt), ...)
697STATIC mp_obj_t espnow_get_peers(mp_obj_t _) {
698 esp_espnow_obj_t *self = _get_singleton_initialised();
699
700 // Build and initialise the peer info tuple.
701 mp_obj_tuple_t *peerinfo_tuple = mp_obj_new_tuple(self->peer_count, NULL);
702 esp_now_peer_info_t peer = {0};
703 for (int i = 0; i < peerinfo_tuple->len; i++) {
704 int status = esp_now_fetch_peer((i == 0), &peer);
705 peerinfo_tuple->items[i] =
706 (status == ESP_OK ? _peer_info_to_tuple(&peer) : mp_const_none);
707 }
708
709 return peerinfo_tuple;
710}
711STATIC MP_DEFINE_CONST_FUN_OBJ_1(espnow_get_peers_obj, espnow_get_peers);
712
713#if MICROPY_ESPNOW_EXTRA_PEER_METHODS
714// ESPNow.get_peer(peer_mac): Get the peer info for peer_mac as a tuple.
715// Raise OSError if ESPNow.init() has not been called.
716// Raise ValueError if mac or LMK are not bytes-like objects or wrong length.
717// Return a tuple of (peer_addr, lmk, channel, ifidx, encrypt).
718STATIC mp_obj_t espnow_get_peer(mp_obj_t _, mp_obj_t arg1) {
719 esp_now_peer_info_t peer = {0};
720 memcpy(peer.peer_addr, _get_peer(arg1), ESP_NOW_ETH_ALEN);
721
722 check_esp_err(esp_now_get_peer(peer.peer_addr, &peer));
723
724 return _peer_info_to_tuple(&peer);
725}
726STATIC MP_DEFINE_CONST_FUN_OBJ_2(espnow_get_peer_obj, espnow_get_peer);
727
728// ESPNow.mod_peer(peer_mac, [lmk, [channel, [ifidx, [encrypt]]]]) or
729// ESPNow.mod_peer(peer_mac, [lmk=b'0123456789abcdef'|b''|None|False],
730// [channel=1..11|0], [ifidx=0|1], [encrypt=True|False])
731// Positional args set to None will be left at current values.
732// Raise OSError if ESPNow.init() has not been called.
733// Raise ValueError if mac or LMK are not bytes-like objects or wrong length.
734// Raise TypeError if invalid keyword args or too many positional args.
735// Return None.
736STATIC mp_obj_t espnow_mod_peer(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
737 esp_now_peer_info_t peer = {0};
738 memcpy(peer.peer_addr, _get_peer(args[1]), ESP_NOW_ETH_ALEN);
739 check_esp_err(esp_now_get_peer(peer.peer_addr, &peer));
740
741 _update_peer_info(&peer, n_args - 2, args + 2, kw_args);
742
743 check_esp_err(esp_now_mod_peer(&peer));
744 _update_peer_count();
745
746 return mp_const_none;
747}
748STATIC MP_DEFINE_CONST_FUN_OBJ_KW(espnow_mod_peer_obj, 2, espnow_mod_peer);
749
750// ESPNow.espnow_peer_count(): Get the number of registered peers.
751// Raise OSError if ESPNow.init() has not been called.
752// Return a tuple of (num_total_peers, num_encrypted_peers).
753STATIC mp_obj_t espnow_peer_count(mp_obj_t _) {
754 esp_now_peer_num_t peer_num = {0};
755 check_esp_err(esp_now_get_peer_num(&peer_num));
756
757 return NEW_TUPLE(
758 mp_obj_new_int(peer_num.total_num),
759 mp_obj_new_int(peer_num.encrypt_num));
760}
761STATIC MP_DEFINE_CONST_FUN_OBJ_1(espnow_peer_count_obj, espnow_peer_count);
762#endif
763
764STATIC const mp_rom_map_elem_t esp_espnow_locals_dict_table[] = {
765 { MP_ROM_QSTR(MP_QSTR_active), MP_ROM_PTR(&espnow_active_obj) },
766 { MP_ROM_QSTR(MP_QSTR_config), MP_ROM_PTR(&espnow_config_obj) },
767 { MP_ROM_QSTR(MP_QSTR_irq), MP_ROM_PTR(&espnow_irq_obj) },
768 { MP_ROM_QSTR(MP_QSTR_stats), MP_ROM_PTR(&espnow_stats_obj) },
769
770 // Send and receive messages
771 { MP_ROM_QSTR(MP_QSTR_recvinto), MP_ROM_PTR(&espnow_recvinto_obj) },
772 { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&espnow_send_obj) },
773 { MP_ROM_QSTR(MP_QSTR_any), MP_ROM_PTR(&espnow_any_obj) },
774
775 // Peer management functions
776 { MP_ROM_QSTR(MP_QSTR_set_pmk), MP_ROM_PTR(&espnow_set_pmk_obj) },
777 { MP_ROM_QSTR(MP_QSTR_add_peer), MP_ROM_PTR(&espnow_add_peer_obj) },
778 { MP_ROM_QSTR(MP_QSTR_del_peer), MP_ROM_PTR(&espnow_del_peer_obj) },
779 { MP_ROM_QSTR(MP_QSTR_get_peers), MP_ROM_PTR(&espnow_get_peers_obj) },
780 #if MICROPY_ESPNOW_EXTRA_PEER_METHODS
781 { MP_ROM_QSTR(MP_QSTR_mod_peer), MP_ROM_PTR(&espnow_mod_peer_obj) },
782 { MP_ROM_QSTR(MP_QSTR_get_peer), MP_ROM_PTR(&espnow_get_peer_obj) },
783 { MP_ROM_QSTR(MP_QSTR_peer_count), MP_ROM_PTR(&espnow_peer_count_obj) },
784 #endif // MICROPY_ESPNOW_EXTRA_PEER_METHODS
785};
786STATIC MP_DEFINE_CONST_DICT(esp_espnow_locals_dict, esp_espnow_locals_dict_table);
787
788STATIC const mp_rom_map_elem_t espnow_globals_dict_table[] = {
789 { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR__espnow) },
790 { MP_ROM_QSTR(MP_QSTR_ESPNowBase), MP_ROM_PTR(&esp_espnow_type) },
791 { MP_ROM_QSTR(MP_QSTR_MAX_DATA_LEN), MP_ROM_INT(ESP_NOW_MAX_DATA_LEN)},
792 { MP_ROM_QSTR(MP_QSTR_ADDR_LEN), MP_ROM_INT(ESP_NOW_ETH_ALEN)},
793 { MP_ROM_QSTR(MP_QSTR_KEY_LEN), MP_ROM_INT(ESP_NOW_KEY_LEN)},
794 { MP_ROM_QSTR(MP_QSTR_MAX_TOTAL_PEER_NUM), MP_ROM_INT(ESP_NOW_MAX_TOTAL_PEER_NUM)},
795 { MP_ROM_QSTR(MP_QSTR_MAX_ENCRYPT_PEER_NUM), MP_ROM_INT(ESP_NOW_MAX_ENCRYPT_PEER_NUM)},
796};
797STATIC MP_DEFINE_CONST_DICT(espnow_globals_dict, espnow_globals_dict_table);
798
799// ### Dummy Buffer Protocol support
800// ...so asyncio can poll.ipoll() on this device
801
802// Support ioctl(MP_STREAM_POLL, ) for asyncio
803STATIC mp_uint_t espnow_stream_ioctl(
804 mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) {
805 if (request != MP_STREAM_POLL) {
806 *errcode = MP_EINVAL;
807 return MP_STREAM_ERROR;
808 }
809 esp_espnow_obj_t *self = _get_singleton();
810 return (self->recv_buffer == NULL) ? 0 : // If not initialised
811 arg ^ (
812 // If no data in the buffer, unset the Read ready flag
813 ((ringbuf_avail(self->recv_buffer) == 0) ? MP_STREAM_POLL_RD : 0) |
814 // If still waiting for responses, unset the Write ready flag
815 ((self->tx_responses < self->tx_packets) ? MP_STREAM_POLL_WR : 0));
816}
817
818STATIC const mp_stream_p_t espnow_stream_p = {
819 .ioctl = espnow_stream_ioctl,
820};
821
822#if MICROPY_ESPNOW_RSSI
823// Return reference to the dictionary of peers we have seen:
824// {peer1: (rssi, time_sec), peer2: (rssi, time_msec), ...}
825// where:
826// peerX is a byte string containing the 6-byte mac address of the peer,
827// rssi is the wifi signal strength from the last msg received
828// (in dBm from -127 to 0)
829// time_sec is the time in milliseconds since device last booted.
830STATIC void espnow_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
831 esp_espnow_obj_t *self = _get_singleton();
832 if (dest[0] != MP_OBJ_NULL) { // Only allow "Load" operation
833 return;
834 }
835 if (attr == MP_QSTR_peers_table) {
836 dest[0] = self->peers_table;
837 return;
838 }
839 dest[1] = MP_OBJ_SENTINEL; // Attribute not found
840}
841#endif // MICROPY_ESPNOW_RSSI
842
843MP_DEFINE_CONST_OBJ_TYPE(
844 esp_espnow_type,
845 MP_QSTR_ESPNowBase,
846 MP_TYPE_FLAG_NONE,
847 make_new, espnow_make_new,
848 #if MICROPY_ESPNOW_RSSI
849 attr, espnow_attr,
850 #endif // MICROPY_ESPNOW_RSSI
851 protocol, &espnow_stream_p,
852 locals_dict, &esp_espnow_locals_dict
853 );
854
855const mp_obj_module_t mp_module_espnow = {
856 .base = { &mp_type_module },
857 .globals = (mp_obj_dict_t *)&espnow_globals_dict,
858};
859
860MP_REGISTER_MODULE(MP_QSTR__espnow, mp_module_espnow);
861MP_REGISTER_ROOT_POINTER(struct _esp_espnow_obj_t *espnow_singleton);