feat: browser simulator served by the controller, desktop build, browser bridge

- led-simulator: the rig runs the C++ led-driver as WebAssembly (sim-driver/),
  one single-threaded worker per bar, no cross-origin isolation needed. Rooms
  (one JSON per room) with an on-page editor, and a pattern gallery. The
  Python server, Pyodide boot and ring buffer are removed.
- sim-controller sim_rig.c: serves /sim/ from an embedded pack, the page's
  WebSocket and the rooms/flash API. The desktop build embeds it too.
- bridge.c: a "browser" bridge kind that carries ESP-NOW frames to the page;
  devices announced through it are marked sim.
- UI: Simulator in the Menu, split view with resize and pop-out, swipe
  between controller and rig on phones; SIM/REAL badges in Devices.
- Fades: preset pushes and Wi-Fi driver bodies always carry fade and
  beat_time, so "off" no longer inherits an earlier fade.
- Also the sequences-v2 work in progress: desktop port, bridge firmware,
  serial bridge, Wi-Fi drivers, sequence timeline, audio and API changes.
- led-driver: ESP-NOW link, beat sync, control messages, sim hooks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-11-16 19:32:46 +13:00
1 parent 698c1463c0
commit 581b751904
506 files changed
+42336 -3599

No files matched your search

+2
View File
@@ -1,2 +1,4 @@
workspace/
__pycache__/
web/wasm/
rooms/*.json.tmp
+98 -102
View File
@@ -1,134 +1,130 @@
# led-simulator
A web app that simulates a whole LED rig behind a **Wi‑Fi bridge**.
A whole LED rig in the browser, served by **led-controller itself**. The host build of the controller
(`sim-controller`, and the desktop build) serves the rig at **`/sim/`**:
- 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`).
- Every LED bar is its own led-driver: the real **C++ firmware** (`led-driver/main`) built to **WebAssembly**
(`../sim-driver/`), one module worker per bar. The worker runs what the board's pattern task and ESP-NOW link task
run (`patterns_frame`, `espnow_link_poll`) from a timer, so there are no threads, no `SharedArrayBuffer`, and the
page works on any address. Only the hardware is replaced: NVS is kept by the controller, ESP-NOW goes
through the page, and the WS2812 strip is the canvas.
- The controller reaches the bars over **ESP-NOW**, through its **`browser` bridge**. The frames it would hand to a
USB or network bridge board go to the page over a WebSocket (`/sim/ws`), and the page delivers them to each bar by
MAC. Beats, sequences, groups and the reliable link all run as on hardware.
- **Rooms** say where the bars are. One room per JSON file, edited on the page. The bars' places go to the
controller's rig layout.
- **`/sim/gallery`** shows every pattern side by side, from the same C++ engine, with each preset field editable.
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.
One program and one port. There is no Python server and no UDP bridge.
## Default rig
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.
| 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` |
Strip 1 is row 1 left, strip 2 row 1 right, and so on (`layout.order`).
## With the simulated controller (no hardware at all)
## Run
From the repository root:
```bash
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`
make sim-web # builds the drivers (Emscripten in Docker), the controller for the host, and runs it
```
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": "<this computer>:8766"` in its settings and restart it.
Then open **http://localhost:8080/sim/** in Chrome, Edge or Firefox. The controller's own UI
is on http://localhost:8080/. Any address works, a phone on the LAN included (`http://<computer>:8080/sim/`): the
drivers need no cross-origin isolation.
### Headless
The bars register with the controller from their announces when they power on, and the page gives the controller
their places from the room. Only one tab runs the rig: opening it in a second tab powers the first one's bars off.
`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).
`make desktop` embeds the rig too (after `make sim-wasm`). There, add **`browser`** to the bridges, under
Settings > Network > Bridges or with the page's *Add the browser bridge* button. `make sim-web` starts the host build
with `LED_SIM_BRIDGE=browser`. With no bridge configured, `browser` is the default.
## Run
## Rooms
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):
The spatial config follows the stage maps of the qlcplus simulator: one file per room, a size in metres,
strip types in `definitions`, and `fixtures` keyed by id, each placed by position and heading.
```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/"
"name": "studio",
"units": "metres",
"width": 7.0,
"depth": 5.0,
"origin": "X=0 at the room centre, +X right; Y=0 at the front edge, +Y up the screen; headings clockwise from +Y",
"definitions": {
"bar-119": { "leds": 119, "pitch_m": 0.01667 }
},
"fixtures": {
"sim-01": { "label": "sim-01", "def": "bar-119", "mac": "02:51:4d:00:00:01", "x": -0.1, "y": 2.55, "direction": -90 }
}
}
```
- `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.
- A **fixture** is one bar, so one simulated driver. `x`, `y` (metres) is **pixel 0**, the data-in end. The bar
runs from there along **`direction`**: degrees clockwise from +Y, so `90` runs right and `-90` runs left. It is
`leds × pitch_m` long. `leds` on a fixture overrides its type's count (1–512).
- **`mac`** identifies the driver. Each bar's flash is kept per MAC, so a bar in two rooms (a copied room, say) is
the same bar with the same presets. New bars get a MAC no room uses yet.
- The first run makes the `default` room: 16 bars × 119 LEDs in 2 columns × 8 rows, pixel 0 at the centre line,
`sim-01` … `sim-16` = `02:51:4d:00:00:01` … `…:10`. The rig's bridge is `02:51:4d:00:00:00`.
## Simulated flash
Everything is kept in the controller's store folder (`LED_SIM_DB`; `sim-controller/data` for `make sim-web`):
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.
| | |
| --- | --- |
| `sim/rooms/<name>.json` | the rooms |
| `sim/flash/<mac>.json` | each bar's NVS store, `{namespace: {key: [type, value]}}` |
| `sim/sim.json` | the active room |
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.
On every boot a bar's `led.num_leds` is set from its room. The first boot also takes its hostname from the fixture's
label. Delete `sim/flash/` to factory-reset every bar.
On the page, pick the room in the header. **Edit room** changes it, and every change is saved and sent to the
controller's rig layout:
- Click the floor to add a bar. Drag a bar to move it, which snaps to 5 cm; hold Alt to move it freely.
- Drag the circle at its far end to turn it, which snaps to 15°; hold Shift to turn it freely. Delete removes the
selected bar.
- The side panel edits a bar's label, type, LED count, position and heading.
- **Size & strip types…** sets the room's size and adds or changes strip types.
- **New room…** makes an empty room or a copy of the current one. **Delete room** removes the room's file.
A bar whose LED count changes keeps running with the old count until it is power-cycled, as `num_leds` is read at
boot.
### API (on the controller)
| | |
| --- | --- |
| `GET /sim/api/config` | the active room, the room list and the bridge state |
| `GET /sim/api/flash/<mac>` | a bar's NVS store |
| `GET /sim/api/rooms` | `{current, rooms}` |
| `POST /sim/api/rooms` | `{name, width, depth, copy_from?}` makes a room |
| `GET`, `PUT`, `DELETE /sim/api/rooms/<name>` | one room: read it, replace it (validated), delete it (not the active one) |
| `POST /sim/api/room` | `{name}` switches the rig to that room |
| `GET /sim/api/next-mac` | a MAC no room uses |
| `WS /sim/ws` | the page's radio: binary `dst_mac + packet` down, `src_mac + packet` up; text `{"t":"flash"}` up |
## 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)
led-controller (host build) ──"browser" bridge──▶ WS /sim/ws ──▶ page ──postMessage──▶ driver worker × N
rel, beats, sequences ◀── src_mac+pkt ───── ◀── tx, px, flash ── (led_driver.wasm:
/sim/ page + rooms (sim_rig.c) sim_tick: link + patterns)
```
- `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).
| Where | What |
| --- | --- |
| `sim-controller/components/sim/sim_rig.c` | serves the page and the wasm from `www_dist/sim.pack`, the page's WebSocket, rooms and flash |
| `main/bridge.c` | the `browser` bridge kind next to UDP and serial |
| `tools/build_sim_web.sh` | packs `web/` and `web/wasm/` into `www_dist/sim.pack`. It is empty when the drivers are not built, so `make desktop` works without Emscripten. |
| `../sim-driver/` | the Emscripten build of the driver (`led_driver`) and the pattern engine for the gallery (`led_fx`) |
| `web/app.js` | the room canvas, editor, power control, packet routing by MAC, and placements for `POST /devices/layout` |
| `web/driver-worker.js` | loads `led_driver.mjs` and boots one bar |
| `web/gallery.js` | one `led_fx` instance per pattern, each stepped every 10 ms of its own clock |
## Notes
Not simulated: the drivers' Wi-Fi, their own web UI and HTTP API, DDP and USB. Bars do not hear each other's
ESP-NOW.
- `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.
## Headless (older)
`python3 led-simulator/bridge_sim.py` ran each bar as a CPython process with the MicroPython driver
(`led-driver/src`, now removed from led-driver) behind a UDP bridge, so it no longer has drivers to run. Its grid
comes from `layout` in `sim.json` (`layout.py`, `rig_seed.py`).
-541
View File
@@ -1,541 +0,0 @@
#!/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/<path:path>")
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/<int:index>")
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())
-177
View File
@@ -1,177 +0,0 @@
"""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)
+756 -309
View File
File diff suppressed because it is too large. Load diff
+83 -62
View File
@@ -1,84 +1,105 @@
/* One simulated led-driver: Pyodide running led-driver/src/main.py.
/* One simulated led-driver: the C++ firmware (led-driver/main) built to WebAssembly (sim-driver/ in led-controller).
*
* 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().
* A module worker. The page posts {t: 'boot', mac, nvs, fps} once; the worker instantiates
* wasm/led_driver.mjs and calls sim_boot. There are no threads (so no SharedArrayBuffer, and the page works
* on any address): every TICK_MS the worker calls sim_tick, which runs what the board's two tasks run, a pass
* of the ESP-NOW link and, every 10 ms, a pattern frame. Packets arrive as plain messages between ticks.
* Power-off is Worker.terminate().
*
* Messages to the page:
* Page -> worker:
* {t:'boot', mac, nvs, fps} mac: 12 hex digits; nvs: the strip's flash (JSON text)
* {t:'rx', data} Uint8Array src_mac(6) + ESP-NOW packet
* Worker -> 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())
* {t:'px', data} Uint8Array RGB frame, pixel 0 first
* {t:'flash', data} the NVS store after a commit (JSON text)
* {t:'exit', error, reset} the driver stopped (reset: esp_restart())
*/
/* global importScripts, loadPyodide, SimRing */
importScripts('/web/ring.js');
import LedDriver from './wasm/led_driver.mjs';
let ring = null;
let sleepView = null;
const FRAME_CAP = 512 * 3; // FX_LEDS_MAX
const TICK_MS = 4;
const RX_CAP = 6 + 250;
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);
}
};
let mod = null;
let rxPtr = 0;
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));
}
function exit(error, reset = false) {
self.postMessage({ t: 'exit', error: String(error), reset });
}
self.onmessage = async (event) => {
const m = event.data || {};
if (m.t !== 'boot') {
return;
}
ring = new SimRing(m.ringSab);
sleepView = new Int32Array(m.sleepSab);
function startPixels(fps) {
const ptr = mod._malloc(FRAME_CAP);
let last = null;
setInterval(() => {
const n = mod._sim_frame(ptr, FRAME_CAP);
const frame = mod.HEAPU8.slice(ptr, ptr + n * 3);
if (last && last.length === frame.length && frame.every((v, i) => v === last[i])) {
return; // unchanged: nothing to redraw
}
last = frame;
const out = frame.slice();
self.postMessage({ t: 'px', data: out }, [out.buffer]);
}, 1000 / Math.max(1, Math.min(60, Number(fps) || 30)));
}
async function boot(m) {
self.postMessage({ t: 'state', state: 'loading' });
try {
importScripts(`${m.pyodideUrl}pyodide.js`);
const py = await loadPyodide({
indexURL: m.pyodideUrl,
stdout: log,
stderr: log,
mod = await LedDriver({
print: log,
printErr: log,
simTx: (u8) => self.postMessage({ t: 'tx', data: u8 }, [u8.buffer]),
simFlash: (json) => self.postMessage({ t: 'flash', data: json }),
simRestart: () => exit('esp_restart()', true),
onAbort: (what) => exit(`abort: ${what}`),
});
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);
log(String((err && err.stack) || err));
exit(`load failed: ${err}`);
return;
}
const mac = mod.stringToNewUTF8(String(m.mac));
const nvs = mod.stringToNewUTF8(String(m.nvs || '{}'));
let rc;
try {
rc = mod._sim_boot(mac, nvs);
} catch (err) {
log(String((err && err.stack) || err));
exit(String(err));
return;
} finally {
mod._free(mac);
mod._free(nvs);
}
if (rc !== 0) {
exit(`sim_boot returned ${rc}`);
return;
}
rxPtr = mod._malloc(RX_CAP);
setInterval(() => {
try {
mod._sim_tick();
} catch (err) {
exit(String((err && err.message) || err));
}
self.postMessage({ t: 'exit', error: reset ? 'machine.reset()' : msg, reset });
}, TICK_MS);
startPixels(m.fps);
self.postMessage({ t: 'state', state: 'running' });
}
self.onmessage = (event) => {
const m = event.data || {};
if (m.t === 'boot' && !mod) {
boot(m);
} else if (m.t === 'rx' && rxPtr && m.data && m.data.length <= RX_CAP) {
mod.HEAPU8.set(m.data, rxPtr);
mod._sim_rx(rxPtr, m.data.length);
}
};
-49
View File
@@ -1,49 +0,0 @@
"""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()
+37
View File
@@ -0,0 +1,37 @@
.gallery-intro { margin: 0; padding: 10px 16px 0; color: var(--muted); max-width: 900px; }
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
gap: 12px;
padding: 12px 16px 24px;
}
.card {
background: var(--panel);
border: 1px solid var(--line);
border-radius: 10px;
padding: 10px 12px;
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
}
.card-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.card-name { font-weight: 600; font-family: ui-monospace, Menlo, Consolas, monospace; }
.card-head .btns { display: flex; gap: 4px; }
.card-head button { padding: 2px 8px; }
.card canvas { width: 100%; height: 22px; display: block; background: #0b0c0f; border-radius: 4px; }
.card form { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px 8px; }
.card form[hidden] { display: none; }
.card form label { display: flex; flex-direction: column; gap: 2px; color: var(--muted); font-size: 11px; }
.card form label.wide { grid-column: span 2; }
.card form label.full { grid-column: 1 / -1; }
.card form label.check { flex-direction: row; align-items: center; gap: 5px; }
.card form input { width: 100%; padding: 3px 5px; }
.card form input[type=checkbox] { width: auto; }
.colours { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; }
.colours input[type=color] { width: 30px; height: 24px; padding: 0; border-radius: 4px; }
.colours button { padding: 1px 7px; }
@media (max-width: 420px) {
.gallery { grid-template-columns: 1fr; padding: 12px 16px; }
.card form { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
+40
View File
@@ -0,0 +1,40 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#0e0f12">
<title>Pattern Gallery</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="/sim/styles.css">
<link rel="stylesheet" href="/sim/gallery.css">
</head>
<body>
<header class="topbar">
<div class="brand">
<span class="brand-mark" aria-hidden="true"></span>
<span class="brand-name">Pattern gallery</span>
</div>
<div class="chips"><span class="chip" id="g-count">loading…</span></div>
<div class="actions">
<label class="field-inline">LEDs <input id="g-leds" type="number" min="1" max="512" step="1" value="119"></label>
<label class="field-inline">Speed
<select id="g-speed">
<option value="0.25">¼×</option><option value="0.5">½×</option><option value="1" selected>1×</option>
<option value="2">2×</option><option value="4">4×</option>
</select>
</label>
<button type="button" id="g-pause" class="secondary">Pause</button>
<button type="button" id="g-restart" class="secondary">Restart all</button>
<a class="button secondary" href="/sim/">Rig</a>
</div>
</header>
<div id="banner" class="banner" hidden></div>
<p class="gallery-intro">
Every pattern of the C++ led-driver, built to WebAssembly and stepped every 10 ms as on the strip. Fields are the
preset's (the names the controller sends). Leave the colour list empty for the pattern's own colours.
</p>
<main class="gallery" id="gallery"></main>
<script type="module" src="/sim/gallery.js"></script>
</body>
</html>
+303
View File
@@ -0,0 +1,303 @@
/* Pattern gallery: every led-driver pattern side by side, from the C++ engine built to WebAssembly
* (wasm/led_fx.mjs: led-driver/main/patterns.cpp and the effects, no threads).
*
* One module instance per pattern, so each has its own engine state; the wasm is compiled once and shared.
* Each instance has its own clock and runs patterns_frame() every 10 ms of it (FRAME_MS on the board).
*/
import LedFx from './wasm/led_fx.mjs';
const FRAME_MS = 10;
const MAX_STEPS = 25; // per animation frame, after the tab was in the background
const LED_CAP = 512;
const $ = (id) => document.getElementById(id);
const state = { leds: 119, speed: 1, paused: false, cards: [] };
function banner(text) {
const el = $('banner');
el.textContent = text;
el.hidden = !text;
}
function hex(c) {
return `#${c.map((v) => Number(v).toString(16).padStart(2, '0')).join('')}`;
}
function rgb(h) {
const v = parseInt(h.slice(1), 16);
return [(v >> 16) & 255, (v >> 8) & 255, v & 255];
}
async function instantiate(wasmModule) {
return LedFx({
print: () => {},
printErr: (t) => console.warn('[fx]', t),
instantiateWasm(imports, receive) {
WebAssembly.instantiate(wasmModule, imports).then((inst) => receive(inst, wasmModule));
return {};
},
});
}
function presetJson(card) {
return JSON.stringify(card.preset);
}
function apply(card, restart) {
const p = card.mod.stringToNewUTF8(presetJson(card));
const ok = card.mod._fx_select_json(p, restart ? 1 : 0);
card.mod._free(p);
if (restart) {
card.clock = 0;
card.next = 0;
}
return ok;
}
function numField(card, key, label, opts = {}) {
const l = document.createElement('label');
if (opts.cls) l.className = opts.cls;
l.textContent = label;
const i = document.createElement('input');
i.type = 'number';
i.step = opts.step ?? 1;
if (opts.min !== undefined) i.min = opts.min;
if (opts.max !== undefined) i.max = opts.max;
i.value = card.preset[key] ?? 0;
i.onchange = () => {
const v = Number(i.value);
if (Number.isFinite(v)) {
card.preset[key] = Math.round(v);
apply(card, opts.restart);
}
};
l.append(i);
return l;
}
function checkField(card, key, label, restart) {
const l = document.createElement('label');
l.className = 'check';
const i = document.createElement('input');
i.type = 'checkbox';
i.checked = Boolean(card.preset[key]);
i.onchange = () => {
card.preset[key] = i.checked;
apply(card, restart);
};
l.append(i, label);
return l;
}
function colourList(card) {
const l = document.createElement('label');
l.className = 'full';
l.textContent = 'Colours';
const box = document.createElement('div');
box.className = 'colours';
const render = () => {
const items = card.preset.colors.map((c, k) => {
const i = document.createElement('input');
i.type = 'color';
i.value = hex(c);
i.title = 'Click to change; right-click to remove';
i.oninput = () => {
card.preset.colors[k] = rgb(i.value);
apply(card, false);
};
i.oncontextmenu = (ev) => {
ev.preventDefault();
card.preset.colors.splice(k, 1);
apply(card, false);
render();
};
return i;
});
const add = document.createElement('button');
add.type = 'button';
add.className = 'secondary';
add.textContent = '+';
add.title = 'Add a colour';
add.disabled = card.preset.colors.length >= 8;
add.onclick = () => {
const last = card.preset.colors[card.preset.colors.length - 1];
card.preset.colors.push(last ? [last[2], last[0], last[1]] : [255, 0, 0]);
apply(card, false);
render();
};
const clear = document.createElement('button');
clear.type = 'button';
clear.className = 'link';
clear.textContent = card.preset.colors.length ? 'use defaults' : 'pattern defaults';
clear.disabled = !card.preset.colors.length;
clear.onclick = () => {
card.preset.colors = [];
apply(card, false);
render();
};
box.replaceChildren(...items, add, clear);
};
render();
l.append(box);
return l;
}
function bgField(card) {
const l = document.createElement('label');
l.textContent = 'Background';
const i = document.createElement('input');
i.type = 'color';
i.value = hex(card.preset.background || [0, 0, 0]);
i.oninput = () => {
card.preset.background = rgb(i.value);
apply(card, false);
};
l.append(i);
return l;
}
function buildCard(mod, index) {
mod._fx_init(state.leds);
const name = mod.UTF8ToString(mod._fx_name(index));
const ptr = mod._fx_defaults_json(index);
const preset = JSON.parse(mod.UTF8ToString(ptr));
mod._free(ptr);
preset.n5 = preset.n5 ?? 0;
const el = document.createElement('section');
el.className = 'card';
el.innerHTML =
'<div class="card-head"><span class="card-name"></span><span class="btns">' +
'<button type="button" class="secondary" data-a="restart" title="Restart the pattern">↺</button>' +
'<button type="button" class="secondary" data-a="edit" aria-expanded="false">Edit</button></span></div>' +
'<canvas></canvas>';
el.querySelector('.card-name').textContent = name;
const card = {
mod,
index,
name,
preset,
el,
canvas: el.querySelector('canvas'),
clock: 0,
next: 0,
framePtr: mod._malloc(LED_CAP * 3),
last: null,
};
const form = document.createElement('form');
form.hidden = true;
form.onsubmit = (ev) => ev.preventDefault();
form.append(
colourList(card),
bgField(card),
numField(card, 'delay', 'Delay d (ms)', { min: 10, max: 10000 }),
numField(card, 'brightness', 'Bright b', { min: 0, max: 255 }),
numField(card, 'mode', 'Style n6', { min: 0 }),
numField(card, 'n1', 'n1'),
numField(card, 'n2', 'n2'),
numField(card, 'n3', 'n3'),
numField(card, 'n4', 'n4'),
numField(card, 'n5', 'n5'),
checkField(card, 'reverse', 'reverse', false),
checkField(card, 'auto', 'auto a', true),
checkField(card, 'beat_time', 'beat time', false),
);
el.append(form);
el.querySelector('[data-a=edit]').onclick = (ev) => {
form.hidden = !form.hidden;
ev.currentTarget.setAttribute('aria-expanded', String(!form.hidden));
ev.currentTarget.textContent = form.hidden ? 'Edit' : 'Close';
};
el.querySelector('[data-a=restart]').onclick = () => apply(card, true);
apply(card, true);
return card;
}
function draw(card) {
const mod = card.mod;
const n = mod._sim_frame(card.framePtr, LED_CAP * 3);
const px = mod.HEAPU8.subarray(card.framePtr, card.framePtr + n * 3);
const c = card.canvas;
const dpr = window.devicePixelRatio || 1;
const w = Math.max(1, Math.round(c.clientWidth * dpr));
const h = Math.max(1, Math.round(c.clientHeight * dpr));
if (c.width !== w || c.height !== h) {
c.width = w;
c.height = h;
}
const ctx = c.getContext('2d');
ctx.fillStyle = '#0b0c0f';
ctx.fillRect(0, 0, w, h);
if (!n) return;
const pitch = w / n;
const gap = pitch >= 3 ? 1 : 0;
for (let i = 0; i < n; i += 1) {
const r = px[i * 3];
const g = px[i * 3 + 1];
const b = px[i * 3 + 2];
ctx.fillStyle = r | g | b ? `rgb(${r},${g},${b})` : '#1d1f24';
ctx.fillRect(Math.floor(i * pitch), 2 * dpr, Math.max(1, Math.ceil(pitch) - gap), h - 4 * dpr);
}
}
let lastT = 0;
function tick(t) {
const dt = lastT ? Math.min(250, t - lastT) : 0;
lastT = t;
if (!state.paused) {
for (const card of state.cards) {
card.clock += dt * state.speed;
let steps = 0;
while (card.next <= card.clock && steps < MAX_STEPS) {
card.mod._fx_step(card.next);
card.next += FRAME_MS;
steps += 1;
}
if (card.next <= card.clock) {
card.next = Math.ceil(card.clock / FRAME_MS) * FRAME_MS; // fell behind: skip ahead
}
draw(card);
}
}
requestAnimationFrame(tick);
}
async function main() {
let wasmModule;
try {
wasmModule = await WebAssembly.compileStreaming(fetch('/sim/wasm/led_fx.wasm'));
} catch (err) {
banner(`Could not load the pattern engine (web/wasm/led_fx.wasm): ${err}. Build it with make sim-wasm, then rebuild the controller.`);
return;
}
const first = await instantiate(wasmModule);
const count = first._fx_count();
$('g-count').textContent = `${count} patterns`;
const grid = $('gallery');
for (let i = 0; i < count; i += 1) {
const mod = i === 0 ? first : await instantiate(wasmModule);
const card = buildCard(mod, i);
state.cards.push(card);
grid.append(card.el);
}
$('g-leds').onchange = () => {
const n = Math.max(1, Math.min(LED_CAP, Math.round(Number($('g-leds').value)) || 119));
$('g-leds').value = n;
state.leds = n;
for (const card of state.cards) {
card.mod._fx_init(n);
apply(card, true);
}
};
$('g-speed').onchange = () => {
state.speed = Number($('g-speed').value) || 1;
};
$('g-pause').onclick = () => {
state.paused = !state.paused;
$('g-pause').textContent = state.paused ? 'Play' : 'Pause';
};
$('g-restart').onclick = () => state.cards.forEach((c) => apply(c, true));
requestAnimationFrame(tick);
}
main();
+75 -5
View File
@@ -6,7 +6,7 @@
<meta name="theme-color" content="#0e0f12">
<title>LED Rig Simulator</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="/web/styles.css">
<link rel="stylesheet" href="/sim/styles.css">
</head>
<body>
<header class="topbar">
@@ -15,11 +15,25 @@
<span class="brand-name">led-simulator</span>
</div>
<div class="chips">
<span class="chip" id="bridge-chip" title="Simulated Wi-Fi bridge">bridge</span>
<span class="chip" id="bridge-chip" title="The rig's bridge: frames from the controller come in as from this MAC">bridge</span>
<span class="chip" id="controller-chip">controller: –</span>
<button type="button" id="add-bridge" class="secondary" hidden
title="The controller sends its ESP-NOW frames only to the bridges in its settings">Add the browser bridge</button>
<span class="chip" id="strips-chip">strips: –</span>
</div>
<div class="room-bar">
<label class="field-inline">Room <select id="room-select" aria-label="Room"></select></label>
<button type="button" id="edit-toggle" class="secondary">Edit room</button>
<span id="edit-tools" class="edit-tools" hidden>
<button type="button" id="room-settings" class="secondary">Size &amp; strip types…</button>
<button type="button" id="room-new" class="secondary">New room…</button>
<button type="button" id="room-delete" class="secondary">Delete room</button>
<span class="muted" id="save-state"></span>
</span>
</div>
<div class="actions">
<a class="button secondary not-embedded" href="/">Controller</a>
<a class="button secondary" href="/sim/gallery" target="_blank" rel="noopener">Pattern gallery</a>
<button type="button" id="power-on-all">Power on all</button>
<button type="button" id="power-cycle-all">Power cycle all</button>
<button type="button" id="power-off-all" class="secondary">Power off all</button>
@@ -30,6 +44,9 @@
</header>
<div id="banner" class="banner" hidden></div>
<div class="edit-hint" id="edit-hint">
Click the floor to add a strip · drag a strip to move it (Alt: no snap) · drag its end circle to turn it (Shift: no snap) · Delete removes the selected strip
</div>
<main class="stage">
<div class="rig" id="rig">
@@ -37,6 +54,11 @@
</div>
<aside class="drawer" id="drawer" hidden aria-label="Strip details">
<p class="drawer-empty" id="d-empty" hidden>
Select a strip to edit it, or click the floor to add one. Changes are saved to
<code>rooms/&lt;room&gt;.json</code> as you make them.
</p>
<div class="drawer-body" id="d-body">
<div class="drawer-head">
<div>
<div class="drawer-title" id="d-name">sim-01</div>
@@ -49,6 +71,16 @@
<dt>Position</dt><dd id="d-pos">–</dd>
<dt>Packets</dt><dd id="d-packets">–</dd>
</dl>
<p class="note" id="d-note" hidden></p>
<form class="edit-form" id="d-edit" hidden onsubmit="return false">
<label>Label <input id="e-label" maxlength="47"></label>
<label>Strip type <select id="e-def"></select></label>
<label>LEDs <input id="e-leds" type="number" min="1" max="512" step="1" title="Empty: the strip type's count"></label>
<label>Pixel 0 x (m) <input id="e-x" type="number" step="0.05"></label>
<label>Pixel 0 y (m) <input id="e-y" type="number" step="0.05"></label>
<label>Heading (°) <input id="e-dir" type="number" step="15" title="Degrees clockwise from up: 90 runs right, -90 runs left"></label>
<button type="button" id="d-delete" class="danger">Remove strip</button>
</form>
<div class="drawer-actions">
<button type="button" id="d-on">Power on</button>
<button type="button" id="d-reset">Reset</button>
@@ -59,13 +91,51 @@
<button type="button" class="link" id="d-clear">clear</button>
</div>
<pre class="log" id="d-log"></pre>
</div>
</aside>
</main>
<footer class="hint" id="hint">Loading…</footer>
<script src="/web/ring.js"></script>
<script src="/web/layout.js"></script>
<script src="/web/app.js"></script>
<dialog id="room-dialog" aria-labelledby="r-title">
<h2 id="r-title">Room size and strip types</h2>
<div class="dialog-row">
<label>Width (m) <input id="r-width" type="number" min="0.5" max="200" step="0.1"></label>
<label>Depth (m) <input id="r-depth" type="number" min="0.5" max="200" step="0.1"></label>
</div>
<table class="defs">
<thead><tr><th>Type</th><th>LEDs</th><th>LEDs per metre</th><th></th><th></th></tr></thead>
<tbody id="r-defs"></tbody>
<tfoot>
<tr>
<td><input id="r-def-name" placeholder="name, e.g. bar-60"></td>
<td><input id="r-def-leds" type="number" min="1" max="512" step="1" value="60"></td>
<td><input id="r-def-perm" type="number" min="1" max="1000" step="1" value="60"></td>
<td colspan="2"><button type="button" id="r-add-def" class="secondary">Add type</button></td>
</tr>
</tfoot>
</table>
<div class="dialog-actions"><button type="button" id="r-close">Done</button></div>
</dialog>
<dialog id="new-dialog" aria-labelledby="n-title">
<form id="new-form">
<h2 id="n-title">New room</h2>
<label>Name <input id="n-name" required pattern="[A-Za-z0-9_\-]{1,40}" title="Letters, digits, - or _"></label>
<div class="dialog-row">
<label>Width (m) <input id="n-width" type="number" min="0.5" max="200" step="0.1" required></label>
<label>Depth (m) <input id="n-depth" type="number" min="0.5" max="200" step="0.1" required></label>
</div>
<label class="check"><input type="checkbox" id="n-copy"> Copy the strips of the current room</label>
<p class="error" id="n-error"></p>
<div class="dialog-actions">
<button type="button" id="n-cancel" class="secondary">Cancel</button>
<button type="submit">Create and edit</button>
</div>
</form>
</dialog>
<script src="/sim/layout.js"></script>
<script src="/sim/app.js"></script>
</body>
</html>
+62 -84
View File
@@ -1,103 +1,81 @@
/* 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).
/* Room geometry for the canvas: metres <-> canvas pixels, and where each strip's LEDs are.
*
* A room (rooms/<name>.json, see rooms.py) spans x -width/2..width/2 and y 0..depth, metres,
* y up on screen. A fixture's x, y is pixel 0; the strip runs along `direction` (degrees clockwise
* from +y) for leds x pitch_m metres. roomStrips() mirrors rooms.room_strips() on the server.
*/
(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);
function fixtureLeds(room, f) {
return Number(f.leds) || room.definitions[f.def].leds;
}
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;
function fixtureEnd(room, f) {
const len = fixtureLeds(room, f) * room.definitions[f.def].pitch_m;
const a = (f.direction * Math.PI) / 180;
return [f.x + len * Math.sin(a), f.y + len * Math.cos(a)];
}
/** One entry per fixture, in file order. */
function roomStrips(room) {
return Object.entries(room.fixtures).map(([id, f], i) => {
const [x1, y1] = fixtureEnd(room, f);
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',
index: i,
n: i + 1,
id,
label: f.label,
mac: f.mac,
leds: fixtureLeds(room, f),
x: f.x,
y: f.y,
x1,
y1,
direction: f.direction,
};
});
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}
* Fit the room to a width x height canvas with one scale.
* @returns {object} {scale, sx(x), sy(y), mx(px), my(py)} metres -> px and back
*/
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);
function fit(room, width, height, margin = 28) {
const scale = Math.max(
1e-3,
Math.min((width - 2 * margin) / room.width, (height - 2 * margin) / room.depth),
);
const ox = width / 2;
const oy = height / 2 + (room.depth / 2) * scale;
return {
scale,
sx: (x) => ox + x * scale,
sy: (y) => oy - y * scale,
mx: (px) => (px - ox) / scale,
my: (py) => (oy - py) / scale,
};
}
/** Canvas geometry of each strip: pixel 0 at (ax, ay), the end at (bx, by). */
function stripGeometry(view, strips) {
return strips.map((s) => {
const ax = view.sx(s.x);
const ay = view.sy(s.y);
const bx = view.sx(s.x1);
const by = view.sy(s.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 { ax, ay, bx, by, len, ang: Math.atan2(by - ay, bx - ax), pitch: len / s.leds };
});
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;
/** Distance from point (x, y) to the segment of a strip, canvas px. */
function distToStrip(sg, x, y) {
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)));
return Math.hypot(x - (sg.ax + t * dx), y - (sg.ay + t * dy));
}
g.RigLayout = { computeGeometry, computePlaced, pixelX };
g.RigLayout = { roomStrips, fit, stripGeometry, distToStrip, fixtureLeds };
})(typeof self !== 'undefined' ? self : globalThis);
-93
View File
@@ -1,93 +0,0 @@
/* 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);
+84
View File
@@ -167,3 +167,87 @@ button.link {
.drawer { width: auto; border-left: none; border-top: 1px solid var(--line); max-height: 50vh; }
.actions { margin-left: 0; }
}
/* ---- rooms and the editor ---- */
.room-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.edit-tools { display: inline-flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.edit-tools[hidden] { display: none; }
.field-inline { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); }
.muted { color: var(--muted); }
select, input {
font: inherit;
color: var(--text);
background: var(--panel-2);
border: 1px solid var(--line);
border-radius: 6px;
padding: 4px 7px;
min-width: 0;
}
input:focus, select:focus { outline: 2px solid #34465f; outline-offset: 0; }
a.button {
display: inline-block;
text-decoration: none;
color: var(--text);
border: 1px solid var(--line);
background: var(--panel-2);
border-radius: 6px;
padding: 5px 11px;
}
a.button:hover { background: #232730; }
button.danger { background: #3a1d22; border-color: #5c2a31; color: #ffd6d6; }
button.danger:hover:not(:disabled) { background: #4a242b; }
.edit-hint {
display: none;
padding: 6px 16px;
background: #1d2a3a;
color: #d6e8ff;
border-bottom: 1px solid #2a405c;
}
body.editing .edit-hint { display: block; }
.note { margin: 0; color: var(--warn); }
.edit-form {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px 10px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--panel-2);
}
.edit-form[hidden] { display: none; }
.edit-form label { display: flex; flex-direction: column; gap: 3px; color: var(--muted); }
.edit-form label:first-child, .edit-form label:nth-child(2) { grid-column: 1 / -1; }
.edit-form button { grid-column: 1 / -1; justify-self: start; }
dialog {
color: var(--text);
background: var(--panel);
border: 1px solid var(--line);
border-radius: 10px;
padding: 16px 18px;
width: min(560px, calc(100vw - 32px));
}
dialog::backdrop { background: rgba(0, 0, 0, .55); }
dialog h2 { margin: 0 0 12px; font-size: 15px; }
dialog form, dialog { display: flex; flex-direction: column; gap: 10px; }
dialog:not([open]) { display: none; }
dialog label { display: flex; flex-direction: column; gap: 3px; color: var(--muted); }
dialog label.check { flex-direction: row; align-items: center; gap: 6px; }
.dialog-row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.dialog-actions { display: flex; justify-content: flex-end; gap: 6px; }
.error { color: var(--bad); margin: 0; min-height: 1em; }
table.defs { width: 100%; border-collapse: collapse; }
table.defs th { text-align: left; color: var(--muted); font-weight: normal; padding: 4px; }
table.defs td { padding: 4px; }
table.defs input { width: 100%; }
.drawer-body { display: flex; flex-direction: column; gap: 10px; flex: 1; min-height: 0; }
.drawer-body[hidden] { display: none; }
.drawer-empty { margin: 0; color: var(--muted); }
.drawer-empty[hidden] { display: none; }
.drawer-empty code { color: var(--text); }
/* In the controller's split view (an iframe beside it) */
body.embedded .not-embedded { display: none; }