feat: simulator bridge, rig seed and web UI (in progress)

Work in progress from the same tree as the controller's sequences-v2 changes.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Haiku 5.5 committed 2026-11-11 14:10:55 +13:00
1 parent 4fc3345fc9
commit 4d8aeb5df8
26 files changed
+3907 -288

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
"""Driver side of the simulator link: radio, pixels, flash and sleeps.
In the browser (Pyodide) this is ``_simlink_web``. Under CPython (``bridge_sim.py`` /
``sim_driver.py``) it is ``_simlink_proc``: a multiprocessing connection to the bridge.
"""
try:
import js # noqa: F401 (Pyodide only)
except ImportError:
from _simlink_proc import * # noqa: F401,F403
else:
from _simlink_web import * # noqa: F401,F403
+111
View File
@@ -0,0 +1,111 @@
"""CPython link between one simulated led-driver process and ``bridge_sim.py``.
Frames on the multiprocessing connection (first byte is the kind):
- driver -> bridge: ``H`` + index (once), ``P`` + RGB bytes, ``T`` + dest_mac(6) + packet
- bridge -> driver: ``R`` + src_mac(6) + packet
"""
import threading
import time
from collections import deque
from multiprocessing.connection import Client
_conn = None
_rx = deque()
_rx_cond = threading.Condition()
_tx_lock = threading.Lock()
_px_period = 1 / 30.0
_last_px = 0.0
_pixels = None
_pixels_dirty = False
def connect(address, authkey, index, fps=30):
global _conn, _px_period
_px_period = 1.0 / max(1.0, float(fps))
_conn = Client(address, authkey=authkey)
_conn.send_bytes(b"H" + bytes([index]))
threading.Thread(target=_reader, daemon=True).start()
def _reader():
import os
while True:
try:
frame = _conn.recv_bytes()
except (EOFError, OSError):
os._exit(0) # bridge gone: power off
if frame[:1] == b"R" and len(frame) >= 7:
with _rx_cond:
_rx.append((frame[1:7], frame[7:]))
_rx_cond.notify()
def connected():
return _conn is not None
def real_sleep(seconds):
if seconds > 0:
time.sleep(seconds)
def recv_nowait():
with _rx_cond:
if _rx:
return _rx.popleft()
return (None, None)
def recv(timeout_ms=0):
with _rx_cond:
if not _rx and timeout_ms:
_rx_cond.wait(None if timeout_ms < 0 else timeout_ms / 1000.0)
if _rx:
return _rx.popleft()
return (None, None)
def pending():
return len(_rx)
def send_tx(dest_mac, packet):
with _tx_lock:
_conn.send_bytes(b"T" + bytes(dest_mac) + bytes(packet))
def _send_pixels():
global _pixels_dirty, _last_px
_pixels_dirty = False
_last_px = time.monotonic()
with _tx_lock:
_conn.send_bytes(b"P" + _pixels)
def push_pixels(buf):
global _pixels, _pixels_dirty
data = bytearray(len(buf) * 3)
j = 0
for r, g, b in buf:
data[j] = r
data[j + 1] = g
data[j + 2] = b
j += 3
_pixels = bytes(data)
_pixels_dirty = True
if time.monotonic() - _last_px >= _px_period:
_send_pixels()
def start_new_thread(fn, args, kwargs=None):
t = threading.Thread(target=fn, args=tuple(args), kwargs=kwargs or {}, daemon=True)
t.start()
return t.ident
def on_feed():
if _pixels_dirty and time.monotonic() - _last_px >= _px_period:
_send_pixels()
+177
View File
@@ -0,0 +1,177 @@
"""Link between one simulated led-driver (Pyodide, in a web worker) and the page (via ``_simlink``).
Not a MicroPython module. ``web/driver-worker.js`` defines these functions on
the worker global before the driver boots:
- ``simRecv()`` next received ESP-NOW frame ``src_mac(6) + packet`` as a
Uint8Array, or ``undefined``. Frames come from a
SharedArrayBuffer ring the page writes, so they arrive even
though ``main.py`` never yields to the JS event loop.
- ``simPending()`` number of frames waiting in the ring
- ``simTx(u8)`` transmit ``dest_mac(6) + packet``
- ``simPixels(u8)`` latest strip frame, RGB bytes
- ``simFlash(path, text)`` persist a flash file (settings.json, presets.json)
- ``simSleep(ms)`` block without spinning (``Atomics.wait``)
``machine.WDT.feed()`` calls :func:`on_feed` once per driver main-loop pass.
"""
import os
import random
import time
import js
FLASH_FILES = ("settings.json", "presets.json")
_fps = max(1.0, float(os.environ.get("LED_SIM_FPS", "30")))
_px_period = 1.0 / _fps
_pixels = None
_pixels_dirty = False
_last_px = 0.0
_jobs = [] # [due, fn, args]
_in_job = False
_flash_seen = {}
_last_flash_check = 0.0
def _u8(data):
arr = js.Uint8Array.new(len(data))
arr.assign(data)
return arr
def connected():
return True
# ----- time ---------------------------------------------------------------
def real_sleep(seconds):
"""Replacement for ``time.sleep``. Skipped inside deferred jobs (see defer)."""
if _in_job or seconds <= 0:
return
js.simSleep(float(seconds) * 1000.0)
# ----- radio --------------------------------------------------------------
def recv_nowait():
frame = js.simRecv()
if frame is None:
return (None, None)
data = bytes(frame.to_bytes())
if len(data) < 6:
return (None, None)
return (data[:6], data[6:])
def recv(timeout_ms=0):
host, msg = recv_nowait()
if host is not None or timeout_ms == 0:
return host, msg
deadline = None if timeout_ms is None or timeout_ms < 0 else time.monotonic() + timeout_ms / 1000.0
while True:
real_sleep(0.001)
host, msg = recv_nowait()
if host is not None:
return host, msg
if deadline is not None and time.monotonic() >= deadline:
return (None, None)
def pending():
return int(js.simPending())
def send_tx(dest_mac, packet):
js.simTx(_u8(bytes(dest_mac) + bytes(packet)))
# ----- pixels -------------------------------------------------------------
def _send_pixels():
global _pixels_dirty, _last_px
_pixels_dirty = False
_last_px = time.monotonic()
js.simPixels(_u8(_pixels))
def push_pixels(buf):
"""``buf``: list of (r, g, b). Sent at most ``LED_SIM_FPS`` times a second."""
global _pixels, _pixels_dirty
data = bytearray(len(buf) * 3)
j = 0
for r, g, b in buf:
data[j] = r
data[j + 1] = g
data[j + 2] = b
j += 3
_pixels = bytes(data)
_pixels_dirty = True
if time.monotonic() - _last_px >= _px_period:
_send_pixels()
# ----- background work ----------------------------------------------------
def start_new_thread(fn, args, kwargs=None):
"""``_thread.start_new_thread`` stand-in: there are no threads in Pyodide.
led-driver uses a thread only to answer pings after a random 50-500 ms
delay. The job runs from the main loop after a delay in that range, with
its own sleeps skipped so the strip keeps animating meanwhile.
"""
_jobs.append([time.monotonic() + random.uniform(0.05, 0.5), fn, tuple(args), kwargs or {}])
return len(_jobs)
def _run_jobs(now):
global _in_job
if not _jobs:
return
due = [j for j in _jobs if j[0] <= now]
if not due:
return
for j in due:
_jobs.remove(j)
_in_job = True
try:
j[1](*j[2], **j[3])
except Exception as e: # noqa: BLE001
print("sim job error:", e)
finally:
_in_job = False
def _check_flash(now):
global _last_flash_check
if now - _last_flash_check < 1.0:
return
_last_flash_check = now
for name in FLASH_FILES:
try:
with open(name, "r") as f:
text = f.read()
except OSError:
continue
if name not in _flash_seen:
_flash_seen[name] = text
continue
if _flash_seen[name] != text:
_flash_seen[name] = text
js.simFlash(name, text)
def on_feed():
now = time.monotonic()
if _pixels_dirty and now - _last_px >= _px_period:
_send_pixels()
_run_jobs(now)
_check_flash(now)
+79
View File
@@ -0,0 +1,79 @@
"""MicroPython ``espnow`` stub for led-simulator (Pyodide).
Packets go to and from the simulated bridge through ``_simlink``. ``irq()`` is
not supported, so ``main.py`` falls back to polling ``any()`` / ``recv(0)`` in
its main loop, as it does on boards without the irq callback.
"""
import _simlink
MAX_DATA_LEN = 250
ESP_ERR_ESPNOW_EXIST = -12395
ESP_ERR_ESPNOW_NOT_FOUND = -12393
_BROADCAST = b"\xff\xff\xff\xff\xff\xff"
class ESPNow:
def __init__(self):
self._active = False
self._peers = set()
self._timeout_ms = 300000
def active(self, flag=None):
if flag is None:
return self._active
self._active = bool(flag)
return self._active
def config(self, *args, **kwargs):
if "timeout_ms" in kwargs:
self._timeout_ms = int(kwargs["timeout_ms"])
return None
def add_peer(self, mac, *args, **kwargs):
mac = bytes(mac)
if mac in self._peers:
raise OSError(ESP_ERR_ESPNOW_EXIST, "ESP_ERR_ESPNOW_EXIST")
self._peers.add(mac)
def del_peer(self, mac):
mac = bytes(mac)
if mac not in self._peers:
raise OSError(ESP_ERR_ESPNOW_NOT_FOUND, "ESP_ERR_ESPNOW_NOT_FOUND")
self._peers.discard(mac)
def get_peers(self):
return tuple((m, b"", 0, 0, False) for m in self._peers)
def send(self, mac, msg=None, sync=True):
if msg is None:
# send(msg): to every registered peer
msg, dests = mac, list(self._peers) or [_BROADCAST]
else:
dests = [_BROADCAST if mac is None else bytes(mac)]
if isinstance(msg, str):
msg = msg.encode("utf-8")
msg = bytes(msg)
if len(msg) > MAX_DATA_LEN:
raise ValueError("ESP_ERR_ESPNOW_ARG")
for dest in dests:
_simlink.send_tx(dest, msg)
return True
def recv(self, timeout_ms=None):
if timeout_ms is None:
timeout_ms = self._timeout_ms
return _simlink.recv(timeout_ms)
irecv = recv
def any(self):
return _simlink.pending() > 0
def irq(self, callback):
# main.py treats AttributeError as "firmware without irq support" and polls instead
raise AttributeError("espnow irq not available in led-simulator (polling)")
def stats(self):
return (0, 0, 0, 0, 0)
+74 -3
View File
@@ -1,18 +1,89 @@
"""CPython stub for MicroPython `machine` (led-simulator)."""
"""MicroPython ``machine`` stub for led-simulator (Pyodide)."""
import os
import time
try:
import _simlink
except ImportError: # outside the simulator
_simlink = None
PWRON_RESET = 1
HARD_RESET = 2
WDT_RESET = 3
DEEPSLEEP_RESET = 4
SOFT_RESET = 5
# SystemExit code that tells the page to boot this driver again (machine.reset()).
RESET_EXIT_CODE = 75
# The driver main loop calls wdt.feed() once per pass with no sleep. A short
# sleep here keeps 16 simulated drivers from pinning every CPU core, and the
# feed is where the simulator flushes pixels and flash writes.
_LOOP_SLEEP_S = max(0.0, float(os.environ.get("LED_SIM_LOOP_SLEEP_MS", "2")) / 1000.0)
_freq = 160000000
class Pin:
OUT = 1
IN = 0
PULL_UP = 1
PULL_DOWN = 2
def __init__(self, pin_id, mode=None, *, pull=None, value=None):
self.id = pin_id
self.mode = mode
self._value = value or 0
def value(self, v=None):
if v is None:
return self._value
self._value = 1 if v else 0
return None
def on(self):
self._value = 1
def off(self):
self._value = 0
class WDT:
def __init__(self, timeout=10000):
def __init__(self, id=0, timeout=10000):
self._timeout = timeout
def feed(self):
pass
if _LOOP_SLEEP_S:
time.sleep(_LOOP_SLEEP_S)
if _simlink is not None:
_simlink.on_feed()
def freq(hz=None):
global _freq
if hz is None:
return _freq
_freq = int(hz)
return None
def reset():
raise SystemExit(RESET_EXIT_CODE)
def soft_reset():
raise SystemExit(RESET_EXIT_CODE)
def reset_cause():
return PWRON_RESET
def unique_id():
mac = os.environ.get("LED_SIM_MAC", "aabbccddeeff")
return bytes.fromhex(mac)
def idle():
time.sleep(0.001)
+37 -22
View File
@@ -1,37 +1,52 @@
"""Host NeoPixel: keeps RGB buffer and notifies the GUI on `write()`."""
"""Host NeoPixel with MicroPython's semantics: a ``buf`` bytearray in ``ORDER`` (GRB), which led-driver
writes directly. ``write()`` sends the frame to the simulator as RGB."""
# Set by led-simulator main: callable(list[tuple[int,int,int]]) -> None
import _simlink
# Optional extra hook: callable(list[tuple[int, int, int]]) -> None
PIXEL_SINK = None
class NeoPixel:
def __init__(self, pin, n):
ORDER = (1, 0, 2, 3) # as MicroPython: buf holds G, R, B (, W)
def __init__(self, pin, n, bpp=3, timing=1):
self.pin = pin
self.n = n
self._buf = [(0, 0, 0)] * n
self.bpp = bpp
self.timing = timing
self.buf = bytearray(n * bpp)
def __len__(self):
return self.n
def __setitem__(self, index, value):
if isinstance(value, (list, tuple)) and len(value) >= 3:
r, g, b = (int(value[0]), int(value[1]), int(value[2]))
self._buf[index] = (
max(0, min(255, r)),
max(0, min(255, g)),
max(0, min(255, b)),
)
if index < 0:
index += self.n
off = index * self.bpp
for j in range(self.bpp):
self.buf[off + self.ORDER[j]] = int(value[j]) & 255
def __getitem__(self, index):
return self._buf[index]
if index < 0:
index += self.n
off = index * self.bpp
return tuple(self.buf[off + self.ORDER[j]] for j in range(self.bpp))
def fill(self, color):
c = (0, 0, 0)
if isinstance(color, (list, tuple)) and len(color) >= 3:
c = (
max(0, min(255, int(color[0]))),
max(0, min(255, int(color[1]))),
max(0, min(255, int(color[2]))),
)
self._buf = [c] * self.n
px = bytearray(self.bpp)
for j in range(self.bpp):
px[self.ORDER[j]] = int(color[j]) & 255
self.buf[:] = px * self.n
def _rgb(self):
b, bpp, o = self.buf, self.bpp, self.ORDER
return [(b[i + o[0]], b[i + o[1]], b[i + o[2]]) for i in range(0, self.n * bpp, bpp)]
def write(self):
if PIXEL_SINK is not None:
PIXEL_SINK(list(self._buf))
if _simlink.connected() or PIXEL_SINK is not None:
px = self._rgb()
if _simlink.connected():
_simlink.push_pixels(px)
if PIXEL_SINK is not None:
PIXEL_SINK(px)
+25 -6
View File
@@ -1,16 +1,23 @@
"""Minimal `network` stub so imports succeed (led-simulator)."""
"""Minimal ``network`` stub so imports succeed (led-simulator).
Each simulated driver gets its own MAC from ``LED_SIM_MAC`` (12 hex digits).
"""
import os
STA_IF = 0
AP_IF = 1
# Fixed “STA” identity for hello.py / discovery on the host.
_SIM_MAC = b"\xaa\xbb\xcc\xdd\xee\xff"
_SIM_MAC = bytes.fromhex(os.environ.get("LED_SIM_MAC", "aabbccddeeff"))
_channel = 1
class WLAN:
PM_NONE = 0
PM_PERFORMANCE = 1
PM_POWERSAVE = 2
def __init__(self, interface):
def __init__(self, interface=STA_IF):
self._interface = interface
self._active = False
@@ -21,18 +28,30 @@ class WLAN:
return None
def config(self, param=None, **kwargs):
global _channel
if "channel" in kwargs:
_channel = int(kwargs["channel"])
if param == "mac":
return _SIM_MAC
if param == "channel":
return _channel
if param == "essid":
return ""
return None
def connect(self, *args, **kwargs):
return None
def disconnect(self):
return None
def isconnected(self):
return True
def status(self, param=None):
return 1010 # STAT_GOT_IP
def ifconfig(self, config_tuple=None):
if config_tuple is None:
# ip, subnet, gateway, dns — enough for hello UDP targets
return ("192.168.1.100", "255.255.255.0", "192.168.1.1", "8.8.8.8")
return ("192.168.4.%d" % (10 + _SIM_MAC[-1] % 200), "255.255.255.0", "192.168.4.1", "8.8.8.8")
return None
+8
View File
@@ -0,0 +1,8 @@
"""Map MicroPython ``urandom`` to CPython ``random`` (led-simulator)."""
from random import choice, randint, random, randrange, seed, uniform # noqa: F401
from random import getrandbits as _getrandbits
def getrandbits(n):
return _getrandbits(int(n)) if n > 0 else 0
+35 -8
View File
@@ -1,22 +1,49 @@
"""CPython stub for MicroPython `utime` (led-simulator)."""
"""CPython stub for MicroPython ``utime`` (led-simulator)."""
import time
import time as _time
_MS_MASK = (1 << 30) - 1
_MS_PERIOD = 1 << 30
_MS_MASK = _MS_PERIOD - 1
_HALF = _MS_PERIOD // 2
_T0 = _time.monotonic()
def sleep_ms(ms):
time.sleep(max(0, ms) / 1000.0)
_time.sleep(max(0, ms) / 1000.0)
def sleep_us(us):
_time.sleep(max(0, us) / 1000000.0)
def sleep(s):
time.sleep(s)
_time.sleep(s)
def ticks_ms():
return int(time.monotonic() * 1000) & _MS_MASK
return int((_time.monotonic() - _T0) * 1000) & _MS_MASK
def ticks_us():
return int((_time.monotonic() - _T0) * 1000000) & _MS_MASK
ticks_cpu = ticks_us
def ticks_add(ticks, delta):
return (int(ticks) + int(delta)) & _MS_MASK
def ticks_diff(t1, t0):
"""Approximate MicroPython ticks_diff for host monotonic ms."""
return ((t1 - t0 + (1 << 29)) & _MS_MASK) - (1 << 29)
"""Signed difference with wrap-around, like MicroPython."""
return ((int(t1) - int(t0) + _HALF) & _MS_MASK) - _HALF
def time():
"""Whole seconds, like MicroPython."""
return int(_time.time())
def time_ns():
return _time.time_ns()