split espnow between bindings and common-hal

This commit is contained in:
MicroDev 2023-02-01 17:54:51 +05:30
parent 9c430d45d1
commit ae4bb75e29
No known key found for this signature in database
GPG Key ID: 2C0867BE60967730
8 changed files with 539 additions and 311 deletions

View File

@ -491,6 +491,7 @@ msgstr ""
msgid "Already have all-matches listener"
msgstr ""
#: ports/espressif/bindings/espnow/ESPNow.c
#: ports/espressif/common-hal/espulp/ULP.c
#: shared-module/memorymonitor/AllocationAlarm.c
#: shared-module/memorymonitor/AllocationSize.c
@ -2431,6 +2432,7 @@ msgid "addresses is empty"
msgstr ""
#: ports/espressif/bindings/espnow/ESPNow.c
#: ports/espressif/common-hal/espnow/ESPNow.c
msgid "an error occured"
msgstr ""
@ -3818,6 +3820,10 @@ msgstr ""
msgid "peer already exists"
msgstr ""
#: ports/espressif/bindings/espnow/ESPNow.c
msgid "peer not found"
msgstr ""
#: shared-bindings/bitmaptools/__init__.c shared-bindings/displayio/Bitmap.c
msgid "pixel coordinates out of bounds"
msgstr ""

View File

