From 61400df66778065905241a808d619e5870042d3f Mon Sep 17 00:00:00 2001 From: Givou Date: Sun, 1 Nov 2026 21:14:04 +0100 Subject: [PATCH] Add device lock support and demo mode Device lock (hardware lock of the DSP, independent of the app lock): - detect a locked DSP from the 0x2C answer during connect and wait for the code - unlock with 0x2D, optionally remember the code and unlock automatically - set a new code (0x2F) from the device settings - simulator: --lock CODE Demo mode: - switch in the settings starts a simulated DSP 204/408 inside the server - real DSPs are disconnected and greyed out meanwhile and resume afterwards - demo devices are never saved or exported; sim.py ships with the Pi image and EXEs Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 15 ++++- PROTOCOL.md | 19 +++++- README.md | 7 +- dsp/device.py | 74 +++++++++++++++++++-- dsp/protocol.py | 12 +++- packaging/build.py | 2 +- pi_image.py | 2 +- server.py | 99 ++++++++++++++++++++++++++-- sim.py | 19 +++++- static/app.js | 142 +++++++++++++++++++++++++++++++++++++---- static/i18n.js | 36 ++++++++++- static/style.css | 20 ++++++ tests/test_protocol.py | 17 +++++ 13 files changed, 426 insertions(+), 38 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 44ca17c..39a7cd5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,7 +33,14 @@ pi_writer.py → pi_image.py (cloud-init SD card, installs server.py as a system current view (`mixer`, `channel`, `routing`, `link`, `limiter`, `settings`). Live widgets register in `live` and are updated without a full redraw. **All UI text goes through `t("English text", {vars})`**; German lives in `static/i18n.js` (`DE`, plus `DE_PATTERNS` for server messages with variables, applied by `trMsg()`). -* **`sim.py`** – simulated DSP 204/408 speaking the same protocol (meters, limiter flags, links). Use it for all tests. +* **`sim.py`** – simulated DSP 204/408 speaking the same protocol (meters, limiter flags, links, lock code via + `--lock`). Use it for all tests. The server also imports it for the **demo mode** (`App.start_demo`: real + devices are stopped, a `SimDSP` runs on a random localhost port, a `Device` with `demo = True` connects to it; + demo devices are never saved, exported or editable). `sim.py` therefore ships with the Pi image and the EXEs. +* **Device lock** (hardware, unrelated to the app lock) – `Device._wait_for_unlock` holds the init after `0x2C` + reports a lock, tries the remembered code (`lock_code` + `auto_unlock` in `config.json`, clients only see a + boolean) or sets status `locked` and waits for `POST /api/devices//unlock {code, remember}`. + `POST …/lockcode {code}` sets a new code. * **`desktop.py`** – starts `server.App` on 127.0.0.1 with a random port in a thread and opens a pywebview window. `Api` exposes native file dialogs to the page (`window.pywebview.api.save_file/open_file`). Single instance via a named mutex (Windows) or lock file (macOS). Data in `%APPDATA%\DSP Control` / `~/Library/Application Support/DSP Control`. @@ -77,8 +84,10 @@ Not verified yet – ask for a log (`python server.py -v`) from real hardware be * **DSP 408 on real hardware** (layout and frames match published captures, limiter bits for Out 5–8 assumed) * USB on Windows and Linux against a real DSP (only tested against a fake HID device) -* Where the PEQ bypass flag lives in the memory image; format of the set-command acknowledgement; payload of the - preset-count answer (`0x2C`) +* Where the PEQ bypass flag lives in the memory image; format of the set-command acknowledgement; where the number + of preset slots comes from (20 is assumed when the `0x2C` answer carries the lock state) +* Device lock (`0x2C` byte 5, `0x2D`, `0x2F`, `0x11`) – implemented from the control software's behaviour and + tested against the simulator only; no command to remove a lock is known * Limiter calculator reference level (assumes limiter 0 dB = 0 dBu at the output; adjustable per device) * Pi Writer: raw write to a real SD card and first boot on a real Pi (only tested with an image file) diff --git a/PROTOCOL.md b/PROTOCOL.md index b74e40a..ca9a847 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -36,7 +36,7 @@ All 16-bit words are little endian. |-----|-----------|---------|---------| | `10` | → | – | Handshake | | `13` | → / ← | – / ASCII | Device info, answer starts with `DSP204` or `DSP408` | -| `2C` | → / ← | – / `[?][count]` | Number of presets (payload meaning partly *assumed*) | +| `2C` | → / ← | – / `[time lock][4 bytes][device lock]` | Lock state, see [Device lock](#device-lock) | | `22`, `14` | → | – | Init queries (sent during connect, content unknown) | | `29` | → / ← | `[idx]` / `[idx][name…]` | Preset name (idx 0-based) | | `20` | → | `[idx+1]` | Recall preset | @@ -45,6 +45,9 @@ All 16-bit words are little endian. | `27` | → | `[chunk]` | Request config chunk | | `24` | ← | `[chunk][50 bytes]` | Config chunk; 204: chunks 0…14, 408: 0…28 | | `12` | → | – | Status (sent after the dump) | +| `2D` | → / ← | `[0][code 4]` / `[0][result]` | Unlock with the lock code, result `1` = unlocked, `0` = wrong code | +| `2F` | → | `[code 4]` | Set a new lock code | +| `11` | → | – | Sent after setting a lock code (meaning not fully known) | | `40` | → / ← | – / meters | Read levels (also serves as keepalive) | ### Meter answer @@ -126,6 +129,20 @@ or within the outputs): * A member with mask `00` that is not part of a group ignores changes: when unlinking, give every channel its own bit again. +## Device lock + +The DSP can be protected with a 4-character code (digits and upper-case letters, e.g. `A1BA`, sent as ASCII). + +* During connect, the answer to `2C` reports the lock state: byte 5 ≠ 0 means the device is locked. Byte 0 and + bytes 1–4 belong to a separate time-based lock that this app does not use. +* A locked device waits for `2D [00][code]` before the rest of the initialisation (`22`, `14`, preset names, dump). + The answer `2D [00][01]` means unlocked, `2D [00][00]` wrong code. +* `2F [code]` stores a new code; the control software sends `11` afterwards. The device asks for the new code from + the next connection on. A command to remove the lock is not known. + +Status: derived from the behaviour of the control software and implemented against the simulator; **not yet +verified on a real device**. + ## Config dump = memory image Chunk `n` carries bytes `n·50 … n·50+49` of the device memory image. diff --git a/README.md b/README.md index f899762..c12a5d7 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,10 @@ Control both devices at the same time from your phone, tablet or computer – ov outputs, and see the resulting power when the limiter engages, the clipping headroom and the speaker load. "Limit to … W" calculates the threshold. Attack/release presets per band (infra, sub, kick, mid, high) * **Settings backup** – devices, amplifier data, PIN and remote access in one file +* **Device lock** – DSPs locked with their 4-character code (e.g. `A1BA`) are detected on connect and the app asks + for the code; optionally it remembers the code and unlocks automatically. A new code can be set under ⚙ +* **Demo mode** – one switch under ⚙ starts a simulated DSP 204 or 408 inside the app to try everything; the real + DSPs are disconnected meanwhile and nothing is sent to them * **Many phones at once** – every change is pushed live to all connected clients * Tap a value to type it in (`-3.5`, `1.2k`, delay in metres `2.5m`); faders snap at 0 dB, double-tap = 0 dB @@ -117,7 +121,8 @@ DSPs on USB, pick the right one in the drop-down. ## Testing without hardware -A simulator emulates both models: +The quickest way is the **demo mode** (⚙ → Demo mode). For development, a stand-alone simulator emulates both +models (`--lock A1BA` makes it ask for a lock code): ```bash python sim.py --model 204 --port 9761 diff --git a/dsp/device.py b/dsp/device.py index a6cba10..3400430 100644 --- a/dsp/device.py +++ b/dsp/device.py @@ -20,7 +20,8 @@ LINK_RESYNC_DELAY = 1.5 # re-read the config this long after the last change on class Device: def __init__(self, dev_id: str, name: str, host: str, port: int = P.PORT, model: str = "auto", - addr: int = 1, autoconnect: bool = True, on_event=None, transport: str = "tcp", usb: str = ""): + addr: int = 1, autoconnect: bool = True, on_event=None, transport: str = "tcp", usb: str = "", + lock_code: str = "", auto_unlock: bool = False): self.id = dev_id self.name = name self.host = host @@ -31,8 +32,12 @@ class Device: self.transport = "usb" if transport == "usb" else "tcp" self.usb = usb # HID device path, "" = first DSP found self.on_event = on_event or (lambda ev: None) + # hardware lock of the DSP itself (not the app lock): remembered code for automatic unlocking + self.lock_code = lock_code if P.LOCK_CODE.fullmatch(lock_code or "") else "" + self.auto_unlock = auto_unlock + self.demo = False # in-process simulator of the demo mode, never saved - self.status = "disconnected" # disconnected | connecting | loading | online | error + self.status = "disconnected" # disconnected | connecting | loading | locked | online | error self.error = "" self.info = "" self.model: P.Model | None = P.MODELS.get(model) @@ -53,16 +58,20 @@ class Device: self._want_connected = False self._resync: asyncio.TimerHandle | None = None self._changes = 0 # bumped on every local change, so a resync never overwrites newer edits + self._codes: asyncio.Queue | None = None # (code, future) entered while the DSP is locked # ------------------------------------------------------------ public API def config(self) -> dict: return {"id": self.id, "name": self.name, "host": self.host, "port": self.port, "model": self.model_key, "addr": self.addr, "autoconnect": self.autoconnect, - "transport": self.transport, "usb": self.usb} + "transport": self.transport, "usb": self.usb, + "lock_code": self.lock_code, "auto_unlock": self.auto_unlock} def snapshot(self) -> dict: - return {**self.config(), "status": self.status, "error": self.error, "info": self.info, + cfg = self.config() + cfg["lock_code"] = bool(self.lock_code) # clients only learn whether a code is remembered + return {**cfg, "demo": self.demo, "status": self.status, "error": self.error, "info": self.info, "detected_model": self.model_name or None, "n_in": self.model.n_in if self.model else 0, "n_out": self.model.n_out if self.model else 0, @@ -75,8 +84,6 @@ class Device: async def stop(self): self._want_connected = False - self._resync: asyncio.TimerHandle | None = None - self._changes = 0 # bumped on every local change, so a resync never overwrites newer edits if self._supervisor: self._supervisor.cancel() try: @@ -121,6 +128,29 @@ class Device: await asyncio.sleep(0.3) await self.refresh() + async def unlock(self, code: str) -> bool: + """Try a lock code while the DSP waits for it. True if the DSP accepted it.""" + code = str(code or "").strip().upper() + if not P.LOCK_CODE.fullmatch(code): + raise ValueError("The code has 4 characters: digits and letters A–Z") + if self.status != "locked" or not self._codes: + raise RuntimeError("The DSP is not locked") + fut = asyncio.get_running_loop().create_future() + await self._codes.put((code, fut)) + return await fut + + async def set_lock_code(self, code: str): + """Store a new lock code in the DSP; it asks for it from the next connection on.""" + code = str(code or "").strip().upper() + if not P.LOCK_CODE.fullmatch(code): + raise ValueError("The code has 4 characters: digits and letters A–Z") + if self.status != "online": + raise RuntimeError("DSP is not connected") + if self.lock_code: # keep auto-unlock working with the new code + self.lock_code = code + await self._request(P.CMD_SET_LOCK_CODE, code.encode("ascii")) + await self._request(P.CMD_LOGOUT) # as the original software does after setting the code + def _schedule_resync(self): """Re-read the config shortly after edits on linked channels, so the app shows exactly what the DSP applied to the group (e.g. mute, which we don't mirror for certain).""" @@ -293,8 +323,11 @@ class Device: if detected and detected != self.model_key: log.warning("%s: configured as %s but device reports %s", self.name, self.model_key, self.info) count_frame = await self._request(P.CMD_PRESET_COUNT, expect=P.CMD_PRESET_COUNT) - count = count_frame.payload[-1] if count_frame and count_frame.payload else 20 + payload = count_frame.payload if count_frame else b"" + count = payload[-1] if 0 < len(payload) < 6 else 20 # the long answer carries the lock state instead count = count if 0 < count <= 60 else 20 + if P.device_locked(payload): + await self._wait_for_unlock() await self._request(P.CMD_INIT_22) await self._request(P.CMD_INIT_14) presets = [] @@ -304,6 +337,33 @@ class Device: self.presets = presets await self._load_config() + async def _try_code(self, code: str) -> bool: + f = await self._request(P.CMD_UNLOCK, b"\x00" + code.encode("ascii"), timeout=2.0, expect=P.CMD_UNLOCK) + return bool(f and len(f.payload) > 1 and f.payload[1] == 1) + + async def _wait_for_unlock(self): + """The DSP is locked with its code: unlock automatically or wait until a code is entered.""" + if self.auto_unlock and self.lock_code: + if await self._try_code(self.lock_code): + log.info("%s: unlocked automatically", self.name) + return + log.warning("%s: remembered lock code was rejected", self.name) + self.error = "The remembered lock code was rejected" + self._codes = asyncio.Queue() + self._set_status("locked") + try: + while True: + code, fut = await self._codes.get() + ok = await self._try_code(code) + if not fut.done(): + fut.set_result(ok) + if ok: + self.error = "" + self._set_status("loading") + return + finally: + self._codes = None + async def _load_config(self): self.state = await self._read_config() diff --git a/dsp/protocol.py b/dsp/protocol.py index 5393953..7f8b530 100644 --- a/dsp/protocol.py +++ b/dsp/protocol.py @@ -2,6 +2,7 @@ import copy import math +import re import struct from dataclasses import dataclass @@ -10,6 +11,7 @@ PORT = 9761 # Read / system commands CMD_ACK = 0x01 CMD_HANDSHAKE = 0x10 +CMD_LOGOUT = 0x11 # sent after setting a lock code CMD_STATUS = 0x12 CMD_DEVICE_INFO = 0x13 CMD_INIT_14 = 0x14 @@ -20,7 +22,9 @@ CMD_CONFIG_CHUNK = 0x24 CMD_PRESET_STORE_NAME = 0x26 CMD_CONFIG_REQUEST = 0x27 CMD_PRESET_NAME = 0x29 -CMD_PRESET_COUNT = 0x2C +CMD_PRESET_COUNT = 0x2C # answer: [time lock][4 bytes time lock data][device lock] (see device_locked) +CMD_UNLOCK = 0x2D # [0][code 4] -> answer [0][1 = unlocked, 0 = wrong code] +CMD_SET_LOCK_CODE = 0x2F # [code 4] CMD_METER = 0x40 # Parameter commands @@ -41,6 +45,12 @@ CMD_GEQ = 0x48 CMD_LINK = 0x3B # [ch][u16 link mask], see link_masks() CHUNK_SIZE = 50 +LOCK_CODE = re.compile(r"[A-Z0-9]{4}") # device lock code: 4 characters, digits and upper-case letters + + +def device_locked(count_payload: bytes) -> bool: + """True if the answer to CMD_PRESET_COUNT says the DSP waits for its lock code.""" + return len(count_payload) > 5 and count_payload[5] != 0 def checksum(data: bytes) -> int: diff --git a/packaging/build.py b/packaging/build.py index 5d4ae45..60f57b1 100644 --- a/packaging/build.py +++ b/packaging/build.py @@ -58,6 +58,6 @@ pyinstaller("--name", "DSP Control", "--icon", str(ROOT / "packaging" / "dsp-con *data("static", "static"), str(ROOT / "desktop.py")) pyinstaller("--name", "DSP Control Pi Writer", "--icon", str(ROOT / "packaging" / "pi-writer.ico"), "--uac-admin", - *data("server.py"), *data("dsp", "dsp"), *data("static", "static"), str(ROOT / "pi_writer.py")) + *data("server.py"), *data("sim.py"), *data("dsp", "dsp"), *data("static", "static"), str(ROOT / "pi_writer.py")) print("\nDone:", *(p.name for p in (ROOT / "dist").glob("*.exe")), sep="\n ") diff --git a/pi_image.py b/pi_image.py index 4e080e1..9f41210 100644 --- a/pi_image.py +++ b/pi_image.py @@ -19,7 +19,7 @@ import server OS_LIST_URL = "https://downloads.raspberrypi.com/os_list_imagingutility_v4.json" IMAGE_NAMES = {64: "Raspberry Pi OS Lite (64-bit)", 32: "Raspberry Pi OS Lite (32-bit)"} -APP_FILES = ["server.py", "dsp", "static"] # what gets installed on the Pi +APP_FILES = ["server.py", "sim.py", "dsp", "static"] # what gets installed on the Pi USER_AGENT = "DSP-Control-Pi-Writer/1.0" # Pi models offered in the writer: (name, description, os bits) diff --git a/server.py b/server.py index b474e14..fbcfef4 100644 --- a/server.py +++ b/server.py @@ -21,6 +21,7 @@ import uuid from pathlib import Path from urllib.parse import parse_qs, urlsplit +import sim from dsp import preset, usbhid from dsp.device import Device @@ -112,6 +113,10 @@ class App: self.remote_error = "" self.locked = False # desktop app window read-only until unlocked with the PIN self.lang = "" # UI language chosen in the desktop app ("" = not chosen yet, English) + # demo mode: the real DSPs are disconnected and a simulated one runs inside the server + self.demo = {"enabled": False, "model": "408"} + self.demo_server: asyncio.Server | None = None + self.demo_resume: set[str] = set() # real devices to reconnect when the demo ends # ------------------------------------------------------------ config @@ -149,13 +154,13 @@ class App: def export_config(self) -> dict: """App backup: devices, PIN (hashed), amplifiers/limiter data, remote access - no logins.""" return {"format": CONFIG_FORMAT, "version": 1, "exported": time.strftime("%Y-%m-%dT%H:%M:%S"), - "devices": [d.config() for d in self.devices.values()], "auth": self.auth, + "devices": [d.config() for d in self.real_devices()], "auth": self.auth, "limiter": self.limiter, "remote": self.remote} async def restore_config(self, doc: dict, session: str): if not isinstance(doc, dict) or doc.get("format") != CONFIG_FORMAT: raise ValueError("Not a DSP Control settings backup") - for dev in list(self.devices.values()): + for dev in self.real_devices(): await dev.stop() del self.devices[dev.id] self.broadcast({"type": "removed", "device": dev.id}) @@ -204,7 +209,7 @@ class App: def save(self): sessions = {k: v for k, v in self.sessions.items() if k not in self.app_sessions} - cfg = {"devices": [d.config() for d in self.devices.values()], "auth": self.auth, + cfg = {"devices": [d.config() for d in self.real_devices()], "auth": self.auth, "sessions": sessions, "limiter": self.limiter, "remote": self.remote, "locked": self.locked} if self.lang: cfg["lang"] = self.lang @@ -216,14 +221,69 @@ class App: dev = Device(dev_id, d.get("name") or d.get("host") or "DSP (USB)", str(d.get("host") or ""), int(d.get("port", 9761)), str(d.get("model", "auto")), int(d.get("addr", 1)), bool(d.get("autoconnect", True)), on_event=self.broadcast, - transport="usb" if usb else "tcp", usb=str(d.get("usb") or "")) + transport="usb" if usb else "tcp", usb=str(d.get("usb") or ""), + lock_code=str(d.get("lock_code") or ""), auto_unlock=bool(d.get("auto_unlock"))) self.devices[dev_id] = dev if dev.autoconnect: - dev.start() + if self.demo["enabled"]: + self.demo_resume.add(dev_id) + else: + dev.start() if save: self.save() return dev + def real_devices(self) -> list[Device]: + return [d for d in self.devices.values() if not d.demo] + + # ------------------------------------------------------------ demo mode + + def demo_info(self) -> dict: + return {**self.demo, "error": ""} + + async def set_demo(self, body: dict) -> dict: + enabled = bool(body.get("enabled", self.demo["enabled"])) + model = body.get("model") if body.get("model") in ("204", "408") else self.demo["model"] + if self.demo["enabled"] and (not enabled or model != self.demo["model"]): + await self.stop_demo() + self.demo["model"] = model + if enabled and not self.demo["enabled"]: + await self.start_demo() + self.broadcast({"type": "demo", "data": self.demo_info()}) + return self.demo_info() + + async def start_demo(self): + """Disconnect the real DSPs and start a simulated one inside this server.""" + self.demo_resume = {d.id for d in self.real_devices() if d._want_connected} + for d in self.real_devices(): + await d.stop() + model = self.demo["model"] + logging.getLogger("sim").setLevel(logging.WARNING) + dsp = sim.SimDSP(model) + dsp.presets[1] = {**dsp.presets[0], "preset_name": "Demo"} + self.demo_server = await asyncio.start_server(dsp.serve, "127.0.0.1", 0) + port = self.demo_server.sockets[0].getsockname()[1] + dev = Device("demo", f"Demo DSP {model}", "127.0.0.1", port, model, autoconnect=False, on_event=self.broadcast) + dev.demo = True + self.devices[dev.id] = dev + self.demo["enabled"] = True + self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()}) + dev.start() + + async def stop_demo(self): + dev = self.devices.pop("demo", None) + if dev: + await dev.stop() + self.broadcast({"type": "removed", "device": dev.id}) + if self.demo_server: + self.demo_server.close() + self.demo_server = None + self.demo["enabled"] = False + for dev_id in self.demo_resume: + if dev_id in self.devices: + self.devices[dev_id].start() + self.demo_resume = set() + # ------------------------------------------------------------ auth def set_pin(self, pin: str, save=True): @@ -356,6 +416,9 @@ class App: async def shutdown(self): self.stop_remote() + if self.demo["enabled"]: + self.demo_resume = set() + await self.stop_demo() for d in self.devices.values(): await d.stop() @@ -375,6 +438,8 @@ class App: return [d.snapshot() for d in self.devices.values()] if path == "/api/devices" and method == "POST": return self.add_device(body).snapshot() + if path == "/api/demo": + return await self.set_demo(body) if method == "PUT" else self.demo_info() if path == "/api/usb" and method == "GET": return await asyncio.to_thread(usbhid.list_devices) if path == "/api/limiter" and method == "GET": @@ -389,6 +454,10 @@ class App: raise KeyError(path) dev = self.devices[m.group(1)] action = "/".join(g for g in m.groups()[1:] if g) + if dev.demo and (method in ("DELETE", "PUT") or action in ("unlock", "lockcode")): + raise RuntimeError("Not available for the demo device") + if self.demo["enabled"] and not dev.demo and action == "connect": + raise RuntimeError("Demo mode is on – switch it off to connect the real DSPs") if method == "DELETE" and not action: await dev.stop() del self.devices[dev.id] @@ -408,6 +477,10 @@ class App: setattr(dev, k, int(body[k])) if "autoconnect" in body: dev.autoconnect = bool(body["autoconnect"]) + if "auto_unlock" in body: + dev.auto_unlock = bool(body["auto_unlock"]) + if body.get("lock_code") == "": + dev.lock_code, dev.auto_unlock = "", False # forget the remembered code self.save() if was_running: dev.start() @@ -446,6 +519,19 @@ class App: if action == "refresh": await dev.refresh() return {"ok": True} + if action == "unlock": # hardware lock of the DSP, independent of the app lock + code = str(body.get("code") or "").strip().upper() + ok = await dev.unlock(code) + if ok and body.get("remember"): + dev.lock_code, dev.auto_unlock = code, True + self.save() + self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()}) + return {"ok": ok} + if action == "lockcode": + await dev.set_lock_code(body.get("code")) + self.save() + self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()}) + return {"ok": True} raise KeyError(path) # ------------------------------------------------------------ HTTP @@ -608,7 +694,8 @@ class App: q: asyncio.Queue = asyncio.Queue() self.clients.add(q) try: - hello = {"type": "hello", "devices": [d.snapshot() for d in self.devices.values()], "limiter": self.limiter} + hello = {"type": "hello", "devices": [d.snapshot() for d in self.devices.values()], "limiter": self.limiter, + "demo": self.demo_info()} writer.write(f"data: {json.dumps(hello)}\n\n".encode()) await writer.drain() while True: diff --git a/sim.py b/sim.py index 490faed..887ebcd 100644 --- a/sim.py +++ b/sim.py @@ -2,6 +2,7 @@ Usage: python sim.py --model 204 --port 9761 python sim.py --model 408 --port 9762 + python sim.py --model 204 --port 9761 --lock A1BA (asks for that lock code on every connection) """ import argparse @@ -17,8 +18,10 @@ log = logging.getLogger("sim") class SimDSP: - def __init__(self, model_key: str): + def __init__(self, model_key: str, lock_code: str = ""): self.key = model_key + self.lock_code = lock_code # hardware lock: "" = none + self.unlocked = not lock_code self.model = P.MODELS[model_key] self.state = P.default_state(self.model) self.presets = [copy.deepcopy(self.state) if i == 0 else None for i in range(20)] @@ -33,7 +36,15 @@ class SimDSP: if cmd == P.CMD_DEVICE_INFO: return cmd, f"DSP{self.key} V010 SIM".encode() if cmd == P.CMD_PRESET_COUNT: - return cmd, bytes([0, len(self.presets)]) + return cmd, bytes([0, 0, 0, 0, 0, 0 if self.unlocked else 1]) + if cmd == P.CMD_UNLOCK: + self.unlocked = self.unlocked or p[1:5].decode("latin1") == self.lock_code + return cmd, bytes([0, 1 if self.unlocked else 0]) + if cmd == P.CMD_SET_LOCK_CODE: + self.lock_code = p[:4].decode("latin1") + return P.CMD_ACK, b"\x00" + if not self.unlocked and cmd not in (P.CMD_HANDSHAKE, P.CMD_METER, P.CMD_LOGOUT): + return P.CMD_ACK, b"\x00" # locked: ignores everything until the code was entered if cmd == P.CMD_PRESET_NAME: return cmd, bytes([p[0]]) + self.preset_names()[p[0]].encode("latin1").ljust(14, b" ") if cmd == P.CMD_CONFIG_REQUEST: @@ -72,6 +83,7 @@ class SimDSP: async def serve(self, reader, writer): peer = writer.get_extra_info("peername") log.info("client %s connected", peer) + self.unlocked = not self.lock_code parser = P.FrameParser() try: while data := await reader.read(4096): @@ -92,9 +104,10 @@ async def main(): ap.add_argument("--model", choices=list(P.MODELS), default="204") ap.add_argument("--port", type=int, default=P.PORT) ap.add_argument("--host", default="127.0.0.1") + ap.add_argument("--lock", default="", help="lock code (4 characters A-Z/0-9) the DSP asks for") args = ap.parse_args() logging.basicConfig(level=logging.INFO, format=f"%(asctime)s sim{args.model} %(message)s") - sim = SimDSP(args.model) + sim = SimDSP(args.model, args.lock.upper()) server = await asyncio.start_server(sim.serve, args.host, args.port) log.info("simulated DSP %s on %s:%d", args.model, args.host, args.port) async with server: diff --git a/static/app.js b/static/app.js index a1bdb2c..79b9e8f 100644 --- a/static/app.js +++ b/static/app.js @@ -60,6 +60,7 @@ const S = { sel: { kind: "in", idx: 0 }, band: 0, busy: false, dirty: false, routeOpen: null, es: null, linkSel: { in: [], out: [] }, lim: { amps: [], assign: {}, ref: {} }, + demo: { enabled: false, model: "408" }, }; const $ = sel => document.querySelector(sel); const main = $("#main"); @@ -510,19 +511,116 @@ requestAnimationFrame(meterFrame); function renderTabs() { const tabs = $("#devtabs"); - tabs.replaceChildren(...S.order.map(id => { + const order = [...S.order].sort((a, b) => !!S.devices[b].demo - !!S.devices[a].demo); // demo tab first + tabs.replaceChildren(...order.map(id => { const d = S.devices[id]; const model = d.detected_model || (d.model !== "auto" ? d.model : ""); - return h("button", { class: "devtab" + (id === S.cur && !S.settings ? " active" : ""), title: `${d.name} · ${where(d)}`, - onclick: () => { S.cur = id; S.settings = false; store.set("dsp.cur", id); render(); } }, - h("span", { class: "dot " + d.status }), h("span", { class: "dn" }, d.name), model ? h("small", {}, model) : null); + const paused = S.demo.enabled && !d.demo; // demo mode: the real DSPs are disconnected + return h("button", { class: "devtab" + (id === S.cur && !S.settings ? " active" : "") + (paused ? " paused" : "") + (d.demo ? " demo" : ""), + title: paused ? t("Disconnected while demo mode is on") : d.demo ? t("Demo mode – simulated DSP") : `${d.name} · ${where(d)}`, + disabled: paused, onclick: () => { S.cur = id; S.settings = false; store.set("dsp.cur", id); render(); } }, + h("span", { class: "dot " + d.status }), h("span", { class: "dn" }, d.name), + d.demo ? h("small", { class: "demo-badge" }, "DEMO") : model ? h("small", {}, model) : null); })); $("#btn-settings").classList.toggle("on", S.settings); document.querySelectorAll("#viewtabs button").forEach(b => b.classList.toggle("active", !S.settings && b.dataset.view === S.view)); } const STATUS_TEXT = { disconnected: t("Disconnected"), connecting: t("Connecting…"), loading: t("Loading configuration…"), - online: "Online", error: t("Error") }; + locked: t("Locked with a code"), online: "Online", error: t("Error") }; + +// ------------------------------------------------------------------ hardware lock of the DSP (not the app lock) + +const LOCK_RE = /^[A-Z0-9]{4}$/; +const codeInput = () => { + const el = h("input", { type: "text", maxlength: 4, autocomplete: "off", autocapitalize: "characters", spellcheck: "false", + class: "code", placeholder: "A1B2", "aria-label": t("Lock code") }); + el.addEventListener("input", () => { el.value = el.value.toUpperCase().replace(/[^A-Z0-9]/g, "").slice(0, 4); }); + return el; +}; + +async function unlockDialog(d) { + let error = ""; + for (;;) { + const code = codeInput(); + const remember = h("input", { type: "checkbox", checked: !!d.auto_unlock || !d.lock_code }); + const res = await modal({ + title: t("DSP locked"), + body: h("div", {}, + h("p", { class: "dlg-text" }, t("{name} is locked with a code. Enter the 4-character code (digits and letters A–Z).", { name: q(d.name) })), + code, + error ? h("div", { class: "err" }, error) : null, + h("label", { class: "chk" }, remember, t("Remember the code and unlock automatically"))), + actions: [{ label: t("Cancel") }, + { label: t("Unlock"), primary: true, value: () => LOCK_RE.test(code.value) ? { code: code.value, remember: remember.checked } : (code.focus(), undefined) }], + }); + if (!res) return false; + try { + const r = await api("POST", `/api/devices/${d.id}/unlock`, res); + if (r.ok) { toast(t("DSP unlocked")); return true; } + error = t("Wrong code – please try again."); + } catch (e) { error = trMsg(e.message); } + } +} + +// ask once per lock episode when the DSP on screen turns out to be locked +const lockAsked = new Set(); +function maybeAskUnlock(d) { + if (d.status !== "locked") { lockAsked.delete(d.id); return; } + if (lockAsked.has(d.id) || d.id !== S.cur || S.settings || S.locked) return; + lockAsked.add(d.id); + setTimeout(() => unlockDialog(S.devices[d.id] || d), 50); +} + +const lockOpen = new Set(); // device ids whose lock section is open (survives re-rendering) +function lockSection(d) { + const online = d.status === "online"; + const auto = h("input", { type: "checkbox", checked: !!d.auto_unlock, disabled: !d.lock_code, + onchange: () => api("PUT", `/api/devices/${d.id}`, { auto_unlock: auto.checked }).catch(e => toast(e.message)) }); + const code = codeInput(); + const setCode = async () => { + if (!LOCK_RE.test(code.value)) { code.focus(); return toast(t("The code has 4 characters: digits and letters A–Z")); } + if (!await askConfirm(t("Set lock code"), t("From the next connection on, {name} asks for the code {code} – also in the original software. Note it down: this app cannot remove the lock again.", + { name: q(d.name), code: code.value }), t("Set code"), true)) return; + try { await api("POST", `/api/devices/${d.id}/lockcode`, { code: code.value }); toast(t("Lock code set")); } + catch (e) { toast(t("Error: ") + trMsg(e.message)); } + }; + const box = h("details", { class: "more full lockbox", open: lockOpen.has(d.id), + ontoggle: () => box.open ? lockOpen.add(d.id) : lockOpen.delete(d.id) }, + h("summary", {}, t("Device lock (code)"), d.lock_code ? h("span", { class: "tag" }, t("code remembered")) : null), + h("p", { class: "info" }, t("Hardware lock of the DSP: a locked DSP only accepts a connection after its code was entered. Independent of the lock of this app.")), + h("label", { class: "chk" }, auto, t("Unlock automatically with the remembered code")), + d.lock_code + ? h("div", { class: "row" }, h("span", { class: "grow info" }, t("A code is remembered for this DSP.")), + h("button", { class: "small", onclick: () => api("PUT", `/api/devices/${d.id}`, { lock_code: "" }).then(() => toast(t("Code forgotten"))).catch(e => toast(e.message)) }, t("Forget code"))) + : h("div", { class: "info" }, t("No code remembered – it is asked for when the DSP is locked.")), + h("div", { class: "sub" }, t("Set a new lock code")), + h("div", { class: "row" }, code, h("button", { class: "small", disabled: !online, onclick: setCode }, t("Set code"))), + online ? null : h("div", { class: "info" }, t("Connect the DSP to set a code."))); + return box; +} + +// ------------------------------------------------------------------ demo mode + +async function setDemo(body) { + try { + S.demo = await api("PUT", "/api/demo", body); + if (S.demo.enabled) { S.cur = "demo"; S.settings = false; S.view = "mixer"; } + render(); + } catch (e) { toast(t("Error: ") + trMsg(e.message)); } +} + +function demoCard() { + const on = S.demo.enabled; + return h("div", { class: "card" + (on ? " demo-on" : "") }, + h("h3", {}, h("span", { class: "grow" }, t("Demo mode")), on ? h("span", { class: "demo-badge" }, "DEMO") : null), + h("p", { class: "info" }, t("Try everything with a simulated DSP – nothing is sent to real devices. While demo mode is on, the real DSPs are disconnected.")), + h("div", { class: "row" }, + h("div", { class: "seg grow" }, [[false, t("Off")], [true, t("On")]].map(([v, label]) => + h("button", { class: v === on ? "on" : "", "aria-pressed": String(v === on), onclick: () => v !== on && setDemo({ enabled: v }) }, label))), + h("div", { class: "seg" }, ["204", "408"].map(m => + h("button", { class: m === S.demo.model ? "on" : "", onclick: () => m !== S.demo.model && setDemo({ model: m }) }, "DSP " + m))))); +} async function storePresetDialog(d) { const slot = h("select", {}, d.presets.map((p, i) => h("option", { value: i }, `U${String(i + 1).padStart(2, "0")} ${p || t("— empty —")}`))); @@ -603,8 +701,11 @@ function renderStatus() { bar.replaceChildren( h("div", { class: "preset" }, h("small", {}, `${STATUS_TEXT[d.status] || d.status} · ${d.transport === "usb" ? "USB" : d.host + ":" + d.port}`), h("b", {}, d.name), d.error ? h("div", { class: "err" }, trMsg(d.error)) : null), - d.status === "disconnected" || d.status === "error" - ? h("button", { class: "on", onclick: () => api("POST", `/api/devices/${d.id}/connect`).catch(e => toast(e.message)) }, t("Connect")) + d.status === "locked" + ? h("div", { class: "presetrow" }, h("button", { class: "on", onclick: () => unlockDialog(d) }, t("Enter code")), + h("button", { onclick: () => api("POST", `/api/devices/${d.id}/disconnect`) }, t("Disconnect"))) + : d.status === "disconnected" || d.status === "error" + ? h("button", { class: "on", disabled: S.demo.enabled && !d.demo, onclick: () => api("POST", `/api/devices/${d.id}/connect`).catch(e => toast(trMsg(e.message))) }, t("Connect")) : h("button", { onclick: () => api("POST", `/api/devices/${d.id}/disconnect`) }, t("Cancel"))); return; } @@ -622,7 +723,7 @@ function renderStatus() { presetSel.disabled = false; }); bar.replaceChildren( - h("div", { class: "preset" }, h("small", {}, `${d.info || d.name} · ${where(d)}`), h("b", {}, d.state.preset_name || "—")), + h("div", { class: "preset" }, h("small", {}, d.demo ? t("Demo mode · simulated DSP") : `${d.info || d.name} · ${where(d)}`), h("b", {}, d.state.preset_name || "—")), h("div", { class: "presetrow" }, presetSel, h("button", { onclick: () => storePresetDialog(d) }, t("Save")), h("button", { onclick: () => presetFileDialog(d), title: t("Export / import preset"), "data-view-ok": "" }, t("File…")))); } @@ -1348,7 +1449,7 @@ function deviceForm(d) { : [ h("button", { onclick: async () => { try { await api("PUT", `/api/devices/${d.id}`, values()); toast(t("Saved")); } catch (e) { toast(e.message); } } }, t("Save")), d.status === "disconnected" || d.status === "error" - ? h("button", { class: "on", onclick: async () => { // connects with what the form shows, saved or not + ? h("button", { class: "on", disabled: S.demo.enabled, onclick: async () => { // connects with what the form shows, saved or not try { await api("PUT", `/api/devices/${d.id}`, values()); await api("POST", `/api/devices/${d.id}/connect`); } catch (e) { toast(e.message); } } }, t("Connect")) @@ -1358,7 +1459,9 @@ function deviceForm(d) { await api("DELETE", `/api/devices/${d.id}`).catch(e => toast(e.message)); } }, t("Remove")), ]; - return h("div", { class: "card" }, + const paused = S.demo.enabled && !isNew; + return h("div", { class: "card" + (paused ? " paused" : "") }, + paused ? h("div", { class: "info" }, t("Disconnected while demo mode is on")) : null, h("h3", {}, isNew ? null : h("span", { class: "dot " + d.status }), h("span", { class: "grow" }, isNew ? t("New device") : d.name), isNew ? null : h("span", { class: "info" }, STATUS_TEXT[d.status])), !isNew && d.info ? h("div", { class: "info" }, t("Device reports: ") + d.info) : null, @@ -1369,6 +1472,7 @@ function deviceForm(d) { ...netRows, usbRow, h("label", {}, t("Model"), f.model), h("label", { class: "chk" }, f.autoconnect, t("Connect automatically")), + isNew ? null : lockSection(d), h("div", { class: "actions" }, actions))); } @@ -1471,9 +1575,9 @@ function langCard() { function viewSettings() { return [ - h("div", { class: "cards" }, langCard()), + h("div", { class: "cards" }, langCard(), demoCard()), h("h2", { class: "section" }, t("Devices")), - h("div", { class: "cards" }, ...S.order.map(id => deviceForm(S.devices[id])), deviceForm(null)), + h("div", { class: "cards" }, ...S.order.filter(id => !S.devices[id].demo).map(id => deviceForm(S.devices[id])), deviceForm(null)), h("p", { class: "info" }, t("Both DSPs can be connected at the same time – switch between them at the top. "), t("The DSPs accept only one connection: close the Thomann editor first.")), h("h2", { class: "section" }, S.isApp ? t("Remote access") : t("Security")), @@ -1508,12 +1612,16 @@ function render() { else if (d.status !== "online" || !d.state) content = h("div", { class: "empty" }, h("div", { class: "spinner" + (["loading", "connecting"].includes(d.status) ? "" : " off") }), d.status === "loading" ? t("Loading the configuration from the DSP…") - : d.status === "connecting" ? t("Connecting to {where}…", { where: where(d) }) : t("Not connected.")); + : d.status === "connecting" ? t("Connecting to {where}…", { where: where(d) }) + : d.status === "locked" ? h("div", {}, h("p", {}, t("This DSP is locked with a code.")), + h("button", { class: "on", onclick: () => unlockDialog(d) }, t("Enter code"))) + : S.demo.enabled && !d.demo ? t("Disconnected while demo mode is on") : t("Not connected.")); else content = ({ mixer: viewMixer, channel: viewChannel, routing: viewRouting, link: viewLink, limiter: viewLimiter }[S.view] || viewMixer)(d); main.replaceChildren(...[content].flat().filter(Boolean)); main.querySelectorAll(H_SCROLL).forEach((e, i) => { if (xs[i]) e.scrollLeft = xs[i]; }); window.scrollTo(0, y); collectMeters(); + if (d) maybeAskUnlock(d); } // flush deferred renders once a text field loses focus main.addEventListener("focusout", () => setTimeout(() => { @@ -1596,6 +1704,9 @@ function connectEvents() { case "hello": setDevices(ev.devices); if (ev.limiter) S.lim = ev.limiter; + if (ev.demo) S.demo = ev.demo; + if (S.demo.enabled && S.devices.demo && !S.devices[S.cur]?.demo) S.cur = "demo"; + S.order.forEach(id => maybeAskUnlock(S.devices[id])); if (!S.order.length) S.settings = true; render(); break; case "device": @@ -1610,8 +1721,13 @@ function connectEvents() { if (!d) break; Object.assign(d, { status: ev.status, error: ev.error, info: ev.info }); if (ev.status !== "online") render(); else renderTabs(); + maybeAskUnlock(d); break; } + case "demo": + S.demo = ev.data; + if (!S.demo.enabled && S.cur === "demo") S.cur = S.order.find(id => id !== "demo") || null; + render(); break; case "param": { const d = S.devices[ev.device]; if (!d || !d.state) break; diff --git a/static/i18n.js b/static/i18n.js index abefc7e..f51651b 100644 --- a/static/i18n.js +++ b/static/i18n.js @@ -286,7 +286,41 @@ const DE = { "{pct} % of {rated}": "{pct} % von {rated}", "— empty —": "— leer —", "— no amplifier —": "— kein Verstärker —", - "“{s}”": "„{s}“" + "“{s}”": "„{s}“", + // device lock, demo mode + "A code is remembered for this DSP.": "Für diesen DSP ist ein Code gespeichert.", + "Code forgotten": "Code vergessen", + "Connect the DSP to set a code.": "Zum Festlegen eines Codes den DSP verbinden.", + "DSP locked": "DSP gesperrt", + "DSP unlocked": "DSP entsperrt", + "Device lock (code)": "Gerätesperre (Code)", + "Enter code": "Code eingeben", + "Forget code": "Code vergessen", + "From the next connection on, {name} asks for the code {code} – also in the original software. Note it down: this app cannot remove the lock again.": "Ab der nächsten Verbindung fragt {name} nach dem Code {code} – auch in der Original-Software. Bitte notieren: Diese App kann die Sperre nicht wieder entfernen.", + "Hardware lock of the DSP: a locked DSP only accepts a connection after its code was entered. Independent of the lock of this app.": "Sperre im DSP selbst: Ein gesperrter DSP lässt sich erst nach Eingabe seines Codes bedienen. Unabhängig von der Sperre dieser App.", + "Lock code": "Sperrcode", + "Lock code set": "Sperrcode festgelegt", + "Locked with a code": "Mit Code gesperrt", + "No code remembered – it is asked for when the DSP is locked.": "Kein Code gespeichert – er wird abgefragt, wenn der DSP gesperrt ist.", + "Remember the code and unlock automatically": "Code merken und automatisch entsperren", + "Set a new lock code": "Neuen Sperrcode festlegen", + "Set code": "Code festlegen", + "Set lock code": "Sperrcode festlegen", + "The code has 4 characters: digits and letters A–Z": "Der Code hat 4 Zeichen: Ziffern und Buchstaben A–Z", + "This DSP is locked with a code.": "Dieser DSP ist mit einem Code gesperrt.", + "Unlock automatically with the remembered code": "Mit dem gespeicherten Code automatisch entsperren", + "Wrong code – please try again.": "Falscher Code – bitte erneut versuchen.", + "code remembered": "Code gespeichert", + "{name} is locked with a code. Enter the 4-character code (digits and letters A–Z).": "{name} ist mit einem Code gesperrt. Bitte den 4-stelligen Code eingeben (Ziffern und Buchstaben A–Z).", + "The DSP is not locked": "Der DSP ist nicht gesperrt", + "The remembered lock code was rejected": "Der gespeicherte Sperrcode wurde abgelehnt", + "Demo mode": "Demo-Modus", + "Demo mode · simulated DSP": "Demo-Modus · simulierter DSP", + "Demo mode – simulated DSP": "Demo-Modus – simulierter DSP", + "Disconnected while demo mode is on": "Getrennt, solange der Demo-Modus aktiv ist", + "Try everything with a simulated DSP – nothing is sent to real devices. While demo mode is on, the real DSPs are disconnected.": "Alles gefahrlos mit einem simulierten DSP ausprobieren – an echte Geräte wird nichts gesendet. Solange der Demo-Modus aktiv ist, sind die echten DSPs getrennt.", + "Not available for the demo device": "Für das Demo-Gerät nicht verfügbar", + "Demo mode is on – switch it off to connect the real DSPs": "Der Demo-Modus ist aktiv – zum Verbinden der echten DSPs bitte ausschalten", }; const DE_PATTERNS = [ diff --git a/static/style.css b/static/style.css index d97329e..b73b73b 100644 --- a/static/style.css +++ b/static/style.css @@ -442,3 +442,23 @@ body.locked #statusbar :is(button, select):not([data-view-ok]) { cursor: not-all .limled.h { width: auto; height: auto; margin: 0; padding: 2px 6px; font-size: 10px; font-weight: 700; letter-spacing: .06em; color: color-mix(in srgb, var(--led-o) 45%, transparent); } .limled.h.on { color: #1a1000; } + +/* ---- demo mode */ +.demo-badge { font-size: 10px; font-weight: 700; letter-spacing: .08em; color: #1a1000 !important; + background: var(--warn) !important; border-radius: 5px; padding: 1px 6px; } +.devtab.demo { border-color: var(--warn); } +.devtab.paused, .card.paused { opacity: .45; } +.devtab.paused { cursor: not-allowed; } +.card.demo-on { border-color: var(--warn); } + +/* ---- device lock (hardware) */ +input.code { width: 7.5em; text-align: center; font-family: ui-monospace, Menlo, Consolas, monospace; + font-size: 20px; letter-spacing: .3em; text-transform: uppercase; } +.dialog input.code { display: block; margin: 8px auto 4px; } +.lockbox .row { align-items: center; gap: 8px; margin: 6px 0; } +.lockbox .sub { margin-top: 10px; } +.dot.locked { background: var(--warn); } +.dialog label.chk { display: flex; align-items: center; gap: 8px; margin-top: 12px; font-size: 14px; } +.dialog label.chk input { width: 20px; height: 20px; } +.dialog .err { text-align: center; } +.lockbox input.code { flex: none; width: 7.5em; } diff --git a/tests/test_protocol.py b/tests/test_protocol.py index 024e2e9..6a8e0e7 100644 --- a/tests/test_protocol.py +++ b/tests/test_protocol.py @@ -120,6 +120,23 @@ def test_channel_names(): assert P.param_command(m, "in", 0, {"name": "Süd"}, "name") == (0x3D, b"\x00Sued ") +def test_device_lock(): + # answer to 0x2C: [time lock][4 bytes time lock data][device lock] + assert P.device_locked(bytes([0, 0, 0, 0, 0, 1])) + assert not P.device_locked(bytes([0, 0, 0, 0, 0, 0])) + assert not P.device_locked(bytes([0, 20])) # short answer: no lock information + assert P.LOCK_CODE.fullmatch("A1BA") and not P.LOCK_CODE.fullmatch("a1ba") and not P.LOCK_CODE.fullmatch("A1B") + assert P.build_frame(P.CMD_UNLOCK, b"\x00A1BA")[5:11] == bytes([0x2D, 0x00]) + b"A1BA" + import sim + dsp = sim.SimDSP("204", "A1BA") + assert P.device_locked(dsp.handle(P.CMD_PRESET_COUNT, b"")[1]) + assert dsp.handle(P.CMD_UNLOCK, b"\x00ZZZZ") == (P.CMD_UNLOCK, bytes([0, 0])) + assert dsp.handle(P.CMD_UNLOCK, b"\x00A1BA") == (P.CMD_UNLOCK, bytes([0, 1])) + assert not P.device_locked(dsp.handle(P.CMD_PRESET_COUNT, b"")[1]) + dsp.handle(P.CMD_SET_LOCK_CODE, b"B2C3") + assert dsp.lock_code == "B2C3" + + if __name__ == "__main__": for name, fn in list(globals().items()): if name.startswith("test_"):