Compare commits
14
Commits
main
..
495da4e366
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
495da4e366 | ||
|
|
940d1d0a77 | ||
|
|
20d1af7177 | ||
|
|
3286c4002d | ||
|
|
68eb547ec4 | ||
|
|
8403df531d | ||
|
|
088fe161a8 | ||
|
|
c9895df512 | ||
|
|
39a84696c3 | ||
|
|
c7560b2e87 | ||
|
|
ea21563900 | ||
|
|
a97f6c7c2c | ||
|
|
1fdb2c9441 | ||
|
|
3e718f7432 |
No files matched your search
@@ -0,0 +1,8 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
PORT="${1:-/dev/ttyACM0}"
|
||||||
|
|
||||||
|
while true; do
|
||||||
|
ls "$PORT" && led-cli -p "$PORT" --erase --src --patterns && led-cli -p "$PORT" --reset -f
|
||||||
|
sleep 0.5
|
||||||
|
done
|
||||||
@@ -1,11 +1,7 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import utime
|
import utime
|
||||||
|
|
||||||
from hello import broadcast_hello_udp
|
|
||||||
from mem_stats import print_mem
|
from mem_stats import print_mem
|
||||||
from wifi_sta import try_reconnect
|
|
||||||
|
|
||||||
_UDP_HELLO_ATTEMPT = 0
|
|
||||||
|
|
||||||
|
|
||||||
async def presets_loop(presets, wdt):
|
async def presets_loop(presets, wdt):
|
||||||
@@ -18,41 +14,4 @@ async def presets_loop(presets, wdt):
|
|||||||
if utime.ticks_diff(now, last_mem_log) >= 5000:
|
if utime.ticks_diff(now, last_mem_log) >= 5000:
|
||||||
print_mem("runtime")
|
print_mem("runtime")
|
||||||
last_mem_log = now
|
last_mem_log = now
|
||||||
# tick() does not await; yield so UDP hello and HTTP/WebSocket can run.
|
|
||||||
await asyncio.sleep(0)
|
await asyncio.sleep(0)
|
||||||
|
|
||||||
|
|
||||||
async def udp_hello_loop_after_http_ready(sta_if, settings, wdt, runtime_state):
|
|
||||||
"""UDP hello on cadence; if STA drops, one reconnect campaign per iteration."""
|
|
||||||
global _UDP_HELLO_ATTEMPT
|
|
||||||
await asyncio.sleep(1)
|
|
||||||
started_ms = utime.ticks_ms()
|
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
wifi_ok = sta_if.isconnected()
|
|
||||||
except Exception:
|
|
||||||
wifi_ok = False
|
|
||||||
if not wifi_ok:
|
|
||||||
ssid = settings.get("ssid") or ""
|
|
||||||
if ssid:
|
|
||||||
try_reconnect(sta_if, ssid, settings.get("password") or "", wdt)
|
|
||||||
try:
|
|
||||||
wifi_ok = sta_if.isconnected()
|
|
||||||
except Exception:
|
|
||||||
wifi_ok = False
|
|
||||||
if wifi_ok and runtime_state.hello:
|
|
||||||
_UDP_HELLO_ATTEMPT += 1
|
|
||||||
print("UDP hello broadcast attempt", _UDP_HELLO_ATTEMPT)
|
|
||||||
try:
|
|
||||||
broadcast_hello_udp(
|
|
||||||
sta_if,
|
|
||||||
settings.get("name", ""),
|
|
||||||
wait_reply=False,
|
|
||||||
wdt=wdt,
|
|
||||||
dual_destinations=True,
|
|
||||||
)
|
|
||||||
except Exception as ex:
|
|
||||||
print("UDP hello broadcast failed:", ex)
|
|
||||||
elapsed_ms = utime.ticks_diff(utime.ticks_ms(), started_ms)
|
|
||||||
interval_s = 10 if elapsed_ms < 120000 else 30
|
|
||||||
await asyncio.sleep(interval_s)
|
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import struct
|
||||||
|
|
||||||
|
WIRE_MAGIC = 0x4C
|
||||||
|
MSG_BEAT = 0x25
|
||||||
|
FRAME_LEN = 8 # [4C][25][flags][idx u16][period u16][fire_in]
|
||||||
|
MIN_GUARD_MS = 30
|
||||||
|
FREERUN_MISS_MAX = 4
|
||||||
|
|
||||||
|
|
||||||
|
def _diff(a, b):
|
||||||
|
return (a - b) & 0xFFFF
|
||||||
|
|
||||||
|
|
||||||
|
class BeatSync:
|
||||||
|
"""Turns beat frames from the controller into step triggers.
|
||||||
|
|
||||||
|
The controller sends every beat twice with the same index; only the first
|
||||||
|
copy that arrives is acted on. Between frames the driver free-runs on the
|
||||||
|
last period so a lost beat is not noticed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.last_idx = None
|
||||||
|
self.period = 0
|
||||||
|
self.last_fire = 0
|
||||||
|
self.fire_at = None
|
||||||
|
self.downbeat = False
|
||||||
|
self.bar = 0
|
||||||
|
self.missed = 0
|
||||||
|
self.freerun_fire = False # True when the last fire was invented, not triggered by a frame
|
||||||
|
# fires: beats acted on; dups: second copies dropped; late: too-soon or old frames;
|
||||||
|
# freerun: beats the driver made up because no frame arrived
|
||||||
|
self.stats = {"fires": 0, "dups": 0, "late": 0, "freerun": 0}
|
||||||
|
|
||||||
|
def on_frame(self, data, now):
|
||||||
|
"""Handle one received frame. Call from the ESP-NOW irq: no allocation beyond unpack."""
|
||||||
|
if len(data) != FRAME_LEN or data[0] != WIRE_MAGIC or data[1] != MSG_BEAT:
|
||||||
|
return False
|
||||||
|
flags, idx, period, fire_in = struct.unpack_from("<BHHB", data, 2)
|
||||||
|
if self.last_idx is not None:
|
||||||
|
if idx == self.last_idx:
|
||||||
|
self.stats["dups"] += 1
|
||||||
|
return False # second copy of a beat we already took
|
||||||
|
guard = max(MIN_GUARD_MS, self.period // 2)
|
||||||
|
if _diff(idx, self.last_idx) >= 0x8000 or (
|
||||||
|
self.fire_at is None and now - self.last_fire < guard and self.period
|
||||||
|
):
|
||||||
|
self.stats["late"] += 1
|
||||||
|
return False # late copy of an older beat, or too soon after the last one
|
||||||
|
self.last_idx = idx
|
||||||
|
self.period = period
|
||||||
|
self.downbeat = bool(flags & 1)
|
||||||
|
self.bar = (flags >> 1) & 7
|
||||||
|
self.fire_at = now + fire_in
|
||||||
|
self.missed = 0
|
||||||
|
return True
|
||||||
|
|
||||||
|
def poll(self, now):
|
||||||
|
"""True when a beat should step the pattern now. Call every tick."""
|
||||||
|
if self.fire_at is not None:
|
||||||
|
if now - self.fire_at >= 0:
|
||||||
|
self.fire_at = None
|
||||||
|
self.last_fire = now
|
||||||
|
self.freerun_fire = False
|
||||||
|
self.stats["fires"] += 1
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
if self.period and self.last_idx is not None and self.missed < FREERUN_MISS_MAX:
|
||||||
|
if now - (self.last_fire + self.period + self.period // 4) >= 0:
|
||||||
|
self.last_fire += self.period
|
||||||
|
self.missed += 1
|
||||||
|
self.freerun_fire = True
|
||||||
|
self.stats["fires"] += 1
|
||||||
|
self.stats["freerun"] += 1
|
||||||
|
return True
|
||||||
|
return False
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"""ESP32-C3 and ESP32-S3 differences for the LED driver.
|
||||||
|
|
||||||
|
Seeed XIAO silk-screen D10 is GPIO 10 on the C3 and GPIO 9 on the S3.
|
||||||
|
Fresh settings use that pad. A saved ``led_pin`` is left unchanged.
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
import uos as os
|
||||||
|
except ImportError:
|
||||||
|
import os
|
||||||
|
|
||||||
|
import machine
|
||||||
|
|
||||||
|
_LED_PIN_C3 = 10
|
||||||
|
_LED_PIN_S3 = 9
|
||||||
|
_CPU_HZ_C3 = 160000000
|
||||||
|
_CPU_HZ_S3 = 240000000
|
||||||
|
|
||||||
|
|
||||||
|
def mcu():
|
||||||
|
"""Return ``s3``, ``c3``, or ``""`` when the chip is neither."""
|
||||||
|
name = os.uname().machine.upper().replace("-", "")
|
||||||
|
if "ESP32S3" in name:
|
||||||
|
return "s3"
|
||||||
|
if "ESP32C3" in name:
|
||||||
|
return "c3"
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def default_led_pin():
|
||||||
|
if mcu() == "s3":
|
||||||
|
return _LED_PIN_S3
|
||||||
|
return _LED_PIN_C3
|
||||||
|
|
||||||
|
|
||||||
|
def apply_cpu_freq():
|
||||||
|
"""C3 maximum is 160 MHz. S3 (XIAO firmware) runs at 240 MHz."""
|
||||||
|
if mcu() == "s3":
|
||||||
|
machine.freq(_CPU_HZ_S3)
|
||||||
|
else:
|
||||||
|
machine.freq(_CPU_HZ_C3)
|
||||||
+148
-14
@@ -2,7 +2,11 @@
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
import socket
|
import socket
|
||||||
|
import network
|
||||||
|
import ubinascii
|
||||||
|
|
||||||
|
import device_groups as dg
|
||||||
|
from v1_wire import expand_v1
|
||||||
from binary_envelope import parse_binary_envelope
|
from binary_envelope import parse_binary_envelope
|
||||||
from utils import convert_and_reorder_colors
|
from utils import convert_and_reorder_colors
|
||||||
|
|
||||||
@@ -40,8 +44,8 @@ def _log_rx(payload) -> None:
|
|||||||
print("rx (logging failed)")
|
print("rx (logging failed)")
|
||||||
|
|
||||||
|
|
||||||
def process_data(payload, settings, presets, controller_ip=None):
|
def process_data(payload, settings, presets, controller_ip=None, save=False):
|
||||||
"""Read one controller message; binary v1 envelope or JSON v1, then apply fields."""
|
"""Read one controller message; binary v2 envelope or JSON v1, then apply fields."""
|
||||||
_log_rx(payload)
|
_log_rx(payload)
|
||||||
data = None
|
data = None
|
||||||
if isinstance(payload, (bytes, bytearray)):
|
if isinstance(payload, (bytes, bytearray)):
|
||||||
@@ -58,6 +62,18 @@ def process_data(payload, settings, presets, controller_ip=None):
|
|||||||
return
|
return
|
||||||
if data.get("v", "") != "1":
|
if data.get("v", "") != "1":
|
||||||
return
|
return
|
||||||
|
data = expand_v1(data)
|
||||||
|
if save:
|
||||||
|
data["save"] = True
|
||||||
|
set_groups = bool(data.get("set_groups"))
|
||||||
|
groups = data.get("groups")
|
||||||
|
if set_groups and isinstance(groups, list):
|
||||||
|
dg.groups_replace(groups, settings)
|
||||||
|
print("groups set", dg.list_groups())
|
||||||
|
elif isinstance(groups, list) and groups:
|
||||||
|
if not any(dg.in_group(str(g)) for g in groups):
|
||||||
|
print("ignored: not in groups", groups)
|
||||||
|
return
|
||||||
if "device_config" in data:
|
if "device_config" in data:
|
||||||
apply_device_config(data, settings, presets)
|
apply_device_config(data, settings, presets)
|
||||||
if "b" in data:
|
if "b" in data:
|
||||||
@@ -66,7 +82,7 @@ def process_data(payload, settings, presets, controller_ip=None):
|
|||||||
apply_presets(data, settings, presets)
|
apply_presets(data, settings, presets)
|
||||||
if "clear_presets" in data:
|
if "clear_presets" in data:
|
||||||
apply_clear_presets(data, presets)
|
apply_clear_presets(data, presets)
|
||||||
if "select" in data:
|
if ("select" in data or "s" in data) and "presets" not in data:
|
||||||
apply_select(data, settings, presets)
|
apply_select(data, settings, presets)
|
||||||
if "default" in data:
|
if "default" in data:
|
||||||
apply_default(data, settings, presets)
|
apply_default(data, settings, presets)
|
||||||
@@ -80,6 +96,7 @@ def process_data(payload, settings, presets, controller_ip=None):
|
|||||||
settings.save()
|
settings.save()
|
||||||
if "save" in data and "device_config" in data:
|
if "save" in data and "device_config" in data:
|
||||||
settings.save()
|
settings.save()
|
||||||
|
_flush_pending_select(settings, presets)
|
||||||
|
|
||||||
|
|
||||||
_VALID_DEVICE_COLOR_ORDERS = frozenset({"rgb", "rbg", "grb", "gbr", "brg", "bgr"})
|
_VALID_DEVICE_COLOR_ORDERS = frozenset({"rgb", "rbg", "grb", "gbr", "brg", "bgr"})
|
||||||
@@ -108,6 +125,21 @@ def apply_startup_pattern(settings, presets):
|
|||||||
print("Startup preset failed (invalid pattern?):", dp)
|
print("Startup preset failed (invalid pattern?):", dp)
|
||||||
|
|
||||||
|
|
||||||
|
def _config_flag(value):
|
||||||
|
"""Parse a device_config boolean. None if the value is not a flag."""
|
||||||
|
if isinstance(value, bool):
|
||||||
|
return value
|
||||||
|
if isinstance(value, int) and not isinstance(value, bool):
|
||||||
|
return value != 0
|
||||||
|
if isinstance(value, str):
|
||||||
|
s = value.strip().lower()
|
||||||
|
if s in ("1", "true", "yes", "on"):
|
||||||
|
return True
|
||||||
|
if s in ("0", "false", "no", "off"):
|
||||||
|
return False
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def apply_device_config(data, settings, presets):
|
def apply_device_config(data, settings, presets):
|
||||||
"""Apply fields from v1 ``device_config``; reload presets when strip length or colour order changes."""
|
"""Apply fields from v1 ``device_config``; reload presets when strip length or colour order changes."""
|
||||||
dc = data.get("device_config")
|
dc = data.get("device_config")
|
||||||
@@ -140,6 +172,12 @@ def apply_device_config(data, settings, presets):
|
|||||||
if sm in _STARTUP_MODES:
|
if sm in _STARTUP_MODES:
|
||||||
settings["startup_mode"] = sm
|
settings["startup_mode"] = sm
|
||||||
meta_changed = True
|
meta_changed = True
|
||||||
|
if "reversed" in dc:
|
||||||
|
flag = _config_flag(dc["reversed"])
|
||||||
|
if flag is not None:
|
||||||
|
settings["reversed"] = flag
|
||||||
|
presets.reversed = flag
|
||||||
|
meta_changed = True
|
||||||
if not strip_changed and not meta_changed:
|
if not strip_changed and not meta_changed:
|
||||||
return
|
return
|
||||||
if strip_changed:
|
if strip_changed:
|
||||||
@@ -164,13 +202,53 @@ def record_last_preset(settings, preset_name):
|
|||||||
|
|
||||||
def apply_brightness(data, settings, presets):
|
def apply_brightness(data, settings, presets):
|
||||||
try:
|
try:
|
||||||
presets.b = max(0, min(255, int(data["b"])))
|
new_b = max(0, min(255, int(data["b"])))
|
||||||
settings["brightness"] = presets.b
|
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
pass
|
return
|
||||||
|
changed = int(presets.b) != new_b
|
||||||
|
presets.b = new_b
|
||||||
|
settings["brightness"] = new_b
|
||||||
|
# A finished manual chase frame keeps the colours scaled at the last beat.
|
||||||
|
# Skip when this message also selects: that select redraws after ``b`` is set.
|
||||||
|
if not changed or presets.generator is not None:
|
||||||
|
return
|
||||||
|
if "select" in data or "s" in data:
|
||||||
|
return
|
||||||
|
name = presets.selected
|
||||||
|
preset = presets.presets.get(name) if name else None
|
||||||
|
if preset is None or getattr(preset, "p", None) != "chase":
|
||||||
|
return
|
||||||
|
presets.redraw = True
|
||||||
|
try:
|
||||||
|
presets.select(name)
|
||||||
|
finally:
|
||||||
|
presets.redraw = False
|
||||||
|
|
||||||
|
|
||||||
|
_pending_select = None
|
||||||
|
|
||||||
|
|
||||||
|
def _run_select(presets, settings, preset_name, step=None):
|
||||||
|
if presets.select(preset_name, step=step):
|
||||||
|
record_last_preset(settings, preset_name)
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _flush_pending_select(settings, presets):
|
||||||
|
global _pending_select
|
||||||
|
if _pending_select is None:
|
||||||
|
return
|
||||||
|
preset_name, step = _pending_select
|
||||||
|
if preset_name not in presets.presets and preset_name not in ("on", "off"):
|
||||||
|
return
|
||||||
|
_pending_select = None
|
||||||
|
if not _run_select(presets, settings, preset_name, step):
|
||||||
|
print("select failed (pending):", preset_name)
|
||||||
|
|
||||||
|
|
||||||
def apply_presets(data, settings, presets):
|
def apply_presets(data, settings, presets):
|
||||||
|
global _pending_select
|
||||||
presets_map = data["presets"]
|
presets_map = data["presets"]
|
||||||
for id, preset_data in presets_map.items():
|
for id, preset_data in presets_map.items():
|
||||||
if not preset_data:
|
if not preset_data:
|
||||||
@@ -181,8 +259,8 @@ def apply_presets(data, settings, presets):
|
|||||||
preset_data[color_key] = convert_and_reorder_colors(
|
preset_data[color_key] = convert_and_reorder_colors(
|
||||||
preset_data[color_key], settings
|
preset_data[color_key], settings
|
||||||
)
|
)
|
||||||
except (TypeError, ValueError, KeyError):
|
except (TypeError, ValueError, KeyError) as err:
|
||||||
continue
|
print("preset color convert failed:", id, err)
|
||||||
if "bg" in preset_data:
|
if "bg" in preset_data:
|
||||||
try:
|
try:
|
||||||
bg_color = convert_and_reorder_colors([preset_data["bg"]], settings)
|
bg_color = convert_and_reorder_colors([preset_data["bg"]], settings)
|
||||||
@@ -191,18 +269,74 @@ def apply_presets(data, settings, presets):
|
|||||||
except (TypeError, ValueError, KeyError):
|
except (TypeError, ValueError, KeyError):
|
||||||
pass
|
pass
|
||||||
presets.edit(id, preset_data)
|
presets.edit(id, preset_data)
|
||||||
|
# Same message often carries select; apply now while presets are loaded.
|
||||||
|
if "select" in data or "s" in data:
|
||||||
|
apply_select(data, settings, presets)
|
||||||
|
else:
|
||||||
|
_flush_pending_select(settings, presets)
|
||||||
|
|
||||||
|
|
||||||
|
def _select_list_for_this_device(select_val, settings):
|
||||||
|
"""Resolve select to ``[preset_id, step?]`` (wire list or legacy name map)."""
|
||||||
|
if isinstance(select_val, list) and select_val:
|
||||||
|
return select_val
|
||||||
|
if isinstance(select_val, str) and str(select_val).strip():
|
||||||
|
return [str(select_val).strip()]
|
||||||
|
if not isinstance(select_val, dict) or not select_val:
|
||||||
|
return None
|
||||||
|
if "preset" in select_val:
|
||||||
|
preset_name = select_val.get("preset")
|
||||||
|
if preset_name is None:
|
||||||
|
return None
|
||||||
|
out = [str(preset_name)]
|
||||||
|
if "step" in select_val:
|
||||||
|
out.append(select_val["step"])
|
||||||
|
return out
|
||||||
|
device_name = str(settings.get("name") or "").strip()
|
||||||
|
select_list = select_val.get(device_name)
|
||||||
|
if select_list:
|
||||||
|
return select_list
|
||||||
|
try:
|
||||||
|
sta = network.WLAN(network.STA_IF)
|
||||||
|
mac_hex = ubinascii.hexlify(sta.config("mac")).decode().lower()
|
||||||
|
except Exception:
|
||||||
|
mac_hex = ""
|
||||||
|
if mac_hex:
|
||||||
|
for key in select_val:
|
||||||
|
k = str(key).lower().replace(":", "").replace("-", "")
|
||||||
|
if mac_hex in k:
|
||||||
|
return select_val[key]
|
||||||
|
if len(select_val) == 1:
|
||||||
|
return next(iter(select_val.values()))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def apply_select(data, settings, presets):
|
def apply_select(data, settings, presets):
|
||||||
select_map = data["select"]
|
global _pending_select
|
||||||
device_name = settings["name"]
|
select_val = data.get("select")
|
||||||
select_list = select_map.get(device_name, [])
|
if select_val is None:
|
||||||
|
select_val = data.get("s")
|
||||||
|
select_list = _select_list_for_this_device(select_val, settings)
|
||||||
if not select_list:
|
if not select_list:
|
||||||
|
print("select ignored:", repr(select_val))
|
||||||
|
return
|
||||||
|
preset_name = str(select_list[0]).strip()
|
||||||
|
if not preset_name:
|
||||||
return
|
return
|
||||||
preset_name = select_list[0]
|
|
||||||
step = select_list[1] if len(select_list) > 1 else None
|
step = select_list[1] if len(select_list) > 1 else None
|
||||||
if presets.select(preset_name, step=step):
|
if preset_name not in presets.presets and preset_name not in ("on", "off"):
|
||||||
record_last_preset(settings, preset_name)
|
try:
|
||||||
|
presets.load(settings)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if preset_name not in presets.presets and preset_name not in ("on", "off"):
|
||||||
|
_pending_select = (preset_name, step)
|
||||||
|
print("select deferred (preset not loaded yet):", preset_name)
|
||||||
|
return
|
||||||
|
if _run_select(presets, settings, preset_name, step):
|
||||||
|
_pending_select = None
|
||||||
|
else:
|
||||||
|
print("select failed:", preset_name)
|
||||||
|
|
||||||
|
|
||||||
def apply_clear_presets(data, presets):
|
def apply_clear_presets(data, presets):
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""Group membership for GROUP_CMD filtering; persisted in settings.json."""
|
||||||
|
|
||||||
|
_groups = []
|
||||||
|
|
||||||
|
|
||||||
|
def load_from_settings(settings):
|
||||||
|
global _groups
|
||||||
|
g = settings.get("groups") if settings is not None else None
|
||||||
|
if isinstance(g, list):
|
||||||
|
_groups = [str(x) for x in g if str(x).strip()]
|
||||||
|
else:
|
||||||
|
_groups = []
|
||||||
|
|
||||||
|
|
||||||
|
def groups_replace(group_ids, settings=None, *, persist=True):
|
||||||
|
global _groups
|
||||||
|
_groups = [str(g) for g in group_ids]
|
||||||
|
if persist and settings is not None:
|
||||||
|
settings["groups"] = list(_groups)
|
||||||
|
settings.save()
|
||||||
|
|
||||||
|
|
||||||
|
def in_group(group_id):
|
||||||
|
return str(group_id) in _groups
|
||||||
|
|
||||||
|
|
||||||
|
def list_groups():
|
||||||
|
return list(_groups)
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
"""App-file OTA over ESP-NOW (driver side). Imported on the first OTA packet only.
|
||||||
|
|
||||||
|
Inner packets, carried in reliable-link DATA frames (unicast acked, or broadcast):
|
||||||
|
0x07 BEGIN [4C][07][sess u16][size u32][sha256 32B][plen][path]
|
||||||
|
0x08 DATA [4C][08][sess u16][chunk u16] + up to CHUNK bytes at chunk * CHUNK
|
||||||
|
0x09 END [4C][09][sess u16] hash the staged file
|
||||||
|
0x0A COMMIT [4C][0A][sess u16] move every staged file into place, then reset
|
||||||
|
0x0B ABORT [4C][0B][sess u16] delete the staged files
|
||||||
|
0x0C MISSING [4C][0C][sess u16] report which chunks of the current file are missing
|
||||||
|
Reply, sent straight back (not through the link):
|
||||||
|
0x26 STATUS [4C][26][sess u16][op][code] + arg
|
||||||
|
arg: [cnt u16] + missing bitmap for MISSING, else received bytes u32
|
||||||
|
Files are written to <path>.new; a new session discards whatever an older one staged.
|
||||||
|
The committed session is kept in ota_last: the reset can beat a lost reply, and the
|
||||||
|
controller then asks again.
|
||||||
|
"""
|
||||||
|
import struct
|
||||||
|
|
||||||
|
import file_hashes
|
||||||
|
|
||||||
|
WIRE_MAGIC = 0x4C
|
||||||
|
OP_BEGIN = 0x07
|
||||||
|
OP_DATA = 0x08
|
||||||
|
OP_END = 0x09
|
||||||
|
OP_COMMIT = 0x0A
|
||||||
|
OP_ABORT = 0x0B
|
||||||
|
OP_MISSING = 0x0C
|
||||||
|
MSG_STATUS = 0x26
|
||||||
|
|
||||||
|
OK = 0
|
||||||
|
READY = 1
|
||||||
|
SAME = 2
|
||||||
|
BADHASH = 3
|
||||||
|
INCOMPLETE = 4
|
||||||
|
BADPATH = 5
|
||||||
|
IOERR = 6
|
||||||
|
NOSESS = 7
|
||||||
|
TOOBIG = 8
|
||||||
|
|
||||||
|
CHUNK = 944 # 4 link fragments of 238 bytes minus this packet's 8-byte header
|
||||||
|
MAX_SIZE = 65536
|
||||||
|
STAGED_SUFFIX = ".new"
|
||||||
|
LAST_FILE = "ota_last" # session last committed, so a repeated COMMIT after the reset still gets OK
|
||||||
|
|
||||||
|
try:
|
||||||
|
import uos as os
|
||||||
|
except ImportError:
|
||||||
|
import os
|
||||||
|
|
||||||
|
|
||||||
|
def safe_path(path):
|
||||||
|
"""Relative path to a root file, patterns/... or lib/..., never the hash manifest."""
|
||||||
|
if not path or path.startswith("/") or "\\" in path or path == file_hashes.MANIFEST_FILENAME:
|
||||||
|
return False
|
||||||
|
parts = path.split("/")
|
||||||
|
if any(p in ("", ".", "..") for p in parts):
|
||||||
|
return False
|
||||||
|
return len(parts) == 1 or parts[0] in ("patterns", "lib")
|
||||||
|
|
||||||
|
|
||||||
|
def _makedirs(path):
|
||||||
|
parts = path.split("/")[:-1]
|
||||||
|
for i in range(1, len(parts) + 1):
|
||||||
|
try:
|
||||||
|
os.mkdir("/".join(parts[:i]))
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _remove(path):
|
||||||
|
try:
|
||||||
|
os.remove(path)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Ota:
|
||||||
|
def __init__(self, send, reset=None):
|
||||||
|
self.send = send # send(mac, frame)
|
||||||
|
self.reset = reset # called after a commit; defaults to machine.reset
|
||||||
|
self.sess = 0
|
||||||
|
self.staged = {} # path -> sha hex of a verified .new file
|
||||||
|
self.cur = None # [path, size, sha hex, file, have bitmap (bytearray), received bytes]
|
||||||
|
try:
|
||||||
|
with open(LAST_FILE) as f:
|
||||||
|
self.committed = int(f.read())
|
||||||
|
except (OSError, ValueError):
|
||||||
|
self.committed = 0
|
||||||
|
|
||||||
|
def handle(self, mac, pkt):
|
||||||
|
if len(pkt) < 4:
|
||||||
|
return
|
||||||
|
op = pkt[1]
|
||||||
|
sess = pkt[2] | (pkt[3] << 8)
|
||||||
|
if sess == 0:
|
||||||
|
return
|
||||||
|
if op == OP_COMMIT and sess == self.committed:
|
||||||
|
self._reply(mac, sess, op, OK, struct.pack("<I", 0))
|
||||||
|
elif op == OP_BEGIN:
|
||||||
|
self._begin(mac, sess, pkt)
|
||||||
|
elif sess != self.sess:
|
||||||
|
if op != OP_DATA: # data for a session we never started: stay quiet, it may be broadcast
|
||||||
|
self._reply(mac, sess, op, NOSESS)
|
||||||
|
elif op == OP_DATA:
|
||||||
|
self._data(pkt)
|
||||||
|
elif op == OP_END:
|
||||||
|
self._end(mac)
|
||||||
|
elif op == OP_COMMIT:
|
||||||
|
self._commit(mac)
|
||||||
|
elif op == OP_ABORT:
|
||||||
|
self._abort()
|
||||||
|
self._reply(mac, sess, op, OK)
|
||||||
|
elif op == OP_MISSING:
|
||||||
|
self._missing(mac)
|
||||||
|
|
||||||
|
def _reply(self, mac, sess, op, code, arg=None):
|
||||||
|
if arg is None:
|
||||||
|
arg = struct.pack("<I", self.cur[5] if self.cur else 0)
|
||||||
|
self.send(mac, struct.pack("<BBHBB", WIRE_MAGIC, MSG_STATUS, sess, op, code) + arg)
|
||||||
|
|
||||||
|
def _close_cur(self, delete):
|
||||||
|
if self.cur is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
self.cur[3].close()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
if delete:
|
||||||
|
_remove(self.cur[0] + STAGED_SUFFIX)
|
||||||
|
self.cur = None
|
||||||
|
|
||||||
|
def _abort(self):
|
||||||
|
self._close_cur(True)
|
||||||
|
for path in self.staged:
|
||||||
|
_remove(path + STAGED_SUFFIX)
|
||||||
|
self.staged = {}
|
||||||
|
|
||||||
|
def _begin(self, mac, sess, pkt):
|
||||||
|
if len(pkt) < 43:
|
||||||
|
return
|
||||||
|
size = struct.unpack_from("<I", pkt, 4)[0]
|
||||||
|
sha = "".join("%02x" % b for b in pkt[8:40])
|
||||||
|
plen = pkt[40]
|
||||||
|
path = bytes(pkt[41 : 41 + plen]).decode()
|
||||||
|
if sess != self.sess:
|
||||||
|
self._abort()
|
||||||
|
self.sess = sess
|
||||||
|
if not safe_path(path):
|
||||||
|
self._reply(mac, sess, OP_BEGIN, BADPATH)
|
||||||
|
return
|
||||||
|
if size > MAX_SIZE:
|
||||||
|
self._reply(mac, sess, OP_BEGIN, TOOBIG)
|
||||||
|
return
|
||||||
|
if self.cur is not None:
|
||||||
|
if self.cur[0] == path and self.cur[2] == sha:
|
||||||
|
self._reply(mac, sess, OP_BEGIN, READY) # our earlier reply was lost
|
||||||
|
return
|
||||||
|
self._close_cur(True)
|
||||||
|
if self.staged.get(path) == sha:
|
||||||
|
self._reply(mac, sess, OP_BEGIN, READY)
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
if file_hashes._hash_file(path) == sha:
|
||||||
|
self._reply(mac, sess, OP_BEGIN, SAME)
|
||||||
|
return
|
||||||
|
except OSError:
|
||||||
|
pass # no such file yet
|
||||||
|
try:
|
||||||
|
_makedirs(path)
|
||||||
|
f = open(path + STAGED_SUFFIX, "w+b")
|
||||||
|
except OSError:
|
||||||
|
self._reply(mac, sess, OP_BEGIN, IOERR)
|
||||||
|
return
|
||||||
|
cnt = (size + CHUNK - 1) // CHUNK
|
||||||
|
self.staged.pop(path, None)
|
||||||
|
self.cur = [path, size, sha, f, bytearray((cnt + 7) // 8), 0]
|
||||||
|
self._reply(mac, sess, OP_BEGIN, READY)
|
||||||
|
|
||||||
|
def _data(self, pkt):
|
||||||
|
cur = self.cur
|
||||||
|
if cur is None or len(pkt) < 6:
|
||||||
|
return
|
||||||
|
idx = pkt[4] | (pkt[5] << 8)
|
||||||
|
body = pkt[6:]
|
||||||
|
off = idx * CHUNK
|
||||||
|
have = cur[4]
|
||||||
|
if off >= cur[1] or have[idx >> 3] & (1 << (idx & 7)):
|
||||||
|
return # past the end, or a copy we already wrote
|
||||||
|
if len(body) != min(CHUNK, cur[1] - off):
|
||||||
|
return
|
||||||
|
f = cur[3]
|
||||||
|
try:
|
||||||
|
end = f.seek(0, 2)
|
||||||
|
if end < off:
|
||||||
|
f.write(bytes(off - end)) # a chunk before this one is still missing
|
||||||
|
f.seek(off)
|
||||||
|
f.write(body)
|
||||||
|
except OSError:
|
||||||
|
self._close_cur(True)
|
||||||
|
return
|
||||||
|
have[idx >> 3] |= 1 << (idx & 7)
|
||||||
|
cur[5] += len(body)
|
||||||
|
|
||||||
|
def _missing_bitmap(self):
|
||||||
|
cur = self.cur
|
||||||
|
cnt = (cur[1] + CHUNK - 1) // CHUNK
|
||||||
|
miss = bytearray(len(cur[4]))
|
||||||
|
for i in range(cnt):
|
||||||
|
if not cur[4][i >> 3] & (1 << (i & 7)):
|
||||||
|
miss[i >> 3] |= 1 << (i & 7)
|
||||||
|
return cnt, miss
|
||||||
|
|
||||||
|
def _missing(self, mac):
|
||||||
|
if self.cur is None:
|
||||||
|
self._reply(mac, self.sess, OP_MISSING, OK, struct.pack("<H", 0))
|
||||||
|
return
|
||||||
|
cnt, miss = self._missing_bitmap()
|
||||||
|
self._reply(mac, self.sess, OP_MISSING, OK, struct.pack("<H", cnt) + miss)
|
||||||
|
|
||||||
|
def _end(self, mac):
|
||||||
|
cur = self.cur
|
||||||
|
if cur is None:
|
||||||
|
# already verified: our OK was lost and the controller asks again
|
||||||
|
self._reply(mac, self.sess, OP_END, OK if self.staged else NOSESS)
|
||||||
|
return
|
||||||
|
if cur[5] < cur[1]:
|
||||||
|
self._reply(mac, self.sess, OP_END, INCOMPLETE)
|
||||||
|
return
|
||||||
|
path, sha = cur[0], cur[2]
|
||||||
|
self._close_cur(False)
|
||||||
|
try:
|
||||||
|
ok = file_hashes._hash_file(path + STAGED_SUFFIX) == sha
|
||||||
|
except OSError:
|
||||||
|
ok = False
|
||||||
|
if not ok:
|
||||||
|
_remove(path + STAGED_SUFFIX)
|
||||||
|
self._reply(mac, self.sess, OP_END, BADHASH)
|
||||||
|
return
|
||||||
|
self.staged[path] = sha
|
||||||
|
self._reply(mac, self.sess, OP_END, OK)
|
||||||
|
|
||||||
|
def _commit(self, mac):
|
||||||
|
self._close_cur(True)
|
||||||
|
manifest = file_hashes.load()
|
||||||
|
failed = False
|
||||||
|
for path, sha in self.staged.items():
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
os.rename(path + STAGED_SUFFIX, path)
|
||||||
|
except OSError:
|
||||||
|
_remove(path)
|
||||||
|
os.rename(path + STAGED_SUFFIX, path)
|
||||||
|
manifest[path] = sha
|
||||||
|
except OSError:
|
||||||
|
failed = True
|
||||||
|
moved = len(self.staged)
|
||||||
|
self.staged = {}
|
||||||
|
try:
|
||||||
|
file_hashes.save(manifest)
|
||||||
|
with open(LAST_FILE, "w") as f:
|
||||||
|
f.write(str(self.sess))
|
||||||
|
except OSError:
|
||||||
|
failed = True
|
||||||
|
self.committed = self.sess
|
||||||
|
self._reply(mac, self.sess, OP_COMMIT, IOERR if failed else OK, struct.pack("<I", moved))
|
||||||
|
print("ota: committed", moved, "files" + (" with errors" if failed else ""))
|
||||||
|
if moved:
|
||||||
|
self._schedule_reset()
|
||||||
|
|
||||||
|
def _schedule_reset(self):
|
||||||
|
if self.reset is not None:
|
||||||
|
self.reset()
|
||||||
|
return
|
||||||
|
import machine
|
||||||
|
|
||||||
|
try:
|
||||||
|
t = machine.Timer(0)
|
||||||
|
t.init(mode=machine.Timer.ONE_SHOT, period=300, callback=lambda _: machine.reset())
|
||||||
|
except Exception:
|
||||||
|
import utime
|
||||||
|
|
||||||
|
utime.sleep_ms(300)
|
||||||
|
machine.reset()
|
||||||
|
|
||||||
|
|
||||||
|
_ota = None
|
||||||
|
|
||||||
|
|
||||||
|
def handle(mac, pkt, send):
|
||||||
|
global _ota
|
||||||
|
if _ota is None:
|
||||||
|
_ota = Ota(send)
|
||||||
|
_ota.handle(bytes(mac), pkt)
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
"""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
|
||||||
|
0x26 OTA [4C][26][sess u16][op][code] + arg driver -> controller, see espnow_ota.py
|
||||||
|
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 = 24
|
||||||
|
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
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
"""ESP-NOW receive loop and boot announce."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import urandom
|
||||||
|
import ubinascii
|
||||||
|
|
||||||
|
import espnow
|
||||||
|
import network
|
||||||
|
|
||||||
|
import device_groups as dg
|
||||||
|
from espnow_wire import (
|
||||||
|
BROADCAST_MAC,
|
||||||
|
MSG_ANNOUNCE,
|
||||||
|
MSG_CMD,
|
||||||
|
MSG_GROUP_CMD,
|
||||||
|
MSG_GROUPS,
|
||||||
|
MSG_OTA_FIRST,
|
||||||
|
MSG_OTA_LAST,
|
||||||
|
MSG_PING_REQ,
|
||||||
|
cmd_envelope,
|
||||||
|
pack_announce,
|
||||||
|
pack_ping_rsp,
|
||||||
|
parse_group_cmd,
|
||||||
|
parse_groups,
|
||||||
|
parse_ping_req,
|
||||||
|
wire_msg_type,
|
||||||
|
)
|
||||||
|
|
||||||
|
from controller_messages import process_data
|
||||||
|
from settings import WIFI_CHANNEL_DEFAULT
|
||||||
|
|
||||||
|
_PING_DELAY_MS_MIN = 50
|
||||||
|
_PING_DELAY_MS_MAX = 500
|
||||||
|
|
||||||
|
_esp = None
|
||||||
|
_ota_send = None
|
||||||
|
_groups_received = False
|
||||||
|
_debug = False
|
||||||
|
|
||||||
|
|
||||||
|
def _dlog(*parts):
|
||||||
|
if _debug:
|
||||||
|
print(*parts)
|
||||||
|
|
||||||
|
|
||||||
|
def init_espnow(settings):
|
||||||
|
global _esp, _debug
|
||||||
|
_debug = bool(settings.get("debug", False))
|
||||||
|
try:
|
||||||
|
ch = int(settings.get("wifi_channel", WIFI_CHANNEL_DEFAULT))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
ch = WIFI_CHANNEL_DEFAULT
|
||||||
|
ch = max(1, min(11, ch))
|
||||||
|
sta = network.WLAN(network.STA_IF)
|
||||||
|
sta.active(True)
|
||||||
|
sta.config(pm=network.WLAN.PM_NONE)
|
||||||
|
try:
|
||||||
|
sta.config(channel=ch)
|
||||||
|
except Exception as e:
|
||||||
|
print("espnow sta channel set failed:", e)
|
||||||
|
_esp = espnow.ESPNow()
|
||||||
|
try:
|
||||||
|
# The default 526 bytes holds two full frames; an OTA chunk is four
|
||||||
|
_esp.config(rxbuf=int(settings.get("espnow_rxbuf", 2048)))
|
||||||
|
except Exception as e:
|
||||||
|
print("espnow rxbuf set failed:", e)
|
||||||
|
_esp.active(True)
|
||||||
|
try:
|
||||||
|
_esp.add_peer(BROADCAST_MAC)
|
||||||
|
_dlog("espnow add bcast ok")
|
||||||
|
except Exception as e:
|
||||||
|
print("espnow add bcast failed:", e)
|
||||||
|
try:
|
||||||
|
actual_ch = sta.config("channel")
|
||||||
|
except Exception:
|
||||||
|
actual_ch = "?"
|
||||||
|
print("espnow init ch", ch, "sta_ch", actual_ch, "debug", _debug)
|
||||||
|
return _esp
|
||||||
|
|
||||||
|
|
||||||
|
def _send_ping_rsp(host, settings, ping_id, delay_ms):
|
||||||
|
import utime
|
||||||
|
|
||||||
|
utime.sleep_ms(delay_ms)
|
||||||
|
if _esp is None or not host or len(host) != 6:
|
||||||
|
return
|
||||||
|
pkt = pack_ping_rsp(ping_id, settings.get("name", "led"))
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
_esp.add_peer(host)
|
||||||
|
_dlog("espnow ping add_peer ok", ubinascii.hexlify(host).decode())
|
||||||
|
except Exception as e:
|
||||||
|
_dlog("espnow ping add_peer skip", repr(e))
|
||||||
|
_esp.send(host, pkt)
|
||||||
|
print("espnow ping rsp", ping_id, delay_ms, "ms", ubinascii.hexlify(host).decode())
|
||||||
|
except Exception as e:
|
||||||
|
print("espnow ping rsp failed:", e, "host", ubinascii.hexlify(host).decode(), "len", len(pkt))
|
||||||
|
|
||||||
|
|
||||||
|
async def _send_ping_rsp_delayed(host, settings, ping_id):
|
||||||
|
span = _PING_DELAY_MS_MAX - _PING_DELAY_MS_MIN
|
||||||
|
delay_ms = _PING_DELAY_MS_MIN + (urandom.getrandbits(10) % (span + 1))
|
||||||
|
await asyncio.sleep(delay_ms / 1000)
|
||||||
|
_send_ping_rsp(host, settings, ping_id, delay_ms)
|
||||||
|
|
||||||
|
|
||||||
|
def _schedule_ping_rsp(host, settings, ping_id):
|
||||||
|
span = _PING_DELAY_MS_MAX - _PING_DELAY_MS_MIN
|
||||||
|
delay_ms = _PING_DELAY_MS_MIN + (urandom.getrandbits(10) % (span + 1))
|
||||||
|
try:
|
||||||
|
import _thread
|
||||||
|
|
||||||
|
_thread.start_new_thread(_send_ping_rsp, (host, settings, ping_id, delay_ms))
|
||||||
|
except ImportError:
|
||||||
|
asyncio.create_task(_send_ping_rsp_delayed(host, settings, ping_id))
|
||||||
|
|
||||||
|
|
||||||
|
def send_boot_announce(settings):
|
||||||
|
if _esp is None:
|
||||||
|
return
|
||||||
|
pkt = pack_announce(
|
||||||
|
settings.get("name", "led"),
|
||||||
|
settings.get("num_leds", 1),
|
||||||
|
color_order=settings.get("color_order", "rgb"),
|
||||||
|
startup_mode=settings.get("startup_mode", "default"),
|
||||||
|
brightness=settings.get("brightness", 32),
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
_esp.send(BROADCAST_MAC, pkt)
|
||||||
|
print("espnow announce", len(pkt), "B")
|
||||||
|
except Exception as e:
|
||||||
|
print("espnow announce failed:", e)
|
||||||
|
|
||||||
|
|
||||||
|
def _handle_packet(host, pkt, settings, presets):
|
||||||
|
global _groups_received, _ota_send
|
||||||
|
mt = wire_msg_type(pkt)
|
||||||
|
if mt is not None and MSG_OTA_FIRST <= mt <= MSG_OTA_LAST:
|
||||||
|
import espnow_ota
|
||||||
|
|
||||||
|
if _ota_send is None:
|
||||||
|
from espnow_rx import make_sender
|
||||||
|
|
||||||
|
_ota_send = make_sender(_esp)
|
||||||
|
espnow_ota.handle(host, pkt, _ota_send)
|
||||||
|
return
|
||||||
|
if mt == MSG_GROUPS:
|
||||||
|
ids = parse_groups(pkt)
|
||||||
|
if ids is not None:
|
||||||
|
dg.groups_replace(ids, settings)
|
||||||
|
_groups_received = True
|
||||||
|
print("groups", ids)
|
||||||
|
return
|
||||||
|
if mt == MSG_GROUP_CMD:
|
||||||
|
parsed = parse_group_cmd(pkt)
|
||||||
|
if parsed is None:
|
||||||
|
return
|
||||||
|
gid, env = parsed
|
||||||
|
if not dg.in_group(gid):
|
||||||
|
return
|
||||||
|
from espnow_wire import _envelope_size
|
||||||
|
|
||||||
|
need = _envelope_size(env)
|
||||||
|
save = len(env) > need and env[need] == 1
|
||||||
|
body = env[:need] if save else env
|
||||||
|
if body:
|
||||||
|
process_data(body, settings, presets, save=save)
|
||||||
|
return
|
||||||
|
if mt == MSG_CMD:
|
||||||
|
env, save = cmd_envelope(pkt)
|
||||||
|
if env:
|
||||||
|
process_data(env, settings, presets, save=save)
|
||||||
|
return
|
||||||
|
if mt == MSG_PING_REQ:
|
||||||
|
ping_id = parse_ping_req(pkt)
|
||||||
|
if ping_id is not None and host and len(host) == 6:
|
||||||
|
_schedule_ping_rsp(host, settings, ping_id)
|
||||||
|
return
|
||||||
|
if mt == MSG_ANNOUNCE:
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
|
async def espnow_receive_loop(settings, presets, wdt=None):
|
||||||
|
global _groups_received
|
||||||
|
while True:
|
||||||
|
if _esp is None:
|
||||||
|
await asyncio.sleep(0.1)
|
||||||
|
continue
|
||||||
|
host, msg = _esp.recv(0)
|
||||||
|
if not host:
|
||||||
|
if not _groups_received:
|
||||||
|
await asyncio.sleep(5)
|
||||||
|
send_boot_announce(settings)
|
||||||
|
else:
|
||||||
|
await asyncio.sleep(0.02)
|
||||||
|
if wdt:
|
||||||
|
wdt.feed()
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
_handle_packet(host, msg, settings, presets)
|
||||||
|
except Exception as e:
|
||||||
|
print("espnow rx error:", e)
|
||||||
|
if wdt:
|
||||||
|
wdt.feed()
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
"""ESP-NOW wire format (MicroPython). See docs/espnow-binary-protocol.md in led-controller."""
|
||||||
|
|
||||||
|
import struct
|
||||||
|
|
||||||
|
WIRE_MAGIC = 0x4C
|
||||||
|
MAX_ESPNOW_PAYLOAD = 250
|
||||||
|
|
||||||
|
MSG_ANNOUNCE = 0x01
|
||||||
|
MSG_GROUPS = 0x02
|
||||||
|
MSG_CMD = 0x03
|
||||||
|
MSG_GROUP_CMD = 0x04
|
||||||
|
MSG_PING_REQ = 0x05
|
||||||
|
MSG_PING_RSP = 0x06
|
||||||
|
MSG_OTA_FIRST = 0x07 # 0x07..0x0C app-file OTA, see espnow_ota.py
|
||||||
|
MSG_OTA_LAST = 0x0C
|
||||||
|
|
||||||
|
BROADCAST_MAC = b"\xff\xff\xff\xff\xff\xff"
|
||||||
|
|
||||||
|
COLOR_ORDER_TO_ENUM = {
|
||||||
|
"rgb": 0,
|
||||||
|
"rbg": 1,
|
||||||
|
"grb": 2,
|
||||||
|
"gbr": 3,
|
||||||
|
"brg": 4,
|
||||||
|
"bgr": 5,
|
||||||
|
}
|
||||||
|
STARTUP_MODE_TO_ENUM = {"default": 0, "last": 1, "off": 2}
|
||||||
|
|
||||||
|
|
||||||
|
def _pack_header(msg_type, body):
|
||||||
|
pkt = bytes([WIRE_MAGIC, msg_type]) + body
|
||||||
|
if len(pkt) > MAX_ESPNOW_PAYLOAD:
|
||||||
|
raise ValueError("packet too large")
|
||||||
|
return pkt
|
||||||
|
|
||||||
|
|
||||||
|
def pack_announce(
|
||||||
|
name,
|
||||||
|
num_leds,
|
||||||
|
color_order="rgb",
|
||||||
|
startup_mode="default",
|
||||||
|
brightness=32,
|
||||||
|
device_type=0,
|
||||||
|
):
|
||||||
|
name_b = name.encode("utf-8")
|
||||||
|
co = COLOR_ORDER_TO_ENUM.get(str(color_order).lower(), 0)
|
||||||
|
sm = STARTUP_MODE_TO_ENUM.get(str(startup_mode).lower(), 0)
|
||||||
|
body = (
|
||||||
|
bytes([len(name_b)])
|
||||||
|
+ name_b
|
||||||
|
+ struct.pack("<H", int(num_leds))
|
||||||
|
+ bytes([co & 7, sm & 3, max(0, min(255, int(brightness))), device_type & 255])
|
||||||
|
)
|
||||||
|
return _pack_header(MSG_ANNOUNCE, body)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_groups(payload):
|
||||||
|
if len(payload) >= 2 and payload[0] == WIRE_MAGIC:
|
||||||
|
if payload[1] != MSG_GROUPS:
|
||||||
|
return None
|
||||||
|
body = payload[2:]
|
||||||
|
else:
|
||||||
|
body = payload
|
||||||
|
if not body:
|
||||||
|
return []
|
||||||
|
off = 0
|
||||||
|
count = body[off]
|
||||||
|
off += 1
|
||||||
|
out = []
|
||||||
|
for _ in range(count):
|
||||||
|
gl = body[off]
|
||||||
|
off += 1
|
||||||
|
out.append(body[off : off + gl].decode("utf-8"))
|
||||||
|
off += gl
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def parse_group_cmd(payload):
|
||||||
|
if len(payload) < 2 or payload[0] != WIRE_MAGIC or payload[1] != MSG_GROUP_CMD:
|
||||||
|
return None
|
||||||
|
body = payload[2:]
|
||||||
|
gl = body[0]
|
||||||
|
gid = body[1 : 1 + gl].decode("utf-8")
|
||||||
|
env = body[1 + gl :]
|
||||||
|
return gid, env
|
||||||
|
|
||||||
|
|
||||||
|
HEADER_LEN = 5
|
||||||
|
|
||||||
|
|
||||||
|
def _envelope_size(env):
|
||||||
|
if len(env) < HEADER_LEN:
|
||||||
|
return len(env)
|
||||||
|
lp, ls, ld = env[2], env[3], env[4]
|
||||||
|
return HEADER_LEN + lp + ls + ld
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_envelope(payload):
|
||||||
|
if len(payload) < 2 or payload[0] != WIRE_MAGIC or payload[1] != MSG_CMD:
|
||||||
|
return None, False
|
||||||
|
env = payload[2:]
|
||||||
|
if not env:
|
||||||
|
return None, False
|
||||||
|
need = _envelope_size(env)
|
||||||
|
if need > len(env):
|
||||||
|
return None, False
|
||||||
|
save = len(env) > need and env[need] == 1
|
||||||
|
return env[:need], save
|
||||||
|
|
||||||
|
|
||||||
|
def pack_ping_req(ping_id):
|
||||||
|
body = struct.pack("<I", int(ping_id) & 0xFFFFFFFF)
|
||||||
|
return _pack_header(MSG_PING_REQ, body)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_ping_req(payload):
|
||||||
|
if len(payload) >= 2 and payload[0] == WIRE_MAGIC:
|
||||||
|
if payload[1] != MSG_PING_REQ:
|
||||||
|
return None
|
||||||
|
body = payload[2:]
|
||||||
|
else:
|
||||||
|
body = payload
|
||||||
|
if len(body) < 4:
|
||||||
|
return None
|
||||||
|
return struct.unpack("<I", body[:4])[0]
|
||||||
|
|
||||||
|
|
||||||
|
def pack_ping_rsp(ping_id, name):
|
||||||
|
name_b = name.encode("utf-8")
|
||||||
|
body = struct.pack("<I", int(ping_id) & 0xFFFFFFFF) + bytes([len(name_b)]) + name_b
|
||||||
|
return _pack_header(MSG_PING_RSP, body)
|
||||||
|
|
||||||
|
|
||||||
|
def wire_msg_type(payload):
|
||||||
|
if len(payload) >= 2 and payload[0] == WIRE_MAGIC:
|
||||||
|
return payload[1]
|
||||||
|
return None
|
||||||
+3
-2
@@ -47,16 +47,17 @@ def save(files):
|
|||||||
|
|
||||||
|
|
||||||
def _hash_file(path):
|
def _hash_file(path):
|
||||||
|
import binascii
|
||||||
import hashlib
|
import hashlib
|
||||||
|
|
||||||
h = hashlib.sha256()
|
h = hashlib.sha256()
|
||||||
with open(path, "rb") as f:
|
with open(path, "rb") as f:
|
||||||
while True:
|
while True:
|
||||||
chunk = f.read(256)
|
chunk = f.read(1024)
|
||||||
if not chunk:
|
if not chunk:
|
||||||
break
|
break
|
||||||
h.update(chunk)
|
h.update(chunk)
|
||||||
return h.hexdigest()
|
return binascii.hexlify(h.digest()).decode() # MicroPython's sha256 has no hexdigest()
|
||||||
|
|
||||||
|
|
||||||
def _walk_dir(base, prefix, out):
|
def _walk_dir(base, prefix, out):
|
||||||
|
|||||||
+97
-136
@@ -1,33 +1,34 @@
|
|||||||
import print_timestamp # noqa: F401 — prefixes every print with [ticks_ms]
|
import print_timestamp # noqa: F401
|
||||||
from settings import Settings
|
from settings import Settings
|
||||||
import machine
|
import machine
|
||||||
import utime
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import json
|
|
||||||
import gc
|
import gc
|
||||||
from microdot import Microdot
|
import json
|
||||||
from microdot.websocket import WebSocketError, with_websocket
|
import network
|
||||||
|
import espnow
|
||||||
|
import device_groups as dg
|
||||||
|
from board import apply_cpu_freq
|
||||||
from presets import Presets
|
from presets import Presets
|
||||||
from controller_messages import apply_startup_pattern, process_data
|
from controller_messages import apply_startup_pattern, process_data
|
||||||
from runtime_state import RuntimeState
|
from espnow_transport import _handle_packet, init_espnow
|
||||||
from background_tasks import presets_loop, udp_hello_loop_after_http_ready
|
from espnow_wire import BROADCAST_MAC, WIRE_MAGIC
|
||||||
from mem_stats import print_mem
|
import utime
|
||||||
from wifi_sta import boot_sta
|
from beat_sync import BeatSync
|
||||||
try:
|
from espnow_rx import LinkRx, make_sender
|
||||||
import uos as os
|
|
||||||
except ImportError:
|
|
||||||
import os
|
|
||||||
|
|
||||||
wdt = machine.WDT(timeout=10000)
|
wdt = machine.WDT(timeout=10000)
|
||||||
wdt.feed()
|
wdt.feed()
|
||||||
|
|
||||||
machine.freq(160000000)
|
apply_cpu_freq()
|
||||||
|
|
||||||
|
|
||||||
settings = Settings()
|
settings = Settings()
|
||||||
|
dg.load_from_settings(settings)
|
||||||
|
print(settings)
|
||||||
gc.collect()
|
gc.collect()
|
||||||
sta_if = boot_sta(settings, wdt)
|
|
||||||
|
# Bring Wi-Fi up before the pattern library and the LED driver claim memory: on the ESP32-C3 the radio
|
||||||
|
# tasks otherwise fail to start on about every other cold boot (Wifi Unknown Error 0x0101)
|
||||||
|
esp = init_espnow(settings)
|
||||||
|
|
||||||
presets = Presets(settings["led_pin"], settings["num_leds"])
|
presets = Presets(settings["led_pin"], settings["num_leds"])
|
||||||
presets.load(settings)
|
presets.load(settings)
|
||||||
@@ -37,130 +38,90 @@ gc.collect()
|
|||||||
|
|
||||||
apply_startup_pattern(settings, presets)
|
apply_startup_pattern(settings, presets)
|
||||||
|
|
||||||
|
print(network.WLAN(network.STA_IF).config("channel"))
|
||||||
|
|
||||||
def _print_network_ips(controller_ip=None):
|
hello = json.dumps({
|
||||||
"""Always log STA address and led-controller (WS client) address when known."""
|
"v": "1",
|
||||||
try:
|
"name": settings.get("name", "led"),
|
||||||
led_ip = sta_if.ifconfig()[0]
|
"type": "led",
|
||||||
except Exception:
|
})
|
||||||
led_ip = "?"
|
print(hello)
|
||||||
ctrl = controller_ip if controller_ip else "(not connected)"
|
|
||||||
print("led-driver IP:", led_ip, " led-controller IP:", ctrl)
|
esp.send(BROADCAST_MAC, hello)
|
||||||
|
print("espnow hello", len(hello), "B")
|
||||||
|
|
||||||
|
|
||||||
_print_network_ips()
|
def _on_espnow_message(host, msg):
|
||||||
print_mem("startup")
|
if not msg:
|
||||||
|
return
|
||||||
runtime_state = RuntimeState()
|
if msg[0] == WIRE_MAGIC:
|
||||||
|
_handle_packet(host, msg, settings, presets)
|
||||||
app = Microdot()
|
return
|
||||||
|
if msg[0:1] == b"{":
|
||||||
|
process_data(msg, settings, presets)
|
||||||
|
|
||||||
|
|
||||||
def _safe_pattern_filename(name):
|
beat_sync = BeatSync()
|
||||||
if not isinstance(name, str):
|
link = LinkRx(
|
||||||
return False
|
_on_espnow_message,
|
||||||
if not name.endswith(".py"):
|
beat_sync,
|
||||||
return False
|
make_sender(esp),
|
||||||
if "/" in name or "\\" in name or ".." in name:
|
jitter_ms=int.from_bytes(network.WLAN(network.STA_IF).config("mac")[-2:], "big") % 1000,
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
@app.route("/ws")
|
|
||||||
@with_websocket
|
|
||||||
async def ws_handler(request, ws):
|
|
||||||
runtime_state.ws_connected()
|
|
||||||
controller_ip = None
|
|
||||||
try:
|
|
||||||
client_addr = getattr(request, "client_addr", None)
|
|
||||||
if isinstance(client_addr, (tuple, list)) and client_addr:
|
|
||||||
controller_ip = client_addr[0]
|
|
||||||
elif isinstance(client_addr, str):
|
|
||||||
controller_ip = client_addr
|
|
||||||
except Exception:
|
|
||||||
controller_ip = None
|
|
||||||
_print_network_ips(controller_ip)
|
|
||||||
print_mem("ws connect")
|
|
||||||
try:
|
|
||||||
while True:
|
|
||||||
data = await ws.receive()
|
|
||||||
if not data:
|
|
||||||
break
|
|
||||||
process_data(data, settings, presets, controller_ip=controller_ip)
|
|
||||||
except WebSocketError as e:
|
|
||||||
print("WS client disconnected:", e)
|
|
||||||
except OSError as e:
|
|
||||||
print("WS client dropped (OSError):", e)
|
|
||||||
finally:
|
|
||||||
runtime_state.ws_disconnected()
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/patterns/upload")
|
|
||||||
async def upload_pattern(request):
|
|
||||||
"""Receive one pattern file body from led-controller and reload patterns."""
|
|
||||||
raw_name = request.args.get("name")
|
|
||||||
reload_raw = request.args.get("reload", "1")
|
|
||||||
reload_patterns = str(reload_raw).strip().lower() not in ("0", "false", "no", "off")
|
|
||||||
|
|
||||||
if not isinstance(raw_name, str) or not raw_name.strip():
|
|
||||||
return json.dumps({"error": "name is required"}), 400, {
|
|
||||||
"Content-Type": "application/json"
|
|
||||||
}
|
|
||||||
body = request.body
|
|
||||||
if not isinstance(body, (bytes, bytearray)) or not body:
|
|
||||||
return json.dumps({"error": "code is required"}), 400, {
|
|
||||||
"Content-Type": "application/json"
|
|
||||||
}
|
|
||||||
try:
|
|
||||||
code = body.decode("utf-8")
|
|
||||||
except UnicodeError:
|
|
||||||
return json.dumps({"error": "body must be utf-8 text"}), 400, {
|
|
||||||
"Content-Type": "application/json"
|
|
||||||
}
|
|
||||||
if not code.strip():
|
|
||||||
return json.dumps({"error": "code is required"}), 400, {
|
|
||||||
"Content-Type": "application/json"
|
|
||||||
}
|
|
||||||
|
|
||||||
name = raw_name.strip()
|
|
||||||
if not name.endswith(".py"):
|
|
||||||
name += ".py"
|
|
||||||
if not _safe_pattern_filename(name) or name in ("__init__.py", "main.py"):
|
|
||||||
return json.dumps({"error": "invalid pattern filename"}), 400, {
|
|
||||||
"Content-Type": "application/json"
|
|
||||||
}
|
|
||||||
|
|
||||||
try:
|
|
||||||
os.mkdir("patterns")
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
path = "patterns/" + name
|
|
||||||
try:
|
|
||||||
with open(path, "w") as f:
|
|
||||||
f.write(code)
|
|
||||||
if reload_patterns:
|
|
||||||
presets.reload_patterns()
|
|
||||||
except OSError as e:
|
|
||||||
print("patterns/upload failed:", e)
|
|
||||||
return json.dumps({"error": str(e)}), 500, {
|
|
||||||
"Content-Type": "application/json"
|
|
||||||
}
|
|
||||||
|
|
||||||
return json.dumps({
|
|
||||||
"message": "pattern uploaded",
|
|
||||||
"name": name,
|
|
||||||
"reloaded": reload_patterns,
|
|
||||||
}), 201, {"Content-Type": "application/json"}
|
|
||||||
|
|
||||||
|
|
||||||
async def main(port=80):
|
|
||||||
asyncio.create_task(presets_loop(presets, wdt))
|
|
||||||
asyncio.create_task(
|
|
||||||
udp_hello_loop_after_http_ready(sta_if, settings, wdt, runtime_state)
|
|
||||||
)
|
)
|
||||||
await app.start_server(host="0.0.0.0", port=port)
|
link.loss_pct = int(settings.get("espnow_loss", 0))
|
||||||
|
bench = bool(settings.get("bench", False)) # echo each fired beat to the controller, print stats
|
||||||
|
usb_log = bool(settings.get("usb_log", False)) # print "FIRE <idx> <ticks_us>" per real beat for tools/usb_latency.py
|
||||||
|
fire_log = None
|
||||||
|
last_stat = utime.ticks_ms()
|
||||||
|
beat_pin = None
|
||||||
|
if settings.get("beat_pin") is not None:
|
||||||
|
beat_pin = machine.Pin(int(settings["beat_pin"]), machine.Pin.OUT)
|
||||||
|
|
||||||
|
def _drain(e):
|
||||||
|
# Runs scheduled between bytecodes, so frames are taken while presets.tick() is still busy.
|
||||||
|
# irecv reuses its buffers: on_packet handles beats in place and copies everything else.
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
host, msg = e.irecv(0)
|
||||||
|
except OSError:
|
||||||
|
return
|
||||||
|
if not host:
|
||||||
|
return
|
||||||
|
if msg:
|
||||||
|
try:
|
||||||
|
link.on_packet(host, msg, utime.ticks_ms())
|
||||||
|
except Exception as ex:
|
||||||
|
print("espnow rx error:", ex)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
try:
|
||||||
asyncio.run(main(port=80))
|
esp.irq(_drain)
|
||||||
|
use_irq = True
|
||||||
|
except AttributeError: # firmware built without ESP-NOW irq support: poll as before
|
||||||
|
use_irq = False
|
||||||
|
|
||||||
|
while True:
|
||||||
|
wdt.feed()
|
||||||
|
if not use_irq:
|
||||||
|
_drain(esp)
|
||||||
|
now = utime.ticks_ms()
|
||||||
|
try:
|
||||||
|
link.poll(now)
|
||||||
|
except Exception as e:
|
||||||
|
print("espnow rx error:", e)
|
||||||
|
if beat_sync.poll(now):
|
||||||
|
fire_us = utime.ticks_us()
|
||||||
|
presets.beat()
|
||||||
|
if beat_pin is not None:
|
||||||
|
beat_pin.value(not beat_pin.value()) # edge for the latency measurement
|
||||||
|
if usb_log and not beat_sync.freerun_fire:
|
||||||
|
fire_log = (beat_sync.last_idx, fire_us) # printed after the LED update so it never delays it
|
||||||
|
if bench and not beat_sync.freerun_fire:
|
||||||
|
link.echo(beat_sync.last_idx) # only real triggers: an invented beat has no send time to compare
|
||||||
|
if bench and utime.ticks_diff(now, last_stat) >= 5000:
|
||||||
|
last_stat = now
|
||||||
|
print("beat", beat_sync.stats, "link", link.stats, "radio", esp.stats()) # radio: tx, tx_resp, tx_fail, rx, rx_dropped
|
||||||
|
presets.tick()
|
||||||
|
if fire_log is not None:
|
||||||
|
print("FIRE", fire_log[0], fire_log[1])
|
||||||
|
fire_log = None
|
||||||
+71
-8
@@ -4,6 +4,7 @@ from preset import Preset
|
|||||||
from utils import convert_and_reorder_colors
|
from utils import convert_and_reorder_colors
|
||||||
import json
|
import json
|
||||||
import sys
|
import sys
|
||||||
|
import utime
|
||||||
try:
|
try:
|
||||||
import uos as os
|
import uos as os
|
||||||
except ImportError:
|
except ImportError:
|
||||||
@@ -11,6 +12,9 @@ except ImportError:
|
|||||||
|
|
||||||
MAX_PRESETS = 32
|
MAX_PRESETS = 32
|
||||||
|
|
||||||
|
# Tests set this so pattern import can feed the 10s watchdog.
|
||||||
|
load_wdt = None
|
||||||
|
|
||||||
|
|
||||||
class Presets:
|
class Presets:
|
||||||
def __init__(self, pin, num_leds):
|
def __init__(self, pin, num_leds):
|
||||||
@@ -19,6 +23,7 @@ class Presets:
|
|||||||
self.step = 0
|
self.step = 0
|
||||||
# Global brightness (0–255), controlled via ESPNow {"b": <value>}
|
# Global brightness (0–255), controlled via ESPNow {"b": <value>}
|
||||||
self.b = 255
|
self.b = 255
|
||||||
|
self.reversed = False
|
||||||
|
|
||||||
self.generator = None
|
self.generator = None
|
||||||
self.presets = {}
|
self.presets = {}
|
||||||
@@ -31,6 +36,7 @@ class Presets:
|
|||||||
self.patterns = {
|
self.patterns = {
|
||||||
"off": self.off,
|
"off": self.off,
|
||||||
"on": self.on,
|
"on": self.on,
|
||||||
|
"blink": self.blink,
|
||||||
}
|
}
|
||||||
self.patterns.update(self._load_dynamic_patterns())
|
self.patterns.update(self._load_dynamic_patterns())
|
||||||
|
|
||||||
@@ -42,6 +48,8 @@ class Presets:
|
|||||||
return loaded
|
return loaded
|
||||||
|
|
||||||
for filename in files:
|
for filename in files:
|
||||||
|
if load_wdt is not None:
|
||||||
|
load_wdt.feed()
|
||||||
if not filename.endswith(".py") or filename in ("__init__.py", "main.py"):
|
if not filename.endswith(".py") or filename in ("__init__.py", "main.py"):
|
||||||
continue
|
continue
|
||||||
module_basename = filename[:-3]
|
module_basename = filename[:-3]
|
||||||
@@ -182,6 +190,14 @@ class Presets:
|
|||||||
print(f"Error in tick: {e}")
|
print(f"Error in tick: {e}")
|
||||||
self.generator = None
|
self.generator = None
|
||||||
|
|
||||||
|
def beat(self):
|
||||||
|
"""Step the selected pattern once; same effect as re-selecting it, without the message."""
|
||||||
|
name = self.selected
|
||||||
|
if name in self.presets:
|
||||||
|
preset = self.presets[name]
|
||||||
|
if preset.p in self.patterns:
|
||||||
|
self.generator = self.patterns[preset.p](preset)
|
||||||
|
|
||||||
def select(self, preset_name, step=None):
|
def select(self, preset_name, step=None):
|
||||||
# Auto-create simple built-in presets for common names on first use
|
# Auto-create simple built-in presets for common names on first use
|
||||||
if preset_name not in self.presets and preset_name in ("on", "off"):
|
if preset_name not in self.presets and preset_name in ("on", "off"):
|
||||||
@@ -193,20 +209,23 @@ class Presets:
|
|||||||
if preset_name in self.presets:
|
if preset_name in self.presets:
|
||||||
preset = self.presets[preset_name]
|
preset = self.presets[preset_name]
|
||||||
if preset.p in self.patterns:
|
if preset.p in self.patterns:
|
||||||
# Manual single-shot patterns: if this select arrives before the main loop has
|
if preset.p == "off":
|
||||||
# tick()'d the previous frame, completing it first keeps step in sync with beats.
|
self.generator = None
|
||||||
|
self.step = 0
|
||||||
|
self.fill((0, 0, 0))
|
||||||
|
self.selected = preset_name
|
||||||
|
return True
|
||||||
|
# If re-selecting the same preset before the main loop has tick()'d the
|
||||||
|
# previous frame, run one pending tick so step stays in sync.
|
||||||
if (
|
if (
|
||||||
preset_name == self.selected
|
preset_name == self.selected
|
||||||
and not preset.a
|
|
||||||
and preset.p in ("chase", "pulse")
|
|
||||||
and self.generator is not None
|
and self.generator is not None
|
||||||
):
|
):
|
||||||
while self.generator is not None:
|
|
||||||
self.tick()
|
self.tick()
|
||||||
# Set step value if explicitly provided
|
# Set step value if explicitly provided
|
||||||
if step is not None:
|
if step is not None:
|
||||||
self.step = step
|
self.step = step
|
||||||
elif preset.p == "off" or self.selected != preset_name:
|
elif self.selected != preset_name:
|
||||||
self.step = 0
|
self.step = 0
|
||||||
self.generator = self.patterns[preset.p](preset)
|
self.generator = self.patterns[preset.p](preset)
|
||||||
self.selected = preset_name # Store the preset name, not the object
|
self.selected = preset_name # Store the preset name, not the object
|
||||||
@@ -225,17 +244,22 @@ class Presets:
|
|||||||
def is_reversed(self, preset):
|
def is_reversed(self, preset):
|
||||||
from patterns.pattern_direction import is_reversed as _is_reversed
|
from patterns.pattern_direction import is_reversed as _is_reversed
|
||||||
|
|
||||||
return _is_reversed(preset)
|
return _is_reversed(preset, self)
|
||||||
|
|
||||||
def led_i(self, preset, logical_index):
|
def led_i(self, preset, logical_index):
|
||||||
from patterns.pattern_direction import led_i as _led_i
|
from patterns.pattern_direction import led_i as _led_i
|
||||||
|
|
||||||
return _led_i(self, preset, logical_index)
|
return _led_i(self, preset, logical_index)
|
||||||
|
|
||||||
|
def set(self, preset, logical_index, color):
|
||||||
|
from patterns.pattern_direction import set_led
|
||||||
|
|
||||||
|
set_led(self, preset, logical_index, color)
|
||||||
|
|
||||||
def signed(self, preset, value):
|
def signed(self, preset, value):
|
||||||
from patterns.pattern_direction import signed as _signed
|
from patterns.pattern_direction import signed as _signed
|
||||||
|
|
||||||
return _signed(preset, value)
|
return _signed(preset, value, self)
|
||||||
|
|
||||||
def apply_brightness(self, color, brightness_override=None):
|
def apply_brightness(self, color, brightness_override=None):
|
||||||
# Combine per-preset brightness (override) with global brightness self.b
|
# Combine per-preset brightness (override) with global brightness self.b
|
||||||
@@ -256,4 +280,43 @@ class Presets:
|
|||||||
def on(self, preset):
|
def on(self, preset):
|
||||||
colors = preset.c
|
colors = preset.c
|
||||||
color = colors[0] if colors else (255, 255, 255)
|
color = colors[0] if colors else (255, 255, 255)
|
||||||
|
while True:
|
||||||
self.fill(self.apply_brightness(color, preset.b))
|
self.fill(self.apply_brightness(color, preset.b))
|
||||||
|
yield
|
||||||
|
|
||||||
|
def blink(self, preset):
|
||||||
|
"""Built-in blink (used by controller identify); no patterns/ deploy required."""
|
||||||
|
colors = preset.c if preset.c else [(255, 255, 255)]
|
||||||
|
bg_color = self.apply_brightness(preset.background_or(colors), preset.b)
|
||||||
|
color_index = 0
|
||||||
|
delay_ms = max(1, int(preset.d))
|
||||||
|
period = delay_ms * 2
|
||||||
|
now = utime.ticks_ms()
|
||||||
|
# Phase-lock to wall time so group identify (broadcast select) stays in sync even
|
||||||
|
# when devices process the packet on different main-loop iterations.
|
||||||
|
phase = now % period if period else 0
|
||||||
|
state = phase < delay_ms
|
||||||
|
last_update = utime.ticks_add(now, -phase)
|
||||||
|
if state:
|
||||||
|
base = colors[color_index % len(colors)]
|
||||||
|
self.fill(self.apply_brightness(base, preset.b))
|
||||||
|
color_index += 1
|
||||||
|
else:
|
||||||
|
self.fill(bg_color)
|
||||||
|
while True:
|
||||||
|
now = utime.ticks_ms()
|
||||||
|
if utime.ticks_diff(now, last_update) >= delay_ms:
|
||||||
|
if state:
|
||||||
|
base = colors[color_index % len(colors)]
|
||||||
|
self.fill(self.apply_brightness(base, preset.b))
|
||||||
|
color_index += 1
|
||||||
|
else:
|
||||||
|
self.fill(bg_color)
|
||||||
|
state = not state
|
||||||
|
last_update = utime.ticks_add(last_update, delay_ms)
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
def run_tick(presets):
|
||||||
|
"""Advance one animation frame (standalone tests / mpremote demos)."""
|
||||||
|
presets.tick()
|
||||||
+8
-7
@@ -3,6 +3,8 @@ import ubinascii
|
|||||||
import machine
|
import machine
|
||||||
import network
|
import network
|
||||||
|
|
||||||
|
WIFI_CHANNEL_DEFAULT = 5
|
||||||
|
|
||||||
class Settings(dict):
|
class Settings(dict):
|
||||||
SETTINGS_FILE = "/settings.json"
|
SETTINGS_FILE = "/settings.json"
|
||||||
|
|
||||||
@@ -14,9 +16,9 @@ class Settings(dict):
|
|||||||
def set_defaults(self):
|
def set_defaults(self):
|
||||||
|
|
||||||
self["led_pin"] = 10
|
self["led_pin"] = 10
|
||||||
self["num_leds"] = 119
|
self["num_leds"] = 200
|
||||||
|
|
||||||
self["color_order"] = "rgb"
|
self["color_order"] = "grb"
|
||||||
|
|
||||||
sta = network.WLAN(network.STA_IF)
|
sta = network.WLAN(network.STA_IF)
|
||||||
sta.active(True)
|
sta.active(True)
|
||||||
@@ -31,11 +33,10 @@ class Settings(dict):
|
|||||||
# Power-on: "default" | "last" | "off"
|
# Power-on: "default" | "last" | "off"
|
||||||
self["startup_mode"] = "default"
|
self["startup_mode"] = "default"
|
||||||
self["brightness"] = 32
|
self["brightness"] = 32
|
||||||
self["transport_type"] = "espnow"
|
|
||||||
self["wifi_channel"] = 1
|
self["wifi_channel"] = WIFI_CHANNEL_DEFAULT
|
||||||
# ESP-NOW transport (requires espnow firmware; uses wifi_channel).
|
self["groups"] = []
|
||||||
self["ssid"] = ""
|
|
||||||
self["password"] = ""
|
|
||||||
|
|
||||||
def save(self):
|
def save(self):
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
"""Expand short v1 wire keys to long names (MicroPython)."""
|
||||||
|
|
||||||
|
|
||||||
|
K_PRESETS = "p"
|
||||||
|
K_SELECT = "s"
|
||||||
|
K_GROUPS = "g"
|
||||||
|
K_SET_GROUPS = "sg"
|
||||||
|
K_SAVE = "sv"
|
||||||
|
K_DEFAULT = "df"
|
||||||
|
K_DEVICE_CONFIG = "dc"
|
||||||
|
K_CLEAR_PRESETS = "cp"
|
||||||
|
K_MANIFEST = "mf"
|
||||||
|
|
||||||
|
_SHORT_TO_LONG = {
|
||||||
|
K_PRESETS: "presets",
|
||||||
|
K_SELECT: "select",
|
||||||
|
K_GROUPS: "groups",
|
||||||
|
K_SET_GROUPS: "set_groups",
|
||||||
|
K_SAVE: "save",
|
||||||
|
K_DEFAULT: "default",
|
||||||
|
K_DEVICE_CONFIG: "device_config",
|
||||||
|
K_CLEAR_PRESETS: "clear_presets",
|
||||||
|
K_MANIFEST: "manifest",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def expand_v1(data):
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return data
|
||||||
|
out = dict(data)
|
||||||
|
for short_key, long_key in _SHORT_TO_LONG.items():
|
||||||
|
if short_key in data and long_key not in out:
|
||||||
|
out[long_key] = data[short_key]
|
||||||
|
if short_key in out:
|
||||||
|
del out[short_key]
|
||||||
|
return out
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Send blink preset + select to a driver via the ESP-NOW bridge WebSocket.
|
||||||
|
|
||||||
|
Pairs with the on-device demo ``tests/patterns/blink.py``: same preset slot,
|
||||||
|
pattern, and colours; this script reaches the driver over ESP-NOW through
|
||||||
|
``espnow-sender`` (devices envelope, not legacy broadcast JSON).
|
||||||
|
|
||||||
|
Run from the **led-controller** repo (needs ``websockets`` in Pipenv)::
|
||||||
|
|
||||||
|
pipenv run python led-driver/tests/bridge_ws_blink.py
|
||||||
|
|
||||||
|
pipenv run python led-driver/tests/bridge_ws_blink.py \\
|
||||||
|
--url ws://192.168.4.1/ws --mac 18:8b:0e:15:60:a8
|
||||||
|
|
||||||
|
From **led-driver** (if Pipenv/env is the parent project)::
|
||||||
|
|
||||||
|
pipenv run python tests/bridge_ws_blink.py --dry-run
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
|
# led-driver/tests -> led-driver -> led-controller
|
||||||
|
LED_DRIVER_ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
PROJECT_ROOT = LED_DRIVER_ROOT.parent
|
||||||
|
|
||||||
|
|
||||||
|
def _load_bridge_url(explicit: Optional[str]) -> str:
|
||||||
|
if explicit and explicit.strip():
|
||||||
|
return explicit.strip()
|
||||||
|
for path in (PROJECT_ROOT / "settings.json", LED_DRIVER_ROOT / "settings.json"):
|
||||||
|
if not path.is_file():
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
data = json.loads(path.read_text(encoding="utf-8"))
|
||||||
|
url = str(data.get("bridge_ws_url") or "").strip()
|
||||||
|
if url:
|
||||||
|
return url
|
||||||
|
except (OSError, json.JSONDecodeError, TypeError):
|
||||||
|
pass
|
||||||
|
return "ws://192.168.4.1/ws"
|
||||||
|
|
||||||
|
|
||||||
|
def _format_mac(mac: str) -> str:
|
||||||
|
s = re.sub(r"[^0-9a-fA-F]", "", str(mac or "").strip().lower())
|
||||||
|
if len(s) != 12 or not re.fullmatch(r"[0-9a-f]{12}", s):
|
||||||
|
raise ValueError("MAC must be 12 hex digits (e.g. 188b0e1560a8)")
|
||||||
|
return ":".join(s[i : i + 2] for i in range(0, 12, 2))
|
||||||
|
|
||||||
|
|
||||||
|
def build_blink_envelope(
|
||||||
|
mac: str,
|
||||||
|
*,
|
||||||
|
preset_id: str = "2",
|
||||||
|
delay_ms: int = 200,
|
||||||
|
brightness: int = 64,
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""v1 devices envelope: preset body + list select (same shape as the Pi)."""
|
||||||
|
body = {
|
||||||
|
"p": {
|
||||||
|
preset_id: {
|
||||||
|
"p": "blink",
|
||||||
|
"b": max(0, min(255, int(brightness))),
|
||||||
|
"d": max(1, int(delay_ms)),
|
||||||
|
"c": ["#FF0000", "#0000FF"],
|
||||||
|
"a": True,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"s": [str(preset_id)],
|
||||||
|
}
|
||||||
|
return {"v": "1", "dv": {_format_mac(mac): body}}
|
||||||
|
|
||||||
|
|
||||||
|
async def _send(url: str, envelope: Dict[str, Any], hold_s: float) -> None:
|
||||||
|
import websockets
|
||||||
|
|
||||||
|
packet = json.dumps(envelope, separators=(",", ":")).encode("utf-8")
|
||||||
|
print(f"connecting to {url}")
|
||||||
|
async with websockets.connect(url, ping_interval=20, ping_timeout=20) as ws:
|
||||||
|
print(f"connected, sending {len(packet)} B")
|
||||||
|
print(packet.decode("utf-8"))
|
||||||
|
await ws.send(packet)
|
||||||
|
if hold_s > 0:
|
||||||
|
print(f"holding connection {hold_s}s …")
|
||||||
|
await asyncio.sleep(hold_s)
|
||||||
|
print("done")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Send blink preset+select to one driver via bridge WebSocket.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--url",
|
||||||
|
default=None,
|
||||||
|
help="Bridge WebSocket URL (default: settings.json bridge_ws_url or ws://192.168.4.1/ws)",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--mac",
|
||||||
|
default="188b0e1560a8",
|
||||||
|
help="Driver MAC (12 hex, colons optional). Default: registry example id.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--preset-id",
|
||||||
|
default="2",
|
||||||
|
help="Wire preset slot id (default: 2, matches zone push)",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--delay-ms",
|
||||||
|
type=int,
|
||||||
|
default=200,
|
||||||
|
help="Blink delay in ms (default: 200)",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--brightness",
|
||||||
|
type=int,
|
||||||
|
default=64,
|
||||||
|
help="Preset brightness 0–255 (default: 64)",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--hold",
|
||||||
|
type=float,
|
||||||
|
default=2.0,
|
||||||
|
help="Seconds to keep WebSocket open after send (default: 2)",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--dry-run",
|
||||||
|
action="store_true",
|
||||||
|
help="Print envelope only; do not connect",
|
||||||
|
)
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
url = _load_bridge_url(args.url)
|
||||||
|
try:
|
||||||
|
envelope = build_blink_envelope(
|
||||||
|
args.mac,
|
||||||
|
preset_id=args.preset_id,
|
||||||
|
delay_ms=args.delay_ms,
|
||||||
|
brightness=args.brightness,
|
||||||
|
)
|
||||||
|
except ValueError as e:
|
||||||
|
print(f"error: {e}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
print(f"url={url!r} mac={_format_mac(args.mac)!r}")
|
||||||
|
if args.dry_run:
|
||||||
|
print(json.dumps(envelope, indent=2))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
try:
|
||||||
|
asyncio.run(_send(url, envelope, args.hold))
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("interrupted")
|
||||||
|
return 130
|
||||||
|
except Exception as e:
|
||||||
|
print(f"failed: {e!r}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
"""Device-side radio diagnostic test (MicroPython).
|
||||||
|
|
||||||
|
Checks:
|
||||||
|
1) STA/AP bring-up on channel 5
|
||||||
|
2) ESP-NOW init and broadcast peer add
|
||||||
|
3) Broadcast TX test packet send
|
||||||
|
4) RX wait window to see any incoming ESP-NOW frames
|
||||||
|
"""
|
||||||
|
|
||||||
|
import espnow
|
||||||
|
import machine
|
||||||
|
import network
|
||||||
|
import time
|
||||||
|
import ubinascii
|
||||||
|
|
||||||
|
|
||||||
|
CHANNEL = 5
|
||||||
|
RX_WINDOW_MS = 3000
|
||||||
|
WDT_TIMEOUT_MS = 10000
|
||||||
|
BROADCAST_MAC = b"\xff\xff\xff\xff\xff\xff"
|
||||||
|
TEST_PAYLOAD = b"\x4c\x05\x01\x00\x00\x00"
|
||||||
|
|
||||||
|
|
||||||
|
def _mac_hex(mac_bytes):
|
||||||
|
try:
|
||||||
|
return ubinascii.hexlify(mac_bytes).decode()
|
||||||
|
except Exception:
|
||||||
|
return "?"
|
||||||
|
|
||||||
|
|
||||||
|
def run_diag(channel=CHANNEL, rx_window_ms=RX_WINDOW_MS):
|
||||||
|
wdt = machine.WDT(timeout=WDT_TIMEOUT_MS)
|
||||||
|
wdt.feed()
|
||||||
|
|
||||||
|
print("diag start")
|
||||||
|
print("cpu freq", machine.freq())
|
||||||
|
|
||||||
|
sta = network.WLAN(network.STA_IF)
|
||||||
|
ap = network.WLAN(network.AP_IF)
|
||||||
|
|
||||||
|
# Clean start
|
||||||
|
try:
|
||||||
|
sta.active(False)
|
||||||
|
ap.active(False)
|
||||||
|
time.sleep_ms(100)
|
||||||
|
except Exception as e:
|
||||||
|
print("wifi reset failed", repr(e))
|
||||||
|
|
||||||
|
# STA setup
|
||||||
|
try:
|
||||||
|
sta.active(True)
|
||||||
|
sta.config(pm=network.WLAN.PM_NONE)
|
||||||
|
sta.config(channel=channel)
|
||||||
|
print("sta ok ch", sta.config("channel"), "mac", _mac_hex(sta.config("mac")))
|
||||||
|
except Exception as e:
|
||||||
|
print("sta setup failed", repr(e))
|
||||||
|
|
||||||
|
# AP setup
|
||||||
|
try:
|
||||||
|
ap.active(True)
|
||||||
|
try:
|
||||||
|
ap.config(essid="diag-ap", channel=channel, hidden=True)
|
||||||
|
except TypeError:
|
||||||
|
ap.config(essid="diag-ap", channel=channel)
|
||||||
|
print("ap ok ch", ap.config("channel"), "mac", _mac_hex(ap.config("mac")))
|
||||||
|
except Exception as e:
|
||||||
|
print("ap setup failed", repr(e))
|
||||||
|
|
||||||
|
wdt.feed()
|
||||||
|
|
||||||
|
# ESP-NOW setup
|
||||||
|
try:
|
||||||
|
e = espnow.ESPNow()
|
||||||
|
e.active(True)
|
||||||
|
print("espnow active ok")
|
||||||
|
except Exception as e_err:
|
||||||
|
print("espnow init failed", repr(e_err))
|
||||||
|
return
|
||||||
|
|
||||||
|
# Add broadcast peer
|
||||||
|
try:
|
||||||
|
e.add_peer(BROADCAST_MAC, channel=channel)
|
||||||
|
print("add bcast peer ok")
|
||||||
|
except TypeError:
|
||||||
|
try:
|
||||||
|
e.add_peer(BROADCAST_MAC)
|
||||||
|
print("add bcast peer ok (no channel arg)")
|
||||||
|
except Exception as e_err:
|
||||||
|
print("add bcast peer failed", repr(e_err))
|
||||||
|
except Exception as e_err:
|
||||||
|
print("add bcast peer failed", repr(e_err))
|
||||||
|
|
||||||
|
# TX test
|
||||||
|
try:
|
||||||
|
ok = e.send(BROADCAST_MAC, TEST_PAYLOAD, True)
|
||||||
|
print("tx bcast", ok, "len", len(TEST_PAYLOAD))
|
||||||
|
except Exception as e_err:
|
||||||
|
print("tx bcast failed", repr(e_err))
|
||||||
|
|
||||||
|
# RX window
|
||||||
|
print("rx window ms", rx_window_ms)
|
||||||
|
t_end = time.ticks_add(time.ticks_ms(), rx_window_ms)
|
||||||
|
rx_count = 0
|
||||||
|
while time.ticks_diff(t_end, time.ticks_ms()) > 0:
|
||||||
|
wdt.feed()
|
||||||
|
host, msg = e.recv(100)
|
||||||
|
if host:
|
||||||
|
rx_count += 1
|
||||||
|
print("rx", rx_count, _mac_hex(host), "len", len(msg))
|
||||||
|
time.sleep_ms(5)
|
||||||
|
|
||||||
|
print("diag done rx_count", rx_count)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
run_diag()
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
"""Device test: receive ESP-NOW packets on channel 5 (MicroPython)."""
|
||||||
|
|
||||||
|
import espnow
|
||||||
|
import machine
|
||||||
|
import network
|
||||||
|
import ubinascii
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
CHANNEL = 5
|
||||||
|
TIMEOUT_MS = 1000
|
||||||
|
WDT_TIMEOUT_MS = 10000
|
||||||
|
|
||||||
|
|
||||||
|
def _set_channel(channel):
|
||||||
|
sta = network.WLAN(network.STA_IF)
|
||||||
|
sta.active(True)
|
||||||
|
sta.config(pm=network.WLAN.PM_NONE)
|
||||||
|
sta.config(channel=channel)
|
||||||
|
|
||||||
|
|
||||||
|
def recv_loop(channel=CHANNEL, timeout_ms=TIMEOUT_MS):
|
||||||
|
wdt = machine.WDT(timeout=WDT_TIMEOUT_MS)
|
||||||
|
_set_channel(channel)
|
||||||
|
e = espnow.ESPNow()
|
||||||
|
e.active(True)
|
||||||
|
print("recv ready ch", channel)
|
||||||
|
while True:
|
||||||
|
wdt.feed()
|
||||||
|
host, msg = e.recv(timeout_ms)
|
||||||
|
if host:
|
||||||
|
mac_hex = ubinascii.hexlify(host).decode()
|
||||||
|
print("rx", mac_hex, "len", len(msg), "hex", ubinascii.hexlify(msg).decode())
|
||||||
|
else:
|
||||||
|
print("rx timeout")
|
||||||
|
time.sleep_ms(10)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
recv_loop()
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
"""Device test: send one ESP-NOW packet on channel 5 (MicroPython)."""
|
||||||
|
|
||||||
|
import espnow
|
||||||
|
import machine
|
||||||
|
import network
|
||||||
|
import ubinascii
|
||||||
|
|
||||||
|
|
||||||
|
CHANNEL = 5
|
||||||
|
DEST_HEX = "ffffffffffff"
|
||||||
|
PAYLOAD_HEX = "4c0501000000"
|
||||||
|
WDT_TIMEOUT_MS = 10000
|
||||||
|
|
||||||
|
|
||||||
|
def _set_channel(channel):
|
||||||
|
sta = network.WLAN(network.STA_IF)
|
||||||
|
sta.active(True)
|
||||||
|
sta.config(pm=network.WLAN.PM_NONE)
|
||||||
|
sta.config(channel=channel)
|
||||||
|
|
||||||
|
|
||||||
|
def _add_peer(esp, dest, channel):
|
||||||
|
try:
|
||||||
|
esp.add_peer(dest, channel=channel)
|
||||||
|
except TypeError:
|
||||||
|
esp.add_peer(dest)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def send_once(dest_hex=DEST_HEX, payload_hex=PAYLOAD_HEX, channel=CHANNEL):
|
||||||
|
wdt = machine.WDT(timeout=WDT_TIMEOUT_MS)
|
||||||
|
wdt.feed()
|
||||||
|
dest = ubinascii.unhexlify(dest_hex)
|
||||||
|
pkt = ubinascii.unhexlify(payload_hex)
|
||||||
|
_set_channel(channel)
|
||||||
|
e = espnow.ESPNow()
|
||||||
|
e.active(True)
|
||||||
|
_add_peer(e, dest, channel)
|
||||||
|
wdt.feed()
|
||||||
|
ok = e.send(dest, pkt, True)
|
||||||
|
print("sent", ok, "ch", channel, "dest", dest_hex, "len", len(pkt))
|
||||||
|
return ok
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
send_once()
|
||||||
+59
-20
@@ -1,35 +1,74 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
|
"""Standalone blink pattern demo (WDT-fed tick loop).
|
||||||
|
|
||||||
|
Run on device::
|
||||||
|
|
||||||
|
mpremote connect <port> run tests/patterns/blink.py
|
||||||
|
"""
|
||||||
|
import sys
|
||||||
import utime
|
import utime
|
||||||
from machine import WDT
|
|
||||||
from settings import Settings
|
|
||||||
from presets import Presets, run_tick
|
def _bootstrap_import_path():
|
||||||
|
"""Find ``settings`` / ``presets`` on device or when run via mpremote."""
|
||||||
|
try:
|
||||||
|
import uos as os
|
||||||
|
except ImportError:
|
||||||
|
import os
|
||||||
|
|
||||||
|
candidates = []
|
||||||
|
try:
|
||||||
|
here = __file__.rsplit("/", 1)[0]
|
||||||
|
if here:
|
||||||
|
candidates.append(here)
|
||||||
|
tests = here.rsplit("/", 1)[0]
|
||||||
|
if tests:
|
||||||
|
candidates.append(tests)
|
||||||
|
root = tests.rsplit("/", 1)[0]
|
||||||
|
if root:
|
||||||
|
candidates.append(root)
|
||||||
|
candidates.append(root + "/src")
|
||||||
|
except NameError:
|
||||||
|
pass
|
||||||
|
for p in (".", "..", "/", "src", "/src"):
|
||||||
|
candidates.append(p)
|
||||||
|
for p in candidates:
|
||||||
|
if p and p not in sys.path:
|
||||||
|
sys.path.insert(0, p)
|
||||||
|
|
||||||
|
|
||||||
|
_bootstrap_import_path()
|
||||||
|
|
||||||
|
from machine import WDT # noqa: E402
|
||||||
|
from settings import Settings # noqa: E402
|
||||||
|
from presets import Presets # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def _run_ms(presets, wdt, duration_ms, sleep_ms=10):
|
||||||
|
start = utime.ticks_ms()
|
||||||
|
while utime.ticks_diff(utime.ticks_ms(), start) < duration_ms:
|
||||||
|
wdt.feed()
|
||||||
|
presets.tick()
|
||||||
|
utime.sleep_ms(sleep_ms)
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
s = Settings()
|
settings = Settings()
|
||||||
pin = s.get("led_pin", 10)
|
presets = Presets(settings.get("led_pin", 10), settings.get("num_leds", 30))
|
||||||
num = s.get("num_leds", 30)
|
|
||||||
|
|
||||||
p = Presets(pin=pin, num_leds=num)
|
|
||||||
wdt = WDT(timeout=10000)
|
wdt = WDT(timeout=10000)
|
||||||
|
|
||||||
# Create blink preset (use short-key fields: p=pattern, b=brightness, d=delay, c=colors)
|
presets.edit(
|
||||||
p.edit("test_blink", {
|
"test_blink",
|
||||||
|
{
|
||||||
"p": "blink",
|
"p": "blink",
|
||||||
"b": 64,
|
"b": 64,
|
||||||
"d": 200,
|
"d": 200,
|
||||||
"c": [(255, 0, 0), (0, 0, 255)],
|
"c": [(255, 0, 0), (0, 0, 255)],
|
||||||
})
|
},
|
||||||
p.select("test_blink")
|
)
|
||||||
|
presets.select("test_blink")
|
||||||
start = utime.ticks_ms()
|
_run_ms(presets, wdt, 1500)
|
||||||
while utime.ticks_diff(utime.ticks_ms(), start) < 1500:
|
|
||||||
wdt.feed()
|
|
||||||
run_tick(p)
|
|
||||||
utime.sleep_ms(10)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""BeatSync accepts exactly one of the two copies of each beat - runs on MicroPython."""
|
||||||
|
import struct
|
||||||
|
from beat_sync import BeatSync
|
||||||
|
|
||||||
|
|
||||||
|
def frame(idx, period=500, fire_in=30, flags=0):
|
||||||
|
return struct.pack("<BBBHHB", 0x4C, 0x25, flags, idx, period, fire_in)
|
||||||
|
|
||||||
|
|
||||||
|
def run(events, tick=1):
|
||||||
|
"""events: (time_ms, frame_bytes). Returns the number of fires."""
|
||||||
|
b = BeatSync()
|
||||||
|
fires = 0
|
||||||
|
t = 0
|
||||||
|
end = events[-1][0] + 200
|
||||||
|
ev = list(events)
|
||||||
|
while t < end:
|
||||||
|
while ev and ev[0][0] <= t:
|
||||||
|
b.on_frame(ev.pop(0)[1], t)
|
||||||
|
if b.poll(t):
|
||||||
|
fires += 1
|
||||||
|
t += tick
|
||||||
|
return fires
|
||||||
|
|
||||||
|
|
||||||
|
def test_both_copies():
|
||||||
|
assert run([(0, frame(1)), (2, frame(1, fire_in=28))]) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_only_first():
|
||||||
|
assert run([(0, frame(1))]) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_only_second():
|
||||||
|
assert run([(2, frame(1, fire_in=28))]) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_wraparound():
|
||||||
|
b = BeatSync()
|
||||||
|
assert b.on_frame(frame(0xFFFF), 0)
|
||||||
|
assert not b.on_frame(frame(0xFFFF), 2)
|
||||||
|
assert b.on_frame(frame(0), 500)
|
||||||
|
|
||||||
|
|
||||||
|
def test_late_old_copy_ignored():
|
||||||
|
b = BeatSync()
|
||||||
|
assert b.on_frame(frame(5), 0)
|
||||||
|
assert b.on_frame(frame(6), 500)
|
||||||
|
assert not b.on_frame(frame(5), 502)
|
||||||
|
|
||||||
|
|
||||||
|
def test_two_beats_two_fires():
|
||||||
|
ev = [(0, frame(1)), (2, frame(1)), (500, frame(2)), (502, frame(2))]
|
||||||
|
assert run(ev) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_free_run_covers_missed_beat():
|
||||||
|
# beat 3 lost entirely: the driver still fires about once per period
|
||||||
|
ev = [(0, frame(1)), (2, frame(1)), (500, frame(2)), (502, frame(2)), (1500, frame(4)), (1502, frame(4))]
|
||||||
|
assert run(ev) == 4
|
||||||
|
|
||||||
|
|
||||||
|
def test_bad_frames():
|
||||||
|
b = BeatSync()
|
||||||
|
assert not b.on_frame(b"\x00" * 8, 0)
|
||||||
|
assert not b.on_frame(b"\xb1\x00", 0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_freerun_flag_marks_invented_beats():
|
||||||
|
b = BeatSync()
|
||||||
|
b.on_frame(frame(1), 0)
|
||||||
|
assert b.poll(40) is True and b.freerun_fire is False
|
||||||
|
assert b.poll(700) is True and b.freerun_fire is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_stats_count_dups_and_freerun():
|
||||||
|
b = BeatSync()
|
||||||
|
b.on_frame(frame(1), 0)
|
||||||
|
b.on_frame(frame(1), 2)
|
||||||
|
b.poll(40)
|
||||||
|
assert b.stats["fires"] == 1 and b.stats["dups"] == 1
|
||||||
|
b.poll(700)
|
||||||
|
assert b.stats["freerun"] == 1 and b.stats["fires"] == 2
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
for name, fn in list(globals().items()):
|
||||||
|
if name.startswith("test_"):
|
||||||
|
fn()
|
||||||
|
print("ok", name)
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Ota: staging, chunk bitmap, hash checks, commit and sessions. Runs in a temp directory."""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import struct
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
import espnow_ota as o
|
||||||
|
import file_hashes
|
||||||
|
|
||||||
|
M = b"\x01\x02\x03\x04\x05\x06"
|
||||||
|
|
||||||
|
|
||||||
|
def begin(sess, path, body):
|
||||||
|
p = path.encode()
|
||||||
|
return struct.pack("<BBHI", 0x4C, o.OP_BEGIN, sess, len(body)) + hashlib.sha256(body).digest() + bytes([len(p)]) + p
|
||||||
|
|
||||||
|
|
||||||
|
def chunk(sess, body, idx):
|
||||||
|
return struct.pack("<BBHH", 0x4C, o.OP_DATA, sess, idx) + body[idx * o.CHUNK : (idx + 1) * o.CHUNK]
|
||||||
|
|
||||||
|
|
||||||
|
def cmd(op, sess):
|
||||||
|
return struct.pack("<BBH", 0x4C, op, sess)
|
||||||
|
|
||||||
|
|
||||||
|
def nchunks(body):
|
||||||
|
return (len(body) + o.CHUNK - 1) // o.CHUNK
|
||||||
|
|
||||||
|
|
||||||
|
class Rig:
|
||||||
|
def __init__(self):
|
||||||
|
self.sent, self.resets = [], 0
|
||||||
|
self.ota = o.Ota(lambda mac, f: self.sent.append(f), self._reset)
|
||||||
|
|
||||||
|
def _reset(self):
|
||||||
|
self.resets += 1
|
||||||
|
|
||||||
|
def __call__(self, pkt):
|
||||||
|
self.ota.handle(M, pkt)
|
||||||
|
if self.sent:
|
||||||
|
f = self.sent.pop()
|
||||||
|
_, t, sess, op, code = struct.unpack_from("<BBHBB", f)
|
||||||
|
assert t == o.MSG_STATUS
|
||||||
|
return op, code, f[6:]
|
||||||
|
return None
|
||||||
|
|
||||||
|
def send_file(self, sess, path, body, skip=()):
|
||||||
|
assert self(begin(sess, path, body))[1] == o.READY
|
||||||
|
for i in range(nchunks(body)):
|
||||||
|
if i not in skip:
|
||||||
|
assert self(chunk(sess, body, i)) is None # data is acked by the link, not here
|
||||||
|
return self(cmd(o.OP_END, sess))[1]
|
||||||
|
|
||||||
|
|
||||||
|
def in_tmp(fn):
|
||||||
|
def run():
|
||||||
|
old = os.getcwd()
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
os.chdir(d)
|
||||||
|
try:
|
||||||
|
fn()
|
||||||
|
finally:
|
||||||
|
os.chdir(old)
|
||||||
|
|
||||||
|
run.__name__ = fn.__name__
|
||||||
|
return run
|
||||||
|
|
||||||
|
|
||||||
|
BODY = bytes(range(256)) * 10 # 2560 bytes, 3 chunks
|
||||||
|
|
||||||
|
|
||||||
|
@in_tmp
|
||||||
|
def test_write_commit_and_manifest():
|
||||||
|
r = Rig()
|
||||||
|
assert r.send_file(5, "patterns/wave.py", BODY) == o.OK
|
||||||
|
assert not os.path.exists("patterns/wave.py") # staged only
|
||||||
|
op, code, arg = r(cmd(o.OP_COMMIT, 5))
|
||||||
|
assert (op, code, struct.unpack("<I", arg)[0]) == (o.OP_COMMIT, o.OK, 1)
|
||||||
|
assert open("patterns/wave.py", "rb").read() == BODY and not os.path.exists("patterns/wave.py.new")
|
||||||
|
assert file_hashes.load()["patterns/wave.py"] == hashlib.sha256(BODY).hexdigest()
|
||||||
|
assert r.resets == 1
|
||||||
|
|
||||||
|
|
||||||
|
@in_tmp
|
||||||
|
def test_same_file_is_skipped():
|
||||||
|
with open("main.py", "wb") as f:
|
||||||
|
f.write(BODY)
|
||||||
|
r = Rig()
|
||||||
|
assert r(begin(1, "main.py", BODY))[1] == o.SAME
|
||||||
|
op, code, _ = r(cmd(o.OP_COMMIT, 1))
|
||||||
|
assert code == o.OK and r.resets == 0 # nothing moved, no reset
|
||||||
|
|
||||||
|
|
||||||
|
@in_tmp
|
||||||
|
def test_out_of_order_and_duplicate_chunks():
|
||||||
|
r = Rig()
|
||||||
|
assert r(begin(2, "a.py", BODY))[1] == o.READY
|
||||||
|
for i in (2, 0, 2, 1, 0):
|
||||||
|
r(chunk(2, BODY, i))
|
||||||
|
assert r(cmd(o.OP_END, 2))[1] == o.OK
|
||||||
|
r(cmd(o.OP_COMMIT, 2))
|
||||||
|
assert open("a.py", "rb").read() == BODY
|
||||||
|
|
||||||
|
|
||||||
|
@in_tmp
|
||||||
|
def test_incomplete_then_missing_then_repair():
|
||||||
|
r = Rig()
|
||||||
|
assert r.send_file(3, "a.py", BODY, skip=(0, 2)) == o.INCOMPLETE
|
||||||
|
op, code, arg = r(cmd(o.OP_MISSING, 3))
|
||||||
|
cnt = struct.unpack_from("<H", arg)[0]
|
||||||
|
assert (op, cnt, arg[2]) == (o.OP_MISSING, 3, 0b101)
|
||||||
|
r(chunk(3, BODY, 0))
|
||||||
|
r(chunk(3, BODY, 2))
|
||||||
|
assert r(cmd(o.OP_MISSING, 3))[2][2] == 0
|
||||||
|
assert r(cmd(o.OP_END, 3))[1] == o.OK
|
||||||
|
|
||||||
|
|
||||||
|
@in_tmp
|
||||||
|
def test_bad_hash_is_not_staged():
|
||||||
|
r = Rig()
|
||||||
|
bad = bytearray(begin(4, "a.py", BODY))
|
||||||
|
bad[8] ^= 0xFF
|
||||||
|
assert r(bytes(bad))[1] == o.READY
|
||||||
|
for i in range(nchunks(BODY)):
|
||||||
|
r(chunk(4, BODY, i))
|
||||||
|
assert r(cmd(o.OP_END, 4))[1] == o.BADHASH
|
||||||
|
r(cmd(o.OP_COMMIT, 4))
|
||||||
|
assert not os.path.exists("a.py") and not os.path.exists("a.py.new") and r.resets == 0
|
||||||
|
|
||||||
|
|
||||||
|
@in_tmp
|
||||||
|
def test_bad_paths():
|
||||||
|
r = Rig()
|
||||||
|
for p in ("../x.py", "/main.py", "a/b.py", "lib//x.py", "file_hashes.json", "patterns\\x.py", "lib/../main.py"):
|
||||||
|
assert r(begin(6, p, b"x"))[1] == o.BADPATH, p
|
||||||
|
for p in ("main.py", "patterns/x.py", "lib/microdot/websocket.py"):
|
||||||
|
assert r(begin(6, p, b"x"))[1] == o.READY, p
|
||||||
|
|
||||||
|
|
||||||
|
@in_tmp
|
||||||
|
def test_new_session_discards_staged():
|
||||||
|
r = Rig()
|
||||||
|
assert r.send_file(7, "a.py", BODY) == o.OK
|
||||||
|
assert os.path.exists("a.py.new")
|
||||||
|
assert r(begin(8, "b.py", b"bb"))[1] == o.READY
|
||||||
|
assert not os.path.exists("a.py.new")
|
||||||
|
assert r(cmd(o.OP_COMMIT, 7))[1] == o.NOSESS # old session is gone
|
||||||
|
|
||||||
|
|
||||||
|
@in_tmp
|
||||||
|
def test_repeated_begin_and_end_are_idempotent():
|
||||||
|
r = Rig()
|
||||||
|
assert r(begin(9, "a.py", BODY))[1] == o.READY
|
||||||
|
r(chunk(9, BODY, 0))
|
||||||
|
assert r(begin(9, "a.py", BODY))[1] == o.READY # reply was lost, controller asks again
|
||||||
|
r(chunk(9, BODY, 1))
|
||||||
|
r(chunk(9, BODY, 2))
|
||||||
|
assert r(cmd(o.OP_END, 9))[1] == o.OK
|
||||||
|
assert r(cmd(o.OP_END, 9))[1] == o.OK
|
||||||
|
assert r(begin(9, "a.py", BODY))[1] == o.READY # already staged with that hash
|
||||||
|
|
||||||
|
|
||||||
|
@in_tmp
|
||||||
|
def test_abort_removes_staged():
|
||||||
|
r = Rig()
|
||||||
|
r.send_file(10, "a.py", BODY)
|
||||||
|
assert r(cmd(o.OP_ABORT, 10))[1] == o.OK
|
||||||
|
assert not os.path.exists("a.py.new")
|
||||||
|
assert r(cmd(o.OP_COMMIT, 10))[2] == struct.pack("<I", 0)
|
||||||
|
|
||||||
|
|
||||||
|
@in_tmp
|
||||||
|
def test_broadcast_with_loss_recovers():
|
||||||
|
# three drivers share one broadcast; each drops different chunks, then gets repaired by unicast
|
||||||
|
body = os.urandom(o.CHUNK * 7 + 100)
|
||||||
|
rigs = [Rig() for _ in range(3)]
|
||||||
|
for k, r in enumerate(rigs):
|
||||||
|
os.makedirs(str(k))
|
||||||
|
old = os.getcwd()
|
||||||
|
for k, r in enumerate(rigs):
|
||||||
|
os.chdir(str(k))
|
||||||
|
assert r(begin(11, "lib/x.py", body))[1] == o.READY
|
||||||
|
for i in range(nchunks(body)):
|
||||||
|
if (i + k) % 3:
|
||||||
|
r(chunk(11, body, i))
|
||||||
|
assert r(cmd(o.OP_END, 11))[1] == o.INCOMPLETE
|
||||||
|
arg = r(cmd(o.OP_MISSING, 11))[2]
|
||||||
|
cnt = struct.unpack_from("<H", arg)[0]
|
||||||
|
for i in range(cnt):
|
||||||
|
if arg[2 + (i >> 3)] & (1 << (i & 7)):
|
||||||
|
r(chunk(11, body, i))
|
||||||
|
assert r(cmd(o.OP_END, 11))[1] == o.OK
|
||||||
|
r(cmd(o.OP_COMMIT, 11))
|
||||||
|
assert open("lib/x.py", "rb").read() == body
|
||||||
|
os.chdir(old)
|
||||||
|
|
||||||
|
|
||||||
|
@in_tmp
|
||||||
|
def test_commit_repeated_after_reset():
|
||||||
|
r = Rig()
|
||||||
|
r.send_file(14, "a.py", BODY)
|
||||||
|
assert r(cmd(o.OP_COMMIT, 14))[1] == o.OK
|
||||||
|
fresh = Rig() # the driver reset before its reply arrived
|
||||||
|
op, code, arg = fresh(cmd(o.OP_COMMIT, 14))
|
||||||
|
assert code == o.OK and fresh.resets == 0
|
||||||
|
assert fresh(cmd(o.OP_COMMIT, 15))[1] == o.NOSESS
|
||||||
|
|
||||||
|
|
||||||
|
@in_tmp
|
||||||
|
def test_empty_file():
|
||||||
|
r = Rig()
|
||||||
|
assert r.send_file(13, "lib/pkg/__init__.py", b"") == o.OK
|
||||||
|
r(cmd(o.OP_COMMIT, 13))
|
||||||
|
assert open("lib/pkg/__init__.py", "rb").read() == b""
|
||||||
|
|
||||||
|
|
||||||
|
@in_tmp
|
||||||
|
def test_too_big_rejected():
|
||||||
|
r = Rig()
|
||||||
|
pkt = bytearray(begin(12, "a.py", b"x"))
|
||||||
|
struct.pack_into("<I", pkt, 4, o.MAX_SIZE + 1)
|
||||||
|
assert r(bytes(pkt))[1] == o.TOOBIG
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
for name, fn in list(globals().items()):
|
||||||
|
if name.startswith("test_"):
|
||||||
|
fn()
|
||||||
|
print("ok")
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""LinkRx: reassembly, dedupe, acks, commit and digest resync."""
|
||||||
|
import struct
|
||||||
|
from espnow_rx import LinkRx, MSG_DATA, MSG_ACK, MSG_DIGEST, MSG_RESYNC, F_ACK, F_COMMIT, INBOX_MAX
|
||||||
|
from beat_sync import BeatSync
|
||||||
|
|
||||||
|
M = b"\x01\x02\x03\x04\x05\x06"
|
||||||
|
|
||||||
|
|
||||||
|
def data(seq, payload, idx=0, cnt=1, flags=F_ACK, ver=0):
|
||||||
|
return struct.pack("<BBBHHBB", 0x4C, MSG_DATA, flags, seq, ver, idx, cnt) + payload
|
||||||
|
|
||||||
|
|
||||||
|
def make(jitter=0):
|
||||||
|
got, sent = [], []
|
||||||
|
link = LinkRx(lambda mac, m: got.append(m), BeatSync(), lambda mac, f: sent.append((mac, f)), jitter)
|
||||||
|
return link, got, sent
|
||||||
|
|
||||||
|
|
||||||
|
def feed(link, frame, now=0, mac=M):
|
||||||
|
link.on_packet(mac, frame, now)
|
||||||
|
link.poll(now)
|
||||||
|
|
||||||
|
|
||||||
|
def test_single():
|
||||||
|
link, got, sent = make()
|
||||||
|
feed(link, data(1, b"hello"))
|
||||||
|
assert got == [b"hello"]
|
||||||
|
_, t, _, seq, cnt, mask = struct.unpack("<BBBHBI", sent[0][1])
|
||||||
|
assert (t, seq, cnt, mask) == (MSG_ACK, 1, 1, 1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_duplicate_acks_again_but_delivers_once():
|
||||||
|
link, got, sent = make()
|
||||||
|
feed(link, data(1, b"x"))
|
||||||
|
feed(link, data(1, b"x"), now=60)
|
||||||
|
assert got == [b"x"] and len(sent) == 2 and link.stats["dups"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_fragments_out_of_order_and_partial_mask():
|
||||||
|
link, got, sent = make()
|
||||||
|
feed(link, data(7, b"CC", 2, 3))
|
||||||
|
assert got == [] and struct.unpack("<BBBHBI", sent[-1][1])[5] == 0b100
|
||||||
|
feed(link, data(7, b"AA", 0, 3))
|
||||||
|
assert struct.unpack("<BBBHBI", sent[-1][1])[5] == 0b101
|
||||||
|
feed(link, data(7, b"BB", 1, 3))
|
||||||
|
assert got == [b"AABBCC"] and struct.unpack("<BBBHBI", sent[-1][1])[5] == 0b111
|
||||||
|
|
||||||
|
|
||||||
|
def test_stale_fragments_dropped():
|
||||||
|
link, got, _ = make()
|
||||||
|
feed(link, data(3, b"A", 0, 2), now=0)
|
||||||
|
feed(link, data(9, b"x"), now=4000) # triggers cleanup
|
||||||
|
feed(link, data(3, b"B", 1, 2), now=4001)
|
||||||
|
assert got == [b"x"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_ack_when_not_requested():
|
||||||
|
link, got, sent = make()
|
||||||
|
feed(link, data(2, b"b", flags=0))
|
||||||
|
assert got == [b"b"] and sent == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_commit_sets_version_only_when_complete():
|
||||||
|
link, got, _ = make()
|
||||||
|
feed(link, data(1, b"A", 0, 2, F_ACK | F_COMMIT, ver=5))
|
||||||
|
assert link.ver == 0
|
||||||
|
feed(link, data(1, b"B", 1, 2, F_ACK | F_COMMIT, ver=5))
|
||||||
|
assert link.ver == 5
|
||||||
|
feed(link, data(2, b"p", flags=0, ver=6)) # no commit flag: version unchanged
|
||||||
|
assert link.ver == 5
|
||||||
|
|
||||||
|
|
||||||
|
def digest(ver):
|
||||||
|
return struct.pack("<BBH", 0x4C, MSG_DIGEST, ver)
|
||||||
|
|
||||||
|
|
||||||
|
def test_digest_match_no_resync():
|
||||||
|
link, _, sent = make()
|
||||||
|
feed(link, data(1, b"a", flags=F_COMMIT, ver=4))
|
||||||
|
feed(link, digest(4), now=100)
|
||||||
|
link.poll(5000)
|
||||||
|
assert not [s for s in sent if s[1][1] == MSG_RESYNC]
|
||||||
|
|
||||||
|
|
||||||
|
def test_digest_mismatch_requests_resync_after_jitter_and_rate_limits():
|
||||||
|
link, _, sent = make(jitter=300)
|
||||||
|
feed(link, digest(9), now=1000)
|
||||||
|
link.poll(1100)
|
||||||
|
assert sent == [] # jitter not elapsed
|
||||||
|
link.poll(1300)
|
||||||
|
assert sent[-1] == (M, struct.pack("<BBH", 0x4C, MSG_RESYNC, 0))
|
||||||
|
feed(link, digest(9), now=2000)
|
||||||
|
link.poll(2400)
|
||||||
|
assert len(sent) == 1 # within the 3 s gap
|
||||||
|
feed(link, digest(9), now=4500)
|
||||||
|
link.poll(4900)
|
||||||
|
assert len(sent) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_resync_cancelled_when_state_arrives():
|
||||||
|
link, _, sent = make(jitter=500)
|
||||||
|
feed(link, digest(9), now=0)
|
||||||
|
feed(link, data(1, b"s", flags=F_COMMIT, ver=9), now=100)
|
||||||
|
link.poll(600)
|
||||||
|
assert sent == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_digest_zero_ignored():
|
||||||
|
link, _, sent = make()
|
||||||
|
feed(link, digest(0), now=0)
|
||||||
|
link.poll(5000)
|
||||||
|
assert sent == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_legacy_and_beat_frames():
|
||||||
|
link, got, _ = make()
|
||||||
|
feed(link, b"\x4c\x03\x02\xff\x00\x00\x00") # plain CMD passes straight to the handler
|
||||||
|
feed(link, b'{"v":"1"}')
|
||||||
|
assert len(got) == 2
|
||||||
|
link.on_packet(M, struct.pack("<BBBHHB", 0x4C, 0x25, 0, 1, 500, 0), 0)
|
||||||
|
assert link.beat.poll(0) is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_inbox_overflow_counted():
|
||||||
|
link, _, _ = make()
|
||||||
|
for i in range(INBOX_MAX + 4):
|
||||||
|
link.on_packet(M, data(i, b"x"), 0)
|
||||||
|
assert link.stats["dropped"] == 4
|
||||||
|
|
||||||
|
|
||||||
|
def test_loss_drops_frames_and_can_spare_beats():
|
||||||
|
seq = iter([5, 90, 5, 90])
|
||||||
|
link, got, _ = make()
|
||||||
|
link.rand = lambda: next(seq)
|
||||||
|
link.loss_pct = 50
|
||||||
|
feed(link, data(1, b"a")) # 5 < 50: lost
|
||||||
|
feed(link, data(2, b"b")) # 90: kept
|
||||||
|
assert got == [b"b"] and link.stats["sim_lost"] == 1
|
||||||
|
link.loss_beats = False
|
||||||
|
link.on_packet(M, struct.pack("<BBBHHB", 0x4C, 0x25, 0, 1, 500, 0), 0) # beats exempt, rand not consulted
|
||||||
|
assert link.beat.poll(0) is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_echo_goes_to_master():
|
||||||
|
link, _, sent = make()
|
||||||
|
feed(link, data(1, b"a"))
|
||||||
|
link.echo(0x1234)
|
||||||
|
assert sent[-1] == (M, struct.pack("<BBH", 0x4C, 0x24, 0x1234))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
for name, fn in list(globals().items()):
|
||||||
|
if name.startswith("test_"):
|
||||||
|
fn()
|
||||||
|
print("ok", name)
|
||||||
Reference in new issue
Block a user