Merges led-simulator (sim-bridge, 4d8aeb5) under led-simulator/ with its history,
in place of the submodule.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
80 lines
2.3 KiB
Python
80 lines
2.3 KiB
Python
"""MicroPython ``espnow`` stub for led-simulator (Pyodide).
|
|
|
|
Packets go to and from the simulated bridge through ``_simlink``. ``irq()`` is
|
|
not supported, so ``main.py`` falls back to polling ``any()`` / ``recv(0)`` in
|
|
its main loop, as it does on boards without the irq callback.
|
|
"""
|
|
|
|
import _simlink
|
|
|
|
MAX_DATA_LEN = 250
|
|
ESP_ERR_ESPNOW_EXIST = -12395
|
|
ESP_ERR_ESPNOW_NOT_FOUND = -12393
|
|
|
|
_BROADCAST = b"\xff\xff\xff\xff\xff\xff"
|
|
|
|
|
|
class ESPNow:
|
|
def __init__(self):
|
|
self._active = False
|
|
self._peers = set()
|
|
self._timeout_ms = 300000
|
|
|
|
def active(self, flag=None):
|
|
if flag is None:
|
|
return self._active
|
|
self._active = bool(flag)
|
|
return self._active
|
|
|
|
def config(self, *args, **kwargs):
|
|
if "timeout_ms" in kwargs:
|
|
self._timeout_ms = int(kwargs["timeout_ms"])
|
|
return None
|
|
|
|
def add_peer(self, mac, *args, **kwargs):
|
|
mac = bytes(mac)
|
|
if mac in self._peers:
|
|
raise OSError(ESP_ERR_ESPNOW_EXIST, "ESP_ERR_ESPNOW_EXIST")
|
|
self._peers.add(mac)
|
|
|
|
def del_peer(self, mac):
|
|
mac = bytes(mac)
|
|
if mac not in self._peers:
|
|
raise OSError(ESP_ERR_ESPNOW_NOT_FOUND, "ESP_ERR_ESPNOW_NOT_FOUND")
|
|
self._peers.discard(mac)
|
|
|
|
def get_peers(self):
|
|
return tuple((m, b"", 0, 0, False) for m in self._peers)
|
|
|
|
def send(self, mac, msg=None, sync=True):
|
|
if msg is None:
|
|
# send(msg): to every registered peer
|
|
msg, dests = mac, list(self._peers) or [_BROADCAST]
|
|
else:
|
|
dests = [_BROADCAST if mac is None else bytes(mac)]
|
|
if isinstance(msg, str):
|
|
msg = msg.encode("utf-8")
|
|
msg = bytes(msg)
|
|
if len(msg) > MAX_DATA_LEN:
|
|
raise ValueError("ESP_ERR_ESPNOW_ARG")
|
|
for dest in dests:
|
|
_simlink.send_tx(dest, msg)
|
|
return True
|
|
|
|
def recv(self, timeout_ms=None):
|
|
if timeout_ms is None:
|
|
timeout_ms = self._timeout_ms
|
|
return _simlink.recv(timeout_ms)
|
|
|
|
irecv = recv
|
|
|
|
def any(self):
|
|
return _simlink.pending() > 0
|
|
|
|
def irq(self, callback):
|
|
# main.py treats AttributeError as "firmware without irq support" and polls instead
|
|
raise AttributeError("espnow irq not available in led-simulator (polling)")
|
|
|
|
def stats(self):
|
|
return (0, 0, 0, 0, 0)
|