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