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

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

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

No files matched your search

+210 -211
View File
@@ -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("<Configure>", 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__":