blob: e7e51ee57ec0f91f9d73a4fa1df3f28a3c5f9eaa [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"
Glenn Moloney9f835df2023-10-10 13:06:59 +110050
51#if MICROPY_PY_ESPNOW
52
Glenn Moloney7fa322a2020-09-24 15:37:04 +100053#include "mphalport.h"
54#include "modnetwork.h"
55#include "modespnow.h"
56
Glenn Moloney9f835df2023-10-10 13:06:59 +110057#ifndef MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +100058// Include code to track rssi of peers
Glenn Moloney9f835df2023-10-10 13:06:59 +110059#define MICROPY_PY_ESPNOW_RSSI 1
Glenn Moloney7fa322a2020-09-24 15:37:04 +100060#endif
Glenn Moloney9f835df2023-10-10 13:06:59 +110061#ifndef MICROPY_PY_ESPNOW_EXTRA_PEER_METHODS
Glenn Moloney7fa322a2020-09-24 15:37:04 +100062// Include mod_peer(),get_peer(),peer_count()
Glenn Moloney9f835df2023-10-10 13:06:59 +110063#define MICROPY_PY_ESPNOW_EXTRA_PEER_METHODS 1
Glenn Moloney7fa322a2020-09-24 15:37:04 +100064#endif
65
66// Relies on gcc Variadic Macros and Statement Expressions
67#define NEW_TUPLE(...) \
68 ({mp_obj_t _z[] = {__VA_ARGS__}; mp_obj_new_tuple(MP_ARRAY_SIZE(_z), _z); })
69
70static const uint8_t ESPNOW_MAGIC = 0x99;
71
72// ESPNow packet format for the receive buffer.
73// Use this for peeking at the header of the next packet in the buffer.
74typedef struct {
75 uint8_t magic; // = ESPNOW_MAGIC
76 uint8_t msg_len; // Length of the message
Glenn Moloney9f835df2023-10-10 13:06:59 +110077 #if MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +100078 uint32_t time_ms; // Timestamp (ms) when packet is received
79 int8_t rssi; // RSSI value (dBm) (-127 to 0)
Glenn Moloney9f835df2023-10-10 13:06:59 +110080 #endif // MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +100081} __attribute__((packed)) espnow_hdr_t;
82
83typedef struct {
84 espnow_hdr_t hdr; // The header
85 uint8_t peer[6]; // Peer address
86 uint8_t msg[0]; // Message is up to 250 bytes
87} __attribute__((packed)) espnow_pkt_t;
88
89// The maximum length of an espnow packet (bytes)
90static const size_t MAX_PACKET_LEN = (
91 (sizeof(espnow_pkt_t) + ESP_NOW_MAX_DATA_LEN));
92
93// Enough for 2 full-size packets: 2 * (6 + 7 + 250) = 526 bytes
94// Will allocate an additional 7 bytes for buffer overhead
95static const size_t DEFAULT_RECV_BUFFER_SIZE = (2 * MAX_PACKET_LEN);
96
97// Default timeout (millisec) to wait for incoming ESPNow messages (5 minutes).
98static const size_t DEFAULT_RECV_TIMEOUT_MS = (5 * 60 * 1000);
99
100// Time to wait (millisec) for responses from sent packets: (2 seconds).
101static const size_t DEFAULT_SEND_TIMEOUT_MS = (2 * 1000);
102
103// Number of milliseconds to wait for pending responses to sent packets.
104// This is a fallback which should never be reached.
105static const mp_uint_t PENDING_RESPONSES_TIMEOUT_MS = 100;
106static const mp_uint_t PENDING_RESPONSES_BUSY_POLL_MS = 10;
107
108// The data structure for the espnow_singleton.
109typedef struct _esp_espnow_obj_t {
110 mp_obj_base_t base;
111
112 ringbuf_t *recv_buffer; // A buffer for received packets
113 size_t recv_buffer_size; // The size of the recv_buffer
114 mp_int_t recv_timeout_ms; // Timeout for recv()
115 volatile size_t rx_packets; // # of received packets
116 size_t dropped_rx_pkts; // # of dropped packets (buffer full)
117 size_t tx_packets; // # of sent packets
118 volatile size_t tx_responses; // # of sent packet responses received
119 volatile size_t tx_failures; // # of sent packet responses failed
120 size_t peer_count; // Cache the # of peers for send(sync=True)
121 mp_obj_t recv_cb; // Callback when a packet is received
122 mp_obj_t recv_cb_arg; // Argument passed to callback
Glenn Moloney9f835df2023-10-10 13:06:59 +1100123 #if MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000124 mp_obj_t peers_table; // A dictionary of discovered peers
Glenn Moloney9f835df2023-10-10 13:06:59 +1100125 #endif // MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000126} esp_espnow_obj_t;
127
128const mp_obj_type_t esp_espnow_type;
129
130// ### Initialisation and Config functions
131//
132
133// Return a pointer to the ESPNow module singleton
134// If state == INITIALISED check the device has been initialised.
135// Raises OSError if not initialised and state == INITIALISED.
136static esp_espnow_obj_t *_get_singleton() {
137 return MP_STATE_PORT(espnow_singleton);
138}
139
140static esp_espnow_obj_t *_get_singleton_initialised() {
141 esp_espnow_obj_t *self = _get_singleton();
142 // assert(self);
143 if (self->recv_buffer == NULL) {
144 // Throw an espnow not initialised error
145 check_esp_err(ESP_ERR_ESPNOW_NOT_INIT);
146 }
147 return self;
148}
149
150// Allocate and initialise the ESPNow module as a singleton.
151// Returns the initialised espnow_singleton.
Angus Grattondecf8e62024-02-27 15:32:29 +1100152static mp_obj_t espnow_make_new(const mp_obj_type_t *type, size_t n_args,
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000153 size_t n_kw, const mp_obj_t *all_args) {
154
155 // The espnow_singleton must be defined in MICROPY_PORT_ROOT_POINTERS
156 // (see mpconfigport.h) to prevent memory allocated here from being
157 // garbage collected.
158 // NOTE: on soft reset the espnow_singleton MUST be set to NULL and the
159 // ESP-NOW functions de-initialised (see main.c).
160 esp_espnow_obj_t *self = MP_STATE_PORT(espnow_singleton);
161 if (self != NULL) {
162 return self;
163 }
164 self = m_new_obj(esp_espnow_obj_t);
165 self->base.type = &esp_espnow_type;
166 self->recv_buffer_size = DEFAULT_RECV_BUFFER_SIZE;
167 self->recv_timeout_ms = DEFAULT_RECV_TIMEOUT_MS;
168 self->recv_buffer = NULL; // Buffer is allocated in espnow_init()
169 self->recv_cb = mp_const_none;
Glenn Moloney9f835df2023-10-10 13:06:59 +1100170 #if MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000171 self->peers_table = mp_obj_new_dict(0);
172 // Prevent user code modifying the dict
173 mp_obj_dict_get_map(self->peers_table)->is_fixed = 1;
Glenn Moloney9f835df2023-10-10 13:06:59 +1100174 #endif // MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000175
176 // Set the global singleton pointer for the espnow protocol.
177 MP_STATE_PORT(espnow_singleton) = self;
178
179 return self;
180}
181
182// Forward declare the send and recv ESPNow callbacks
Angus Grattondecf8e62024-02-27 15:32:29 +1100183static void send_cb(const uint8_t *mac_addr, esp_now_send_status_t status);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000184
Angus Grattondecf8e62024-02-27 15:32:29 +1100185static 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 +1000186
187// ESPNow.init(): Initialise the data buffers and ESP-NOW functions.
188// Initialise the Espressif ESPNOW software stack, register callbacks and
189// allocate the recv data buffers.
190// Returns None.
191static mp_obj_t espnow_init(mp_obj_t _) {
192 esp_espnow_obj_t *self = _get_singleton();
193 if (self->recv_buffer == NULL) { // Already initialised
194 self->recv_buffer = m_new_obj(ringbuf_t);
195 ringbuf_alloc(self->recv_buffer, self->recv_buffer_size);
196
197 esp_initialise_wifi(); // Call the wifi init code in network_wlan.c
198 check_esp_err(esp_now_init());
199 check_esp_err(esp_now_register_recv_cb(recv_cb));
200 check_esp_err(esp_now_register_send_cb(send_cb));
201 }
202 return mp_const_none;
203}
204
205// ESPNow.deinit(): De-initialise the ESPNOW software stack, disable callbacks
206// and deallocate the recv data buffers.
207// Note: this function is called from main.c:mp_task() to cleanup before soft
Angus Grattondecf8e62024-02-27 15:32:29 +1100208// reset, so cannot be declared static and must guard against self == NULL;.
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000209mp_obj_t espnow_deinit(mp_obj_t _) {
210 esp_espnow_obj_t *self = _get_singleton();
211 if (self != NULL && self->recv_buffer != NULL) {
212 check_esp_err(esp_now_unregister_recv_cb());
213 check_esp_err(esp_now_unregister_send_cb());
214 check_esp_err(esp_now_deinit());
215 self->recv_buffer->buf = NULL;
216 self->recv_buffer = NULL;
217 self->peer_count = 0; // esp_now_deinit() removes all peers.
218 self->tx_packets = self->tx_responses;
219 }
220 return mp_const_none;
221}
222
Angus Grattondecf8e62024-02-27 15:32:29 +1100223static mp_obj_t espnow_active(size_t n_args, const mp_obj_t *args) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000224 esp_espnow_obj_t *self = _get_singleton();
225 if (n_args > 1) {
226 if (mp_obj_is_true(args[1])) {
227 espnow_init(self);
228 } else {
229 espnow_deinit(self);
230 }
231 }
232 return self->recv_buffer != NULL ? mp_const_true : mp_const_false;
233}
Angus Grattondecf8e62024-02-27 15:32:29 +1100234static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(espnow_active_obj, 1, 2, espnow_active);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000235
236// ESPNow.config(['param'|param=value, ..])
237// Get or set configuration values. Supported config params:
238// buffer: size of buffer for rx packets (default=514 bytes)
239// timeout: Default read timeout (default=300,000 milliseconds)
Angus Grattondecf8e62024-02-27 15:32:29 +1100240static mp_obj_t espnow_config(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000241 esp_espnow_obj_t *self = _get_singleton();
Glenn Moloneyfd277702023-06-09 13:09:46 +1000242 enum { ARG_get, ARG_rxbuf, ARG_timeout_ms, ARG_rate };
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000243 static const mp_arg_t allowed_args[] = {
244 { MP_QSTR_, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
Glenn Moloneyfd277702023-06-09 13:09:46 +1000245 { MP_QSTR_rxbuf, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000246 { MP_QSTR_timeout_ms, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = INT_MIN} },
247 { MP_QSTR_rate, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
248 };
249 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
250 mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
251 MP_ARRAY_SIZE(allowed_args), allowed_args, args);
252
Glenn Moloneyfd277702023-06-09 13:09:46 +1000253 if (args[ARG_rxbuf].u_int >= 0) {
254 self->recv_buffer_size = args[ARG_rxbuf].u_int;
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000255 }
256 if (args[ARG_timeout_ms].u_int != INT_MIN) {
257 self->recv_timeout_ms = args[ARG_timeout_ms].u_int;
258 }
259 if (args[ARG_rate].u_int >= 0) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000260 esp_initialise_wifi(); // Call the wifi init code in network_wlan.c
261 check_esp_err(esp_wifi_config_espnow_rate(ESP_IF_WIFI_STA, args[ARG_rate].u_int));
262 check_esp_err(esp_wifi_config_espnow_rate(ESP_IF_WIFI_AP, args[ARG_rate].u_int));
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000263 }
264 if (args[ARG_get].u_obj == MP_OBJ_NULL) {
265 return mp_const_none;
266 }
267#define QS(x) (uintptr_t)MP_OBJ_NEW_QSTR(x)
268 // Return the value of the requested parameter
269 uintptr_t name = (uintptr_t)args[ARG_get].u_obj;
Glenn Moloneyfd277702023-06-09 13:09:46 +1000270 if (name == QS(MP_QSTR_rxbuf)) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000271 return mp_obj_new_int(self->recv_buffer_size);
272 } else if (name == QS(MP_QSTR_timeout_ms)) {
273 return mp_obj_new_int(self->recv_timeout_ms);
274 } else {
275 mp_raise_ValueError(MP_ERROR_TEXT("unknown config param"));
276 }
277#undef QS
278
279 return mp_const_none;
280}
Angus Grattondecf8e62024-02-27 15:32:29 +1100281static MP_DEFINE_CONST_FUN_OBJ_KW(espnow_config_obj, 1, espnow_config);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000282
283// ESPNow.irq(recv_cb)
284// Set callback function to be invoked when a message is received.
Angus Grattondecf8e62024-02-27 15:32:29 +1100285static mp_obj_t espnow_irq(size_t n_args, const mp_obj_t *args) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000286 esp_espnow_obj_t *self = _get_singleton();
287 mp_obj_t recv_cb = args[1];
288 if (recv_cb != mp_const_none && !mp_obj_is_callable(recv_cb)) {
289 mp_raise_ValueError(MP_ERROR_TEXT("invalid handler"));
290 }
291 self->recv_cb = recv_cb;
292 self->recv_cb_arg = (n_args > 2) ? args[2] : mp_const_none;
293 return mp_const_none;
294}
Angus Grattondecf8e62024-02-27 15:32:29 +1100295static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(espnow_irq_obj, 2, 3, espnow_irq);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000296
297// ESPnow.stats(): Provide some useful stats.
298// Returns a tuple of:
299// (tx_pkts, tx_responses, tx_failures, rx_pkts, dropped_rx_pkts)
Angus Grattondecf8e62024-02-27 15:32:29 +1100300static mp_obj_t espnow_stats(mp_obj_t _) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000301 const esp_espnow_obj_t *self = _get_singleton();
302 return NEW_TUPLE(
303 mp_obj_new_int(self->tx_packets),
304 mp_obj_new_int(self->tx_responses),
305 mp_obj_new_int(self->tx_failures),
306 mp_obj_new_int(self->rx_packets),
307 mp_obj_new_int(self->dropped_rx_pkts));
308}
Angus Grattondecf8e62024-02-27 15:32:29 +1100309static MP_DEFINE_CONST_FUN_OBJ_1(espnow_stats_obj, espnow_stats);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000310
Glenn Moloney9f835df2023-10-10 13:06:59 +1100311#if MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000312// ### Maintaining the peer table and reading RSSI values
313//
314// We maintain a peers table for several reasons, to:
315// - support monitoring the RSSI values for all peers; and
316// - to return unique bytestrings for each peer which supports more efficient
317// application memory usage and peer handling.
318
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000319// Lookup a peer in the peers table and return a reference to the item in the
320// peers_table. Add peer to the table if it is not found (may alloc memory).
321// Will not return NULL.
322static mp_map_elem_t *_lookup_add_peer(esp_espnow_obj_t *self, const uint8_t *peer) {
323 // We do not want to allocate any new memory in the case that the peer
324 // already exists in the peers_table (which is almost all the time).
325 // So, we use a byte string on the stack and look that up in the dict.
326 mp_map_t *map = mp_obj_dict_get_map(self->peers_table);
327 mp_obj_str_t peer_obj = {{&mp_type_bytes}, 0, ESP_NOW_ETH_ALEN, peer};
328 mp_map_elem_t *item = mp_map_lookup(map, &peer_obj, MP_MAP_LOOKUP);
329 if (item == NULL) {
330 // If not found, add the peer using a new bytestring
331 map->is_fixed = 0; // Allow to modify the dict
332 mp_obj_t new_peer = mp_obj_new_bytes(peer, ESP_NOW_ETH_ALEN);
333 item = mp_map_lookup(map, new_peer, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
334 item->value = mp_obj_new_list(2, NULL);
335 map->is_fixed = 1; // Relock the dict
336 }
337 return item;
338}
339
340// Update the peers table with the new rssi value from a received pkt and
341// return a reference to the item in the peers_table.
342static mp_map_elem_t *_update_rssi(const uint8_t *peer, int8_t rssi, uint32_t time_ms) {
343 esp_espnow_obj_t *self = _get_singleton_initialised();
344 // Lookup the peer in the device table
345 mp_map_elem_t *item = _lookup_add_peer(self, peer);
346 mp_obj_list_t *list = MP_OBJ_TO_PTR(item->value);
347 list->items[0] = MP_OBJ_NEW_SMALL_INT(rssi);
348 list->items[1] = mp_obj_new_int(time_ms);
349 return item;
350}
Glenn Moloney9f835df2023-10-10 13:06:59 +1100351#endif // MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000352
353// Return C pointer to byte memory string/bytes/bytearray in obj.
354// Raise ValueError if the length does not match expected len.
355static uint8_t *_get_bytes_len_rw(mp_obj_t obj, size_t len, mp_uint_t rw) {
356 mp_buffer_info_t bufinfo;
357 mp_get_buffer_raise(obj, &bufinfo, rw);
358 if (bufinfo.len != len) {
359 mp_raise_ValueError(MP_ERROR_TEXT("invalid buffer length"));
360 }
361 return (uint8_t *)bufinfo.buf;
362}
363
364static uint8_t *_get_bytes_len(mp_obj_t obj, size_t len) {
365 return _get_bytes_len_rw(obj, len, MP_BUFFER_READ);
366}
367
368static uint8_t *_get_bytes_len_w(mp_obj_t obj, size_t len) {
369 return _get_bytes_len_rw(obj, len, MP_BUFFER_WRITE);
370}
371
372// Return C pointer to the MAC address.
373// Raise ValueError if mac_addr is wrong type or is not 6 bytes long.
374static const uint8_t *_get_peer(mp_obj_t mac_addr) {
375 return mp_obj_is_true(mac_addr)
376 ? _get_bytes_len(mac_addr, ESP_NOW_ETH_ALEN) : NULL;
377}
378
379// Copy data from the ring buffer - wait if buffer is empty up to timeout_ms
380// 0: Success
381// -1: Not enough data available to complete read (try again later)
382// -2: Requested read is larger than buffer - will never succeed
383static int ringbuf_get_bytes_wait(ringbuf_t *r, uint8_t *data, size_t len, mp_int_t timeout_ms) {
384 mp_uint_t start = mp_hal_ticks_ms();
385 int status = 0;
386 while (((status = ringbuf_get_bytes(r, data, len)) == -1)
387 && (timeout_ms < 0 || (mp_uint_t)(mp_hal_ticks_ms() - start) < (mp_uint_t)timeout_ms)) {
388 MICROPY_EVENT_POLL_HOOK;
389 }
390 return status;
391}
392
393// ESPNow.recvinto(buffers[, timeout_ms]):
394// Waits for an espnow message and copies the peer_addr and message into
395// the buffers list.
396// Arguments:
397// buffers: (Optional) list of bytearrays to store return values.
398// timeout_ms: (Optional) timeout in milliseconds (or None).
399// Buffers should be a list: [bytearray(6), bytearray(250)]
400// If buffers is 4 elements long, the rssi and timestamp values will be
401// loaded into the 3rd and 4th elements.
402// Default timeout is set with ESPNow.config(timeout=milliseconds).
403// Return (None, None) on timeout.
Angus Grattondecf8e62024-02-27 15:32:29 +1100404static mp_obj_t espnow_recvinto(size_t n_args, const mp_obj_t *args) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000405 esp_espnow_obj_t *self = _get_singleton_initialised();
406
407 mp_int_t timeout_ms = ((n_args > 2 && args[2] != mp_const_none)
408 ? mp_obj_get_int(args[2]) : self->recv_timeout_ms);
409
410 mp_obj_list_t *list = MP_OBJ_TO_PTR(args[1]);
411 if (!mp_obj_is_type(list, &mp_type_list) || list->len < 2) {
412 mp_raise_ValueError(MP_ERROR_TEXT("ESPNow.recvinto(): Invalid argument"));
413 }
414 mp_obj_array_t *msg = MP_OBJ_TO_PTR(list->items[1]);
415 if (mp_obj_is_type(msg, &mp_type_bytearray)) {
416 msg->len += msg->free; // Make all the space in msg array available
417 msg->free = 0;
418 }
Glenn Moloney9f835df2023-10-10 13:06:59 +1100419 #if MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000420 uint8_t peer_buf[ESP_NOW_ETH_ALEN];
421 #else
422 uint8_t *peer_buf = _get_bytes_len_w(list->items[0], ESP_NOW_ETH_ALEN);
Glenn Moloney9f835df2023-10-10 13:06:59 +1100423 #endif // MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000424 uint8_t *msg_buf = _get_bytes_len_w(msg, ESP_NOW_MAX_DATA_LEN);
425
426 // Read the packet header from the incoming buffer
427 espnow_hdr_t hdr;
428 if (ringbuf_get_bytes_wait(self->recv_buffer, (uint8_t *)&hdr, sizeof(hdr), timeout_ms) < 0) {
429 return MP_OBJ_NEW_SMALL_INT(0); // Timeout waiting for packet
430 }
431 int msg_len = hdr.msg_len;
432
433 // Check the message packet header format and read the message data
434 if (hdr.magic != ESPNOW_MAGIC
435 || msg_len > ESP_NOW_MAX_DATA_LEN
436 || ringbuf_get_bytes(self->recv_buffer, peer_buf, ESP_NOW_ETH_ALEN) < 0
437 || ringbuf_get_bytes(self->recv_buffer, msg_buf, msg_len) < 0) {
438 mp_raise_ValueError(MP_ERROR_TEXT("ESPNow.recv(): buffer error"));
439 }
440 if (mp_obj_is_type(msg, &mp_type_bytearray)) {
441 // Set the length of the message bytearray.
442 size_t size = msg->len + msg->free;
443 msg->len = msg_len;
444 msg->free = size - msg_len;
445 }
446
Glenn Moloney9f835df2023-10-10 13:06:59 +1100447 #if MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000448 // Update rssi value in the peer device table
449 mp_map_elem_t *entry = _update_rssi(peer_buf, hdr.rssi, hdr.time_ms);
450 list->items[0] = entry->key; // Set first element of list to peer
451 if (list->len >= 4) {
452 list->items[2] = MP_OBJ_NEW_SMALL_INT(hdr.rssi);
453 list->items[3] = mp_obj_new_int(hdr.time_ms);
454 }
Glenn Moloney9f835df2023-10-10 13:06:59 +1100455 #endif // MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000456
457 return MP_OBJ_NEW_SMALL_INT(msg_len);
458}
Angus Grattondecf8e62024-02-27 15:32:29 +1100459static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(espnow_recvinto_obj, 2, 3, espnow_recvinto);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000460
461// Test if data is available to read from the buffers
Angus Grattondecf8e62024-02-27 15:32:29 +1100462static mp_obj_t espnow_any(const mp_obj_t _) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000463 esp_espnow_obj_t *self = _get_singleton_initialised();
464
465 return ringbuf_avail(self->recv_buffer) ? mp_const_true : mp_const_false;
466}
Angus Grattondecf8e62024-02-27 15:32:29 +1100467static MP_DEFINE_CONST_FUN_OBJ_1(espnow_any_obj, espnow_any);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000468
469// Used by espnow_send() for sends() with sync==True.
470// Wait till all pending sent packet responses have been received.
471// ie. self->tx_responses == self->tx_packets.
472static void _wait_for_pending_responses(esp_espnow_obj_t *self) {
473 mp_uint_t start = mp_hal_ticks_ms();
474 mp_uint_t t;
475 while (self->tx_responses < self->tx_packets) {
476 if ((t = mp_hal_ticks_ms() - start) > PENDING_RESPONSES_TIMEOUT_MS) {
477 mp_raise_OSError(MP_ETIMEDOUT);
478 }
479 if (t > PENDING_RESPONSES_BUSY_POLL_MS) {
480 // After 10ms of busy waiting give other tasks a look in.
481 MICROPY_EVENT_POLL_HOOK;
482 }
483 }
484}
485
486// ESPNow.send(peer_addr, message, [sync (=true), size])
487// ESPNow.send(message)
488// Send a message to the peer's mac address. Optionally wait for a response.
489// If peer_addr == None or any non-true value, send to all registered peers.
490// If sync == True, wait for response after sending.
491// If size is provided it should be the number of bytes in message to send().
492// Returns:
493// True if sync==False and message sent successfully.
494// True if sync==True and message is received successfully by all recipients
495// False if sync==True and message is not received by at least one recipient
496// Raises: EAGAIN if the internal espnow buffers are full.
Angus Grattondecf8e62024-02-27 15:32:29 +1100497static mp_obj_t espnow_send(size_t n_args, const mp_obj_t *args) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000498 esp_espnow_obj_t *self = _get_singleton_initialised();
499 // Check the various combinations of input arguments
500 const uint8_t *peer = (n_args > 2) ? _get_peer(args[1]) : NULL;
501 mp_obj_t msg = (n_args > 2) ? args[2] : (n_args == 2) ? args[1] : MP_OBJ_NULL;
502 bool sync = n_args <= 3 || args[3] == mp_const_none || mp_obj_is_true(args[3]);
503
504 // Get a pointer to the data buffer of the message
505 mp_buffer_info_t message;
506 mp_get_buffer_raise(msg, &message, MP_BUFFER_READ);
507
508 if (sync) {
509 // Flush out any pending responses.
510 // If the last call was sync==False there may be outstanding responses
511 // still to be received (possible many if we just had a burst of
512 // unsync send()s). We need to wait for all pending responses if this
513 // call has sync=True.
514 _wait_for_pending_responses(self);
515 }
516 int saved_failures = self->tx_failures;
517 // Send the packet - try, try again if internal esp-now buffers are full.
518 esp_err_t err;
519 mp_uint_t start = mp_hal_ticks_ms();
520 while ((ESP_ERR_ESPNOW_NO_MEM == (err = esp_now_send(peer, message.buf, message.len)))
521 && (mp_uint_t)(mp_hal_ticks_ms() - start) < (mp_uint_t)DEFAULT_SEND_TIMEOUT_MS) {
522 MICROPY_EVENT_POLL_HOOK;
523 }
524 check_esp_err(err); // Will raise OSError if e != ESP_OK
525 // Increment the sent packet count. If peer_addr==NULL msg will be
526 // sent to all peers EXCEPT any broadcast or multicast addresses.
527 self->tx_packets += ((peer == NULL) ? self->peer_count : 1);
528 if (sync) {
529 // Wait for and tally all the expected responses from peers
530 _wait_for_pending_responses(self);
531 }
532 // Return False if sync and any peers did not respond.
533 return mp_obj_new_bool(!(sync && self->tx_failures != saved_failures));
534}
Angus Grattondecf8e62024-02-27 15:32:29 +1100535static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(espnow_send_obj, 2, 4, espnow_send);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000536
537// ### The ESP_Now send and recv callback routines
538//
539
540// Callback triggered when a sent packet is acknowledged by the peer (or not).
541// Just count the number of responses and number of failures.
542// These are used in the send() logic.
Angus Grattondecf8e62024-02-27 15:32:29 +1100543static void send_cb(const uint8_t *mac_addr, esp_now_send_status_t status) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000544 esp_espnow_obj_t *self = _get_singleton();
545 self->tx_responses++;
546 if (status != ESP_NOW_SEND_SUCCESS) {
547 self->tx_failures++;
548 }
549}
550
551// Callback triggered when an ESP-Now packet is received.
552// Write the peer MAC address and the message into the recv_buffer as an
553// ESPNow packet.
554// If the buffer is full, drop the message and increment the dropped count.
555// Schedules the user callback if one has been registered (ESPNow.config()).
Angus Grattondecf8e62024-02-27 15:32:29 +1100556static 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 +1000557 esp_espnow_obj_t *self = _get_singleton();
558 ringbuf_t *buf = self->recv_buffer;
559 // TODO: Test this works with ">".
560 if (sizeof(espnow_pkt_t) + msg_len >= ringbuf_free(buf)) {
561 self->dropped_rx_pkts++;
562 return;
563 }
564 espnow_hdr_t header;
565 header.magic = ESPNOW_MAGIC;
566 header.msg_len = msg_len;
Glenn Moloney9f835df2023-10-10 13:06:59 +1100567 #if MICROPY_PY_ESPNOW_RSSI
Glenn Moloney2cc37112023-05-25 10:40:50 +1000568 header.rssi = recv_info->rx_ctrl->rssi;
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000569 header.time_ms = mp_hal_ticks_ms();
Glenn Moloney9f835df2023-10-10 13:06:59 +1100570 #endif // MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000571
572 ringbuf_put_bytes(buf, (uint8_t *)&header, sizeof(header));
Damien Georgee4650122023-05-09 09:52:54 +1000573 ringbuf_put_bytes(buf, recv_info->src_addr, ESP_NOW_ETH_ALEN);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000574 ringbuf_put_bytes(buf, msg, msg_len);
575 self->rx_packets++;
576 if (self->recv_cb != mp_const_none) {
577 mp_sched_schedule(self->recv_cb, self->recv_cb_arg);
578 }
579}
580
581// ### Peer Management Functions
582//
583
584// Set the ESP-NOW Primary Master Key (pmk) (for encrypted communications).
585// Raise OSError if ESP-NOW functions are not initialised.
586// Raise ValueError if key is not a bytes-like object exactly 16 bytes long.
Angus Grattondecf8e62024-02-27 15:32:29 +1100587static mp_obj_t espnow_set_pmk(mp_obj_t _, mp_obj_t key) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000588 check_esp_err(esp_now_set_pmk(_get_bytes_len(key, ESP_NOW_KEY_LEN)));
589 return mp_const_none;
590}
Angus Grattondecf8e62024-02-27 15:32:29 +1100591static MP_DEFINE_CONST_FUN_OBJ_2(espnow_set_pmk_obj, espnow_set_pmk);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000592
593// Common code for add_peer() and mod_peer() to process the args and kw_args:
594// Raise ValueError if the LMK is not a bytes-like object of exactly 16 bytes.
595// Raise TypeError if invalid keyword args or too many positional args.
596// Return true if all args parsed correctly.
Angus Grattondecf8e62024-02-27 15:32:29 +1100597static bool _update_peer_info(
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000598 esp_now_peer_info_t *peer, size_t n_args,
599 const mp_obj_t *pos_args, mp_map_t *kw_args) {
600
601 enum { ARG_lmk, ARG_channel, ARG_ifidx, ARG_encrypt };
602 static const mp_arg_t allowed_args[] = {
603 { MP_QSTR_lmk, MP_ARG_OBJ, {.u_obj = mp_const_none} },
604 { MP_QSTR_channel, MP_ARG_OBJ, {.u_obj = mp_const_none} },
605 { MP_QSTR_ifidx, MP_ARG_OBJ, {.u_obj = mp_const_none} },
606 { MP_QSTR_encrypt, MP_ARG_OBJ, {.u_obj = mp_const_none} },
607 };
608 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
609 mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
610 if (args[ARG_lmk].u_obj != mp_const_none) {
611 mp_obj_t obj = args[ARG_lmk].u_obj;
612 peer->encrypt = mp_obj_is_true(obj);
613 if (peer->encrypt) {
614 // Key must be 16 bytes in length.
615 memcpy(peer->lmk, _get_bytes_len(obj, ESP_NOW_KEY_LEN), ESP_NOW_KEY_LEN);
616 }
617 }
618 if (args[ARG_channel].u_obj != mp_const_none) {
619 peer->channel = mp_obj_get_int(args[ARG_channel].u_obj);
620 }
621 if (args[ARG_ifidx].u_obj != mp_const_none) {
622 peer->ifidx = mp_obj_get_int(args[ARG_ifidx].u_obj);
623 }
624 if (args[ARG_encrypt].u_obj != mp_const_none) {
625 peer->encrypt = mp_obj_is_true(args[ARG_encrypt].u_obj);
626 }
627 return true;
628}
629
630// Update the cached peer count in self->peer_count;
631// The peer_count ignores broadcast and multicast addresses and is used for the
632// send() logic and is updated from add_peer(), mod_peer() and del_peer().
Angus Grattondecf8e62024-02-27 15:32:29 +1100633static void _update_peer_count() {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000634 esp_espnow_obj_t *self = _get_singleton_initialised();
635
636 esp_now_peer_info_t peer = {0};
637 bool from_head = true;
638 int count = 0;
639 // esp_now_fetch_peer() skips over any broadcast or multicast addresses
640 while (esp_now_fetch_peer(from_head, &peer) == ESP_OK) {
641 from_head = false;
642 if (++count >= ESP_NOW_MAX_TOTAL_PEER_NUM) {
643 break; // Should not happen
644 }
645 }
646 self->peer_count = count;
647}
648
649// ESPNow.add_peer(peer_mac, [lmk, [channel, [ifidx, [encrypt]]]]) or
650// ESPNow.add_peer(peer_mac, [lmk=b'0123456789abcdef'|b''|None|False],
651// [channel=1..11|0], [ifidx=0|1], [encrypt=True|False])
652// Positional args set to None will be left at defaults.
653// Raise OSError if ESPNow.init() has not been called.
654// Raise ValueError if mac or LMK are not bytes-like objects or wrong length.
655// Raise TypeError if invalid keyword args or too many positional args.
656// Return None.
Angus Grattondecf8e62024-02-27 15:32:29 +1100657static mp_obj_t espnow_add_peer(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000658 esp_now_peer_info_t peer = {0};
659 memcpy(peer.peer_addr, _get_peer(args[1]), ESP_NOW_ETH_ALEN);
660 _update_peer_info(&peer, n_args - 2, args + 2, kw_args);
661
662 check_esp_err(esp_now_add_peer(&peer));
663 _update_peer_count();
664
665 return mp_const_none;
666}
Angus Grattondecf8e62024-02-27 15:32:29 +1100667static MP_DEFINE_CONST_FUN_OBJ_KW(espnow_add_peer_obj, 2, espnow_add_peer);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000668
669// ESPNow.del_peer(peer_mac): Unregister peer_mac.
670// Raise OSError if ESPNow.init() has not been called.
671// Raise ValueError if peer is not a bytes-like objects or wrong length.
672// Return None.
Angus Grattondecf8e62024-02-27 15:32:29 +1100673static mp_obj_t espnow_del_peer(mp_obj_t _, mp_obj_t peer) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000674 uint8_t peer_addr[ESP_NOW_ETH_ALEN];
675 memcpy(peer_addr, _get_peer(peer), ESP_NOW_ETH_ALEN);
676
677 check_esp_err(esp_now_del_peer(peer_addr));
678 _update_peer_count();
679
680 return mp_const_none;
681}
Angus Grattondecf8e62024-02-27 15:32:29 +1100682static MP_DEFINE_CONST_FUN_OBJ_2(espnow_del_peer_obj, espnow_del_peer);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000683
684// Convert a peer_info struct to python tuple
685// Used by espnow_get_peer() and espnow_get_peers()
686static mp_obj_t _peer_info_to_tuple(const esp_now_peer_info_t *peer) {
687 return NEW_TUPLE(
688 mp_obj_new_bytes(peer->peer_addr, MP_ARRAY_SIZE(peer->peer_addr)),
689 mp_obj_new_bytes(peer->lmk, MP_ARRAY_SIZE(peer->lmk)),
690 mp_obj_new_int(peer->channel),
691 mp_obj_new_int(peer->ifidx),
692 (peer->encrypt) ? mp_const_true : mp_const_false);
693}
694
695// ESPNow.get_peers(): Fetch peer_info records for all registered ESPNow peers.
696// Raise OSError if ESPNow.init() has not been called.
697// Return a tuple of tuples:
698// ((peer_addr, lmk, channel, ifidx, encrypt),
699// (peer_addr, lmk, channel, ifidx, encrypt), ...)
Angus Grattondecf8e62024-02-27 15:32:29 +1100700static mp_obj_t espnow_get_peers(mp_obj_t _) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000701 esp_espnow_obj_t *self = _get_singleton_initialised();
702
703 // Build and initialise the peer info tuple.
704 mp_obj_tuple_t *peerinfo_tuple = mp_obj_new_tuple(self->peer_count, NULL);
705 esp_now_peer_info_t peer = {0};
706 for (int i = 0; i < peerinfo_tuple->len; i++) {
707 int status = esp_now_fetch_peer((i == 0), &peer);
708 peerinfo_tuple->items[i] =
709 (status == ESP_OK ? _peer_info_to_tuple(&peer) : mp_const_none);
710 }
711
712 return peerinfo_tuple;
713}
Angus Grattondecf8e62024-02-27 15:32:29 +1100714static MP_DEFINE_CONST_FUN_OBJ_1(espnow_get_peers_obj, espnow_get_peers);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000715
Glenn Moloney9f835df2023-10-10 13:06:59 +1100716#if MICROPY_PY_ESPNOW_EXTRA_PEER_METHODS
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000717// ESPNow.get_peer(peer_mac): Get the peer info for peer_mac as a tuple.
718// Raise OSError if ESPNow.init() has not been called.
719// Raise ValueError if mac or LMK are not bytes-like objects or wrong length.
720// Return a tuple of (peer_addr, lmk, channel, ifidx, encrypt).
Angus Grattondecf8e62024-02-27 15:32:29 +1100721static mp_obj_t espnow_get_peer(mp_obj_t _, mp_obj_t arg1) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000722 esp_now_peer_info_t peer = {0};
723 memcpy(peer.peer_addr, _get_peer(arg1), ESP_NOW_ETH_ALEN);
724
725 check_esp_err(esp_now_get_peer(peer.peer_addr, &peer));
726
727 return _peer_info_to_tuple(&peer);
728}
Angus Grattondecf8e62024-02-27 15:32:29 +1100729static MP_DEFINE_CONST_FUN_OBJ_2(espnow_get_peer_obj, espnow_get_peer);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000730
731// ESPNow.mod_peer(peer_mac, [lmk, [channel, [ifidx, [encrypt]]]]) or
732// ESPNow.mod_peer(peer_mac, [lmk=b'0123456789abcdef'|b''|None|False],
733// [channel=1..11|0], [ifidx=0|1], [encrypt=True|False])
734// Positional args set to None will be left at current values.
735// Raise OSError if ESPNow.init() has not been called.
736// Raise ValueError if mac or LMK are not bytes-like objects or wrong length.
737// Raise TypeError if invalid keyword args or too many positional args.
738// Return None.
Angus Grattondecf8e62024-02-27 15:32:29 +1100739static mp_obj_t espnow_mod_peer(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000740 esp_now_peer_info_t peer = {0};
741 memcpy(peer.peer_addr, _get_peer(args[1]), ESP_NOW_ETH_ALEN);
742 check_esp_err(esp_now_get_peer(peer.peer_addr, &peer));
743
744 _update_peer_info(&peer, n_args - 2, args + 2, kw_args);
745
746 check_esp_err(esp_now_mod_peer(&peer));
747 _update_peer_count();
748
749 return mp_const_none;
750}
Angus Grattondecf8e62024-02-27 15:32:29 +1100751static MP_DEFINE_CONST_FUN_OBJ_KW(espnow_mod_peer_obj, 2, espnow_mod_peer);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000752
753// ESPNow.espnow_peer_count(): Get the number of registered peers.
754// Raise OSError if ESPNow.init() has not been called.
755// Return a tuple of (num_total_peers, num_encrypted_peers).
Angus Grattondecf8e62024-02-27 15:32:29 +1100756static mp_obj_t espnow_peer_count(mp_obj_t _) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000757 esp_now_peer_num_t peer_num = {0};
758 check_esp_err(esp_now_get_peer_num(&peer_num));
759
760 return NEW_TUPLE(
761 mp_obj_new_int(peer_num.total_num),
762 mp_obj_new_int(peer_num.encrypt_num));
763}
Angus Grattondecf8e62024-02-27 15:32:29 +1100764static MP_DEFINE_CONST_FUN_OBJ_1(espnow_peer_count_obj, espnow_peer_count);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000765#endif
766
Angus Grattondecf8e62024-02-27 15:32:29 +1100767static const mp_rom_map_elem_t esp_espnow_locals_dict_table[] = {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000768 { MP_ROM_QSTR(MP_QSTR_active), MP_ROM_PTR(&espnow_active_obj) },
769 { MP_ROM_QSTR(MP_QSTR_config), MP_ROM_PTR(&espnow_config_obj) },
770 { MP_ROM_QSTR(MP_QSTR_irq), MP_ROM_PTR(&espnow_irq_obj) },
771 { MP_ROM_QSTR(MP_QSTR_stats), MP_ROM_PTR(&espnow_stats_obj) },
772
773 // Send and receive messages
774 { MP_ROM_QSTR(MP_QSTR_recvinto), MP_ROM_PTR(&espnow_recvinto_obj) },
775 { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&espnow_send_obj) },
776 { MP_ROM_QSTR(MP_QSTR_any), MP_ROM_PTR(&espnow_any_obj) },
777
778 // Peer management functions
779 { MP_ROM_QSTR(MP_QSTR_set_pmk), MP_ROM_PTR(&espnow_set_pmk_obj) },
780 { MP_ROM_QSTR(MP_QSTR_add_peer), MP_ROM_PTR(&espnow_add_peer_obj) },
781 { MP_ROM_QSTR(MP_QSTR_del_peer), MP_ROM_PTR(&espnow_del_peer_obj) },
782 { MP_ROM_QSTR(MP_QSTR_get_peers), MP_ROM_PTR(&espnow_get_peers_obj) },
Glenn Moloney9f835df2023-10-10 13:06:59 +1100783 #if MICROPY_PY_ESPNOW_EXTRA_PEER_METHODS
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000784 { MP_ROM_QSTR(MP_QSTR_mod_peer), MP_ROM_PTR(&espnow_mod_peer_obj) },
785 { MP_ROM_QSTR(MP_QSTR_get_peer), MP_ROM_PTR(&espnow_get_peer_obj) },
786 { MP_ROM_QSTR(MP_QSTR_peer_count), MP_ROM_PTR(&espnow_peer_count_obj) },
Glenn Moloney9f835df2023-10-10 13:06:59 +1100787 #endif // MICROPY_PY_ESPNOW_EXTRA_PEER_METHODS
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000788};
Angus Grattondecf8e62024-02-27 15:32:29 +1100789static MP_DEFINE_CONST_DICT(esp_espnow_locals_dict, esp_espnow_locals_dict_table);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000790
Angus Grattondecf8e62024-02-27 15:32:29 +1100791static const mp_rom_map_elem_t espnow_globals_dict_table[] = {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000792 { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR__espnow) },
793 { MP_ROM_QSTR(MP_QSTR_ESPNowBase), MP_ROM_PTR(&esp_espnow_type) },
794 { MP_ROM_QSTR(MP_QSTR_MAX_DATA_LEN), MP_ROM_INT(ESP_NOW_MAX_DATA_LEN)},
795 { MP_ROM_QSTR(MP_QSTR_ADDR_LEN), MP_ROM_INT(ESP_NOW_ETH_ALEN)},
796 { MP_ROM_QSTR(MP_QSTR_KEY_LEN), MP_ROM_INT(ESP_NOW_KEY_LEN)},
797 { MP_ROM_QSTR(MP_QSTR_MAX_TOTAL_PEER_NUM), MP_ROM_INT(ESP_NOW_MAX_TOTAL_PEER_NUM)},
798 { MP_ROM_QSTR(MP_QSTR_MAX_ENCRYPT_PEER_NUM), MP_ROM_INT(ESP_NOW_MAX_ENCRYPT_PEER_NUM)},
799};
Angus Grattondecf8e62024-02-27 15:32:29 +1100800static MP_DEFINE_CONST_DICT(espnow_globals_dict, espnow_globals_dict_table);
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000801
802// ### Dummy Buffer Protocol support
803// ...so asyncio can poll.ipoll() on this device
804
805// Support ioctl(MP_STREAM_POLL, ) for asyncio
Angus Grattondecf8e62024-02-27 15:32:29 +1100806static mp_uint_t espnow_stream_ioctl(
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000807 mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) {
808 if (request != MP_STREAM_POLL) {
809 *errcode = MP_EINVAL;
810 return MP_STREAM_ERROR;
811 }
812 esp_espnow_obj_t *self = _get_singleton();
813 return (self->recv_buffer == NULL) ? 0 : // If not initialised
814 arg ^ (
815 // If no data in the buffer, unset the Read ready flag
816 ((ringbuf_avail(self->recv_buffer) == 0) ? MP_STREAM_POLL_RD : 0) |
817 // If still waiting for responses, unset the Write ready flag
818 ((self->tx_responses < self->tx_packets) ? MP_STREAM_POLL_WR : 0));
819}
820
Angus Grattondecf8e62024-02-27 15:32:29 +1100821static const mp_stream_p_t espnow_stream_p = {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000822 .ioctl = espnow_stream_ioctl,
823};
824
Glenn Moloney9f835df2023-10-10 13:06:59 +1100825#if MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000826// Return reference to the dictionary of peers we have seen:
827// {peer1: (rssi, time_sec), peer2: (rssi, time_msec), ...}
828// where:
829// peerX is a byte string containing the 6-byte mac address of the peer,
830// rssi is the wifi signal strength from the last msg received
831// (in dBm from -127 to 0)
832// time_sec is the time in milliseconds since device last booted.
Angus Grattondecf8e62024-02-27 15:32:29 +1100833static void espnow_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000834 esp_espnow_obj_t *self = _get_singleton();
835 if (dest[0] != MP_OBJ_NULL) { // Only allow "Load" operation
836 return;
837 }
838 if (attr == MP_QSTR_peers_table) {
839 dest[0] = self->peers_table;
840 return;
841 }
842 dest[1] = MP_OBJ_SENTINEL; // Attribute not found
843}
Glenn Moloney9f835df2023-10-10 13:06:59 +1100844#endif // MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000845
846MP_DEFINE_CONST_OBJ_TYPE(
847 esp_espnow_type,
848 MP_QSTR_ESPNowBase,
849 MP_TYPE_FLAG_NONE,
850 make_new, espnow_make_new,
Glenn Moloney9f835df2023-10-10 13:06:59 +1100851 #if MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000852 attr, espnow_attr,
Glenn Moloney9f835df2023-10-10 13:06:59 +1100853 #endif // MICROPY_PY_ESPNOW_RSSI
Glenn Moloney7fa322a2020-09-24 15:37:04 +1000854 protocol, &espnow_stream_p,
855 locals_dict, &esp_espnow_locals_dict
856 );
857
858const mp_obj_module_t mp_module_espnow = {
859 .base = { &mp_type_module },
860 .globals = (mp_obj_dict_t *)&espnow_globals_dict,
861};
862
863MP_REGISTER_MODULE(MP_QSTR__espnow, mp_module_espnow);
864MP_REGISTER_ROOT_POINTER(struct _esp_espnow_obj_t *espnow_singleton);
Glenn Moloney9f835df2023-10-10 13:06:59 +1100865
866#endif // MICROPY_PY_ESPNOW