8000 esp32/espnow: Code simplification and optimisation. · micropython/micropython@f125a8e · GitHub
[go: up one dir, main page]

Skip to content

Commit f125a8e

Browse files
committed
esp32/espnow: Code simplification and optimisation.
- No more ring buffer for sent packet responses. Just count transmission failures. - Alloc and init callee-owned tuple and bytearrays (for irecv()) in the ESPnow() constructor instead of on first call to irecv(). - Better comment coverage and fixups for new code - espnow_send(): Wait on send_timeout if ESPNOW internal buffer is full - Streamline some snippets of code - Update docs for latest changes. - Revert mod_peer(key=...) to mod_peer(lmk=...) for consistency with Espressif esp32 docs. - lmk *must* be 16 bytes long now. The aim is to be more explicit about security keys. _get_bytes_max_len() is no longer needed.
1 parent 312a190 commit f125a8e

File tree

2 files changed

+193
-271
lines changed

2 files changed

+193
-271
lines changed

docs/library/espnow.rst

Lines changed: 57 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ Load this module from the :doc:`esp` module. A simple example would be:
2020

2121
e = espnow.ESPNow()
2222
e.init()
23-
peer = b'0\xae\xa4XC\xd0' # MAC address of peer's wifi interface
23+
peer = b'\xbb\xbb\xbb\xbb\xbb\xbb' # MAC address of peer's wifi interface
2424
e.add_peer(peer)
2525

2626
e.send("Starting...") # Send to all peers
@@ -39,7 +39,7 @@ Load this module from the :doc:`esp` module. A simple example would be:
3939

4040
e = espnow.ESPNow()
4141
e.init()
42-
peer = b'0\xae\xa4XC\xa0' # MAC address of peer's wifi interface
42+
peer = b'\xaa\xaa\xaa\xaa\xaa\xaa' # MAC address of peer's wifi interface
4343
e.add_peer(peer)
4444

4545
print(e.irecv())
@@ -70,14 +70,14 @@ Configuration
7070
protocol, including:
7171

7272
- initialise the ESPNow data structures,
73-
- allocate the send and recv data buffers,
73+
- allocate the recv data buffer,
7474
- invoke esp_now_init() and
7575
- register the send and recv callbacks.
7676

7777
.. method:: ESPNow.deinit()
7878

79-
De-initialise the Espressif ESPNow software stack (esp_now_deinit()), disable
80-
the interrupt callbacks and deallocate the send and recv data buffers.
79+
De-initialise the Espressif ESPNow software stack (esp_now_deinit()),
80+
disable callbacks and deallocate the recv data buffer.
8181

8282
**Note**: `deinit()` will also deregister all peers which must be
8383
re-registered after `init()`.
@@ -89,24 +89,18 @@ Configuration
8989
Get or set configuration values of the ESPNow interface. To get a value the
9090
parameter name should be quoted as a string, and just one parameter is
9191
queried at a time. To set values use the keyword syntax, and one or more
92-
parameters can be set at a time. Invocation with no arguments will return a
93-
dict of all parameter names and values.
92+
parameters can be set at a time.
9493

9594
Currently supported values are:
9695

97-
- ``txbuf``: *(default=140)* Get/set the size in bytes of the internal
98-
buffer used to store send response data. Increasing this allows better
99-
handling of bursty outgoing/incoming data.
100-
101-
- ``rxbuf``: *(default=514)* Get/set the size in bytes of the internal
96+
- ``rxbuf``: *(default=516)* Get/set the size in bytes of the internal
10297
buffer used to store incoming ESPNow packet data. The default size is
103-
selected to fit two
104-
max-sized ESPNow packets (250 bytes) with associated mac_address (6 bytes)
105-
and a message byte count (1 byte) plus buffer overhead. Increase this if
106-
you expect to receive a lot of large packets or expect bursty incoming
107-
traffic.
98+
selected to fit two max-sized ESPNow packets (250 bytes) with associated
99+
mac_address (6 bytes) and a message byte count (1 byte) plus buffer
100+
overhead. Increase this if you expect to receive a lot of large packets
101+
or expect bursty incoming traffic.
108102

109-
**Note:** The send and recv buffers are only allocated by `ESPNow.init()`.
103+
**Note:** The recv buffer is only allocated by `ESPNow.init()`.
110104
Changing these values will have no effect until the next call of
111105
`ESPNow.init()`.
112106

@@ -115,7 +109,7 @@ Configuration
115109

116110
.. method:: ESPNow.clear(True)
117111

118-
Clear out any data in the recv (and send-response) buffers. Use this to clean
112+
Clear out any data in the recv buffer. Use this to clean
119113
up after receiving a ``Buffer error`` (should not happen). All data in the
120114
buffers will be discarded. An arg of `True` is required to guard against
121115
inadvertent use.
@@ -131,34 +125,43 @@ Sending and Receiving Data
131125
--------------------------
132126

133127
A wifi interface (``network.STA_IF`` or ``network.AP_IF``) must be
134-
`active()<network.WLAN.active>`
135-
before messages can be sent or received, but it is not necessary to connect or
136-
configure the WLAN interface. For example::
128+
`active()<network.WLAN.active>` before messages can be sent or received,
129+
but it is not necessary to connect or configure the WLAN interface.
130+
For example::
137131

138132
import network
139133

140134
w0 = network.WLAN(network.STA_IF)
141135
w0.active(True)
142136

143-
.. method:: ESPNow.send(mac, msg, [sync])
137+
.. method:: ESPNow.send(mac, msg, [sync=True])
138+
ESPNow.send(msg)
144139

