feat(espnow): reliable link and beat trigger on the 0x4C protocol
Adds the driver half of the v2 controller link as extra 0x4C message types: DATA with fragment reassembly, de-duplication and acks, a state-version digest with jittered resync requests, a bench echo, and a BEAT frame handled by BeatSync (accepts one of the two copies, free-runs on the last period when a beat is missed). Presets.beat() steps the selected pattern without a message. Optional settings: espnow_loss, bench, beat_pin, usb_log. The working tree also carries the files already running on the bench device, which were ahead of origin/p2p: board.py (per-chip LED pin and CPU speed), the reversed device_config flag in controller_messages.py, and the apply_cpu_freq call in main.py. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3286c4002d
commit
20d1af7177
8 files changed
+642
-11
No files matched your search
@@ -0,0 +1,174 @@
|
||||
"""Reliable-link extension of the 0x4C ESP-NOW protocol (driver side).
|
||||
|
||||
Extra message types, all inside the existing wire magic 0x4C:
|
||||
0x20 DATA [4C][20][flags][seq u16][ver u16][idx][cnt] + fragment of an inner packet
|
||||
flags: 1 = ack wanted, 2 = commit (record ver once complete)
|
||||
The inner packet is any normal packet (4C 03 CMD, 4C 04 GROUP_CMD, 4C 02 GROUPS, or JSON).
|
||||
0x21 ACK [4C][21][0][seq u16][cnt][mask u32] driver -> controller
|
||||
0x22 DIGEST [4C][22][ver u16] controller broadcast
|
||||
0x23 RESYNC [4C][23][ver u16] driver -> controller
|
||||
0x24 ECHO [4C][24][beat_idx u16] driver -> controller, bench only
|
||||
0x25 BEAT [4C][25][flags][idx u16][period u16][fire_in] handled by BeatSync
|
||||
Everything else (announce, groups, cmd, group cmd, plain JSON) goes straight to the handler.
|
||||
"""
|
||||
import struct
|
||||
|
||||
WIRE_MAGIC = 0x4C
|
||||
MSG_DATA = 0x20
|
||||
MSG_ACK = 0x21
|
||||
MSG_DIGEST = 0x22
|
||||
MSG_RESYNC = 0x23
|
||||
MSG_ECHO = 0x24
|
||||
MSG_BEAT = 0x25
|
||||
LINK_TYPES = (MSG_DATA, MSG_DIGEST)
|
||||
F_ACK = 1
|
||||
F_COMMIT = 2
|
||||
HDR = 9
|
||||
|
||||
INBOX_MAX = 16
|
||||
DONE_MAX = 16
|
||||
ASM_TIMEOUT_MS = 3000
|
||||
RESYNC_MIN_GAP_MS = 3000
|
||||
|
||||
|
||||
def _due(now, t):
|
||||
return (now - t) & 0x7FFFFFFF < 0x40000000
|
||||
|
||||
|
||||
class LinkRx:
|
||||
def __init__(self, handler, beat, send=None, jitter_ms=0, rand=None):
|
||||
self.handler = handler # handler(mac, packet_bytes)
|
||||
self.beat = beat # BeatSync
|
||||
self.send = send # send(mac, frame)
|
||||
self.jitter_ms = jitter_ms # spreads resync requests across drivers
|
||||
self.ver = 0
|
||||
self.master = None
|
||||
self.inbox = []
|
||||
self.asm = {}
|
||||
self.done = []
|
||||
self.resync_at = None
|
||||
self.last_resync = None
|
||||
self.loss_pct = 0 # lossy-link test: drop this percentage of received frames
|
||||
self.loss_beats = True
|
||||
self.rand = rand # rand() -> 0..99; defaults to the random module
|
||||
self.stats = {"msgs": 0, "dups": 0, "acks": 0, "resyncs": 0, "dropped": 0, "sim_lost": 0}
|
||||
|
||||
def on_packet(self, mac, data, now):
|
||||
"""Call for every received frame (irq or main loop). Beats are handled here; the rest is queued."""
|
||||
if not data:
|
||||
return
|
||||
is_beat = len(data) > 1 and data[0] == WIRE_MAGIC and data[1] == MSG_BEAT
|
||||
if self.loss_pct and (self.loss_beats or not is_beat) and self._rand() < self.loss_pct:
|
||||
self.stats["sim_lost"] += 1
|
||||
return
|
||||
if is_beat:
|
||||
self.beat.on_frame(data, now)
|
||||
elif len(self.inbox) < INBOX_MAX:
|
||||
self.inbox.append((bytes(mac), bytes(data)))
|
||||
else:
|
||||
self.stats["dropped"] += 1
|
||||
|
||||
def _rand(self):
|
||||
if self.rand is None:
|
||||
import random
|
||||
|
||||
self.rand = lambda: random.getrandbits(16) % 100
|
||||
return self.rand()
|
||||
|
||||
def echo(self, idx):
|
||||
"""Tell the controller we just fired beat idx (bench measurement only)."""
|
||||
if self.send and self.master:
|
||||
self.send(self.master, struct.pack("<BBH", WIRE_MAGIC, MSG_ECHO, idx))
|
||||
|
||||
def poll(self, now):
|
||||
"""Process queued frames. Call from the main loop."""
|
||||
while self.inbox:
|
||||
mac, data = self.inbox.pop(0)
|
||||
if len(data) > 1 and data[0] == WIRE_MAGIC and data[1] == MSG_DATA:
|
||||
self._data(mac, data, now)
|
||||
elif len(data) > 1 and data[0] == WIRE_MAGIC and data[1] == MSG_DIGEST:
|
||||
self._digest(mac, data, now)
|
||||
else:
|
||||
self.handler(mac, data)
|
||||
if self.resync_at is not None and _due(now, self.resync_at):
|
||||
self.resync_at = None
|
||||
self._send_resync(now)
|
||||
if self.asm:
|
||||
for k in [k for k, e in self.asm.items() if now - e[3] > ASM_TIMEOUT_MS]:
|
||||
del self.asm[k]
|
||||
|
||||
def _ack(self, mac, seq, cnt, mask):
|
||||
if self.send:
|
||||
self.send(mac, struct.pack("<BBBHBI", WIRE_MAGIC, MSG_ACK, 0, seq, cnt, mask))
|
||||
self.stats["acks"] += 1
|
||||
|
||||
def _data(self, mac, data, now):
|
||||
if len(data) <= HDR:
|
||||
return
|
||||
_, _, flags, seq, ver, idx, cnt = struct.unpack("<BBBHHBB", data[:HDR])
|
||||
if cnt == 0 or cnt > 32 or idx >= cnt:
|
||||
return
|
||||
self.master = mac
|
||||
key = (mac, seq)
|
||||
full = (1 << cnt) - 1 if cnt < 32 else 0xFFFFFFFF
|
||||
if key in self.done:
|
||||
self.stats["dups"] += 1
|
||||
if flags & F_ACK:
|
||||
self._ack(mac, seq, cnt, full) # our earlier ack was lost
|
||||
return
|
||||
e = self.asm.get(key)
|
||||
if e is None:
|
||||
e = self.asm[key] = [cnt, 0, [None] * cnt, now, flags, ver]
|
||||
e[1] |= 1 << idx
|
||||
e[2][idx] = data[HDR:]
|
||||
e[3] = now
|
||||
if flags & F_ACK:
|
||||
self._ack(mac, seq, cnt, e[1])
|
||||
if e[1] != full:
|
||||
return
|
||||
del self.asm[key]
|
||||
self.done.append(key)
|
||||
if len(self.done) > DONE_MAX:
|
||||
self.done.pop(0)
|
||||
msg = e[2][0] if cnt == 1 else b"".join(e[2])
|
||||
self.stats["msgs"] += 1
|
||||
self.handler(mac, msg)
|
||||
if flags & F_COMMIT and ver:
|
||||
self.ver = ver
|
||||
self.resync_at = None
|
||||
|
||||
def _digest(self, mac, data, now):
|
||||
if len(data) < 4:
|
||||
return
|
||||
self.master = mac
|
||||
ver = struct.unpack("<H", data[2:4])[0]
|
||||
if ver == 0 or ver == self.ver or self.resync_at is not None:
|
||||
return
|
||||
if self.last_resync is not None and now - self.last_resync < RESYNC_MIN_GAP_MS:
|
||||
return
|
||||
self.resync_at = now + self.jitter_ms
|
||||
|
||||
def _send_resync(self, now):
|
||||
if self.send and self.master:
|
||||
self.last_resync = now
|
||||
self.stats["resyncs"] += 1
|
||||
self.send(self.master, struct.pack("<BBH", WIRE_MAGIC, MSG_RESYNC, self.ver))
|
||||
|
||||
|
||||
def make_sender(esp):
|
||||
"""send(mac, frame) for an espnow.ESPNow instance, adding the peer on first use."""
|
||||
peers = set()
|
||||
|
||||
def send(mac, frame):
|
||||
if mac not in peers:
|
||||
try:
|
||||
esp.add_peer(mac)
|
||||
except OSError:
|
||||
pass
|
||||
peers.add(mac)
|
||||
try:
|
||||
esp.send(mac, frame, False)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
return send
|
||||
Reference in new issue
Block a user