Merges led-simulator (sim-bridge, 4d8aeb5) under led-simulator/ with its history,
in place of the submodule.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
265 lines
8.8 KiB
Python
265 lines
8.8 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Graphical simulator for an led-controller rig behind a Wi-Fi bridge (CPython).
|
|
|
|
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 sys
|
|
import tkinter as tk
|
|
from pathlib import Path
|
|
from tkinter import messagebox, ttk
|
|
|
|
SIM_ROOT = Path(__file__).resolve().parent
|
|
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 _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):
|
|
self.cfg = load_config()
|
|
self.sim = BridgeSim(self.cfg)
|
|
lay = self.sim.layout
|
|
|
|
self.root = tk.Tk()
|
|
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._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._update_status()
|
|
self.root.after(FRAME_MS, self._tick)
|
|
self.root.protocol("WM_DELETE_WINDOW", self._on_quit)
|
|
|
|
# ----- UI -----------------------------------------------------------
|
|
|
|
def _build_ui(self):
|
|
style = ttk.Style(self.root)
|
|
try:
|
|
style.theme_use("clam")
|
|
except tk.TclError:
|
|
pass
|
|
|
|
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)."
|
|
)
|
|
|
|
# ----- 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:
|
|
for i, frame in self.sim.take_dirty_frames().items():
|
|
self._frames[i] = frame
|
|
self._paint(i, frame)
|
|
finally:
|
|
self.root.after(FRAME_MS, self._tick)
|
|
|
|
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.sim.running:
|
|
return
|
|
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):
|
|
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):
|
|
try:
|
|
self.sim.stop()
|
|
finally:
|
|
self.root.destroy()
|
|
|
|
def run(self):
|
|
self.root.mainloop()
|
|
|
|
|
|
def main():
|
|
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)
|
|
LedSimulatorApp().run()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|