145140
Send the data contained in ``msg`` to the peer with given network ``mac``
146-
address. ``mac` 629A ` must be a byte string exactly 6 bytes long and ``msg`` must
147-
be a string or byte-string such that ``0<len(msg)<=espnow.MAX_DATA_LEN``
148-
(250) bytes. If ``mac`` is ``None`` the message will be sent to all
149-
registered peers as an ESP-Now broadcast.
141+
address. In the second form, ``mac=None`` and ``sync=True``.
142+
143+
Arguments:
150144

151-
- If ``sync=True`` send ``msg`` to the peer and wait for a response (or not).
152-
Returns ``False`` if any peers fail to respond.
145+
- ``mac``: byte string exactly 6 bytes long or ``None``
146+
- ``msg``: string or byte-string such that
147+
``0<len(msg)<=espnow.MAX_DATA_LEN`` (250) bytes
148+
- ``sync``:
153149

154-
- If ``sync=False`` handover ``msg`` to the esp_now software stack for
155-
transmission and return immediately.
156-
Responses from the peers will be discarded.
157-
Always returns ``True``.
150+
- ``True``: (default) send ``msg`` to the peer and wait for a response
151+
(or not). Returns ``False`` if any peers fail to respond.
152+
153+
- ``False`` handover ``msg`` to the esp_now software stack for
154+
transmission and return immediately.
155+
Responses from the peers will be discarded.
156+
Always returns ``True``.
157+
158+
If ``mac`` is ``None`` the message will be sent to all
159+
registered peers as an ESP-Now broadcast.
158160

159161
**Note**: A peer will respond with success if it's wifi interface is
160-
active(), regardless of whether it has initialised it's ESP-Now system or
161-
is actively listening for ESP-Now traffic (see the Espressif ESP-Now docs).
162+
active() and set to the same channel as the sender, regardless of whether
163+
it has initialised it's ESP-Now system or is actively listening for ESP-Now
164+
traffic (see the Espressif ESP-Now docs).
162165

163166
.. method:: ESPNow.recv([timeout])
164167

@@ -169,30 +172,36 @@ configure the WLAN interface. For example::
169172

170173
- ``msg`` is the message/data sent from the peer.
171174

172-
``Timeout`` optionally sets a timeout (in milliseconds) for the read. The
175+
``timeout`` optionally sets a timeout (in milliseconds) for the read. The
173176
default timeout can be set in `ESPNow.config()`.
174177

175-
**Note**: repeatedly calling `irecv()<ESPNow.send()>` will exercise the
176-
micropython garbage collection as new storage is allocated for each new< F438 /div>
178+
**Note**: repeatedly calling `recv()<ESPNow.recv()>` will exercise the
179+
micropython memory allocation as new storage is allocated for each new
177180
message and tuple. Use `irecv()<ESPNow.irecv()>`
178181
for a more memory-efficient option.
179182

180183
.. method:: ESPNow.irecv([timeout])
181184

182185
As for `recv()<ESPNow.recv()>` except that ``irecv()`` will return a
183-
"callee-owned" tuple.
184-
That is, memory will be allocated for the tuple and byte strings on the
185-
first call and re-used for subsequent calls. You must make copies if you
186+
"callee-owned" tuple of bytearrays.
187+
That is, memory will be allocated once for the tuple and byte strings on
188+
invocation of espnow.ESPNow() and re-used for subsequent calls to
189+
`irecv()<ESPNow.irecv()>`. You must make copies if you
186190
wish to keep the values across calls to ``irecv()``.
187191

188192
.. method:: ESPNow.stats()
189193

190-
Return a 4-tuple containing the number of packets sent/received/lost:
191-
``(sent_packets, send_responses, recv_packets, lost_rx_packets)``. Packets
192-
are *lost* when the recv buffers are full. To reduce packet loss,
193-
increase the ``txbuf`` and ``rxbuf`` config parameters and ensure you are
194+
Return a 5-tuple containing the number of packets sent/received/lost::
195+
196+
(sent_packets, sent_responses, sent_failures, recv_packets, lost_rx_packets)
197+
198+
Incoming packets are *dropped* when the recv buffers are full. To reduce
199+
packet loss, increase the ``rxbuf`` config parameters and ensure you are
194200
in a tight loop calling `irecv()<ESPNow.irecv()>` as quickly as possible.
195201

202+
**Note**: Dropped packets will still be acknowledged to the sender as
203+
received.
204+
196205
Iteration over ESPNow
197206
---------------------
198207

@@ -209,8 +218,8 @@ for a message.
209218
Peer Management
210219
---------------
211220

212-
The ESP-Now protocol requires that other devices (peers) must be *registered*
213-
before we can `send()<ESPNow.send()>` them messages.
221+
The Esspresif ESP-Now software requires that other devices (peers) must be
222+
*registered* before we can `send()<ESPNow.send()>` them messages.
214223

215224
.. method:: ESPNow.add_peer(mac, [lmk], [channel], [ifidx], [encrypt])
216225
ESPNow.add_peer(mac, 'param'=value, ...)
@@ -222,8 +231,7 @@ before we can `send()<ESPNow.send()>` them messages.
222231
- ``lmk``: The Local Master Key (LMK) key used to encrypt data transfers
223232
with this peer (if the *encrypt* parameter is set to *True*). Must be:
224233

225-
- a byte-string of length ``<= espnow.KEY_LEN`` (16 bytes) (the key will be
226-
padded to the right with zeroes), or
234+
- a byte-string of length ``espnow.KEY_LEN`` (16 bytes), or
227235
- any non-`True` python value (default= ``b''``), signifying an *empty* key
228236
which will disable encryption.
229237

0 commit comments

Comments
 (0)
0