diff --git a/.gitignore b/.gitignore index 8022c72..8196a6e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,2 @@ -workspace/settings.json -workspace/presets.json -workspace/patterns/* -!workspace/patterns/__init__.py -!workspace/patterns/.gitkeep +workspace/ +__pycache__/ diff --git a/README.md b/README.md index 055a6a7..cfa73f7 100644 --- a/README.md +++ b/README.md @@ -1,48 +1,134 @@ # led-simulator -Graphical **NeoPixel** simulator for host Python. It uses the same layout as device flash: +A web app that simulates a whole LED rig behind a **Wi‑Fi bridge**. -- **`led-driver/src`** → flash root **`/`** (application modules, `patterns/`, `presets.json`, …) -- **`led-driver/lib`** → **`/lib`** (Microdot, utemplate, …) +- To **led-controller** it *is* a `bridge-wifi`: a WebSocket on **`/ws`** with the same downlink + rules (binary wire packets are broadcast; v1 JSON envelopes `{"v":"1","dv":{mac: body}}` are + split per MAC) and the same uplink framing (`0x00 + peer MAC + ESP-NOW packet`). +- In the **browser**, every strip is its own led-driver: a web worker running the real + **`led-driver/src/main.py`** and **`led-driver/src/patterns/`** in [Pyodide](https://pyodide.org), + as [led-editor](https://git.technical.kiwi/technicalkiwi/led-editor) runs MicroPython. Only the + hardware modules are stubbed (`stubs/`: `machine`, `neopixel`, `network`, `espnow`, `utime`, + `urandom`, `ubinascii`). -It runs the **whole application**: **`led-driver/src/main.py`** as **`__main__`** (`runpy.run_path(..., run_name="__main__")` → `asyncio.run(main(port=…))`). Startup matches the device — **`Settings`**, **`presets.load`**, **default preset** from settings, **`patterns/`**, **Microdot** **`/ws`**, **`presets_loop`**, **UDP hello**. Only **`machine`**, **`neopixel`**, **`network`**, **`utime`**, and **`ubinascii`** are stubbed (`stubs/`). +Strips **register like hardware**: each driver sends its JSON hello once when it powers on, and +the bridge forwards it to the controllers connected at that moment. A strip that booted while no +controller was connected is not registered until you power-cycle it. -The GUI sets **`LED_SIM_ROOT`** so **`main.py`** can register the Microdot app for **Stop**, and **`LED_SIM_PORT`** for the HTTP/WebSocket listen port (default **80** on device when unset). On the ESP32 those variables are unset. +## Default rig -## Requirements +16 strips × 119 LEDs in **2 columns × 8 rows**. Each strip runs along its row and **starts in the +middle**: pixel 0 is next to the centre line, so left-column strips run right-to-left and +right-column strips run left-to-right. -- Python 3.10+ -- Tk (e.g. `python3-tk` on Debian/Ubuntu if the window fails to open) +| Strip | Name | MAC | +| --- | --- | --- | +| 1 … 16 | `sim-01` … `sim-16` | `02:51:4d:00:00:01` … `02:51:4d:00:00:10` | +| bridge | `bridge-sim` | `02:51:4d:00:00:00` | -## Run +Strip 1 is row 1 left, strip 2 row 1 right, and so on (`layout.order`). + +## With the simulated controller (no hardware at all) From the repository root: ```bash -pipenv install # optional; Microdot is vendored under led-driver/lib -python3 led-simulator/gui_main.py +make sim-web # this page at http://localhost:8765/ + led-controller built for the host at :8080 +make sim # the same with headless drivers (bridge_sim.py), for tests +make test-sim # API and rig tests (groups, field patterns, sequences) against `make sim` ``` -## UI +The controller reaches the strips over the **UDP bridge** on port **8766**: each datagram is +`dst_mac(6) + packet` down and `src_mac(6) + packet` up, exactly the frames it would send over ESP-NOW. +A board can use it too: set `"bridge": ":8766"` in its settings and restart it. -- **Start** / **Stop**: start or stop the full **`main.py`** process (same code path as the chip). -- **HTTP / WS port**: Microdot listen port; WebSocket URL **`ws://127.0.0.1:/ws`** (JSON **v1**). +### Headless -Configure the app like on flash: **`workspace/settings.json`** (patched as device settings path), **`presets.json`** and **`patterns/`** under **`led-simulator/workspace/`** when the simulator creates symlinks from **`src/`**, or edit files directly under **`led-driver/src/`** if you use a real **`patterns/`** directory there. +`python3 led-simulator/bridge_sim.py [--udp-port 8766] [--port 8765]` runs every strip as its own +CPython process (`sim_driver.py`, `stubs/_simlink_proc.py`) with no browser. `GET /api/pixels` on its +port returns each strip's place and current RGB frame (`rgb`, hex, pixel 0 first). -Example pattern modules: **`led-simulator/examples/`** (`Blink`, `Chase`). Copy into **`patterns/`** as on the device. +## Run + +From the repository root (Python 3.10+, no extra packages; Microdot comes from `led-driver/lib`): + +```bash +python3 led-simulator/server.py # --port 8765 --host 0.0.0.0 --debug +``` + +1. Open **http://localhost:8765/** in Chrome, Edge or Firefox **on the same computer**. + Drivers need `SharedArrayBuffer`, which browsers only allow on a cross-origin isolated page in + a secure context: `localhost` or HTTPS, not a plain `http://192.168.…` address. +2. In led-controller add a bridge: transport **`ip`**, address **`127.0.0.1`** (controller on + this computer) or this computer's LAN address, port **`8765`**. +3. Power the strips on (or power-cycle them) once the controller is connected, so their hellos + reach it. + +The first boot downloads Pyodide (~10 MB) from the CDN; after that the browser caches it. +Strips boot four at a time (`drivers.boot_concurrency`). + +Only one tab runs the rig: opening the page in a second tab powers the first one's strips off. + +## Page + +- **Power on all / Power cycle all / Power off all**, and *Power on when opened*. +- Click a strip for its details: state, MAC, packets received and sent, power on / reset / off, + and its serial output (what the board would print over USB). +- The dot at each strip's start end shows its state: grey off, amber booting, green running, + red stopped (see its serial log for the traceback). + +## Configuration + +`workspace/sim.json` overrides `sim.default.json` (keep only the keys you change): + +```json +{ + "bridge": { "name": "bridge-sim", "host": "0.0.0.0", "ws_port": 8765, "wifi_channel": 5, "debug": false }, + "layout": { "rows": 8, "columns": 2, "leds_per_strip": 119, "order": "row", "start": "center" }, + "drivers": { "name": "sim-{n:02d}", "fps": 30, "loop_sleep_ms": 2, "boot_concurrency": 4 }, + "pyodide_url": "https://cdn.jsdelivr.net/pyodide/v0.26.4/full/" +} +``` + +- `layout.order`: `row` (1 = row 1 left, 2 = row 1 right, …) or `column` (1–8 down the left + column, 9–16 down the right). +- `layout.start`: `center` (pixel 0 next to the middle), `left`, or `right`. +- `drivers.name`: format for new strips; `{n}`, `{row}`, `{col}`, `{side}` (`left`/`right`). + A name the controller sets is kept. +- `drivers.fps`: how often each strip sends its pixels to the page. +- `drivers.loop_sleep_ms`: sleep per driver main-loop pass (in the `WDT.feed()` stub) so 16 + drivers do not pin the CPU. +- `pyodide_url`: point at a local copy of Pyodide (full distribution folder, trailing `/`) to run + offline. + +## Simulated flash + +Each strip keeps `settings.json` and `presets.json` in **`workspace/drivers/NN/`** on the server: +created from **`settings.default.json`** on first boot, then saved whenever the driver writes +them. `num_leds` always follows the layout. Delete `workspace/drivers/` to factory-reset every +strip. + +Driver code and **patterns are always the current `led-driver/src`**, loaded fresh on every +boot. Patterns the controller pushes by OTA live only until that strip powers off. + +## How it fits together + +``` +led-controller ──ws /ws──▶ server.py (bridge rules) ──ws /sim──▶ page ──SharedArrayBuffer──▶ worker × 16 + ◀── 0x00+mac+pkt ── ◀── mac+pkt ── ◀──── postMessage ──── (Pyodide, main.py) +``` + +- `server.py` – HTTP + both WebSockets, bridge downlink rules, flash files. +- `web/app.js` – rig canvas, power control, packet routing by MAC. +- `web/driver-worker.js` – loads Pyodide, writes the strip's flash, runs `web/driver_boot.py`. +- `web/ring.js` – the SharedArrayBuffer queue that delivers packets to a driver while `main.py` + runs (it never yields to the JavaScript event loop). +- `stubs/_simlink.py` – the driver side of that link (radio, pixels, flash, sleeps). ## Notes -- Changing the port spinbox only takes effect on the next **Start**. -- If **`led-driver/src/patterns`** already exists as a normal directory, the simulator leaves it in place. - -## Shell (no GUI) - -```bash -cd led-driver/src -PYTHONPATH="../lib:../../led-simulator/stubs" LED_SIM_ROOT="../../led-simulator" LED_SIM_PORT=8765 \ - python3 main.py -``` - -(Adjust paths from your checkout root; **`LED_SIM_ROOT`** must point at **`led-simulator/`** so **Stop**-style hooks work if you use them.) +- `machine.reset()` in a driver reboots that strip. +- The ping reply that led-driver sends from a thread runs from the main loop after the same + 50–500 ms delay (Pyodide has no threads). +- Strips do not hear each other's ESP-NOW broadcasts; the bridge forwards driver transmissions to + the controller only. diff --git a/bridge_sim.py b/bridge_sim.py new file mode 100644 index 0000000..0da1b2f --- /dev/null +++ b/bridge_sim.py @@ -0,0 +1,782 @@ +"""Simulated Wi-Fi ESP-NOW bridge with a rig of simulated led-drivers behind it. + +To led-controller this looks like ``bridge-wifi``: a WebSocket on ``/ws`` +with the same downlink handling (binary wire packets are broadcast, v1 JSON +envelopes are split per MAC) and the same uplink framing +(``0x00 + peer_mac + packet``). Add it in the controller as an IP bridge. + +Behind the bridge, every strip is a separate process running the real +``led-driver/src/main.py`` (see ``sim_driver.py``), so each strip keeps its +own settings, presets, groups and pattern state, as on hardware. +""" + +from __future__ import annotations + +import asyncio +import json +import os +import secrets +import shutil +import socket +import subprocess +import sys +import threading +import time +from multiprocessing.connection import Listener, wait +from pathlib import Path + +from layout import normalise_layout, side_name, strip_places +from rig_seed import seed, seed_soon + +SIM_ROOT = Path(__file__).resolve().parent +WORKSPACE = SIM_ROOT / "workspace" +DRIVERS_DIR = WORKSPACE / "drivers" +SHARED_PATTERNS = WORKSPACE / "patterns" +SIM_DEFAULTS = SIM_ROOT / "sim.default.json" +SIM_CONFIG = WORKSPACE / "sim.json" +DRIVER_SETTINGS_TEMPLATE = SIM_ROOT / "settings.default.json" +DRIVER_ROOT = SIM_ROOT.parent / "led-driver" +DRIVER_SRC = DRIVER_ROOT / "src" +DRIVER_LIB = DRIVER_ROOT / "lib" +SIM_DRIVER = SIM_ROOT / "sim_driver.py" + +BROADCAST = b"\xff\xff\xff\xff\xff\xff" +WIRE = 0x4C +MSG_ANNOUNCE = 0x01 +MAX_ESPNOW = 250 +RESET_EXIT_CODE = 75 # stubs/machine.py: machine.reset() + +# Locally administered MACs: 02:51:4d ("QM") : 00 : 00 : NN. The bridge is NN=00. +MAC_PREFIX = bytes([0x02, 0x51, 0x4D, 0x00, 0x00]) + +BUILTIN_DEFAULTS = { + "bridge": { + "name": "bridge-sim", + "host": "0.0.0.0", + "ws_port": 8765, + "udp_port": 8766, + "wifi_channel": 5, + "debug": False, + }, + "layout": {}, + "drivers": { + "name": "sim-{n:02d}", + "fps": 30, + "loop_sleep_ms": 2, + }, +} + + +def mac_str(mac: bytes) -> str: + return ":".join("%02x" % b for b in mac) + + +def driver_mac(index: int) -> bytes: + return MAC_PREFIX + bytes([(index + 1) & 0xFF]) + + +BRIDGE_MAC = MAC_PREFIX + b"\x00" + + +def _merge(base: dict, extra: dict) -> dict: + out = dict(base) + for k, v in (extra or {}).items(): + if isinstance(v, dict) and isinstance(out.get(k), dict): + out[k] = _merge(out[k], v) + else: + out[k] = v + return out + + +def _read_json(path: Path) -> dict: + try: + with open(path, encoding="utf-8") as f: + data = json.load(f) + return data if isinstance(data, dict) else {} + except (OSError, ValueError): + return {} + + +def load_config() -> dict: + """Built-in defaults <- sim.default.json <- workspace/sim.json.""" + WORKSPACE.mkdir(parents=True, exist_ok=True) + if not SIM_CONFIG.is_file() and SIM_DEFAULTS.is_file(): + shutil.copy2(SIM_DEFAULTS, SIM_CONFIG) + cfg = _merge(BUILTIN_DEFAULTS, _read_json(SIM_DEFAULTS)) + cfg = _merge(cfg, _read_json(SIM_CONFIG)) + cfg["layout"] = normalise_layout(cfg.get("layout")) + return cfg + + +def lan_ip() -> str: + """Best guess at this computer's LAN address (for the controller to dial).""" + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + s.connect(("10.255.255.255", 1)) + return s.getsockname()[0] + except OSError: + return "127.0.0.1" + finally: + s.close() + + +def sync_patterns() -> None: + """Copy led-driver/src/patterns into the shared simulated flash patterns/ folder. + + Files the controller pushed by OTA under other names are kept. + """ + SHARED_PATTERNS.mkdir(parents=True, exist_ok=True) + src = DRIVER_SRC / "patterns" + if not src.is_dir(): + return + for f in src.glob("*.py"): + dst = SHARED_PATTERNS / f.name + try: + if not dst.exists() or f.stat().st_mtime > dst.stat().st_mtime: + shutil.copy2(f, dst) + except OSError as e: + print("[sim] pattern copy failed:", f.name, e) + + +class Strip: + def __init__(self, place, name: str): + self.place = place + self.index = place.index + self.mac = driver_mac(place.index) + self.name = name + self.dir = DRIVERS_DIR / ("%02d" % place.number) + self.proc: subprocess.Popen | None = None + self.conn = None + self.frame = bytes(place.leds * 3) + self.hello: bytes | None = None + self.announce: bytes | None = None + self.rx_packets = 0 + self.tx_packets = 0 + self.reported = False + + +class BridgeSim: + """Owns the WebSocket server (asyncio thread) and the driver processes.""" + + def __init__(self, cfg: dict | None = None): + self.cfg = cfg or load_config() + self.layout = self.cfg["layout"] + self.places = strip_places(self.layout) + dcfg = self.cfg["drivers"] + self.strips: list[Strip] = [] + for p in self.places: + name = str(dcfg.get("name", "sim-{n:02d}")).format( + n=p.number, + row=p.row + 1, + col=p.col + 1, + side=side_name(p.col, self.layout["columns"]), + ) + self.strips.append(Strip(p, name)) + self.by_mac = {s.mac: s for s in self.strips} + + self.running = False + self.port = int(self.cfg["bridge"]["ws_port"]) + self.error: str | None = None + self.debug = bool(self.cfg["bridge"].get("debug", False)) + + self._lock = threading.Lock() + self._dirty: set[int] = set() + self._clients: set = set() + self._loop: asyncio.AbstractEventLoop | None = None + self._loop_thread: threading.Thread | None = None + self._reader_thread: threading.Thread | None = None + self._accept_thread: threading.Thread | None = None + self._listener: Listener | None = None + self._authkey = b"" + self._stopping = False + self._app = None + self.downlink_count = 0 + self.uplink_count = 0 + # UDP bridge (led-controller settings.bridge): dst_mac(6)+packet down, src_mac(6)+packet up + self.udp_port = int(self.cfg["bridge"].get("udp_port", 8766)) + self._udp: socket.socket | None = None + self._udp_peer = None + self._udp_thread: threading.Thread | None = None + + # ----- public ------------------------------------------------------- + + @property + def client_count(self) -> int: + return len(self._clients) + + def take_dirty_frames(self) -> dict[int, bytes]: + with self._lock: + out = {i: self.strips[i].frame for i in self._dirty} + self._dirty.clear() + return out + + def alive_count(self) -> int: + return sum(1 for s in self.strips if s.proc is not None and s.proc.poll() is None) + + def connected_count(self) -> int: + return sum(1 for s in self.strips if s.conn is not None) + + def start(self, port: int | None = None) -> None: + if self.running: + return + if port is not None: + self.port = int(port) + self.error = None + self._stopping = False + self._check_paths() + sync_patterns() + self._prepare_driver_dirs() + + # Bind the WebSocket port first so a clash fails before drivers boot. + ready = threading.Event() + self._loop_thread = threading.Thread( + target=self._loop_main, args=(ready,), name="bridge-ws", daemon=True + ) + self._loop_thread.start() + ready.wait(5) + if self.error: + raise RuntimeError(self.error) + + if self.udp_port: + self._udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + self._udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self._udp.bind((str(self.cfg["bridge"].get("host", "0.0.0.0")), self.udp_port)) + self._udp.settimeout(0.5) + + self._authkey = secrets.token_bytes(16) + # backlog: all strips connect at once; the default of 1 makes late + # drivers wait on SYN retries. + self._listener = Listener(("127.0.0.1", 0), authkey=self._authkey, backlog=64) + self.running = True + if self._udp is not None: + self._udp_thread = threading.Thread(target=self._udp_main, name="bridge-udp", daemon=True) + self._udp_thread.start() + self._accept_thread = threading.Thread( + target=self._accept_main, name="bridge-accept", daemon=True + ) + self._accept_thread.start() + for s in self.strips: + s.reported = False + self._spawn(s) + self._reader_thread = threading.Thread( + target=self._reader_main, name="bridge-drivers", daemon=True + ) + self._reader_thread.start() + print( + "[sim] bridge %s ws://%s:%d/ws udp %d %d strips x %d LEDs" + % ( + self.cfg["bridge"]["name"], + lan_ip(), + self.port, + self.udp_port, + len(self.strips), + self.layout["leds_per_strip"], + ) + ) + + def stop(self) -> None: + if not self.running and self._loop is None: + return + self._stopping = True + self.running = False + if self._udp is not None: + if self._udp_thread is not None: + self._udp_thread.join(1) + self._udp.close() + self._udp = None + if self._reader_thread is not None: + self._reader_thread.join(1) + self._reader_thread = None + for s in self.strips: + if s.proc is not None and s.proc.poll() is None: + s.proc.terminate() + deadline = time.monotonic() + 3 + for s in self.strips: + if s.proc is None: + continue + try: + s.proc.wait(max(0.1, deadline - time.monotonic())) + except subprocess.TimeoutExpired: + s.proc.kill() + s.proc = None + if s.conn is not None: + try: + s.conn.close() + except OSError: + pass + s.conn = None + s.hello = None + s.announce = None + s.frame = bytes(s.place.leds * 3) + with self._lock: + self._dirty.update(range(len(self.strips))) + if self._listener is not None: + # close() does not wake a thread blocked in accept() on Linux; + # a throwaway connection does. + try: + socket.create_connection(self._listener.address, timeout=0.5).close() + except OSError: + pass + try: + self._listener.close() + except OSError: + pass + self._listener = None + loop = self._loop + if loop is not None: + fut = asyncio.run_coroutine_threadsafe(self._shutdown_ws(), loop) + try: + fut.result(3) + except Exception: + pass + if self._loop_thread is not None: + self._loop_thread.join(3) + if self._loop_thread.is_alive(): + loop.call_soon_threadsafe(loop.stop) + self._loop_thread.join(1) + self._loop = None + self._clients.clear() + print("[sim] stopped") + + # ----- driver processes -------------------------------------------- + + def _check_paths(self): + if not (DRIVER_SRC / "main.py").is_file(): + raise RuntimeError("led-driver/src/main.py not found next to led-simulator") + + def _prepare_driver_dirs(self): + template = _read_json(DRIVER_SETTINGS_TEMPLATE) + for s in self.strips: + s.dir.mkdir(parents=True, exist_ok=True) + settings_path = s.dir / "settings.json" + current = _read_json(settings_path) + merged = dict(template) + merged.update(current) + if not current.get("name"): + merged["name"] = s.name + # Strip length is physical: the layout decides it. + merged["num_leds"] = s.place.leds + merged["wifi_channel"] = int(self.cfg["bridge"].get("wifi_channel", 5)) + with open(settings_path, "w", encoding="utf-8") as f: + json.dump(merged, f) + s.name = merged["name"] + presets_path = s.dir / "presets.json" + if not presets_path.is_file(): + presets_path.write_text("{}\n", encoding="utf-8") + self._link_patterns(s.dir / "patterns") + + def _link_patterns(self, link: Path): + if link.is_symlink() or link.exists(): + return + try: + link.symlink_to(SHARED_PATTERNS.resolve(), target_is_directory=True) + except OSError: + # No symlinks (e.g. Windows without developer mode): private copy. + shutil.copytree(SHARED_PATTERNS, link) + + def _spawn(self, s: Strip): + addr = self._listener.address + env = dict(os.environ) + env.update( + { + "LED_SIM_INDEX": str(s.index), + "LED_SIM_MAC": s.mac.hex(), + "LED_SIM_DIR": str(s.dir), + "LED_SIM_ADDR": "%s:%d" % addr, + "LED_SIM_AUTH": self._authkey.hex(), + "LED_SIM_FPS": str(self.cfg["drivers"].get("fps", 30)), + "LED_SIM_LOOP_SLEEP_MS": str(self.cfg["drivers"].get("loop_sleep_ms", 2)), + "PYTHONDONTWRITEBYTECODE": "1", + "PYTHONUNBUFFERED": "1", + } + ) + s.proc = subprocess.Popen( + [sys.executable, str(SIM_DRIVER)], + cwd=str(s.dir), + env=env, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + def _accept_main(self): + listener = self._listener + while self.running and listener is not None: + try: + conn = listener.accept() + except (OSError, EOFError): + if not self.running: + return + # A failed auth handshake (stray client): keep listening. + continue + try: + first = conn.recv_bytes() + except (OSError, EOFError): + continue + if first[:1] != b"H" or len(first) < 2 or first[1] >= len(self.strips): + conn.close() + continue + self.strips[first[1]].conn = conn + + def _report_dead(self, s: Strip): + log = s.dir / "driver.log" + tail = "" + try: + tail = log.read_text(encoding="utf-8", errors="replace")[-600:] + except OSError: + pass + print("[sim] strip %d (%s) stopped. Last log lines:\n%s" % (s.place.number, s.name, tail)) + + def _reader_main(self): + while self.running: + for s in self.strips: + if s.conn is None and not s.reported and s.proc is not None and s.proc.poll() is not None: + s.reported = True + self._report_dead(s) + conns = {s.conn: s for s in self.strips if s.conn is not None} + if not conns: + time.sleep(0.2) + continue + try: + ready = wait(list(conns), timeout=0.2) + except OSError: + continue + for c in ready: + s = conns[c] + try: + frame = c.recv_bytes() + except (OSError, EOFError): + self._driver_gone(s) + continue + kind = frame[:1] + if kind == b"P": + with self._lock: + s.frame = frame[1:] + self._dirty.add(s.index) + elif kind == b"T" and len(frame) >= 7: + s.tx_packets += 1 + self._from_driver(s, frame[1:7], frame[7:]) + + def _driver_gone(self, s: Strip): + if s.conn is not None: + try: + s.conn.close() + except OSError: + pass + s.conn = None + if self._stopping or not self.running: + return + code = None + if s.proc is not None: + try: + code = s.proc.wait(2) + except subprocess.TimeoutExpired: + code = None + if code == RESET_EXIT_CODE: + print("[sim] strip %d reset, booting again" % s.place.number) + self._spawn(s) + return + s.reported = True + self._report_dead(s) + with self._lock: + s.frame = bytes(s.place.leds * 3) + self._dirty.add(s.index) + + def _to_driver(self, s: Strip, packet: bytes): + if s.conn is None: + return + try: + s.conn.send_bytes(b"R" + BRIDGE_MAC + packet) + s.rx_packets += 1 + except (OSError, EOFError, ValueError): + pass + + def _from_driver(self, s: Strip, dest: bytes, packet: bytes): + """Driver ESP-NOW transmit. The bridge forwards everything it hears.""" + if packet[:1] == b"{": + s.hello = packet + elif len(packet) >= 2 and packet[0] == WIRE and packet[1] == MSG_ANNOUNCE: + s.announce = packet + if self.debug: + print("[sim] up %s %d B" % (mac_str(s.mac), len(packet))) + udp, peer = self._udp, self._udp_peer + if udp is not None and peer is not None: + try: + udp.sendto(s.mac + packet, peer) + self.uplink_count += 1 + except OSError: + pass + loop = self._loop + if loop is not None: + frame = bytes([0]) + s.mac + packet + loop.call_soon_threadsafe(self._uplink_soon, frame) + + # ----- UDP bridge ---------------------------------------------------- + + def _udp_main(self): + udp = self._udp + while self.running and udp is not None: + try: + data, addr = udp.recvfrom(2048) + except socket.timeout: + continue + except OSError: + return + if len(data) < 7: + continue + if self._udp_peer != addr: + self._udp_peer = addr + print("[sim] udp controller", "%s:%d" % addr) + seed_soon(self.cfg, {st.index: mac_str(st.mac) for st in self.strips}, addr[0]) + # A controller that (re)started after the strips booted still gets their hellos + for st in self.strips: + for pkt in (st.hello, st.announce): + if pkt: + try: + udp.sendto(st.mac + pkt, addr) + except OSError: + pass + self.downlink_count += 1 + if self.debug: + print("[sim] udp dl %s %d B" % (mac_str(data[:6]), len(data) - 6)) + self._deliver(bytes(data[:6]), bytes(data[6:])) + + def pixels(self) -> dict: + with self._lock: + frames = [s.frame for s in self.strips] + return { + "layout": self.layout, + "strips": [ + { + "n": s.place.number, + "name": s.name, + "mac": mac_str(s.mac), + "row": s.place.row, + "col": s.place.col, + "reversed": s.place.reversed, + "running": s.conn is not None, + "rx": s.rx_packets, + "tx": s.tx_packets, + "place": _read_json(s.dir / "settings.json").get("place"), + "rgb": frames[i].hex(), + } + for i, s in enumerate(self.strips) + ], + } + + # ----- WebSocket side (asyncio thread) ------------------------------ + + def _loop_main(self, ready: threading.Event): + for p in (str(DRIVER_LIB),): + if p not in sys.path: + sys.path.insert(0, p) + try: + from microdot import Microdot + from microdot.websocket import WebSocketError, with_websocket + except ImportError as e: + self.error = "Microdot not found in led-driver/lib (%s)" % e + ready.set() + return + + app = Microdot() + self._app = app + bridge = self + + @app.route("/ws") + @with_websocket + async def ws_handler(request, ws): + bridge._clients.add(ws) + print("[sim] ws client + (%d)" % len(bridge._clients)) + # A real bridge forwards boot hellos only to clients that are + # connected at the time. Replay them so the controller learns the + # strips even when it connects after Start. + for s in bridge.strips: + for pkt in (s.hello, s.announce): + if pkt: + try: + await ws.send(bytes([0]) + s.mac + pkt) + except Exception: + pass + try: + while True: + try: + raw = await ws.receive() + except WebSocketError: + break + if not raw: + break + if isinstance(raw, str): + raw = raw.encode("utf-8") + bridge.downlink_count += 1 + bridge._downlink(raw) + finally: + bridge._clients.discard(ws) + print("[sim] ws client - (%d)" % len(bridge._clients)) + + @app.route("/api/pixels") + async def api_pixels(request): + return bridge.pixels() + + @app.route("/api/seed-layout", methods=["POST"]) + async def api_seed_layout(request): + """Send the simulator's layout to the controller for every unplaced strip, now.""" + if bridge._udp_peer is None: + return {"error": "no controller on the UDP bridge yet"}, 409 + macs = {st.index: mac_str(st.mac) for st in bridge.strips} + reply = await asyncio.to_thread(seed, bridge.cfg, macs, bridge._udp_peer[0], print, 30) + return {"sent": reply} + + @app.route("/") + async def index(request): + info = { + "bridge": bridge.cfg["bridge"]["name"], + "mac": mac_str(BRIDGE_MAC), + "ws": "/ws", + "strips": [ + {"n": s.place.number, "name": s.name, "mac": mac_str(s.mac)} + for s in bridge.strips + ], + } + return info + + loop = asyncio.new_event_loop() + self._loop = loop + asyncio.set_event_loop(loop) + host = str(self.cfg["bridge"].get("host", "0.0.0.0")) + + async def run(): + try: + # Probe the port so a clash is reported at Start. + srv = await asyncio.start_server(lambda r, w: None, host, self.port) + srv.close() + await srv.wait_closed() + except OSError as e: + self.error = "Port %d not available: %s" % (self.port, e.strerror or e) + ready.set() + return + ready.set() + await app.start_server(host=host, port=self.port) + + try: + loop.run_until_complete(run()) + except Exception as e: # noqa: BLE001 + if not self._stopping: + self.error = str(e) + print("[sim] ws server error:", e) + finally: + ready.set() + try: + loop.close() + except Exception: + pass + + async def _shutdown_ws(self): + for ws in list(self._clients): + try: + await ws.close() + except Exception: + pass + try: + ws.request.sock[1].close() + except Exception: + pass + if self._app is not None and getattr(self._app, "server", None): + self._app.shutdown() + + def _uplink_soon(self, frame: bytes): + self.uplink_count += 1 + for ws in list(self._clients): + asyncio.ensure_future(self._send_ws(ws, frame)) + + async def _send_ws(self, ws, frame): + try: + await ws.send(frame) + except Exception: + self._clients.discard(ws) + + def _deliver(self, dest: bytes, packet: bytes): + if dest == BROADCAST: + for s in self.strips: + self._to_driver(s, packet) + return + s = self.by_mac.get(dest) + if s is None: + if self.debug: + print("[sim] dl no such peer", mac_str(dest)) + return + self._to_driver(s, packet) + + def _downlink(self, raw: bytes): + """Same rules as bridge-wifi/src/main.py ``downlink``.""" + n = len(raw) + if not raw: + return + if raw[0] == WIRE: + if n < 2: + return + if n > MAX_ESPNOW: + if self.debug: + print("[sim] dl skip big wire", n) + return + self._deliver(BROADCAST, raw) + return + if n < 8 or raw[:1] != b"{": + return + try: + data = json.loads(raw) + except ValueError: + return + if not isinstance(data, dict): + return + devs = data.get("dv") or data.get("devices") + if data.get("v") != "1" or not isinstance(devs, dict): + return + for mac_s, body in devs.items(): + if not isinstance(body, dict): + continue + try: + h = str(mac_s).replace(":", "").replace("-", "").strip().lower() + dest = BROADCAST if h == "ffffffffffff" else bytes.fromhex(h) + if len(dest) != 6: + continue + except ValueError: + continue + msg = {"v": "1"} + msg.update(body) + pkt = json.dumps(msg, separators=(",", ":")).encode() + if len(pkt) > MAX_ESPNOW: + if self.debug: + print("[sim] dl skip big", len(pkt)) + continue + self._deliver(dest, pkt) + + +def main(argv=None): + """Headless rig: ``python3 led-simulator/bridge_sim.py [--udp-port 8766] [--port 8765]``.""" + import argparse + import signal + + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--port", type=int, help="WebSocket/HTTP port (default from sim.json, 8765)") + ap.add_argument("--udp-port", type=int, help="UDP bridge port (default 8766, 0 = off)") + ap.add_argument("--debug", action="store_true") + a = ap.parse_args(argv) + cfg = load_config() + if a.udp_port is not None: + cfg["bridge"]["udp_port"] = a.udp_port + if a.debug: + cfg["bridge"]["debug"] = True + sim = BridgeSim(cfg) + sim.start(a.port) + stop = threading.Event() + signal.signal(signal.SIGTERM, lambda *_: stop.set()) + signal.signal(signal.SIGINT, lambda *_: stop.set()) + try: + while not stop.wait(5): + print(flush=True, *("[sim] running %d/%d dl %d ul %d" % (sim.connected_count(), len(sim.strips), sim.downlink_count, sim.uplink_count),)) + finally: + sim.stop() + + +if __name__ == "__main__": + main() diff --git a/gui_main.py b/gui_main.py index b6ff8ce..53dcc2c 100644 --- a/gui_main.py +++ b/gui_main.py @@ -1,264 +1,263 @@ #!/usr/bin/env python3 """ -Graphical NeoPixel simulator for led-driver (CPython). +Graphical simulator for an led-controller rig behind a Wi-Fi bridge (CPython). -Treats ``led-driver/src`` as flash root (``/``) and ``led-driver/lib`` as ``/lib``. -**Start** runs the full application: ``led-driver/src/main.py`` as ``__main__`` -(``asyncio.run(main(port=…))``) — same startup as the device: ``settings``, -``presets.json``, default preset, ``patterns/``, WebSocket, UDP hello, etc. +To led-controller the simulator is a ``bridge-wifi``: a WebSocket on ``/ws`` +(add it as an IP bridge). Behind the bridge, every strip runs the real +``led-driver/src/main.py`` in its own process (see ``bridge_sim.py``). + +Default rig: 16 strips x 119 LEDs, 2 columns x 8 rows, each strip running +along its row with pixel 0 next to the centre line. Change it in +``workspace/sim.json`` (created from ``sim.default.json``). """ from __future__ import annotations -import os -import queue -import runpy -import shutil import sys -import threading import tkinter as tk from pathlib import Path from tkinter import messagebox, ttk -# --- Paths (before importing driver code) --- SIM_ROOT = Path(__file__).resolve().parent -WORKSPACE = SIM_ROOT / "workspace" -STUBS_ROOT = SIM_ROOT / "stubs" -DRIVER_ROOT = SIM_ROOT.parent / "led-driver" -DRIVER_SRC = DRIVER_ROOT / "src" -DRIVER_LIB = DRIVER_ROOT / "lib" -DRIVER_MAIN = DRIVER_SRC / "main.py" -DEFAULT_SETTINGS = SIM_ROOT / "settings.default.json" +if str(SIM_ROOT) not in sys.path: + sys.path.insert(0, str(SIM_ROOT)) + +from bridge_sim import ( # noqa: E402 + BRIDGE_MAC, + DRIVER_SRC, + SIM_CONFIG, + BridgeSim, + lan_ip, + load_config, + mac_str, +) +from layout import compute_geometry # noqa: E402 + +BG = "#0e0f12" +LED_OFF = "#1d1f24" +CENTRE = "#2c3038" +LABEL = "#8a909c" +LABEL_ON = "#c9ced8" +FRAME_MS = 33 -def _ensure_workspace_dirs(): - WORKSPACE.mkdir(parents=True, exist_ok=True) - (WORKSPACE / "patterns").mkdir(parents=True, exist_ok=True) - settings_path = WORKSPACE / "settings.json" - if not settings_path.is_file() and DEFAULT_SETTINGS.is_file(): - shutil.copy2(DEFAULT_SETTINGS, settings_path) - presets_path = WORKSPACE / "presets.json" - if not presets_path.is_file(): - presets_path.write_text("{}\n", encoding="utf-8") - - -def _install_driver_path_and_stubs(): - """``/lib`` then ``/`` then stubs (MicroPython search order, stubs win).""" - for p in (DRIVER_LIB, DRIVER_SRC, STUBS_ROOT): - sys.path.insert(0, str(p)) - - -def _patch_settings_path(): - _ensure_workspace_dirs() - import settings as led_settings - - led_settings.Settings.SETTINGS_FILE = str(WORKSPACE / "settings.json") - - -_install_driver_path_and_stubs() -_patch_settings_path() - -import neopixel as neopixel_stub # noqa: E402 - - -def _ensure_src_symlinks(): - """If flash root (``src``) has no ``patterns`` / ``presets.json``, link workspace copies.""" - _ensure_workspace_dirs() - pat_ws = WORKSPACE / "patterns" - pat_link = DRIVER_SRC / "patterns" - if not pat_link.exists(): - pat_link.symlink_to(pat_ws.resolve(), target_is_directory=True) - elif pat_link.is_symlink(): - pass - # Real directory: treat as on-device flash (do not replace). - - pr_ws = WORKSPACE / "presets.json" - if not pr_ws.is_file(): - pr_ws.write_text("{}\n", encoding="utf-8") - pr_link = DRIVER_SRC / "presets.json" - if not pr_link.exists(): - pr_link.symlink_to(pr_ws.resolve()) +def _hex(r, g, b): + if r == 0 and g == 0 and b == 0: + return LED_OFF + return "#%02x%02x%02x" % (r, g, b) class LedSimulatorApp: def __init__(self): - _ensure_workspace_dirs() + self.cfg = load_config() + self.sim = BridgeSim(self.cfg) + lay = self.sim.layout self.root = tk.Tk() - self.root.title("led-simulator — led-driver (full app)") - self.root.minsize(640, 280) + self.root.title("led-simulator: %s" % self.cfg["bridge"]["name"]) + self.root.geometry("1280x620") + self.root.minsize(760, 360) + self.root.configure(background=BG) - self._pixel_queue: queue.Queue[list[tuple[int, int, int]] | None] = queue.Queue() - self._driver_thread: threading.Thread | None = None - self._driver_running = False - self._ws_port = tk.IntVar(value=8765) - self._status = tk.StringVar( - value="Idle — Start runs the full main.py (settings, presets, patterns/, /ws)." - ) - self._canvas_leds: list[int] = [] + self._port = tk.IntVar(value=int(self.cfg["bridge"]["ws_port"])) + self._status = tk.StringVar() + self._hint = tk.StringVar() + + # canvas item ids per strip / pixel, and last drawn colour per pixel + self._items: list[list[int]] = [] + self._drawn: list[list[str]] = [] + self._label_items: list[int] = [] + self._label_lit: list[bool] = [] + self._frames: list[bytes] = [bytes(lay["leds_per_strip"] * 3)] * len(self.sim.strips) + self._resize_job = None + self._last_size = (0, 0) self._build_ui() - self._install_pixel_sink() - self.root.after(50, self._pump_pixels) - + self._update_status() + self.root.after(FRAME_MS, self._tick) self.root.protocol("WM_DELETE_WINDOW", self._on_quit) + # ----- UI ----------------------------------------------------------- + def _build_ui(self): - top = ttk.Frame(self.root, padding=8) - top.pack(fill=tk.X) - - row = ttk.Frame(top) - row.pack(fill=tk.X) - - ttk.Button(row, text="Start", command=self._on_start).pack(side=tk.LEFT, padx=(0, 6)) - ttk.Button(row, text="Stop", command=self._on_stop).pack(side=tk.LEFT, padx=(0, 16)) - ttk.Label(row, text="HTTP / WS port:").pack(side=tk.LEFT) - ttk.Spinbox(row, from_=1024, to=65535, textvariable=self._ws_port, width=8).pack( - side=tk.LEFT, padx=4 - ) - ttk.Label(row, text="(Microdot; path /ws)").pack(side=tk.LEFT, padx=8) - - hint = ttk.Label( - top, - text=( - "Flash root is led-driver/src: edit workspace/settings.json, presets.json, " - "and patterns/ (or use files already under src/)." - ), - wraplength=620, - justify=tk.LEFT, - ) - hint.pack(fill=tk.X, pady=(8, 0)) - - self._canvas = tk.Canvas(self.root, height=120, background="#1a1a1a", highlightthickness=0) - self._canvas.pack(fill=tk.BOTH, expand=True, padx=8, pady=(0, 8)) - - st = ttk.Label(self.root, textvariable=self._status, padding=(8, 0, 8, 8)) - st.pack(fill=tk.X) - - def _install_pixel_sink(self): - def sink(buf: list[tuple[int, int, int]]): - self._pixel_queue.put(buf) - - neopixel_stub.PIXEL_SINK = sink - - def _pump_pixels(self): + style = ttk.Style(self.root) try: - while True: - buf = self._pixel_queue.get_nowait() - if buf is None: - self._draw_leds([(0, 0, 0)] * max(1, len(self._canvas_leds))) - else: - self._draw_leds(buf) - except queue.Empty: + style.theme_use("clam") + except tk.TclError: pass - self.root.after(50, self._pump_pixels) - def _draw_leds(self, buf: list[tuple[int, int, int]]): - self._canvas.delete("led") - n = len(buf) - if n == 0: - return - cw = self._canvas.winfo_width() or 700 - margin = 12 - usable = max(40, cw - 2 * margin) - gap = 4 - diam = max(6, min(22, (usable - (n - 1) * gap) // n)) - y = 50 - total_w = n * diam + (n - 1) * gap - x0 = max(margin, (cw - total_w) // 2) - self._canvas_leds = [] - for i, (r, g, b) in enumerate(buf): - x = x0 + i * (diam + gap) - fill = f"#{r:02x}{g:02x}{b:02x}" - outline = "#444444" if (r + g + b) > 40 else "#666666" - oid = self._canvas.create_oval( - x, y, x + diam, y + diam, fill=fill, outline=outline, width=1, tags="led" + top = ttk.Frame(self.root, padding=(10, 8)) + top.pack(fill=tk.X) + self._start_btn = ttk.Button(top, text="Start", command=self._on_start) + self._start_btn.pack(side=tk.LEFT, padx=(0, 6)) + self._stop_btn = ttk.Button(top, text="Stop", command=self._on_stop, state=tk.DISABLED) + self._stop_btn.pack(side=tk.LEFT, padx=(0, 16)) + ttk.Label(top, text="Bridge WebSocket port:").pack(side=tk.LEFT) + self._port_box = ttk.Spinbox( + top, from_=1, to=65535, textvariable=self._port, width=7 + ) + self._port_box.pack(side=tk.LEFT, padx=4) + ttk.Label(top, textvariable=self._status).pack(side=tk.LEFT, padx=(16, 0)) + + hint = ttk.Label(self.root, textvariable=self._hint, padding=(10, 0, 10, 6)) + hint.pack(fill=tk.X) + + self._canvas = tk.Canvas(self.root, background=BG, highlightthickness=0) + self._canvas.pack(fill=tk.BOTH, expand=True) + self._canvas.bind("", self._on_resize) + + def _update_status(self): + b = self.cfg["bridge"] + lay = self.sim.layout + rig = "%d strips x %d LEDs, %d x %d" % ( + len(self.sim.strips), + lay["leds_per_strip"], + lay["columns"], + lay["rows"], + ) + if self.sim.running: + self._status.set( + "%s (%s) ws://%s:%d/ws | controller connections: %d | strips up: %d/%d | %s" + % ( + b["name"], + mac_str(BRIDGE_MAC), + lan_ip(), + self.sim.port, + self.sim.client_count, + self.sim.connected_count(), + len(self.sim.strips), + rig, + ) + ) + self._hint.set( + "In led-controller add a bridge with transport IP, address %s " + "(127.0.0.1 on this computer) and port %d. Strips register from their hello." + % (lan_ip(), self.sim.port) + ) + else: + self._status.set("Stopped | %s | config: %s" % (rig, SIM_CONFIG)) + self._hint.set( + "Start boots the wifi bridge and one led-driver per strip " + "(led-driver/src/main.py, flash in workspace/drivers/NN)." ) - self._canvas_leds.append(oid) - def _run_main_py_thread(self, port: int): + # ----- drawing ------------------------------------------------------- + + def _on_resize(self, event): + if (event.width, event.height) == self._last_size: + return + if self._resize_job is not None: + self.root.after_cancel(self._resize_job) + self._resize_job = self.root.after(60, self._rebuild) + + def _rebuild(self): + self._resize_job = None + c = self._canvas + w, h = c.winfo_width(), c.winfo_height() + if w < 50 or h < 50: + return + self._last_size = (w, h) + c.delete("all") + geo = compute_geometry(self.sim.places, self.sim.layout, w, h) + for x in geo.centre_lines: + c.create_line(x, 6, x, h - 6, fill=CENTRE, dash=(4, 4)) + self._items = [] + self._drawn = [] + self._label_items = [] + self._label_lit = [] + font = ("TkDefaultFont", 8) + for s, rects, (lx, ly, anchor) in zip(self.sim.strips, geo.rects, geo.labels): + if anchor == "e": + text = "%s %d ◂" % (s.name, s.place.number) + else: + text = "▸ %d %s" % (s.place.number, s.name) + self._label_items.append( + c.create_text(lx, ly, text=text, anchor=anchor, fill=LABEL, font=font) + ) + ids = [] + for x0, y0, x1, y1 in rects: + ids.append(c.create_rectangle(x0, y0, x1, y1, fill=LED_OFF, width=0)) + self._items.append(ids) + self._drawn.append([LED_OFF] * len(ids)) + self._label_lit.append(False) + for i, frame in enumerate(self._frames): + self._paint(i, frame) + + def _paint(self, strip_index: int, frame: bytes): + if strip_index >= len(self._items): + return + ids = self._items[strip_index] + drawn = self._drawn[strip_index] + itemconfig = self._canvas.itemconfigure + lit = False + for i in range(min(len(ids), len(frame) // 3)): + j = i * 3 + col = _hex(frame[j], frame[j + 1], frame[j + 2]) + if col != LED_OFF: + lit = True + if drawn[i] != col: + itemconfig(ids[i], fill=col) + drawn[i] = col + if self._label_lit[strip_index] != lit: + self._label_lit[strip_index] = lit + itemconfig(self._label_items[strip_index], fill=LABEL_ON if lit else LABEL) + + def _tick(self): try: - try: - import led_driver_sim_hook as sim_hook - - sim_hook.clear_app() - except ImportError: - pass - - os.environ["LED_SIM_PORT"] = str(port) - os.environ["LED_SIM_ROOT"] = str(SIM_ROOT) - - runpy.run_path(str(DRIVER_MAIN), run_name="__main__") - except Exception as ex: # noqa: BLE001 - self.root.after(0, lambda e=ex: messagebox.showerror("Simulator", str(e))) + for i, frame in self.sim.take_dirty_frames().items(): + self._frames[i] = frame + self._paint(i, frame) finally: - for key in ("LED_SIM_PORT", "LED_SIM_ROOT"): - os.environ.pop(key, None) - try: - import led_driver_sim_hook as sim_hook + self.root.after(FRAME_MS, self._tick) - sim_hook.clear_app() - except ImportError: - pass - self._driver_running = False - self._pixel_queue.put(None) - self.root.after(0, lambda: self._status.set("Stopped.")) + def _status_tick(self): + self._update_status() + if self.sim.running: + self.root.after(1000, self._status_tick) + + # ----- actions ------------------------------------------------------- def _on_start(self): - if self._driver_running: - messagebox.showwarning("Simulator", "Already running — press Stop first.") + if self.sim.running: return - - for k in list(sys.modules): - if k.startswith("patterns."): - del sys.modules[k] - - _ensure_src_symlinks() - os.chdir(DRIVER_SRC) - - port = int(self._ws_port.get()) - self._driver_running = True - self.root.after( - 0, - lambda p=port: self._status.set( - f"Running full app (main.py) — ws://127.0.0.1:{p}/ws" - ), - ) - - self._driver_thread = threading.Thread( - target=self._run_main_py_thread, - args=(port,), - daemon=True, - ) - self._driver_thread.start() + try: + port = int(self._port.get()) + except (tk.TclError, ValueError): + messagebox.showerror("Simulator", "Port must be a number.") + return + try: + self.sim.start(port=port) + except Exception as e: # noqa: BLE001 + self.sim.stop() + messagebox.showerror("Simulator", str(e)) + return + self._start_btn.configure(state=tk.DISABLED) + self._stop_btn.configure(state=tk.NORMAL) + self._port_box.configure(state=tk.DISABLED) + self._status_tick() def _on_stop(self): - try: - import led_driver_sim_hook as sim_hook - - app = sim_hook.get_app() - if app is not None and getattr(app, "server", None): - app.shutdown() - except ImportError: - pass + self.sim.stop() + self._start_btn.configure(state=tk.NORMAL) + self._stop_btn.configure(state=tk.DISABLED) + self._port_box.configure(state=tk.NORMAL) + self._update_status() def _on_quit(self): - self._on_stop() - self.root.destroy() + try: + self.sim.stop() + finally: + self.root.destroy() def run(self): self.root.mainloop() def main(): - if not DRIVER_SRC.is_dir() or not DRIVER_MAIN.is_file(): + if not (DRIVER_SRC / "main.py").is_file(): print("led-driver/src/main.py not found next to led-simulator.", file=sys.stderr) sys.exit(1) - if not DRIVER_LIB.is_dir(): - print("led-driver/lib not found next to led-simulator.", file=sys.stderr) - sys.exit(1) - app = LedSimulatorApp() - app.run() + LedSimulatorApp().run() if __name__ == "__main__": diff --git a/layout.py b/layout.py new file mode 100644 index 0000000..d1fe9c9 --- /dev/null +++ b/layout.py @@ -0,0 +1,114 @@ +"""Physical strip layout for led-simulator (server side; the page draws it in web/layout.js). + +The default rig is 16 strips of 119 LEDs in 2 columns x 8 rows. Each strip +runs along its row, and pixel 0 sits next to the centre line between the +columns: left-column strips run right-to-left, right-column strips run +left-to-right. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +DEFAULT_LAYOUT = { + "rows": 8, + "columns": 2, + "leds_per_strip": 119, + # "row": strip 1 = row 1 left, strip 2 = row 1 right, strip 3 = row 2 left, ... + # "column": strips 1-8 = left column top to bottom, 9-16 = right column. + "order": "row", + # "center": pixel 0 next to the middle of the columns (default rig). + # "left": every strip starts at its left end. "right": at its right end. + "start": "center", +} + + +@dataclass(frozen=True) +class StripPlace: + index: int # 0-based strip number + row: int # 0-based, top row first + col: int # 0-based, left column first + leds: int + reversed: bool # True: pixel 0 is at the strip's right end + + @property + def number(self) -> int: + return self.index + 1 + + +def normalise_layout(raw: dict | None) -> dict: + lay = dict(DEFAULT_LAYOUT) + if isinstance(raw, dict): + lay.update({k: v for k, v in raw.items() if v is not None}) + lay["rows"] = max(1, int(lay["rows"])) + lay["columns"] = max(1, int(lay["columns"])) + lay["leds_per_strip"] = max(1, min(2048, int(lay["leds_per_strip"]))) + lay["order"] = "column" if str(lay["order"]).lower() == "column" else "row" + start = str(lay["start"]).lower() + lay["start"] = start if start in ("center", "left", "right") else "center" + return lay + + +def strip_count(layout: dict) -> int: + lay = normalise_layout(layout) + return lay["rows"] * lay["columns"] + + +def _reversed_for_column(col: int, columns: int, start: str) -> bool: + if start == "left": + return False + if start == "right": + return True + # centre-out: columns left of the middle run leftwards from their right end. + # With an odd column count the middle column runs left-to-right. + return col < columns // 2 + + +def strip_places(layout: dict) -> list[StripPlace]: + lay = normalise_layout(layout) + rows, cols = lay["rows"], lay["columns"] + out = [] + for i in range(rows * cols): + if lay["order"] == "column": + row, col = i % rows, i // rows + else: + row, col = i // cols, i % cols + out.append( + StripPlace( + index=i, + row=row, + col=col, + leds=lay["leds_per_strip"], + reversed=_reversed_for_column(col, cols, lay["start"]), + ) + ) + return out + + +def side_name(col: int, columns: int) -> str: + if columns == 2: + return "left" if col == 0 else "right" + return "c%d" % (col + 1) + + +# Rig coordinates for led-controller's rig layout (POST /devices/layout): the same 1000 x 700 canvas as its +# rig-layout editor, y up. Each strip runs along its row inside its column; x0,y0 is pixel 0's end. +RIG_W = 1000 +RIG_H = 700 +RIG_GAP = 20 # space between a strip's end and its column's edge + + +def rig_placements(layout: dict) -> tuple[dict[int, dict], dict]: + """({strip index: {x0, y0, x1, y1}}, centre {x, y}) for the controller's rig layout.""" + lay = normalise_layout(layout) + rows, cols = lay["rows"], lay["columns"] + col_w = RIG_W / cols + row_h = RIG_H / rows + out = {} + for p in strip_places(lay): + y = round(RIG_H - (p.row + 0.5) * row_h, 1) # row 1 at the top + left = round(p.col * col_w + RIG_GAP, 1) + right = round((p.col + 1) * col_w - RIG_GAP, 1) + x0, x1 = (right, left) if p.reversed else (left, right) + out[p.index] = {"x0": x0, "y0": y, "x1": x1, "y1": y} + return out, {"x": RIG_W / 2, "y": RIG_H / 2} diff --git a/rig_seed.py b/rig_seed.py new file mode 100644 index 0000000..034f941 --- /dev/null +++ b/rig_seed.py @@ -0,0 +1,85 @@ +"""Give led-controller the simulator's rig layout once its strips have registered. + +The layout is the simulator's (``layout`` in sim.json, see ``layout.rig_placements``). Only strips the +controller has no placement for are sent, so moving bars in the controller's rig-layout page sticks: +the simulator page then draws them where the controller put them (each driver's ``place``). +""" + +from __future__ import annotations + +import json +import threading +import time +import urllib.request + +from layout import rig_placements + + +def _get(url: str, timeout: float = 3): + with urllib.request.urlopen(url, timeout=timeout) as r: + return json.loads(r.read()) + + +def _post(url: str, body: dict, timeout: float = 15): + req = urllib.request.Request( + url, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}, method="POST" + ) + with urllib.request.urlopen(req, timeout=timeout) as r: + return json.loads(r.read()) + + +def controller_url(cfg: dict, peer_ip: str) -> str | None: + """The controller's web API: ``controller.url`` in sim.json, else the bridge peer on 8080 or 80.""" + url = (cfg.get("controller") or {}).get("url") + candidates = [url] if url else ["http://%s:8080" % peer_ip, "http://%s" % peer_ip] + for base in candidates: + try: + _get(base.rstrip("/") + "/status", timeout=2) + return base.rstrip("/") + except (OSError, ValueError): + continue + return None + + +def seed(cfg: dict, macs: dict[int, str], peer_ip: str, log=print, wait_s: float = 180) -> dict | None: + """Wait for the strips to register, then send placements for the unplaced ones. Returns the reply.""" + if (cfg.get("controller") or {}).get("seed_layout", True) is False: + return None + base = controller_url(cfg, peer_ip) + if base is None: + log("[layout] controller web API not found at %s (set controller.url in sim.json)" % peer_ip) + return None + want = {i: m.replace(":", "").lower() for i, m in macs.items()} + end = time.monotonic() + wait_s + devs = {} + while time.monotonic() < end: + try: + devs = _get(base + "/devices") + except (OSError, ValueError): + devs = {} + if all(m in devs for m in want.values()): + break + time.sleep(1) + places, center = rig_placements(cfg["layout"]) + todo = { + m: places[i] + for i, m in want.items() + if m in devs and not isinstance(devs[m].get("placement"), dict) + } + if not todo: + log("[layout] controller already has every strip placed") + return None + body = {"placements": todo} + if not any(isinstance(d, dict) and isinstance(d.get("placement"), dict) for d in devs.values()): + body["center"] = center # a fresh rig: the simulator's centre too + try: + reply = _post(base + "/devices/layout", body) + except (OSError, ValueError) as e: + log("[layout] sending the rig layout failed: %s" % e) + return None + log("[layout] sent %d strip placements to %s: %s" % (len(todo), base, reply)) + return reply + + +def seed_soon(cfg: dict, macs: dict[int, str], peer_ip: str, log=print) -> None: + threading.Thread(target=seed, args=(cfg, macs, peer_ip, log), name="rig-seed", daemon=True).start() diff --git a/server.py b/server.py new file mode 100644 index 0000000..e88bb95 --- /dev/null +++ b/server.py @@ -0,0 +1,541 @@ +#!/usr/bin/env python3 +"""led-simulator web app: a simulated Wi-Fi ESP-NOW bridge plus a browser rig. + +One Microdot server (from ``led-driver/lib``, no extra installs) provides: + +- UDP ``8766`` the bridge for led-controller's ``settings.bridge`` (and its host build, + ``sim-controller/``): ``dst_mac + packet`` down, ``src_mac + packet`` up. +- ``/ws`` the older bridge WebSocket, same protocol as + ``bridge-wifi``: binary wire packets are broadcast, v1 JSON envelopes are + split per MAC, and driver transmissions go up as ``0x00 + mac + packet``. +- ``/`` the simulator page. Every strip is a led-driver running the real + ``led-driver/src/main.py`` and patterns in Pyodide, one web worker each. +- ``/sim`` the page's radio link: the server hands it the ESP-NOW packets the + bridge would transmit and takes back what the drivers transmit. + +Strips register with the controller the way hardware does: each driver sends +its JSON hello once when it powers on. A strip that boots while no controller +is connected has to be power-cycled to register. + +Run from the repository root:: + + python3 led-simulator/server.py # http://localhost:8765/ +""" + +from __future__ import annotations + +import argparse +import asyncio +import json +import socket +import sys +from pathlib import Path + +SIM_ROOT = Path(__file__).resolve().parent +REPO_ROOT = SIM_ROOT.parent +DRIVER_ROOT = REPO_ROOT / "led-driver" +DRIVER_SRC = DRIVER_ROOT / "src" +DRIVER_LIB = DRIVER_ROOT / "lib" +WEB_ROOT = SIM_ROOT / "web" +STUBS_ROOT = SIM_ROOT / "stubs" +WORKSPACE = SIM_ROOT / "workspace" +DRIVERS_DIR = WORKSPACE / "drivers" +SIM_DEFAULTS = SIM_ROOT / "sim.default.json" +SIM_CONFIG = WORKSPACE / "sim.json" +DRIVER_SETTINGS_TEMPLATE = SIM_ROOT / "settings.default.json" + +sys.path.insert(0, str(SIM_ROOT)) +sys.path.insert(0, str(DRIVER_LIB)) + +from layout import normalise_layout, side_name, strip_places # noqa: E402 +from rig_seed import seed, seed_soon # noqa: E402 + +BROADCAST = b"\xff\xff\xff\xff\xff\xff" +WIRE = 0x4C +MAX_ESPNOW = 250 +# Locally administered MACs 02:51:4d:00:00:NN. The bridge is NN=00. +MAC_PREFIX = bytes([0x02, 0x51, 0x4D, 0x00, 0x00]) +BRIDGE_MAC = MAC_PREFIX + b"\x00" + +# Files a driver may persist in its simulated flash (workspace/drivers/NN/). +# Patterns are not persisted: every boot loads led-driver/src/patterns. +FLASH_FILES = ("settings.json", "presets.json") + +BUILTIN_DEFAULTS = { + "bridge": { + "name": "bridge-sim", + "host": "0.0.0.0", + "ws_port": 8765, + "wifi_channel": 5, + "debug": False, + }, + "layout": {}, + "drivers": { + "name": "sim-{n:02d}", + "fps": 30, + "loop_sleep_ms": 2, + "boot_concurrency": 4, + }, + "pyodide_url": "https://cdn.jsdelivr.net/pyodide/v0.26.4/full/", +} + +CONTENT_TYPES = { + ".html": "text/html; charset=utf-8", + ".js": "text/javascript; charset=utf-8", + ".mjs": "text/javascript; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".json": "application/json", + ".svg": "image/svg+xml", + ".png": "image/png", + ".ico": "image/x-icon", + ".py": "text/x-python; charset=utf-8", +} + + +def mac_str(mac: bytes) -> str: + return ":".join("%02x" % b for b in mac) + + +def driver_mac(index: int) -> bytes: + return MAC_PREFIX + bytes([(index + 1) & 0xFF]) + + +def _merge(base: dict, extra: dict) -> dict: + out = dict(base) + for k, v in (extra or {}).items(): + if isinstance(v, dict) and isinstance(out.get(k), dict): + out[k] = _merge(out[k], v) + else: + out[k] = v + return out + + +def _read_json(path: Path) -> dict: + try: + with open(path, encoding="utf-8") as f: + data = json.load(f) + return data if isinstance(data, dict) else {} + except (OSError, ValueError): + return {} + + +def load_config() -> dict: + """Built-in defaults <- sim.default.json <- workspace/sim.json.""" + WORKSPACE.mkdir(parents=True, exist_ok=True) + cfg = _merge(BUILTIN_DEFAULTS, _read_json(SIM_DEFAULTS)) + cfg = _merge(cfg, _read_json(SIM_CONFIG)) + cfg["layout"] = normalise_layout(cfg.get("layout")) + return cfg + + +def lan_ip() -> str: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + s.connect(("10.255.255.255", 1)) + return s.getsockname()[0] + except OSError: + return "127.0.0.1" + finally: + s.close() + + +def bridge_downlink(raw: bytes, debug: bool = False) -> list[tuple[bytes, bytes]]: + """What the bridge transmits for one controller WebSocket message. + + Same rules as ``bridge-wifi/src/main.py`` ``downlink``. Returns a list of + ``(dest_mac, espnow_packet)``. + """ + out: list[tuple[bytes, bytes]] = [] + n = len(raw) + if not raw: + return out + if raw[0] == WIRE: + if n < 2 or n > MAX_ESPNOW: + if debug: + print("[bridge] dl skip wire", n) + return out + out.append((BROADCAST, bytes(raw))) + return out + if n < 8 or raw[:1] != b"{": + return out + try: + data = json.loads(raw) + except ValueError: + return out + if not isinstance(data, dict): + return out + devs = data.get("dv") or data.get("devices") + if data.get("v") != "1" or not isinstance(devs, dict): + return out + for mac_s, body in devs.items(): + if not isinstance(body, dict): + continue + h = str(mac_s).replace(":", "").replace("-", "").strip().lower() + try: + dest = BROADCAST if h == "ffffffffffff" else bytes.fromhex(h) + except ValueError: + continue + if len(dest) != 6: + continue + msg = {"v": "1"} + msg.update(body) + pkt = json.dumps(msg, separators=(",", ":")).encode() + if len(pkt) > MAX_ESPNOW: + if debug: + print("[bridge] dl skip big", len(pkt)) + continue + out.append((dest, pkt)) + return out + + +class Rig: + """Strip list, simulated flash on disk, and the two WebSocket sides.""" + + def __init__(self, cfg: dict): + self.cfg = cfg + self.layout = cfg["layout"] + self.debug = bool(cfg["bridge"].get("debug", False)) + self.places = strip_places(self.layout) + self.strips = [] + name_fmt = str(cfg["drivers"].get("name", "sim-{n:02d}")) + for p in self.places: + default_name = name_fmt.format( + n=p.number, + row=p.row + 1, + col=p.col + 1, + side=side_name(p.col, self.layout["columns"]), + ) + self.strips.append( + { + "index": p.index, + "n": p.number, + "row": p.row, + "col": p.col, + "leds": p.leds, + "reversed": p.reversed, + "mac": mac_str(driver_mac(p.index)), + "default_name": default_name, + "dir": DRIVERS_DIR / ("%02d" % p.number), + } + ) + self.controllers: set = set() + self.page = None + self.udp = None # asyncio datagram transport + self.udp_peer = None # the controller that last sent a datagram + self.hellos: dict[bytes, bytes] = {} # mac -> boot hello, replayed to a new UDP controller + self.port = int(cfg["bridge"]["ws_port"]) + + # ----- flash ---------------------------------------------------------- + + def flash(self, index: int) -> dict: + """Read (creating on first use) a strip's settings.json and presets.json.""" + s = self.strips[index] + d: Path = s["dir"] + d.mkdir(parents=True, exist_ok=True) + template = _read_json(DRIVER_SETTINGS_TEMPLATE) + current = _read_json(d / "settings.json") + settings = dict(template) + settings.update(current) + if not current.get("name"): + settings["name"] = s["default_name"] + # Strip length is physical: the layout decides it. + settings["num_leds"] = s["leds"] + settings["wifi_channel"] = int(self.cfg["bridge"].get("wifi_channel", 5)) + settings_text = json.dumps(settings) + (d / "settings.json").write_text(settings_text, encoding="utf-8") + presets_path = d / "presets.json" + if not presets_path.is_file(): + presets_path.write_text("{}", encoding="utf-8") + return { + "settings.json": settings_text, + "presets.json": presets_path.read_text(encoding="utf-8"), + } + + def write_flash(self, index, path, data) -> bool: + try: + index = int(index) + except (TypeError, ValueError): + return False + if not (0 <= index < len(self.strips)) or path not in FLASH_FILES: + return False + if not isinstance(data, str) or len(data) > 512 * 1024: + return False + d: Path = self.strips[index]["dir"] + d.mkdir(parents=True, exist_ok=True) + tmp = d / (path + ".tmp") + tmp.write_text(data, encoding="utf-8") + tmp.replace(d / path) + return True + + def bundle(self) -> dict: + """Files for a driver's flash: led-driver/src (with patterns) and stubs.""" + driver = {} + for f in sorted(DRIVER_SRC.rglob("*.py")): + rel = f.relative_to(DRIVER_SRC).as_posix() + if "__pycache__" in rel: + continue + driver[rel] = f.read_text(encoding="utf-8") + stubs = {} + for f in sorted(STUBS_ROOT.glob("*.py")): + stubs[f.name] = f.read_text(encoding="utf-8") + return {"driver": driver, "stubs": stubs} + + def public_config(self) -> dict: + return { + "bridge": { + "name": self.cfg["bridge"]["name"], + "mac": mac_str(BRIDGE_MAC), + "port": self.port, + "udp_port": int(self.cfg["bridge"].get("udp_port", 8766)), + "lan_ip": lan_ip(), + "wifi_channel": int(self.cfg["bridge"].get("wifi_channel", 5)), + }, + "layout": self.layout, + "drivers": { + k: self.cfg["drivers"][k] + for k in ("fps", "loop_sleep_ms", "boot_concurrency") + if k in self.cfg["drivers"] + }, + "pyodide_url": self.cfg["pyodide_url"], + "strips": [ + dict({k: v for k, v in s.items() if k != "dir"}, + place=_read_json(s["dir"] / "settings.json").get("place")) + for s in self.strips + ], + } + + # ----- radio ------------------------------------------------------------ + + async def to_page(self, frame): + page = self.page + if page is None: + return + try: + await page.send(frame) + except Exception: + if self.page is page: + self.page = None + + async def page_status(self): + n = len(self.controllers) + (1 if self.udp_peer is not None else 0) + await self.to_page(json.dumps({"t": "status", "controllers": n})) + + async def from_controller(self, raw: bytes): + for dest, pkt in bridge_downlink(raw, self.debug): + if self.debug: + print("[bridge] dl", mac_str(dest), len(pkt)) + # Nobody listening (page closed) = radio packet lost, as on air. + await self.to_page(dest + pkt) + + def from_udp(self, data: bytes, addr): + if len(data) < 7: + return + if addr != self.udp_peer: + self.udp_peer = addr + print("[bridge] udp controller %s:%d" % addr) + seed_soon(self.cfg, {s["index"]: s["mac"] for s in self.strips}, addr[0]) + asyncio.ensure_future(self.page_status()) + for mac, pkt in self.hellos.items(): + self.udp.sendto(mac + pkt, addr) + if self.debug: + print("[bridge] udp dl", mac_str(data[:6]), len(data) - 6) + asyncio.ensure_future(self.to_page(bytes(data))) + + async def from_page(self, frame: bytes): + """``src_mac + packet`` from a driver: the bridge forwards it up.""" + if len(frame) < 7: + return + if frame[6:7] == b"{" or frame[6:8] == bytes([0x4C, 0x01]): + self.hellos[frame[:6]] = frame[6:] + if self.udp is not None and self.udp_peer is not None: + self.udp.sendto(frame, self.udp_peer) + up = bytes([0]) + frame + if self.debug: + print("[bridge] up", mac_str(frame[:6]), len(frame) - 6) + for ws in list(self.controllers): + try: + await ws.send(up) + except Exception: + self.controllers.discard(ws) + + +def build_app(rig: Rig): + from microdot import Microdot, Response, send_file + from microdot.websocket import WebSocketError, with_websocket + + app = Microdot() + + @app.after_request + async def isolation_headers(request, response): + # SharedArrayBuffer (driver packet rings) needs a cross-origin isolated + # page. credentialless keeps the Pyodide CDN loading, as in led-editor. + if response is not None and response is not Response.already_handled: + response.headers["Cross-Origin-Opener-Policy"] = "same-origin" + response.headers["Cross-Origin-Embedder-Policy"] = "credentialless" + response.headers["Cache-Control"] = "no-cache" + return response + + def static(path: Path): + try: + path = path.resolve() + path.relative_to(WEB_ROOT.resolve()) + except (OSError, ValueError): + return "Not found", 404 + if not path.is_file(): + return "Not found", 404 + ctype = CONTENT_TYPES.get(path.suffix.lower(), "application/octet-stream") + return send_file(str(path), content_type=ctype) + + @app.route("/") + async def index(request): + return static(WEB_ROOT / "index.html") + + @app.route("/web/") + async def web(request, path): + return static(WEB_ROOT / path) + + @app.route("/api/seed-layout", methods=["POST"]) + async def api_seed_layout(request): + """Send the simulator's layout to the controller for every unplaced strip, now.""" + if rig.udp_peer is None: + return {"error": "no controller on the UDP bridge yet"}, 409 + macs = {s["index"]: s["mac"] for s in rig.strips} + reply = await asyncio.to_thread(seed, rig.cfg, macs, rig.udp_peer[0], print, 30) + return {"sent": reply} + + @app.route("/api/config") + async def api_config(request): + return rig.public_config() + + @app.route("/api/bundle") + async def api_bundle(request): + return rig.bundle() + + @app.route("/api/flash/") + async def api_flash(request, index): + if not (0 <= index < len(rig.strips)): + return {"error": "no such strip"}, 404 + return rig.flash(index) + + @app.route("/ws") + @with_websocket + async def controller_ws(request, ws): + rig.controllers.add(ws) + print("[bridge] controller + (%d)" % len(rig.controllers)) + await rig.page_status() + try: + while True: + try: + raw = await ws.receive() + except WebSocketError: + break + if not raw: + break + if isinstance(raw, str): + raw = raw.encode("utf-8") + await rig.from_controller(raw) + finally: + rig.controllers.discard(ws) + print("[bridge] controller - (%d)" % len(rig.controllers)) + await rig.page_status() + + @app.route("/sim") + @with_websocket + async def page_ws(request, ws): + old = rig.page + rig.page = ws + if old is not None: + try: + await old.send(json.dumps({"t": "takeover"})) + await old.close() + except Exception: + pass + print("[sim] page connected") + await rig.page_status() + try: + while True: + try: + msg = await ws.receive() + except WebSocketError: + break + if not msg: + break + if rig.page is not ws: + break + if isinstance(msg, (bytes, bytearray)): + await rig.from_page(bytes(msg)) + continue + try: + data = json.loads(msg) + except ValueError: + continue + if isinstance(data, dict) and data.get("t") == "flash": + rig.write_flash(data.get("n"), data.get("path"), data.get("data")) + finally: + if rig.page is ws: + rig.page = None + print("[sim] page disconnected") + + return app + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--port", type=int, help="HTTP + bridge WebSocket port (default 8765)") + ap.add_argument("--host", help="listen address (default 0.0.0.0)") + ap.add_argument("--udp-port", type=int, help="UDP bridge port (default 8766, 0 = off)") + ap.add_argument("--debug", action="store_true", help="log every bridge packet") + args = ap.parse_args(argv) + + if not (DRIVER_SRC / "main.py").is_file(): + print("led-driver/src/main.py not found next to led-simulator.", file=sys.stderr) + return 1 + try: + import microdot # noqa: F401 + except ImportError: + print("Microdot not found in led-driver/lib.", file=sys.stderr) + return 1 + + cfg = load_config() + if args.port: + cfg["bridge"]["ws_port"] = args.port + if args.host: + cfg["bridge"]["host"] = args.host + if args.debug: + cfg["bridge"]["debug"] = True + if args.udp_port is not None: + cfg["bridge"]["udp_port"] = args.udp_port + rig = Rig(cfg) + app = build_app(rig) + udp_port = int(cfg["bridge"].get("udp_port", 8766)) + host = str(cfg["bridge"]["host"]) + port = rig.port + lay = rig.layout + print( + "led-simulator: %d strips x %d LEDs (%d x %d)" + % (len(rig.strips), lay["leds_per_strip"], lay["columns"], lay["rows"]) + ) + print(" simulator page: http://localhost:%d/" % port) + if udp_port: + print(" bridge for led-controller: settings.bridge \"%s:%d\" (or 127.0.0.1:%d)" % (lan_ip(), udp_port, udp_port)) + + class Udp(asyncio.DatagramProtocol): + def datagram_received(self, data, addr): + rig.from_udp(data, addr) + + async def run(): + if udp_port: + rig.udp, _ = await asyncio.get_running_loop().create_datagram_endpoint( + Udp, local_addr=(host, udp_port) + ) + await app.start_server(host=host, port=port) + + try: + asyncio.run(run()) + except KeyboardInterrupt: + pass + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/settings.default.json b/settings.default.json index f2518ed..19f417c 100644 --- a/settings.default.json +++ b/settings.default.json @@ -1,13 +1,13 @@ { "led_pin": 10, - "num_leds": 32, + "num_leds": 119, "color_order": "rgb", - "name": "sim", "debug": false, "default": "on", + "last_preset": "", + "startup_mode": "default", "brightness": 255, - "transport_type": "wifi", + "reversed": false, "wifi_channel": 5, - "ssid": "", - "password": "" + "groups": [] } diff --git a/sim.default.json b/sim.default.json new file mode 100644 index 0000000..5dd293f --- /dev/null +++ b/sim.default.json @@ -0,0 +1,28 @@ +{ + "bridge": { + "name": "bridge-sim", + "host": "0.0.0.0", + "ws_port": 8765, + "udp_port": 8766, + "wifi_channel": 5, + "debug": false + }, + "layout": { + "rows": 8, + "columns": 2, + "leds_per_strip": 119, + "order": "row", + "start": "center" + }, + "drivers": { + "name": "sim-{n:02d}", + "fps": 30, + "loop_sleep_ms": 2, + "boot_concurrency": 4 + }, + "pyodide_url": "https://cdn.jsdelivr.net/pyodide/v0.26.4/full/", + "controller": { + "url": null, + "seed_layout": true + } +} diff --git a/sim_driver.py b/sim_driver.py new file mode 100644 index 0000000..352b8b5 --- /dev/null +++ b/sim_driver.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Run one simulated led-driver (one strip) in its own process. + +Started by ``bridge_sim.py``; not normally run by hand. Runs the real +``led-driver/src/main.py`` as ``__main__``, with: + +- ``stubs/`` first on ``sys.path`` (machine, neopixel, network, espnow, ...) +- the driver's own folder ``workspace/drivers/NN`` as its flash root (cwd): + ``settings.json``, ``presets.json`` and ``patterns/`` live there +- ESP-NOW and pixel output carried to the bridge simulator by ``_simlink`` + +Environment (set by the bridge): ``LED_SIM_INDEX``, ``LED_SIM_MAC``, +``LED_SIM_DIR``, ``LED_SIM_ADDR`` (host:port), ``LED_SIM_AUTH`` (hex), +``LED_SIM_FPS``, ``LED_SIM_LOOP_SLEEP_MS``. +""" + +import os +import runpy +import sys +from pathlib import Path + +SIM_ROOT = Path(__file__).resolve().parent +STUBS_ROOT = SIM_ROOT / "stubs" +DRIVER_ROOT = SIM_ROOT.parent / "led-driver" +DRIVER_SRC = DRIVER_ROOT / "src" +DRIVER_LIB = DRIVER_ROOT / "lib" +DRIVER_MAIN = DRIVER_SRC / "main.py" + + +def main(): + index = int(os.environ["LED_SIM_INDEX"]) + drv_dir = Path(os.environ["LED_SIM_DIR"]).resolve() + host, port = os.environ["LED_SIM_ADDR"].rsplit(":", 1) + authkey = bytes.fromhex(os.environ["LED_SIM_AUTH"]) + fps = float(os.environ.get("LED_SIM_FPS", "30")) + + os.chdir(drv_dir) + log = open(drv_dir / "driver.log", "w", buffering=1, encoding="utf-8") + sys.stdout = log + sys.stderr = log + import faulthandler + import signal + + faulthandler.register(signal.SIGUSR1, file=log, all_threads=True) # kill -USR1 : stacks to driver.log + + # MicroPython search order is cwd (flash root) then /lib. Stubs go first so + # they replace the hardware modules; the driver folder comes before src so + # its patterns/ package (OTA target) wins over led-driver/src/patterns. + sys.path[:] = [ + str(STUBS_ROOT), + str(drv_dir), + str(DRIVER_LIB), + str(DRIVER_SRC), + ] + [p for p in sys.path[1:] if p] + + import gc + + if not hasattr(gc, "mem_free"): + gc.mem_free = lambda: 256 * 1024 + gc.mem_alloc = lambda: 64 * 1024 + + import _simlink + + _simlink.connect((host, int(port)), authkey, index, fps=fps) + + import settings as led_settings + + led_settings.Settings.SETTINGS_FILE = str(drv_dir / "settings.json") + + runpy.run_path(str(DRIVER_MAIN), run_name="__main__") + + +if __name__ == "__main__": + try: + main() + except SystemExit: + raise + except BaseException: + import traceback + + traceback.print_exc() + sys.stdout.flush() + raise SystemExit(1) diff --git a/stubs/_simlink.py b/stubs/_simlink.py new file mode 100644 index 0000000..94fbff9 --- /dev/null +++ b/stubs/_simlink.py @@ -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 diff --git a/stubs/_simlink_proc.py b/stubs/_simlink_proc.py new file mode 100644 index 0000000..d560475 --- /dev/null +++ b/stubs/_simlink_proc.py @@ -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() diff --git a/stubs/_simlink_web.py b/stubs/_simlink_web.py new file mode 100644 index 0000000..77a528c --- /dev/null +++ b/stubs/_simlink_web.py @@ -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) diff --git a/stubs/espnow.py b/stubs/espnow.py new file mode 100644 index 0000000..668d773 --- /dev/null +++ b/stubs/espnow.py @@ -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) diff --git a/stubs/machine.py b/stubs/machine.py index d4d00bc..dd3cd75 100644 --- a/stubs/machine.py +++ b/stubs/machine.py @@ -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) diff --git a/stubs/neopixel.py b/stubs/neopixel.py index 36f2213..71e0b64 100644 --- a/stubs/neopixel.py +++ b/stubs/neopixel.py @@ -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) diff --git a/stubs/network.py b/stubs/network.py index add5267..fb6392a 100644 --- a/stubs/network.py +++ b/stubs/network.py @@ -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 diff --git a/stubs/urandom.py b/stubs/urandom.py new file mode 100644 index 0000000..15c0c8a --- /dev/null +++ b/stubs/urandom.py @@ -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 diff --git a/stubs/utime.py b/stubs/utime.py index 1ed55e5..6fb392a 100644 --- a/stubs/utime.py +++ b/stubs/utime.py @@ -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() diff --git a/web/app.js b/web/app.js new file mode 100644 index 0000000..48ef4f2 --- /dev/null +++ b/web/app.js @@ -0,0 +1,816 @@ +/* led-simulator page: the rig of simulated led-drivers behind the bridge. + * + * Each strip is a web worker running led-driver/src/main.py in Pyodide + * (driver-worker.js). The page is the radio between them and the bridge + * (server.py, WebSocket /sim): + * server -> page binary dest_mac(6) + ESP-NOW packet (bridge transmit) + * page -> server binary src_mac(6) + ESP-NOW packet (driver transmit) + * server -> page text {"t":"status","controllers":n} | {"t":"takeover"} + * page -> server text {"t":"flash","n":i,"path":..,"data":..} + * Received packets reach a driver through its SharedArrayBuffer ring. + */ +/* global SimRing, RigLayout */ +(function () { + 'use strict'; + + const OFF_COLOUR = '#1d1f24'; + const LABEL = '#8a909c'; + const LABEL_LIT = '#d6dae2'; + const CENTRE = '#2c3038'; + const SELECT = '#5aa9ff'; + const STATE_COLOUR = { + off: '#4b505b', + queued: '#f2b84b', + loading: '#f2b84b', + running: '#3ecf8e', + crashed: '#ff6b6b', + }; + const LOG_LINES = 600; + const BROADCAST = 'ff:ff:ff:ff:ff:ff'; + const AUTO_KEY = 'ledsim.autoPower'; + + const $ = (id) => document.getElementById(id); + const params = new URLSearchParams(location.search); + // Test hook: a stand-in worker script under /web/. + const workerUrl = /^\/web\/[\w.-]+\.js$/.test(params.get('worker') || '') + ? params.get('worker') + : '/web/driver-worker.js'; + + const app = { + cfg: null, + bundle: null, + bundleAt: 0, + bootPy: '', + bridgeMac: null, + strips: [], + byMac: new Map(), + ws: null, + wsOpen: false, + takenOver: false, + controllers: 0, + queue: [], + booting: 0, + geo: null, + fullRedraw: true, + selected: null, + canvas: null, + ctx: null, + dpr: 1, + }; + + // ----- helpers ----------------------------------------------------------- + + function macBytes(s) { + return new Uint8Array(s.split(':').map((h) => parseInt(h, 16))); + } + + function macOf(u8, off = 0) { + const parts = []; + for (let i = off; i < off + 6; i += 1) { + parts.push(u8[i].toString(16).padStart(2, '0')); + } + return parts.join(':'); + } + + function banner(text, kind) { + const el = $('banner'); + if (!text) { + el.hidden = true; + return; + } + el.textContent = text; + el.className = `banner${kind ? ` ${kind}` : ''}`; + el.hidden = false; + } + + function readAuto() { + try { + const v = localStorage.getItem(AUTO_KEY); + return v === null ? true : v === '1'; + } catch (_e) { + return true; + } + } + + function writeAuto(on) { + try { + localStorage.setItem(AUTO_KEY, on ? '1' : '0'); + } catch (_e) { + // storage unavailable: setting lasts for this page only + } + } + + // ----- strips: power and workers ------------------------------------------ + + function validPlace(p) { + return Array.isArray(p) && p.length === 4 && p.every((v) => typeof v === 'number') ? p : null; + } + + /** A driver's settings.json changed (or was read): pick up its place in the rig. */ + function notePlace(s, settingsText) { + let place = null; + try { + place = validPlace(JSON.parse(settingsText).place); + } catch (_e) { + return; + } + if (JSON.stringify(place) !== JSON.stringify(s.place)) { + s.place = place; + resize(); + } + } + + function makeStrip(info) { + return { + info, + index: info.index, + mac: info.mac, + macBytes: macBytes(info.mac), + name: info.default_name, + state: 'off', + worker: null, + ring: null, + frame: new Uint8Array(info.leds * 3), + place: validPlace(info.place), + lit: false, + dirty: true, + logs: [], + rx: 0, + tx: 0, + error: '', + }; + } + + function setState(s, state, error = '') { + s.state = state; + s.error = error; + s.dirty = true; + updateChips(); + if (app.selected === s) { + renderDrawer(); + } + } + + function addLog(s, text) { + const lines = String(text).split('\n'); + for (const line of lines) { + s.logs.push(line); + } + if (s.logs.length > LOG_LINES) { + s.logs.splice(0, s.logs.length - LOG_LINES); + } + if (app.selected === s) { + const el = $('d-log'); + const atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 8; + el.textContent = s.logs.join('\n'); + if (atBottom) { + el.scrollTop = el.scrollHeight; + } + } + } + + function powerOn(s) { + if (!self.crossOriginIsolated || app.takenOver) { + return; + } + if (s.state !== 'off' && s.state !== 'crashed') { + return; + } + setState(s, 'queued'); + app.queue.push(s); + pumpQueue(); + } + + function powerOff(s) { + const i = app.queue.indexOf(s); + if (i >= 0) { + app.queue.splice(i, 1); + } + if (s.worker) { + s.worker.terminate(); + s.worker = null; + if (s.state === 'loading') { + app.booting = Math.max(0, app.booting - 1); + } + } + s.ring = null; + s.frame = new Uint8Array(s.info.leds * 3); + setState(s, 'off'); + pumpQueue(); + } + + function reset(s) { + powerOff(s); + addLog(s, '--- reset ---'); + powerOn(s); + } + + async function ensureBundle() { + // Re-read led-driver/src (main.py, patterns/) for each batch of boots. + if (app.bundle && Date.now() - app.bundleAt < 3000) { + return; + } + const [bundle, bootPy] = await Promise.all([ + fetch('/api/bundle').then((r) => r.json()), + fetch('/web/driver_boot.py').then((r) => r.text()), + ]); + app.bundle = bundle; + app.bootPy = bootPy; + app.bundleAt = Date.now(); + } + + async function pumpQueue() { + const limit = Math.max(1, Number(app.cfg.drivers.boot_concurrency) || 4); + while (app.queue.length && app.booting < limit) { + const s = app.queue.shift(); + app.booting += 1; + try { + await ensureBundle(); + if (s.state !== 'queued') { + app.booting -= 1; + continue; + } + await startWorker(s); + } catch (err) { + app.booting = Math.max(0, app.booting - 1); + addLog(s, `boot failed: ${err}`); + setState(s, 'crashed', String(err)); + } + } + } + + async function startWorker(s) { + const flash = await fetch(`/api/flash/${s.index}`).then((r) => r.json()); + notePlace(s, flash['settings.json']); + try { + s.name = JSON.parse(flash['settings.json']).name || s.name; + } catch (_e) { + // keep the default name + } + if (s.state !== 'queued') { + app.booting -= 1; + return; + } + s.ring = SimRing.create(64 * 1024); + const worker = new Worker(workerUrl); + s.worker = worker; + setState(s, 'loading'); + worker.onmessage = (ev) => onWorkerMessage(s, worker, ev.data || {}); + worker.onerror = (ev) => { + if (s.worker !== worker) { + return; + } + ev.preventDefault(); + addLog(s, `worker error: ${ev.message || ev}`); + driverStopped(s, worker, String(ev.message || 'worker error'), false); + }; + worker.postMessage({ + t: 'boot', + index: s.index, + ringSab: s.ring.sab, + sleepSab: new SharedArrayBuffer(4), + pyodideUrl: app.cfg.pyodide_url, + files: app.bundle, + flash: { 'settings.json': flash['settings.json'], 'presets.json': flash['presets.json'] }, + bootPy: app.bootPy, + env: { + LED_SIM_MAC: s.mac.replace(/:/g, ''), + LED_SIM_FPS: String(app.cfg.drivers.fps ?? 30), + LED_SIM_LOOP_SLEEP_MS: String(app.cfg.drivers.loop_sleep_ms ?? 2), + LED_SIM_FLASH: '/flash', + LED_SIM_STUBS: '/stubs', + }, + }); + } + + function driverStopped(s, worker, error, isReset) { + if (s.worker !== worker) { + return; + } + if (s.state === 'loading') { + app.booting = Math.max(0, app.booting - 1); + } + worker.terminate(); + s.worker = null; + s.ring = null; + if (isReset) { + s.frame = new Uint8Array(s.info.leds * 3); + setState(s, 'off'); + addLog(s, '--- machine.reset() ---'); + powerOn(s); + return; + } + setState(s, 'crashed', error); + pumpQueue(); + } + + function onWorkerMessage(s, worker, m) { + if (s.worker !== worker) { + return; + } + switch (m.t) { + case 'state': + if (m.state === 'running' && s.state === 'loading') { + app.booting = Math.max(0, app.booting - 1); + setState(s, 'running'); + pumpQueue(); + } + break; + case 'log': + addLog(s, m.text); + break; + case 'tx': { + // dest(6) + packet. The bridge forwards everything it hears upstream. + const data = m.data; + if (data.length <= 6) { + break; + } + s.tx += 1; + const up = new Uint8Array(data.length); + up.set(s.macBytes, 0); + up.set(data.subarray(6), 6); + if (app.wsOpen) { + app.ws.send(up); + } + if (app.selected === s) { + renderFacts(); + } + break; + } + case 'px': + s.frame = m.data; + s.dirty = true; + break; + case 'flash': + if (app.wsOpen) { + app.ws.send(JSON.stringify({ t: 'flash', n: s.index, path: m.path, data: m.data })); + } + if (m.path === 'settings.json') { + notePlace(s, m.data); + try { + const name = JSON.parse(m.data).name; + if (name && name !== s.name) { + s.name = name; + s.dirty = true; + app.fullRedraw = true; + } + } catch (_e) { + // ignore + } + } + break; + case 'exit': + driverStopped(s, worker, m.error || 'stopped', Boolean(m.reset)); + break; + default: + break; + } + } + + // ----- bridge link --------------------------------------------------------- + + function deliver(s, payload) { + if (s.state !== 'running' || !s.ring) { + return; // powered off or still booting: the packet is lost, as on air + } + if (s.ring.push(payload)) { + s.rx += 1; + if (app.selected === s) { + renderFacts(); + } + } + } + + function onDownlink(u8) { + if (u8.length < 7) { + return; + } + const dest = macOf(u8, 0); + // The driver sees the bridge as the sender. + const payload = new Uint8Array(u8.length); + payload.set(app.bridgeMac, 0); + payload.set(u8.subarray(6), 6); + if (dest === BROADCAST) { + for (const s of app.strips) { + deliver(s, payload); + } + return; + } + const s = app.byMac.get(dest); + if (s) { + deliver(s, payload); + } + } + + function connectBridge() { + if (app.takenOver) { + return; + } + const proto = location.protocol === 'https:' ? 'wss' : 'ws'; + const ws = new WebSocket(`${proto}://${location.host}/sim`); + ws.binaryType = 'arraybuffer'; + app.ws = ws; + ws.onopen = () => { + app.wsOpen = true; + if (!app.takenOver && self.crossOriginIsolated) { + banner(''); + } + updateChips(); + }; + ws.onmessage = (ev) => { + if (typeof ev.data === 'string') { + let m = null; + try { + m = JSON.parse(ev.data); + } catch (_e) { + return; + } + if (m.t === 'status') { + app.controllers = Number(m.controllers) || 0; + updateChips(); + } else if (m.t === 'takeover') { + app.takenOver = true; + for (const s of app.strips) { + powerOff(s); + } + banner('The rig is running in another tab. This page has powered its strips off; reload to take it back.', 'info'); + setButtons(); + } + return; + } + onDownlink(new Uint8Array(ev.data)); + }; + ws.onclose = () => { + app.wsOpen = false; + updateChips(); + if (app.takenOver) { + return; + } + banner('Lost the simulator server. Reconnecting…'); + setTimeout(connectBridge, 2000); + }; + } + + // ----- UI: chips, drawer --------------------------------------------------- + + function updateChips() { + if (!app.cfg) { + return; + } + const b = app.cfg.bridge; + $('bridge-chip').textContent = `${b.name} · ${b.mac}`; + const cc = $('controller-chip'); + cc.textContent = app.wsOpen + ? `controller: ${app.controllers ? `${app.controllers} connected` : 'not connected'}` + : 'controller: –'; + cc.className = `chip ${app.controllers ? 'ok' : 'warn'}`; + const running = app.strips.filter((s) => s.state === 'running').length; + const booting = app.strips.filter((s) => s.state === 'queued' || s.state === 'loading').length; + const crashed = app.strips.filter((s) => s.state === 'crashed').length; + let text = `strips: ${running}/${app.strips.length} running`; + if (booting) { + text += ` · ${booting} booting`; + } + if (crashed) { + text += ` · ${crashed} stopped`; + } + const sc = $('strips-chip'); + sc.textContent = text; + sc.className = `chip ${crashed ? 'warn' : running ? 'ok' : ''}`; + } + + function renderFacts() { + const s = app.selected; + if (!s) { + return; + } + const st = $('d-state'); + st.textContent = s.state + (s.error && s.state === 'crashed' ? ` – ${s.error.split('\n').slice(-2).join(' ')}` : ''); + st.className = `state-${s.state}`; + const lay = app.cfg.layout; + const side = lay.columns === 2 ? (s.info.col === 0 ? 'left' : 'right') : `column ${s.info.col + 1}`; + $('d-pos').textContent = `row ${s.info.row + 1}, ${side} · ${s.info.leds} LEDs · pixel 0 ${s.info.reversed ? 'at right end' : 'at left end'}`; + $('d-packets').textContent = `${s.rx} received · ${s.tx} sent`; + } + + function renderDrawer() { + const s = app.selected; + $('drawer').hidden = !s; + if (!s) { + return; + } + $('d-name').textContent = s.name; + $('d-meta').textContent = `strip ${s.info.n} · ${s.mac}`; + renderFacts(); + const off = s.state === 'off' || s.state === 'crashed'; + $('d-on').disabled = !off || !self.crossOriginIsolated || app.takenOver; + $('d-off').disabled = off; + $('d-reset').disabled = !self.crossOriginIsolated || app.takenOver; + const el = $('d-log'); + el.textContent = s.logs.join('\n'); + el.scrollTop = el.scrollHeight; + } + + function select(s) { + app.selected = app.selected === s ? null : s; + app.fullRedraw = true; + renderDrawer(); + requestAnimationFrame(resize); + } + + function setButtons() { + const ok = self.crossOriginIsolated && !app.takenOver; + for (const id of ['power-on-all', 'power-cycle-all', 'power-off-all']) { + $(id).disabled = !ok; + } + renderDrawer(); + } + + // ----- canvas ---------------------------------------------------------------- + + function resize() { + const c = app.canvas; + const rect = c.getBoundingClientRect(); + app.dpr = window.devicePixelRatio || 1; + c.width = Math.max(1, Math.round(rect.width * app.dpr)); + c.height = Math.max(1, Math.round(rect.height * app.dpr)); + // Drawn where the controller placed each bar once every bar has a place, else as the layout grid + app.geo = app.strips.length && app.strips.every((s) => s.place) + ? RigLayout.computePlaced( + app.strips.map((s) => ({ place: s.place, leds: s.info.leds })), + rect.width, + rect.height, + ) + : RigLayout.computeGeometry( + app.cfg.layout, + app.strips.map((s) => s.info), + rect.width, + rect.height, + ); + app.fullRedraw = true; + } + + function colourAt(frame, i) { + const j = i * 3; + const r = frame[j] | 0; + const g = frame[j + 1] | 0; + const b = frame[j + 2] | 0; + if (r === 0 && g === 0 && b === 0) { + return null; + } + return `rgb(${r},${g},${b})`; + } + + function drawLabel(s, sg) { + const ctx = app.ctx; + const pad = 4; + // clear the label band for this strip + ctx.fillStyle = '#0e0f12'; + ctx.fillRect(sg.x0 - 1, sg.top, sg.w + 2, sg.y - sg.top - 1); + ctx.font = '11px system-ui, -apple-system, Segoe UI, Roboto, sans-serif'; + ctx.textBaseline = 'middle'; + ctx.textAlign = sg.labelAlign; + const arrow = sg.reversed ? '◂' : '▸'; + const text = sg.reversed ? `${s.name} ${s.info.n} ${arrow}` : `${arrow} ${s.info.n} ${s.name}`; + ctx.fillStyle = s.lit ? LABEL_LIT : LABEL; + const dot = 7; + let tx = sg.labelX; + if (sg.reversed) { + tx -= dot + pad; + } else { + tx += dot + pad; + } + ctx.fillText(text, tx, sg.labelY); + // power state dot at the strip's start end + ctx.fillStyle = STATE_COLOUR[s.state] || STATE_COLOUR.off; + ctx.beginPath(); + const dx = sg.reversed ? sg.labelX - dot / 2 : sg.labelX + dot / 2; + ctx.arc(dx, sg.labelY, dot / 2, 0, Math.PI * 2); + ctx.fill(); + } + + function drawPlaced(s) { + const ctx = app.ctx; + const geo = app.geo; + const sg = geo.strips[s.index]; + const leds = s.info.leds; + const gap = sg.pitch >= 3 ? 1 : 0; + let lit = false; + ctx.save(); + ctx.translate(sg.ax, sg.ay); + ctx.rotate(sg.ang); + for (let i = 0; i < leds; i += 1) { + const col = colourAt(s.frame, i); + if (col) { + lit = true; + } + ctx.fillStyle = col || OFF_COLOUR; + ctx.fillRect(i * sg.pitch, -geo.ledH / 2, Math.max(1, sg.pitch - gap), geo.ledH); + } + if (app.selected === s) { + ctx.strokeStyle = SELECT; + ctx.lineWidth = 1.5; + ctx.strokeRect(-1.5, -geo.ledH / 2 - 1.5, sg.len + 3, geo.ledH + 3); + } + // power state dot just before pixel 0 (the data-in head) + ctx.fillStyle = STATE_COLOUR[s.state] || STATE_COLOUR.off; + ctx.beginPath(); + ctx.arc(-7, 0, 3.5, 0, Math.PI * 2); + ctx.fill(); + ctx.restore(); + ctx.font = '11px system-ui, -apple-system, Segoe UI, Roboto, sans-serif'; + ctx.textBaseline = 'middle'; + ctx.textAlign = 'center'; + ctx.fillStyle = lit ? LABEL_LIT : LABEL; + ctx.fillText(`${s.info.n} ${s.name}`, sg.labelX, sg.labelY); + s.lit = lit; + } + + function drawStrip(s) { + const ctx = app.ctx; + const geo = app.geo; + const sg = geo.strips[s.index]; + const leds = s.info.leds; + ctx.fillStyle = '#0e0f12'; + ctx.fillRect(sg.x0 - 2, sg.y - 2, sg.w + 4, sg.h + 4); + let lit = false; + for (let i = 0; i < leds; i += 1) { + const col = colourAt(s.frame, i); + if (col) { + lit = true; + } + ctx.fillStyle = col || OFF_COLOUR; + ctx.fillRect(RigLayout.pixelX(geo, sg, i, leds), sg.y, geo.ledW, sg.h); + } + if (app.selected === s) { + ctx.strokeStyle = SELECT; + ctx.lineWidth = 1.5; + ctx.strokeRect(sg.x0 - 1.5, sg.y - 1.5, sg.w + 3, sg.h + 3); + } + s.lit = lit; + drawLabel(s, sg); + } + + function frame() { + if (app.geo) { + const ctx = app.ctx; + ctx.setTransform(app.dpr, 0, 0, app.dpr, 0, 0); + if (app.geo.placed) { + // rotated bars overlap their neighbours' clear boxes: redraw everything when anything changed + if (app.fullRedraw || app.strips.some((s) => s.dirty)) { + const c = app.canvas; + ctx.fillStyle = '#0e0f12'; + ctx.fillRect(0, 0, c.width / app.dpr, c.height / app.dpr); + ctx.fillStyle = CENTRE; + ctx.beginPath(); + ctx.arc(app.geo.centre.x, app.geo.centre.y, 3, 0, Math.PI * 2); + ctx.fill(); + for (const s of app.strips) { + s.dirty = false; + drawPlaced(s); + } + app.fullRedraw = false; + } + requestAnimationFrame(frame); + return; + } + if (app.fullRedraw) { + const c = app.canvas; + ctx.fillStyle = '#0e0f12'; + ctx.fillRect(0, 0, c.width / app.dpr, c.height / app.dpr); + ctx.strokeStyle = CENTRE; + ctx.setLineDash([4, 4]); + ctx.lineWidth = 1; + for (const x of app.geo.centreLines) { + ctx.beginPath(); + ctx.moveTo(x + 0.5, 6); + ctx.lineTo(x + 0.5, c.height / app.dpr - 6); + ctx.stroke(); + } + ctx.setLineDash([]); + for (const s of app.strips) { + s.dirty = true; + } + app.fullRedraw = false; + } + for (const s of app.strips) { + if (s.dirty) { + s.dirty = false; + drawStrip(s); + } + } + } + requestAnimationFrame(frame); + } + + function stripAt(x, y) { + const geo = app.geo; + if (!geo) { + return null; + } + if (geo.placed) { + let best = null; + let bestD = 12; + for (const s of app.strips) { + const sg = geo.strips[s.index]; + const dx = sg.bx - sg.ax; + const dy = sg.by - sg.ay; + const t = Math.max(0, Math.min(1, ((x - sg.ax) * dx + (y - sg.ay) * dy) / (dx * dx + dy * dy || 1))); + const d = Math.hypot(x - (sg.ax + t * dx), y - (sg.ay + t * dy)); + if (d < bestD) { + bestD = d; + best = s; + } + } + return best; + } + for (const s of app.strips) { + const sg = geo.strips[s.index]; + if (x >= sg.x0 - 4 && x <= sg.x0 + sg.w + 4 && y >= sg.top && y <= sg.top + sg.rowH) { + return s; + } + } + return null; + } + + // ----- boot -------------------------------------------------------------------- + + function wireUi() { + $('power-on-all').onclick = () => app.strips.forEach(powerOn); + $('power-off-all').onclick = () => app.strips.forEach(powerOff); + $('power-cycle-all').onclick = () => { + app.strips.forEach(powerOff); + app.strips.forEach(powerOn); + }; + const auto = $('auto-power'); + auto.checked = readAuto(); + auto.onchange = () => writeAuto(auto.checked); + $('d-close').onclick = () => select(app.selected); + $('d-on').onclick = () => app.selected && powerOn(app.selected); + $('d-off').onclick = () => app.selected && powerOff(app.selected); + $('d-reset').onclick = () => app.selected && reset(app.selected); + $('d-clear').onclick = () => { + if (app.selected) { + app.selected.logs = []; + $('d-log').textContent = ''; + } + }; + app.canvas.addEventListener('click', (ev) => { + const r = app.canvas.getBoundingClientRect(); + const s = stripAt(ev.clientX - r.left, ev.clientY - r.top); + if (s) { + select(s); + } + }); + new ResizeObserver(() => resize()).observe($('rig')); + window.addEventListener('keydown', (ev) => { + if (ev.key === 'Escape' && app.selected) { + select(app.selected); + } + }); + } + + async function main() { + app.canvas = $('rig-canvas'); + app.ctx = app.canvas.getContext('2d'); + try { + app.cfg = await fetch('/api/config').then((r) => r.json()); + } catch (err) { + banner(`Could not load /api/config: ${err}`); + return; + } + app.bridgeMac = macBytes(app.cfg.bridge.mac); + app.strips = app.cfg.strips.map(makeStrip); + for (const s of app.strips) { + app.byMac.set(s.mac, s); + } + const b = app.cfg.bridge; + const lay = app.cfg.layout; + document.title = `${b.name} · LED Rig Simulator`; + $('hint').innerHTML = + `${app.strips.length} strips × ${lay.leds_per_strip} LEDs, ${lay.columns} × ${lay.rows}. ` + + (b.udp_port + ? `In led-controller set "bridge": "${b.lan_ip}:${b.udp_port}" (or 127.0.0.1:${b.udp_port}) ` + + 'in settings and restart it, or run its host build (make sim). ' + : `In led-controller add a bridge: transport ip, address ${b.lan_ip} ` + + `(or 127.0.0.1), port ${b.port}. `) + + 'Strips register with their hello when they power on; power-cycle a strip to register it again.'; + wireUi(); + resize(); + requestAnimationFrame(frame); + updateChips(); + if (!self.crossOriginIsolated) { + banner( + `This page is not cross-origin isolated, so drivers cannot run (they need SharedArrayBuffer). ` + + `Open it as http://localhost:${b.port}/ on the computer running server.py, or over HTTPS.`, + ); + } + setButtons(); + connectBridge(); + if (self.crossOriginIsolated && readAuto()) { + app.strips.forEach(powerOn); + } + } + + main(); +})(); diff --git a/web/driver-worker.js b/web/driver-worker.js new file mode 100644 index 0000000..cad744a --- /dev/null +++ b/web/driver-worker.js @@ -0,0 +1,84 @@ +/* One simulated led-driver: Pyodide running led-driver/src/main.py. + * + * The page posts {t: 'boot', ...} once. The worker loads Pyodide, writes the + * strip's flash (driver source, patterns, settings.json, presets.json) and the + * stubs into the Pyodide filesystem, then runs web/driver_boot.py, which never + * returns while the driver is powered. Power-off is Worker.terminate(). + * + * Messages to the page: + * {t:'state', state} loading | running + * {t:'log', text} driver serial output (one line) + * {t:'tx', data} Uint8Array dest_mac(6) + ESP-NOW packet + * {t:'px', data} Uint8Array RGB frame + * {t:'flash', path, data} settings.json / presets.json changed + * {t:'exit', error, reset} main.py stopped (reset: machine.reset()) + */ +/* global importScripts, loadPyodide, SimRing */ +importScripts('/web/ring.js'); + +let ring = null; +let sleepView = null; + +self.simRecv = () => (ring ? ring.pop() : undefined); +self.simPending = () => (ring ? ring.count() : 0); +self.simTx = (u8) => self.postMessage({ t: 'tx', data: u8 }, [u8.buffer]); +self.simPixels = (u8) => self.postMessage({ t: 'px', data: u8 }, [u8.buffer]); +self.simFlash = (path, text) => + self.postMessage({ t: 'flash', path: String(path), data: String(text) }); +self.simSleep = (ms) => { + if (ms > 0 && sleepView) { + // Nobody notifies this slot: it is a plain blocking sleep. + Atomics.wait(sleepView, 0, 0, ms); + } +}; + +function log(text) { + self.postMessage({ t: 'log', text: String(text) }); +} + +function writeTree(FS, root, files) { + for (const [rel, body] of Object.entries(files)) { + const path = `${root}/${String(rel).replace(/^\/+/, '')}`; + const dir = path.slice(0, path.lastIndexOf('/')); + if (dir) { + FS.mkdirTree(dir); + } + FS.writeFile(path, String(body)); + } +} + +self.onmessage = async (event) => { + const m = event.data || {}; + if (m.t !== 'boot') { + return; + } + ring = new SimRing(m.ringSab); + sleepView = new Int32Array(m.sleepSab); + self.postMessage({ t: 'state', state: 'loading' }); + try { + importScripts(`${m.pyodideUrl}pyodide.js`); + const py = await loadPyodide({ + indexURL: m.pyodideUrl, + stdout: log, + stderr: log, + }); + const FS = py.FS; + writeTree(FS, '/flash', m.files.driver); + writeTree(FS, '/flash', m.flash); + writeTree(FS, '/stubs', m.files.stubs); + FS.writeFile('/boot.py', m.bootPy); + py.globals.set('__sim_env', py.toPy(m.env)); + py.runPython('import os\nos.environ.update({str(k): str(v) for k, v in __sim_env.items()})\ndel __sim_env'); + self.postMessage({ t: 'state', state: 'running' }); + // Blocks until main.py exits (it normally never does). + py.runPython('import runpy\nrunpy.run_path("/boot.py", run_name="__boot__")'); + self.postMessage({ t: 'exit', error: 'main.py returned', reset: false }); + } catch (err) { + const msg = String((err && err.message) || err); + const reset = /SystemExit:\s*75\b/.test(msg); + if (!reset) { + log(msg); + } + self.postMessage({ t: 'exit', error: reset ? 'machine.reset()' : msg, reset }); + } +}; diff --git a/web/driver_boot.py b/web/driver_boot.py new file mode 100644 index 0000000..728771f --- /dev/null +++ b/web/driver_boot.py @@ -0,0 +1,49 @@ +"""Boot one simulated led-driver inside Pyodide (run by web/driver-worker.js). + +The worker has already written the strip's flash into ``LED_SIM_FLASH`` +(``led-driver/src`` including ``patterns/``, plus this strip's +``settings.json`` and ``presets.json``) and the stubs into ``LED_SIM_STUBS``. +This then runs the real ``main.py`` as ``__main__``, as the board does at +power-on: settings, presets, startup preset, ESP-NOW hello, main loop. +""" + +import gc +import os +import runpy +import sys +import time + + +def boot(): + flash = os.environ.get("LED_SIM_FLASH", "/flash") + stubs = os.environ.get("LED_SIM_STUBS", "/stubs") + + # Stubs replace the hardware modules; the flash root plays the device's + # "/" (cwd), where main.py, settings.json, presets.json and patterns/ live. + for p in (flash, stubs): + while p in sys.path: + sys.path.remove(p) + sys.path[:0] = [stubs, flash] + os.chdir(flash) + + import _simlink + + # No threads and no event loop turns while main.py runs: sleeps block on + # Atomics.wait, and the ping-reply "thread" runs from the main loop. + time.sleep = _simlink.real_sleep + import _thread + + _thread.start_new_thread = _simlink.start_new_thread + + if not hasattr(gc, "mem_free"): + gc.mem_free = lambda: 256 * 1024 + gc.mem_alloc = lambda: 64 * 1024 + + import settings as led_settings + + led_settings.Settings.SETTINGS_FILE = flash.rstrip("/") + "/settings.json" + + runpy.run_path(flash.rstrip("/") + "/main.py", run_name="__main__") + + +boot() diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..e7f0d34 --- /dev/null +++ b/web/index.html @@ -0,0 +1,71 @@ + + + + + + + LED Rig Simulator + + + + +
+
+ + led-simulator +
+
+ bridge + controller: – + strips: – +
+
+ + + + +
+
+ + + +
+
+ +
+ + +
+ +
Loading…
+ + + + + + diff --git a/web/layout.js b/web/layout.js new file mode 100644 index 0000000..4c8d20e --- /dev/null +++ b/web/layout.js @@ -0,0 +1,103 @@ +/* Rig geometry for the canvas: strips along their rows, pixel 0 at the + * strip's start end (next to the centre line for start: "center"). + * Strip placement (row, col, reversed) comes from the server (layout.py). + */ +(function (g) { + 'use strict'; + + /** + * @param {object} layout {rows, columns, leds_per_strip} + * @param {Array} strips [{row, col, leds, reversed}] + * @returns {object} {ledPitch, ledW, ledH, strips:[{x0, y, w, labelX, labelY, labelAlign}], centreLines} + */ + function computeGeometry(layout, strips, width, height, opts = {}) { + const margin = opts.margin ?? 16; + const colGap = opts.colGap ?? 32; + const labelH = opts.labelH ?? 16; + const rows = layout.rows; + const cols = layout.columns; + const n = layout.leds_per_strip; + const usableW = Math.max(cols * n, width - 2 * margin - (cols - 1) * colGap); + const colW = usableW / cols; + const pitch = colW / n; + const rowH = Math.max(labelH + 6, (height - 2 * margin) / rows); + const ledH = Math.max(6, Math.min(rowH - labelH - 10, 18)); + const gap = pitch >= 3 ? 1 : 0; + const ledW = Math.max(1, pitch - gap); + + const out = strips.map((s) => { + const x0 = margin + s.col * (colW + colGap); + const yTop = margin + s.row * rowH; + // strip sits just under its label; leftover row space goes below it + const y = yTop + labelH + 4; + return { + x0, + y, + w: colW, + h: ledH, + top: yTop, + rowH, + reversed: Boolean(s.reversed), + labelX: s.reversed ? x0 + colW : x0, + labelY: yTop + labelH / 2 + 2, + labelAlign: s.reversed ? 'right' : 'left', + }; + }); + const centreLines = []; + for (let c = 1; c < cols; c += 1) { + centreLines.push(margin + c * (colW + colGap) - colGap / 2); + } + return { ledPitch: pitch, ledW, ledH, strips: out, centreLines }; + } + + /** + * Geometry from each strip's rig place [x0, y0, x1, y1] (y up, centre 0, as the controller sends it), + * fitted to the canvas with one scale. Used once every strip has a place. + * @returns {object} {placed: true, ledH, strips: [{ax, ay, bx, by, ang, len, pitch, labelX, labelY}], centre} + */ + function computePlaced(strips, width, height, opts = {}) { + const margin = opts.margin ?? 28; + const ledH = opts.ledH ?? 12; + let lo = [Infinity, Infinity]; + let hi = [-Infinity, -Infinity]; + for (const s of strips) { + const p = s.place; + for (let k = 0; k < 4; k += 2) { + lo = [Math.min(lo[0], p[k]), Math.min(lo[1], p[k + 1])]; + hi = [Math.max(hi[0], p[k]), Math.max(hi[1], p[k + 1])]; + } + } + const spanX = Math.max(hi[0] - lo[0], 1e-3); + const spanY = Math.max(hi[1] - lo[1], 1e-3); + const scale = Math.min((width - 2 * margin) / spanX, (height - 2 * margin) / spanY); + const ox = width / 2 - ((lo[0] + hi[0]) / 2) * scale; + const oy = height / 2 + ((lo[1] + hi[1]) / 2) * scale; + const tx = (x) => ox + x * scale; + const ty = (y) => oy - y * scale; + const out = strips.map((s) => { + const [x0, y0, x1, y1] = s.place; + const ax = tx(x0); + const ay = ty(y0); + const bx = tx(x1); + const by = ty(y1); + const len = Math.hypot(bx - ax, by - ay); + const n = s.leds; + return { + ax, ay, bx, by, len, + ang: Math.atan2(by - ay, bx - ax), + pitch: len / n, + labelX: (ax + bx) / 2, + labelY: (ay + by) / 2 - ledH / 2 - 9, + }; + }); + return { placed: true, ledH, strips: out, centre: { x: tx(0), y: ty(0) } }; + } + + /** x of pixel i of a strip (pixel 0 at the start end). */ + function pixelX(geo, sg, i, leds) { + const pos = sg.reversed ? leds - 1 - i : i; + return sg.x0 + pos * geo.ledPitch; + } + + g.RigLayout = { computeGeometry, computePlaced, pixelX }; +})(typeof self !== 'undefined' ? self : globalThis); diff --git a/web/ring.js b/web/ring.js new file mode 100644 index 0000000..ae32866 --- /dev/null +++ b/web/ring.js @@ -0,0 +1,93 @@ +/* SharedArrayBuffer message ring: the page pushes received ESP-NOW frames, + * the driver worker pops them while main.py runs (it never yields to the JS + * event loop, so postMessage cannot reach it). + * + * Layout: Int32[4] header {head, tail, dropped, count} then `capacity` bytes. + * Each message is a little-endian u16 length followed by the bytes. + * One producer (page) and one consumer (worker). + * + * Loaded as a classic script by both the page and the worker. + */ +(function (g) { + 'use strict'; + const HEADER = 16; + const HEAD = 0; + const TAIL = 1; + const DROPPED = 2; + const COUNT = 3; + + class SimRing { + constructor(sab) { + this.sab = sab; + this.idx = new Int32Array(sab, 0, 4); + this.cap = sab.byteLength - HEADER; + this.data = new Uint8Array(sab, HEADER, this.cap); + } + + static create(capacity = 65536) { + return new SimRing(new SharedArrayBuffer(HEADER + capacity)); + } + + used() { + const h = Atomics.load(this.idx, HEAD); + const t = Atomics.load(this.idx, TAIL); + return (h - t + this.cap) % this.cap; + } + + count() { + return Atomics.load(this.idx, COUNT); + } + + dropped() { + return Atomics.load(this.idx, DROPPED); + } + + /** Producer: false (and counted as dropped) when the ring is full. */ + push(bytes) { + const n = bytes.length; + if (n > 0xffff || n + 2 >= this.cap - this.used()) { + Atomics.add(this.idx, DROPPED, 1); + return false; + } + const cap = this.cap; + const data = this.data; + let h = Atomics.load(this.idx, HEAD); + data[h] = n & 0xff; + h = (h + 1) % cap; + data[h] = n >> 8; + h = (h + 1) % cap; + for (let i = 0; i < n; i += 1) { + data[h] = bytes[i]; + h = (h + 1) % cap; + } + Atomics.store(this.idx, HEAD, h); + Atomics.add(this.idx, COUNT, 1); + return true; + } + + /** Consumer: next message as a Uint8Array, or undefined when empty. */ + pop() { + let t = Atomics.load(this.idx, TAIL); + if (t === Atomics.load(this.idx, HEAD)) { + return undefined; + } + const cap = this.cap; + const data = this.data; + const lo = data[t]; + t = (t + 1) % cap; + const hi = data[t]; + t = (t + 1) % cap; + const n = lo | (hi << 8); + const out = new Uint8Array(n); + for (let i = 0; i < n; i += 1) { + out[i] = data[t]; + t = (t + 1) % cap; + } + Atomics.store(this.idx, TAIL, t); + Atomics.sub(this.idx, COUNT, 1); + return out; + } + } + + g.SimRing = SimRing; +})(typeof self !== 'undefined' ? self : globalThis); diff --git a/web/styles.css b/web/styles.css new file mode 100644 index 0000000..164a3b0 --- /dev/null +++ b/web/styles.css @@ -0,0 +1,169 @@ +:root { + --bg: #0e0f12; + --panel: #15171c; + --panel-2: #1b1e24; + --line: #2a2e36; + --text: #d6dae2; + --muted: #8a909c; + --accent: #5aa9ff; + --ok: #3ecf8e; + --warn: #f2b84b; + --bad: #ff6b6b; + --off: #4b505b; + color-scheme: dark; +} + +* { box-sizing: border-box; } + +html, body { + margin: 0; + height: 100%; + background: var(--bg); + color: var(--text); + font: 13px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; +} + +body { + display: flex; + flex-direction: column; + min-height: 100vh; +} + +button { + font: inherit; + color: var(--text); + background: #253041; + border: 1px solid #34465f; + border-radius: 6px; + padding: 5px 11px; + cursor: pointer; +} +button:hover:not(:disabled) { background: #2d3b50; } +button:disabled { opacity: .45; cursor: default; } +button.secondary { background: var(--panel-2); border-color: var(--line); } +button.secondary:hover:not(:disabled) { background: #232730; } +button.icon { + background: none; border: none; font-size: 20px; line-height: 1; + padding: 0 4px; color: var(--muted); +} +button.link { + background: none; border: none; padding: 0; color: var(--muted); + text-decoration: underline; +} + +.topbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px 18px; + padding: 10px 16px; + border-bottom: 1px solid var(--line); + background: var(--panel); +} +.brand { display: flex; align-items: center; gap: 8px; font-weight: 600; } +.brand-mark { + width: 14px; height: 14px; border-radius: 3px; + background: linear-gradient(90deg, #ff3b3b, #ffd23b, #3bff8a, #3bb2ff, #b03bff); +} +.chips { display: flex; flex-wrap: wrap; gap: 6px; } +.chip { + border: 1px solid var(--line); + background: var(--panel-2); + border-radius: 999px; + padding: 2px 10px; + color: var(--muted); + white-space: nowrap; +} +.chip.ok { color: var(--ok); border-color: #22533f; } +.chip.warn { color: var(--warn); border-color: #5a4720; } +.actions { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-left: auto; } +.toggle { display: flex; align-items: center; gap: 5px; color: var(--muted); margin-left: 6px; } + +.banner { + padding: 8px 16px; + background: #3a1d22; + color: #ffd6d6; + border-bottom: 1px solid #5c2a31; +} +.banner.info { background: #1d2a3a; color: #d6e8ff; border-color: #2a405c; } + +.stage { + flex: 1; + display: flex; + min-height: 0; +} +.rig { + flex: 1; + position: relative; + min-width: 0; + min-height: 360px; +} +.rig canvas { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + cursor: pointer; +} + +.drawer { + width: 360px; + max-width: 100%; + border-left: 1px solid var(--line); + background: var(--panel); + display: flex; + flex-direction: column; + padding: 12px 14px; + gap: 10px; + min-height: 0; +} +.drawer[hidden] { display: none; } +.drawer-head { display: flex; justify-content: space-between; align-items: flex-start; } +.drawer-title { font-size: 16px; font-weight: 600; } +.drawer-sub { color: var(--muted); font-family: ui-monospace, Menlo, Consolas, monospace; } +.facts { + display: grid; + grid-template-columns: 80px 1fr; + gap: 4px 10px; + margin: 0; +} +.facts dt { color: var(--muted); } +.facts dd { margin: 0; } +.drawer-actions { display: flex; gap: 6px; flex-wrap: wrap; } +.log-head { display: flex; justify-content: space-between; color: var(--muted); } +.log { + flex: 1; + min-height: 120px; + margin: 0; + overflow: auto; + background: #0b0c0f; + border: 1px solid var(--line); + border-radius: 6px; + padding: 8px; + font: 11px/1.45 ui-monospace, Menlo, Consolas, monospace; + color: #b9c0cc; + white-space: pre-wrap; + word-break: break-all; +} + +.state-off { color: var(--off); } +.state-queued, .state-loading { color: var(--warn); } +.state-running { color: var(--ok); } +.state-crashed { color: var(--bad); } + +.hint { + padding: 8px 16px; + border-top: 1px solid var(--line); + color: var(--muted); + background: var(--panel); +} +.hint code { + color: var(--text); + font-family: ui-monospace, Menlo, Consolas, monospace; +} + +@media (max-width: 760px) { + .stage { flex-direction: column; } + .drawer { width: auto; border-left: none; border-top: 1px solid var(--line); max-height: 50vh; } + .actions { margin-left: 0; } +}