From a295fefac067649b9fd6ca952658c908056bafb5 Mon Sep 17 00:00:00 2001 From: jimmy Date: Thu, 22 Oct 2026 14:05:42 +1300 Subject: [PATCH] Pick the simulator's stage map from a drop-down, and make the QLC+ show optional. Co-Authored-By: Claude Opus 5.5 --- .claude/launch.json | 6 +++++ README.md | 6 ++++- simulator/__main__.py | 19 ++++++++------ simulator/server.py | 45 +++++++++++++++++++++++++++++++-- simulator/static/app.js | 50 ++++++++++++++++++++++++++++++------- simulator/static/index.html | 3 +++ simulator/static/style.css | 23 ++++++++++++++++- tests/test_simulator.py | 22 ++++++++++++++++ 8 files changed, 154 insertions(+), 20 deletions(-) diff --git a/.claude/launch.json b/.claude/launch.json index 30035ae..23842aa 100644 --- a/.claude/launch.json +++ b/.claude/launch.json @@ -6,6 +6,12 @@ "runtimeExecutable": ".venv/bin/python", "runtimeArgs": ["-m", "padcontroller", "--no-browser"], "port": 8770 + }, + { + "name": "simulator", + "runtimeExecutable": ".venv/bin/python", + "runtimeArgs": ["-m", "simulator", "--http", "127.0.0.1:8766", "--artnet", "127.0.0.1:6455", "--demo"], + "port": 8766 } ] } diff --git a/README.md b/README.md index 07ecde7..96dd991 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,11 @@ Options after the command go to the pad controller (for example `--lock-knobs`). ## Stage simulator `python -m simulator` listens for Art-Net on port 6454 and draws the rig at -http://127.0.0.1:8765. It can run as a systemd user service the same way: +http://127.0.0.1:8765. The Stage drop-down on the page switches between the +stage maps in `stage/`. No QLC+ show is needed: `stage/map.json` holds every +address. `--show ` only fills in addresses a stage map leaves out and +shows where that workspace sends Art-Net. It can run as a systemd user service +the same way: ```bash simulator/systemd/install.sh diff --git a/simulator/__main__.py b/simulator/__main__.py index b481911..4c55fad 100644 --- a/simulator/__main__.py +++ b/simulator/__main__.py @@ -6,6 +6,10 @@ Art-Net. Open the printed URL and point QLC+ Art-Net output at this machine. python -m simulator python -m simulator --stage stage/map.json --show shows/templeoftechno.qxw python -m simulator --demo + +The show is optional: it only fills addresses the stage map leaves out, and +shows the QLC+ Art-Net output it sends to. The page can switch to any other +stage map in the same folder. """ from __future__ import annotations @@ -114,24 +118,25 @@ def _parse_host_port(value: str, default_port: int) -> tuple[str, int]: def main() -> None: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--stage", type=Path, default=ROOT / "stage" / "map.json") - parser.add_argument("--show", type=Path, default=ROOT / "shows" / "templeoftechno.qxw") - parser.add_argument("--no-show", action="store_true", help="Use addresses stored in the stage file only") + parser.add_argument("--show", type=Path, help="QLC+ workspace to fill addresses the stage map leaves out") + parser.add_argument("--no-show", action="store_true", help="Ignore --show (kept for older commands)") parser.add_argument("--http", default="0.0.0.0:8765", help="Web view host:port") parser.add_argument("--artnet", default="0.0.0.0:6454", help="Art-Net listen host:port") parser.add_argument("--demo", action="store_true", help="Play a local look when you want to see the rig without QLC+") args = parser.parse_args() stage = load_stage(args.stage) - if not args.no_show: - if not args.show.is_file(): - raise SystemExit(f"Show not found: {args.show}") - apply_show(stage, args.show) + show = None if args.no_show else args.show + if show is not None: + if not show.is_file(): + raise SystemExit(f"Show not found: {show}") + apply_show(stage, show) http_host, http_port = _parse_host_port(args.http, 8765) artnet_host, artnet_port = _parse_host_port(args.artnet, 6454) node = ArtNetNode(artnet_host, artnet_port) node.start() - server = make_server(Simulator(stage, node), http_host, http_port) + server = make_server(Simulator(stage, node, show), http_host, http_port) print("Stage simulator", flush=True) print(f" stage: {args.stage}", flush=True) diff --git a/simulator/server.py b/simulator/server.py index 1fd7cbe..40e8721 100644 --- a/simulator/server.py +++ b/simulator/server.py @@ -9,7 +9,7 @@ from urllib.parse import urlparse from simulator.artnet import ArtNetNode from simulator.decode import view_stage -from simulator.stage import Stage, set_heading +from simulator.stage import Stage, apply_show, load_stage, set_heading STATIC = Path(__file__).resolve().parent / "static" @@ -21,15 +21,37 @@ CONTENT_TYPES = { class Simulator: - def __init__(self, stage: Stage, node: ArtNetNode): + def __init__(self, stage: Stage, node: ArtNetNode, show: Path | None = None): self.stage = stage self.node = node + self.show = show def state(self) -> dict: stats = self.node.stats() stats["fixtures"] = view_stage(self.stage, self.node.snapshot()) return stats + def stage_dir(self) -> Path | None: + return self.stage.path.parent if self.stage.path else None + + def stages(self) -> dict: + """The stage maps next to the current one, for the page's drop-down.""" + folder = self.stage_dir() + files = sorted(path.name for path in folder.glob("*.json")) if folder else [] + current = self.stage.path.name if self.stage.path else None + return {"current": current, "stages": files} + + def switch(self, name: str) -> Stage: + """Load another stage map from the same folder, with the same show.""" + folder = self.stage_dir() + if folder is None or name not in self.stages()["stages"]: + raise KeyError(name) + stage = load_stage(folder / name) + if self.show is not None: + apply_show(stage, self.show) + self.stage = stage + return stage + def make_handler(sim: Simulator): class Handler(BaseHTTPRequestHandler): @@ -40,6 +62,9 @@ def make_handler(sim: Simulator): def do_POST(self) -> None: path = urlparse(self.path).path + if path == "/api/stage": + self._switch_stage() + return if path != "/api/heading": self.send_error(404) return @@ -68,6 +93,9 @@ def make_handler(sim: Simulator): if path == "/api/stage": self._json(self.simulator.stage.to_json()) return + if path == "/api/stages": + self._json(self.simulator.stages()) + return if path in ("/", "/index.html"): self._file(STATIC / "index.html") return @@ -78,6 +106,19 @@ def make_handler(sim: Simulator): return self.send_error(404) + def _switch_stage(self) -> None: + length = int(self.headers.get("Content-Length") or 0) + if length <= 0 or length > 4096: + self._json({"error": "bad stage"}, 400) + return + try: + name = str(json.loads(self.rfile.read(length))["file"]) + stage = self.simulator.switch(name) + except (KeyError, TypeError, ValueError, json.JSONDecodeError): + self._json({"error": "bad stage"}, 400) + return + self._json(stage.to_json()) + def _json(self, payload: dict, status: int = 200) -> None: body = json.dumps(payload).encode() self.send_response(status) diff --git a/simulator/static/app.js b/simulator/static/app.js index df383f4..6e42d2b 100644 --- a/simulator/static/app.js +++ b/simulator/static/app.js @@ -9,6 +9,7 @@ const detailEl = document.getElementById("detail"); const detailTitle = document.getElementById("detail-title"); const detailMeta = document.getElementById("detail-meta"); const channelsEl = document.getElementById("channels"); +const stageFileEl = document.getElementById("stage-file"); let stage = null; let state = { fixtures: {}, age: null, rate: 0, universe: null, packets: 0 }; @@ -592,18 +593,49 @@ canvas.addEventListener("pointercancel", () => { window.addEventListener("resize", resize); +function showStage(loaded) { + stage = loaded; + selected = null; + detailEl.hidden = true; + nameEl.textContent = stage.name || "xchc"; + document.title = stage.name || "xchc"; + originEl.textContent = stage.origin || ""; + const show = stage.show ? stage.show : "addresses from the stage map"; + const target = stage.output_ip ? ` · QLC+ output ${stage.output_ip}` : ""; + patchEl.textContent = `${show}${target}`; + buildList(); + resize(); +} + +async function loadStageList() { + const { current, stages } = await fetch("/api/stages").then((response) => response.json()); + stageFileEl.replaceChildren( + ...stages.map((name) => new Option(name.replace(/\.json$/, ""), name, false, name === current)), + ); + stageFileEl.disabled = stages.length < 2; +} + +stageFileEl.addEventListener("change", async () => { + stageFileEl.disabled = true; + try { + const response = await fetch("/api/stage", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ file: stageFileEl.value }), + }); + if (!response.ok) throw new Error("bad stage"); + showStage(await response.json()); + } catch { + statusEl.textContent = "could not load that stage"; + } + await loadStageList().catch(() => {}); +}); + fetch("/api/stage") .then((response) => response.json()) .then((loaded) => { - stage = loaded; - nameEl.textContent = stage.name || "xchc"; - document.title = stage.name || "xchc"; - originEl.textContent = stage.origin || ""; - const show = stage.show ? stage.show : "stage file"; - const target = stage.output_ip ? ` · QLC+ output ${stage.output_ip}` : ""; - patchEl.textContent = `${show}${target}`; - buildList(); - resize(); + showStage(loaded); + loadStageList().catch(() => {}); poll(); setInterval(poll, 50); requestAnimationFrame(frame); diff --git a/simulator/static/index.html b/simulator/static/index.html index 25a76ba..0e48ccf 100644 --- a/simulator/static/index.html +++ b/simulator/static/index.html @@ -12,6 +12,9 @@

xchc

+

waiting for Art-Net

diff --git a/simulator/static/style.css b/simulator/static/style.css index 747ebcc..5b60d20 100644 --- a/simulator/static/style.css +++ b/simulator/static/style.css @@ -30,8 +30,9 @@ body { header { display: flex; align-items: center; + flex-wrap: wrap; justify-content: space-between; - gap: 16px; + gap: 8px 16px; padding: 12px 16px; border-bottom: 1px solid var(--line); } @@ -44,12 +45,32 @@ h1, h2 { h2 { font-size: 14px; } +.titles { flex: 1 1 240px; } + .titles p, .meta { margin: 2px 0 0; color: var(--muted); font-size: 12px; } +.stage-pick { + display: flex; + align-items: center; + gap: 6px; + margin-left: auto; + color: var(--muted); + font-size: 12px; +} + +.stage-pick select { + padding: 3px 6px; + border: 1px solid var(--line); + border-radius: 6px; + background: var(--panel); + color: var(--text); + font: inherit; +} + .pill { margin: 0; padding: 4px 10px; diff --git a/tests/test_simulator.py b/tests/test_simulator.py index b1f6069..5a51e97 100644 --- a/tests/test_simulator.py +++ b/tests/test_simulator.py @@ -228,3 +228,25 @@ def test_heading_is_stored_in_the_map(tmp_path): by_id = {fixture.id: fixture for fixture in again.fixtures} assert by_id["#1"].direction == 45 assert by_id["M1"].zero == -30 + + +def test_switch_stage_lists_and_loads_maps_in_the_same_folder(tmp_path): + first = tmp_path / "map.json" + first.write_text((ROOT / "stage" / "map.json").read_text()) + data = json.loads(first.read_text()) + data["name"] = "movers only" + data["fixtures"] = {key: value for key, value in data["fixtures"].items() if key.startswith("M")} + (tmp_path / "movers.json").write_text(json.dumps(data)) + sim = Simulator(load_stage(first), node=None, show=ROOT / "shows" / "xchc.qxw") + assert sim.stages() == {"current": "map.json", "stages": ["map.json", "movers.json"]} + stage = sim.switch("movers.json") + assert stage.name == "movers only" + assert stage.show == "xchc.qxw" + assert sim.stages()["current"] == "movers.json" + for bad in ("../map.json", "missing.json"): + try: + sim.switch(bad) + except KeyError: + pass + else: + raise AssertionError(bad)