@ -260,7 +260,9 @@ CFLAGS += -isystem esp32-camera/conversions/include
endif
ifneq ($(CIRCUITPY_ESPNOW),0)
SRC_ESPNOW := $(wildcard bindings/espnow/*.c)
SRC_ESPNOW := \
$(wildcard common-hal/espnow/*.c) \
$(wildcard bindings/espnow/*.c)
SRC_C += $(SRC_ESPNOW)
endif

View File

@ -41,57 +41,8 @@
#include "bindings/espnow/ESPNow.h"
#include "shared-bindings/util.h"
#include "shared-bindings/wifi/__init__.h"
#define ESPNOW_MAGIC 0x99
// The maximum length of an espnow packet (bytes)
#define MAX_PACKET_LEN (sizeof(espnow_packet_t) + ESP_NOW_MAX_DATA_LEN)
// Enough for 2 full-size packets: 2 * (6 + 7 + 250) = 526 bytes
// Will allocate an additional 7 bytes for buffer overhead
#define DEFAULT_RECV_BUFFER_SIZE (2 * MAX_PACKET_LEN)
// Default timeout (millisec) to wait for incoming ESPNow messages (5 minutes).
#define DEFAULT_RECV_TIMEOUT_MS (5 * 60 * 1000)
// Time to wait (millisec) for responses from sent packets: (2 seconds).
#define DEFAULT_SEND_TIMEOUT_MS (2 * 1000)
// Number of milliseconds to wait for pending responses to sent packets.
// This is a fallback which should never be reached.
#define PENDING_RESPONSES_TIMEOUT_MS 100
#define PENDING_RESPONSES_BUSY_POLL_MS 10
// ESPNow packet format for the receive buffer.
// Use this for peeking at the header of the next packet in the buffer.
typedef struct {
uint8_t magic; // = ESPNOW_MAGIC
uint8_t msg_len; // Length of the message
uint32_t time_ms; // Timestamp (ms) when packet is received
int8_t rssi; // RSSI value (dBm) (-127 to 0)
} __attribute__((packed)) espnow_header_t;
typedef struct {
espnow_header_t header; // The header
uint8_t peer[6]; // Peer address
uint8_t msg[0]; // Message is up to 250 bytes
} __attribute__((packed)) espnow_packet_t;
// The data structure for the espnow_singleton.
typedef struct _espnow_obj_t {
mp_obj_base_t base;
ringbuf_t *recv_buffer; // A buffer for received packets
size_t recv_buffer_size; // The size of the recv_buffer
wifi_phy_rate_t phy_rate; // The ESP-NOW physical layer rate.
volatile size_t rx_packets; // # of received packets
volatile size_t rx_failures; // # of dropped packets (buffer full)
size_t tx_packets; // # of sent packets
volatile size_t tx_responses; // # of sent packet responses received
volatile size_t tx_failures; // # of sent packet responses failed
size_t peers_count; // Cache the # of peers for send(sync=True)
mp_obj_t peers_table; // A dictionary of discovered peers
} espnow_obj_t;
#include "common-hal/espnow/ESPNow.h"
static void check_esp_err(esp_err_t status) {
if (status != ESP_OK) {
@ -101,154 +52,59 @@ static void check_esp_err(esp_err_t status) {
// --- Initialisation and Config functions ---
// Return a pointer to the ESPNow module singleton
static espnow_obj_t *_get_singleton(void) {
return MP_STATE_PORT(espnow_singleton);
}
static bool espnow_deinited(espnow_obj_t *self) {
return self->recv_buffer == NULL;
}
static void check_for_deinit(espnow_obj_t *self) {
if (espnow_deinited(self)) {
if (common_hal_espnow_deinited(self)) {
raise_deinited_error();
}
}
static void _set_buffer_size(espnow_obj_t *self, mp_int_t value) {
self->recv_buffer_size = mp_arg_validate_int_min(value, MAX_PACKET_LEN, MP_QSTR_buffer_size);
};
static void _set_phy_rate(espnow_obj_t *self, mp_int_t value) {
self->phy_rate = mp_arg_validate_int_range(value, 0, WIFI_PHY_RATE_MAX - 1, MP_QSTR_phy_rate);
};
//| class ESPNow:
//| """Provides access to the ESP-NOW protocol."""
//|
//| def __init__(self, buffer_size: Optional[int], phy_rate: Optional[int]) -> None:
//| """Allocate and initialize `ESPNow` instance as a singleton.
//|
//| :param int buffer_size: The size of the internal ring buffer (length > 263 bytes). Default: 526 bytes.
//| :param int phy_rate: The ESP-NOW physical layer rate. Default 1 Mbps."""
//| :param int buffer_size: The size of the internal ring buffer. Default: 526 bytes.
//| :param int phy_rate: The ESP-NOW physical layer rate. Default: 1 Mbps."""
//| ...
STATIC mp_obj_t espnow_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
enum { ARG_buffer_size, ARG_phy_rate };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_buffer_size, MP_ARG_INT, { .u_int = DEFAULT_RECV_BUFFER_SIZE } },
{ MP_QSTR_buffer_size, MP_ARG_INT, { .u_int = 526 } },
{ MP_QSTR_phy_rate, MP_ARG_INT, { .u_int = WIFI_PHY_RATE_1M_L } },
};
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
espnow_obj_t *self = _get_singleton();
espnow_obj_t *self = MP_STATE_PORT(espnow_singleton);
if (self == NULL) {
self = m_new_obj(espnow_obj_t);
self->base.type = &espnow_type;
_set_buffer_size(self, args[ARG_buffer_size].u_int);
_set_phy_rate(self, args[ARG_phy_rate].u_int);
self->peers_table = mp_obj_new_dict(0);
// Prevent user code modifying the dict
mp_obj_dict_get_map(self->peers_table)->is_fixed = 1;
// Set the global singleton pointer for the espnow protocol.
MP_STATE_PORT(espnow_singleton) = self;
if (self != NULL) {
mp_raise_RuntimeError(translate("Already running"));
}
self = m_new_obj(espnow_obj_t);
self->base.type = &espnow_type;
common_hal_espnow_set_buffer_size(self, args[ARG_buffer_size].u_int);
common_hal_espnow_set_phy_rate(self, args[ARG_phy_rate].u_int);
self->peers_table = mp_obj_new_dict(0);
// Prevent user code modifying the dict
mp_obj_dict_get_map(self->peers_table)->is_fixed = 1;
// Set the global singleton pointer for the espnow protocol.
MP_STATE_PORT(espnow_singleton) = self;
common_hal_espnow_init(self);
return self;
}
// --- The ESP-NOW send and recv callback routines ---
// Callback triggered when a sent packet is acknowledged by the peer (or not).
// Just count the number of responses and number of failures.
// These are used in the send() logic.
static void send_cb(const uint8_t *mac, esp_now_send_status_t status) {
espnow_obj_t *self = _get_singleton();
self->tx_responses++;
if (status != ESP_NOW_SEND_SUCCESS) {
self->tx_failures++;
}
}
static inline int8_t _get_rssi_from_wifi_packet(const uint8_t *msg);
// Callback triggered when an ESP-NOW packet is received.
// Write the peer MAC address and the message into the recv_buffer as an ESPNow packet.
// If the buffer is full, drop the message and increment the dropped count.
static void recv_cb(const uint8_t *mac, const uint8_t *msg, int msg_len) {
espnow_obj_t *self = _get_singleton();
ringbuf_t *buf = self->recv_buffer;
if (sizeof(espnow_packet_t) + msg_len > ringbuf_num_empty(buf)) {
self->rx_failures++;
return;
}
espnow_header_t header;
header.magic = ESPNOW_MAGIC;
header.msg_len = msg_len;
header.rssi = _get_rssi_from_wifi_packet(msg);
header.time_ms = mp_hal_ticks_ms();
ringbuf_put_n(buf, (uint8_t *)&header, sizeof(header));
ringbuf_put_n(buf, mac, ESP_NOW_ETH_ALEN);
ringbuf_put_n(buf, msg, msg_len);
self->rx_packets++;
}
// Initialize the ESP-NOW software stack,
// register callbacks and allocate the recv data buffers.
static void espnow_init(espnow_obj_t *self) {
if (espnow_deinited(self)) {
self->recv_buffer = m_new_obj(ringbuf_t);
if (!ringbuf_alloc(self->recv_buffer, self->recv_buffer_size, true)) {
m_malloc_fail(self->recv_buffer_size);
}
if (!common_hal_wifi_radio_get_enabled(&common_hal_wifi_radio_obj)) {
common_hal_wifi_init(false);
common_hal_wifi_radio_set_enabled(&common_hal_wifi_radio_obj, true);
}
check_esp_err(esp_wifi_config_espnow_rate(ESP_IF_WIFI_STA, self->phy_rate));
check_esp_err(esp_wifi_config_espnow_rate(ESP_IF_WIFI_AP, self->phy_rate));
check_esp_err(esp_now_init());
check_esp_err(esp_now_register_send_cb(send_cb));
check_esp_err(esp_now_register_recv_cb(recv_cb));
}
}
// De-initialize the ESP-NOW software stack,
// disable callbacks and deallocate the recv data buffers.
static void espnow_deinit(espnow_obj_t *self) {
if (self != NULL && !espnow_deinited(self)) {
check_esp_err(esp_now_unregister_send_cb());
check_esp_err(esp_now_unregister_recv_cb());
check_esp_err(esp_now_deinit());
self->recv_buffer->buf = NULL;
self->recv_buffer = NULL;
self->peers_count = 0; // esp_now_deinit() removes all peers.
self->tx_packets = self->tx_responses;
}
}
void espnow_reset(void) {
espnow_deinit(_get_singleton());
MP_STATE_PORT(espnow_singleton) = NULL;
}
// Return C pointer to byte memory string/bytes/bytearray in obj.
// Raise ValueError if the length does not match expected len.
static uint8_t *_get_bytes_len(mp_obj_t obj, size_t len, mp_uint_t rw) {
static const uint8_t *_get_bytes_len(mp_obj_t obj, size_t len, mp_uint_t rw) {
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(obj, &bufinfo, rw);
mp_arg_validate_length(bufinfo.len, len, MP_QSTR_buffer);
@ -261,7 +117,8 @@ static uint8_t *_get_bytes_len(mp_obj_t obj, size_t len, mp_uint_t rw) {
//| :param ReadableBuffer pmk: The ESP-NOW Primary Master Key (length = 16 bytes)."""
//| ...
STATIC mp_obj_t espnow_set_pmk(mp_obj_t self_in, mp_obj_t key) {
check_esp_err(esp_now_set_pmk(_get_bytes_len(key, ESP_NOW_KEY_LEN, MP_BUFFER_READ)));
espnow_obj_t *self = MP_OBJ_TO_PTR(self_in);
common_hal_espnow_set_pmk(self, _get_bytes_len(key, ESP_NOW_KEY_LEN, MP_BUFFER_READ));
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(espnow_set_pmk_obj, espnow_set_pmk);
@ -271,13 +128,13 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(espnow_set_pmk_obj, espnow_set_pmk);
//|
STATIC mp_obj_t espnow_get_active(const mp_obj_t self_in) {
espnow_obj_t *self = MP_OBJ_TO_PTR(self_in);
return mp_obj_new_bool(!espnow_deinited(self));
return mp_obj_new_bool(!common_hal_espnow_deinited(self));
}
MP_DEFINE_CONST_FUN_OBJ_1(espnow_get_active_obj, espnow_get_active);
STATIC mp_obj_t espnow_set_active(const mp_obj_t self_in, const mp_obj_t value) {
espnow_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_is_true(value) ? espnow_init(self) : espnow_deinit(self);
mp_obj_is_true(value) ? common_hal_espnow_init(self) : common_hal_espnow_deinit(self);
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(espnow_set_active_obj, espnow_set_active);
@ -298,7 +155,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(espnow_get_buffer_size_obj, espnow_get_buffer_size);
STATIC mp_obj_t espnow_set_buffer_size(const mp_obj_t self_in, const mp_obj_t value) {
espnow_obj_t *self = MP_OBJ_TO_PTR(self_in);
_set_buffer_size(self, mp_obj_get_int(value));
common_hal_espnow_set_buffer_size(self, mp_obj_get_int(value));
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(espnow_set_buffer_size_obj, espnow_set_buffer_size);
@ -318,7 +175,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(espnow_get_phy_rate_obj, espnow_get_phy_rate);
STATIC mp_obj_t espnow_set_phy_rate(const mp_obj_t self_in, const mp_obj_t value) {
espnow_obj_t *self = MP_OBJ_TO_PTR(self_in);
_set_phy_rate(self, mp_obj_get_int(value));
common_hal_espnow_set_phy_rate(self, mp_obj_get_int(value));
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(espnow_set_phy_rate_obj, espnow_set_phy_rate);
@ -368,36 +225,6 @@ static inline int8_t _get_rssi_from_wifi_packet(const uint8_t *msg) {
return wifi_packet->rx_ctrl.rssi;
}
// Lookup a peer in the peers table and return a reference to the item in the peers_table.
// Add peer to the table if it is not found (may alloc memory). Will not return NULL.
static mp_map_elem_t *_lookup_add_peer(espnow_obj_t *self, const uint8_t *peer) {
// We do not want to allocate any new memory in the case that the peer
// already exists in the peers_table (which is almost all the time).
// So, we use a byte string on the stack and look that up in the dict.
mp_map_t *map = mp_obj_dict_get_map(self->peers_table);
mp_obj_str_t peer_obj = {{&mp_type_bytes}, 0, ESP_NOW_ETH_ALEN, peer};
mp_map_elem_t *item = mp_map_lookup(map, &peer_obj, MP_MAP_LOOKUP);
if (item == NULL) {
// If not found, add the peer using a new bytestring
map->is_fixed = 0; // Allow to modify the dict
mp_obj_t new_peer = mp_obj_new_bytes(peer, ESP_NOW_ETH_ALEN);
item = mp_map_lookup(map, new_peer, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
item->value = mp_obj_new_list(2, NULL);
map->is_fixed = 1; // Relock the dict
}
return item;
}
// Update the peers table with the new rssi value from a received packet and
// return a reference to the item in the peers_table.
static void _update_rssi(espnow_obj_t *self, const uint8_t *peer, int8_t rssi, uint32_t time_ms) {
// Lookup the peer in the device table
mp_map_elem_t *item = _lookup_add_peer(self, peer);
mp_obj_list_t *list = MP_OBJ_TO_PTR(item->value);
list->items[0] = MP_OBJ_NEW_SMALL_INT(rssi);
list->items[1] = mp_obj_new_int(time_ms);
}
// --- Handling espnow packets in the recv buffer ---
// --- Send and Receive ESP-NOW data ---
@ -408,22 +235,6 @@ static const uint8_t *_get_peer_addr(mp_obj_t mac) {
return mp_obj_is_true(mac) ? _get_bytes_len(mac, ESP_NOW_ETH_ALEN, MP_BUFFER_READ) : NULL;
}
// Used by espnow_send() for sends() with sync==True.
// Wait till all pending sent packet responses have been received.
// ie. self->tx_responses == self->tx_packets.
static void _wait_for_pending_responses(espnow_obj_t *self) {
mp_uint_t t, start = mp_hal_ticks_ms();
while (self->tx_responses < self->tx_packets) {
if ((t = mp_hal_ticks_ms() - start) > PENDING_RESPONSES_TIMEOUT_MS) {
mp_raise_OSError(MP_ETIMEDOUT);
}
if (t > PENDING_RESPONSES_BUSY_POLL_MS) {
// After 10ms of busy waiting give other tasks a look in.
RUN_BACKGROUND_TASKS;
}
}
}
//| def send(
//| self,
//| message: ReadableBuffer,
@ -458,106 +269,26 @@ STATIC mp_obj_t espnow_send(size_t n_args, const mp_obj_t *pos_args, mp_map_t *k
check_for_deinit(self);
const bool sync = mp_obj_is_true(args[ARG_sync].u_obj);
if (sync) {
// Flush out any pending responses.
// If the last call was sync == False there may be outstanding responses
// still to be received (possible many if we just had a burst of unsync send()s).
// We need to wait for all pending responses if this call has sync = True.
_wait_for_pending_responses(self);
}
const uint8_t *peer_addr = _get_peer_addr(args[ARG_mac].u_obj);
// Get a pointer to the data buffer of the message
mp_buffer_info_t message;
mp_get_buffer_raise(args[ARG_message].u_obj, &message, MP_BUFFER_READ);
// Send the packet - try, try again if internal esp-now buffers are full.
esp_err_t err;
size_t saved_failures = self->tx_failures;
mp_uint_t start = mp_hal_ticks_ms();
while ((ESP_ERR_ESPNOW_NO_MEM == (err = esp_now_send(peer_addr, message.buf, message.len))) &&
(mp_hal_ticks_ms() - start) <= DEFAULT_SEND_TIMEOUT_MS) {
RUN_BACKGROUND_TASKS;
}
check_esp_err(err);
// Increment the sent packet count.
// If peer_addr == NULL msg will be sent to all peers EXCEPT any broadcast or multicast addresses.
self->tx_packets += ((peer_addr == NULL) ? self->peers_count : 1);
if (sync) {
// Wait for and tally all the expected responses from peers
_wait_for_pending_responses(self);
}
// Return False if sync and any peers did not respond.
return mp_obj_new_bool(!(sync && self->tx_failures != saved_failures));
return common_hal_espnow_send(self, sync, peer_addr, &message);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(espnow_send_obj, 2, espnow_send);
//| def recv(self, buffers: List[WriteableBuffer]) -> int:
//| """Loads mac, message, rssi and timestamp into the provided buffers.
//| def recv(self) -> Optional[ESPNowPacket]:
//| """Receive a message from the peer(s).
//|
//| If buffers is 2 elements long, the mac and message will be
//| loaded into the 1st and 2nd elements.
//| If buffers is 4 elements long, the rssi and timestamp values will be
//| loaded into the 3rd and 4th elements.
//|
//| :param List[WriteableBuffer] buffers: List of buffers to be loaded.
//|
//| :returns: Length of the message."""
//| :returns: An `ESPNowPacket` if available in the buffer, otherwise `None`."""
//| ...
STATIC mp_obj_t espnow_recv(mp_obj_t self_in, mp_obj_t buffers) {
espnow_obj_t *self = MP_OBJ_TO_PTR(self_in);
check_for_deinit(self);
mp_obj_list_t *list = MP_OBJ_TO_PTR(buffers);
if (!mp_obj_is_type(list, &mp_type_list) || list->len < 2) {
mp_arg_error_invalid(MP_QSTR_buffers);
}
mp_obj_array_t *msg = MP_OBJ_TO_PTR(list->items[1]);
if (mp_obj_is_type(msg, &mp_type_bytearray)) {
msg->len += msg->free; // Make all the space in msg array available
msg->free = 0;
}
uint8_t *peer_buf = _get_bytes_len(list->items[0], ESP_NOW_ETH_ALEN, MP_BUFFER_WRITE);
uint8_t *msg_buf = _get_bytes_len(msg, ESP_NOW_MAX_DATA_LEN, MP_BUFFER_WRITE);
// Read the packet header from the incoming buffer
espnow_header_t header;
if (!ringbuf_get_n(self->recv_buffer, (uint8_t *)&header, sizeof(header))) {
return MP_OBJ_NEW_SMALL_INT(0);
}
uint8_t msg_len = header.msg_len;
// Check the message packet header format and read the message data
if (header.magic != ESPNOW_MAGIC ||
msg_len > ESP_NOW_MAX_DATA_LEN ||
!ringbuf_get_n(self->recv_buffer, peer_buf, ESP_NOW_ETH_ALEN) ||
!ringbuf_get_n(self->recv_buffer, msg_buf, msg_len)) {
mp_arg_error_invalid(MP_QSTR_buffer);
}
if (mp_obj_is_type(msg, &mp_type_bytearray)) {
// Set the length of the message bytearray.
size_t size = msg->len + msg->free;
msg->len = msg_len;
msg->free = size - msg_len;
}
// Update rssi value in the peer device table
_update_rssi(self, peer_buf, header.rssi, header.time_ms);
if (list->len == 4) {
list->items[2] = MP_OBJ_NEW_SMALL_INT(header.rssi);
list->items[3] = mp_obj_new_int(header.time_ms);
}
return MP_OBJ_NEW_SMALL_INT(msg_len);
return common_hal_espnow_recv(self);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(espnow_recv_obj, espnow_recv);
@ -581,7 +312,9 @@ static void _update_peer_info(size_t n_args, const mp_obj_t *pos_args, mp_map_t
memcpy(peer.peer_addr, _get_peer_addr(args[ARG_mac].u_obj), ESP_NOW_ETH_ALEN);
if (modify) {
check_esp_err(esp_now_get_peer(peer.peer_addr, &peer));
if (esp_now_get_peer(peer.peer_addr, &peer) != ESP_OK) {
mp_raise_RuntimeError(translate("peer not found"));
}
} else {
if (esp_now_is_peer_exist(peer.peer_addr)) {
mp_raise_RuntimeError(translate("peer already exists"));
@ -593,7 +326,7 @@ static void _update_peer_info(size_t n_args, const mp_obj_t *pos_args, mp_map_t
const mp_obj_t channel = args[ARG_channel].u_obj;
if (channel != mp_const_none) {
peer.channel = mp_arg_validate_int_range(mp_obj_get_int(channel), 1, 14, MP_QSTR_channel);
peer.channel = mp_arg_validate_int_range(mp_obj_get_int(channel), 0, 14, MP_QSTR_channel);
}
const mp_obj_t interface = args[ARG_interface].u_obj;
@ -837,7 +570,7 @@ STATIC mp_uint_t espnow_stream_ioctl(mp_obj_t self_in, mp_uint_t request, uintpt
}
espnow_obj_t *self = MP_OBJ_TO_PTR(self_in);
return (espnow_deinited(self)) ? 0 : // If not initialized
return (common_hal_espnow_deinited(self)) ? 0 : // If not initialized
arg ^ (
// If no data in the buffer, unset the Read ready flag
((!ringbuf_num_filled(self->recv_buffer)) ? MP_STREAM_POLL_RD : 0) |

View File

@ -0,0 +1,70 @@
/*
* This file is part of the CircuitPython project, https://github.com/adafruit/circuitpython
*
* The MIT License (MIT)
*
* Copyright (c) 2023 MicroDev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "bindings/espnow/ESPNowPacket.h"
//| class ESPNowPacket:
//| """A packet retreived from ESP-NOW communication protocol"""
//|
//| mac: ReadableBuffer
//| """The sender's mac address (length = 6 bytes)"""
//|
//| msg: RedableBuffer
//| """The message sent by the peer (length <= 250 bytes)"""
//|
//| rssi: int
//| """The received signal strength indication (in dBm from -127 to 0)"""
//|
//| time: int
//| """The is the time in milliseconds since device last booted"""
//|
const mp_obj_namedtuple_type_t espnow_packet_type_obj = {
.base = {
.base = {
.type = &mp_type_type
},
.flags = MP_TYPE_FLAG_EXTENDED,
.name = MP_QSTR_ESPNowPacket,
.print = namedtuple_print,
.parent = &mp_type_tuple,
.make_new = namedtuple_make_new,
.attr = namedtuple_attr,
MP_TYPE_EXTENDED_FIELDS(
.unary_op = mp_obj_tuple_unary_op,
.binary_op = mp_obj_tuple_binary_op,
.subscr = mp_obj_tuple_subscr,
.getiter = mp_obj_tuple_getiter,
),
},
.n_fields = 4,
.fields = {
MP_QSTR_mac,
MP_QSTR_msg,
MP_QSTR_rssi,
MP_QSTR_time,
},
};

View File

@ -0,0 +1,30 @@
/*
* This file is part of the Micro Python project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2023 MicroDev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include "py/objnamedtuple.h"
extern const mp_obj_namedtuple_type_t espnow_packet_type_obj;

View File

@ -28,6 +28,7 @@
#include "bindings/espnow/__init__.h"
#include "bindings/espnow/ESPNow.h"
#include "bindings/espnow/ESPNowPacket.h"
//| """ESP-NOW Module
//|
@ -75,9 +76,11 @@
STATIC const mp_rom_map_elem_t espnow_module_globals_table[] = {
// module name
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_espnow) },
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_espnow) },
// module classes
{ MP_ROM_QSTR(MP_QSTR_ESPNow), MP_ROM_PTR(&espnow_type) },
{ MP_ROM_QSTR(MP_QSTR_ESPNow), MP_ROM_PTR(&espnow_type) },
{ MP_ROM_QSTR(MP_QSTR_ESPNowPacket),MP_ROM_PTR(&espnow_packet_type_obj) },
};
STATIC MP_DEFINE_CONST_DICT(espnow_module_globals, espnow_module_globals_table);

View File

@ -0,0 +1,327 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2017-2020 Nick Moore
* Copyright (c) 2018 shawwwn <shawwwn1@gmail.com>
* Copyright (c) 2020-2021 Glenn Moloney @glenn20
* Copyright (c) 2023 MicroDev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "py/mperrno.h"
#include "py/runtime.h"
#include "bindings/espnow/ESPNowPacket.h"
#include "shared-bindings/wifi/__init__.h"
#include "common-hal/espnow/ESPNow.h"
#include "mphalport.h"
#include "esp_now.h"
#define ESPNOW_MAGIC 0x99
// The maximum length of an espnow packet (bytes)
#define MAX_PACKET_LEN (sizeof(espnow_packet_t) + ESP_NOW_MAX_DATA_LEN)
// Enough for 2 full-size packets: 2 * (6 + 7 + 250) = 526 bytes
// Will allocate an additional 7 bytes for buffer overhead
#define DEFAULT_RECV_BUFFER_SIZE (2 * MAX_PACKET_LEN)
// Time to wait (millisec) for responses from sent packets: (2 seconds).
#define DEFAULT_SEND_TIMEOUT_MS (2 * 1000)
// Number of milliseconds to wait for pending responses to sent packets.
// This is a fallback which should never be reached.
#define PENDING_RESPONSES_TIMEOUT_MS 100
#define PENDING_RESPONSES_BUSY_POLL_MS 10
// ESPNow packet format for the receive buffer.
// Use this for peeking at the header of the next packet in the buffer.
typedef struct {
uint8_t magic; // = ESPNOW_MAGIC
uint8_t msg_len; // Length of the message
uint32_t time_ms; // Timestamp (ms) when packet is received
int8_t rssi; // RSSI value (dBm) (-127 to 0)
} __attribute__((packed)) espnow_header_t;
typedef struct {
espnow_header_t header; // The header
uint8_t peer[6]; // Peer address
uint8_t msg[0]; // Message is up to 250 bytes
} __attribute__((packed)) espnow_packet_t;
static void check_esp_err(esp_err_t status) {
if (status != ESP_OK) {
mp_raise_RuntimeError(translate("an error occured"));
}
}
// Return a pointer to the ESPNow module singleton
static espnow_obj_t *_get_singleton(void) {
return MP_STATE_PORT(espnow_singleton);
}
// --- The ESP-NOW send and recv callback routines ---
// Callback triggered when a sent packet is acknowledged by the peer (or not).
// Just count the number of responses and number of failures.
// These are used in the send() logic.
static void send_cb(const uint8_t *mac, esp_now_send_status_t status) {
espnow_obj_t *self = _get_singleton();
self->tx_responses++;
if (status != ESP_NOW_SEND_SUCCESS) {
self->tx_failures++;
}
}
static inline int8_t _get_rssi_from_wifi_packet(const uint8_t *msg);
// Callback triggered when an ESP-NOW packet is received.
// Write the peer MAC address and the message into the recv_buffer as an ESPNow packet.
// If the buffer is full, drop the message and increment the dropped count.
static void recv_cb(const uint8_t *mac, const uint8_t *msg, int msg_len) {
espnow_obj_t *self = _get_singleton();
ringbuf_t *buf = self->recv_buffer;
if (sizeof(espnow_packet_t) + msg_len > ringbuf_num_empty(buf)) {
self->rx_failures++;
return;
}
espnow_header_t header;
header.magic = ESPNOW_MAGIC;
header.msg_len = msg_len;
header.rssi = _get_rssi_from_wifi_packet(msg);
header.time_ms = mp_hal_ticks_ms();
ringbuf_put_n(buf, (uint8_t *)&header, sizeof(header));
ringbuf_put_n(buf, mac, ESP_NOW_ETH_ALEN);
ringbuf_put_n(buf, msg, msg_len);
self->rx_packets++;
}
bool common_hal_espnow_deinited(espnow_obj_t *self) {
return self->recv_buffer == NULL;
}
// Initialize the ESP-NOW software stack,
// register callbacks and allocate the recv data buffers.
void common_hal_espnow_init(espnow_obj_t *self) {
if (!common_hal_espnow_deinited(self)) {
return;
}
self->recv_buffer = m_new_obj(ringbuf_t);
if (!ringbuf_alloc(self->recv_buffer, self->recv_buffer_size, true)) {
m_malloc_fail(self->recv_buffer_size);
}
if (!common_hal_wifi_radio_get_enabled(&common_hal_wifi_radio_obj)) {
common_hal_wifi_init(false);
common_hal_wifi_radio_set_enabled(&common_hal_wifi_radio_obj, true);
}
check_esp_err(esp_wifi_config_espnow_rate(ESP_IF_WIFI_STA, self->phy_rate));
check_esp_err(esp_wifi_config_espnow_rate(ESP_IF_WIFI_AP, self->phy_rate));
check_esp_err(esp_now_init());
check_esp_err(esp_now_register_send_cb(send_cb));
check_esp_err(esp_now_register_recv_cb(recv_cb));
}
// De-initialize the ESP-NOW software stack,
// disable callbacks and deallocate the recv data buffers.
void common_hal_espnow_deinit(espnow_obj_t *self) {
if (self == NULL || common_hal_espnow_deinited(self)) {
return;
}
check_esp_err(esp_now_unregister_send_cb());
check_esp_err(esp_now_unregister_recv_cb());
check_esp_err(esp_now_deinit());
self->recv_buffer->buf = NULL;
self->recv_buffer = NULL;
self->peers_count = 0; // esp_now_deinit() removes all peers.
self->tx_packets = self->tx_responses;
}
void espnow_reset(void) {
common_hal_espnow_deinit(_get_singleton());
MP_STATE_PORT(espnow_singleton) = NULL;
}
void common_hal_espnow_set_buffer_size(espnow_obj_t *self, mp_int_t value) {
self->recv_buffer_size = mp_arg_validate_int_min(value, MAX_PACKET_LEN, MP_QSTR_buffer_size);
};
void common_hal_espnow_set_phy_rate(espnow_obj_t *self, mp_int_t value) {
self->phy_rate = mp_arg_validate_int_range(value, 0, WIFI_PHY_RATE_MAX - 1, MP_QSTR_phy_rate);
};
void common_hal_espnow_set_pmk(espnow_obj_t *self, const uint8_t *key) {
check_esp_err(esp_now_set_pmk(key));
}
// --- Maintaining the peer table and reading RSSI values ---
// We maintain a peers table for several reasons, to:
// - support monitoring the RSSI values for all peers; and
// - to return unique bytestrings for each peer which supports more efficient
// application memory usage and peer handling.
// Get the RSSI value from the wifi packet header
static inline int8_t _get_rssi_from_wifi_packet(const uint8_t *msg) {
// Warning: Secret magic to get the rssi from the wifi packet header
// See espnow.c:espnow_recv_cb() at https://github.com/espressif/esp-now/
// In the wifi packet the msg comes after a wifi_promiscuous_pkt_t
// and a espnow_frame_format_t.
// Backtrack to get a pointer to the wifi_promiscuous_pkt_t.
#define SIZEOF_ESPNOW_FRAME_FORMAT 39
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-align"
wifi_promiscuous_pkt_t *wifi_packet = (wifi_promiscuous_pkt_t *)(
msg - SIZEOF_ESPNOW_FRAME_FORMAT - sizeof(wifi_promiscuous_pkt_t));
#pragma GCC diagnostic pop
return wifi_packet->rx_ctrl.rssi;
}
// Lookup a peer in the peers table and return a reference to the item in the peers_table.
// Add peer to the table if it is not found (may alloc memory). Will not return NULL.
static mp_map_elem_t *_lookup_add_peer(espnow_obj_t *self, const uint8_t *peer) {
// We do not want to allocate any new memory in the case that the peer
// already exists in the peers_table (which is almost all the time).
// So, we use a byte string on the stack and look that up in the dict.
mp_map_t *map = mp_obj_dict_get_map(self->peers_table);
mp_obj_str_t peer_obj = {{&mp_type_bytes}, 0, ESP_NOW_ETH_ALEN, peer};
mp_map_elem_t *item = mp_map_lookup(map, &peer_obj, MP_MAP_LOOKUP);
if (item == NULL) {
// If not found, add the peer using a new bytestring
map->is_fixed = 0; // Allow to modify the dict
mp_obj_t new_peer = mp_obj_new_bytes(peer, ESP_NOW_ETH_ALEN);
item = mp_map_lookup(map, new_peer, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
item->value = mp_obj_new_list(2, NULL);
map->is_fixed = 1; // Relock the dict
}
return item;
}
// Update the peers table with the new rssi value from a received packet and
// return a reference to the item in the peers_table.
static void _update_rssi(espnow_obj_t *self, const uint8_t *peer, int8_t rssi, uint32_t time_ms) {
// Lookup the peer in the device table
mp_map_elem_t *item = _lookup_add_peer(self, peer);
mp_obj_list_t *list = MP_OBJ_TO_PTR(item->value);
list->items[0] = MP_OBJ_NEW_SMALL_INT(rssi);
list->items[1] = mp_obj_new_int(time_ms);
}
// --- Send and Receive ESP-NOW data ---
// Used by espnow_send() for sends() with sync==True.
// Wait till all pending sent packet responses have been received.
// ie. self->tx_responses == self->tx_packets.
static void _wait_for_pending_responses(espnow_obj_t *self) {
mp_uint_t t, start = mp_hal_ticks_ms();
while (self->tx_responses < self->tx_packets) {
if ((t = mp_hal_ticks_ms() - start) > PENDING_RESPONSES_TIMEOUT_MS) {
mp_raise_OSError(MP_ETIMEDOUT);
}
if (t > PENDING_RESPONSES_BUSY_POLL_MS) {
// After 10ms of busy waiting give other tasks a look in.
RUN_BACKGROUND_TASKS;
}
}
}
mp_obj_t common_hal_espnow_send(espnow_obj_t *self, const bool sync, const uint8_t *mac, const mp_buffer_info_t *message) {
if (sync) {
// Flush out any pending responses.
// If the last call was sync == False there may be outstanding responses
// still to be received (possible many if we just had a burst of unsync send()s).
// We need to wait for all pending responses if this call has sync = True.
_wait_for_pending_responses(self);
}
// Send the packet - try, try again if internal esp-now buffers are full.
esp_err_t err;
size_t saved_failures = self->tx_failures;
mp_uint_t start = mp_hal_ticks_ms();
while ((ESP_ERR_ESPNOW_NO_MEM == (err = esp_now_send(mac, message->buf, message->len))) &&
(mp_hal_ticks_ms() - start) <= DEFAULT_SEND_TIMEOUT_MS) {
RUN_BACKGROUND_TASKS;
}
check_esp_err(err);
// Increment the sent packet count.
// If mac == NULL msg will be sent to all peers EXCEPT any broadcast or multicast addresses.
self->tx_packets += ((mac == NULL) ? self->peers_count : 1);
if (sync) {
// Wait for and tally all the expected responses from peers
_wait_for_pending_responses(self);
}
// Return False if sync and any peers did not respond.
return mp_obj_new_bool(!(sync && self->tx_failures != saved_failures));
}
mp_obj_t common_hal_espnow_recv(espnow_obj_t *self) {
if (!ringbuf_num_filled(self->recv_buffer)) {
return mp_const_none;
}
// Read the packet header from the incoming buffer
espnow_header_t header;
if (ringbuf_get_n(self->recv_buffer, (uint8_t *)&header, sizeof(header)) != sizeof(header)) {
mp_arg_error_invalid(MP_QSTR_buffer);
}
uint8_t msg_len = header.msg_len;
uint8_t mac_buf[ESP_NOW_ETH_ALEN];
uint8_t msg_buf[msg_len];
// Check the message packet header format and read the message data
if (header.magic != ESPNOW_MAGIC ||
msg_len > ESP_NOW_MAX_DATA_LEN ||
ringbuf_get_n(self->recv_buffer, mac_buf, ESP_NOW_ETH_ALEN) != ESP_NOW_ETH_ALEN ||
ringbuf_get_n(self->recv_buffer, msg_buf, msg_len) != msg_len) {
mp_arg_error_invalid(MP_QSTR_buffer);
}
// Update rssi value in the peer device table
_update_rssi(self, mac_buf, header.rssi, header.time_ms);
mp_obj_t elems[4] = {
mp_obj_new_bytes(mac_buf, ESP_NOW_ETH_ALEN),
mp_obj_new_bytes(msg_buf, msg_len),
MP_OBJ_NEW_SMALL_INT(header.rssi),
mp_obj_new_int(header.time_ms),
};
return namedtuple_make_new((const mp_obj_type_t *)&espnow_packet_type_obj, 4, 0, elems);
}

View File

@ -0,0 +1,57 @@
/*
* This file is part of the Micro Python project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2023 MicroDev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "py/ringbuf.h"
#include "esp_wifi.h"
// The data structure for the espnow_singleton.
typedef struct _espnow_obj_t {
mp_obj_base_t base;
ringbuf_t *recv_buffer; // A buffer for received packets
size_t recv_buffer_size; // The size of the recv_buffer
wifi_phy_rate_t phy_rate; // The ESP-NOW physical layer rate.
volatile size_t rx_packets; // # of received packets
volatile size_t rx_failures; // # of dropped packets (buffer full)
size_t tx_packets; // # of sent packets
volatile size_t tx_responses; // # of sent packet responses received
volatile size_t tx_failures; // # of sent packet responses failed
size_t peers_count; // Cache the # of peers for send(sync=True)
mp_obj_t peers_table; // A dictionary of discovered peers
} espnow_obj_t;
extern void espnow_reset(void);
extern void common_hal_espnow_init(espnow_obj_t *self);
extern void common_hal_espnow_deinit(espnow_obj_t *self);
extern bool common_hal_espnow_deinited(espnow_obj_t *self);
extern void common_hal_espnow_set_buffer_size(espnow_obj_t *self, mp_int_t value);
extern void common_hal_espnow_set_phy_rate(espnow_obj_t *self, mp_int_t value);
extern void common_hal_espnow_set_pmk(espnow_obj_t *self, const uint8_t *key);
extern mp_obj_t common_hal_espnow_send(espnow_obj_t *self, const bool sync, const uint8_t *mac, const mp_buffer_info_t *message);
extern mp_obj_t common_hal_espnow_recv(espnow_obj_t *self);