# CLAUDE.md – guide for AI coding assistants BetterDSPControl controls t.racks DSP 204 / DSP 408 loudspeaker processors. Read `README.md` (features, usage) and `PROTOCOL.md` (wire protocol) first. This file explains how the code is built and what to watch out for. ## Architecture ``` browser / phone ──HTTP + SSE──► server.py (asyncio, stdlib only) ──► dsp/device.py ──TCP 9761 or USB HID──► DSP ▲ desktop.py (pywebview window, logs in with a one-time token, no PIN) pi_writer.py → pi_image.py (cloud-init SD card, installs server.py as a systemd service on a Raspberry Pi) ``` * **`server.py`** – own HTTP server on `asyncio.start_server` (no framework). JSON API under `/api/…`, live updates as server-sent events on `/api/events` (`App.broadcast`). `App` holds devices, auth, limiter data, remote access, backups. Config is one JSON file (`config.json`, gitignored) – `load()` / `apply_config()` / `save()`. * **Auth** – 4-digit PIN, PBKDF2 hash in `config.json`, session cookie `dspsess` (30 days), lockout after 5 failures. The desktop app logs in via `/app-login?t=`; app sessions live in memory only, skip the PIN and may toggle remote access (`/api/remote`) and the lock (`/api/lock`, server answers 423 while locked). Remote clients always need the PIN. * **`dsp/device.py`** – one `Device` per DSP: connect (TCP or `usbhid.open_stream`), handshake, config dump (50-byte chunks), command queue (one request in flight), meter polling (also keepalive), auto-reconnect. Mirrors changes within link groups locally and re-reads the config ~1.5 s after the last change (resync). * **`dsp/protocol.py`** – frames, checksum, value scales, model layouts (`MODELS["204"|"408"]`), memory image ↔ state dict (`parse_state` / `build_state_buffer`), parameter → command (`param_command`), link masks, meter/limiter decoding. State values are **raw device values**; conversion to dB/Hz/ms happens in the UI (`SPEC` in `app.js`). Channels also carry `peq_bypass` (master bypass, `0x3C`) and inputs `geq_bypass` (`0x49`), stored as bit masks at the end of the memory image. * **EQ curve** (`app.js`, `drawCurve`) – complex response per section: PEQ bands as RBJ biquads at 96 kHz, crossover filters from analog prototypes (Butterworth poles, Bessel polynomial normalised to −3 dB, Linkwitz-Riley = Butterworth²). Mag/Phase view (`dsp.curve` in localStorage), overlays of other channels (`dsp.overlay.`). How exactly the DSP realises the Bessel and crossover filters is not verified – the curves are the textbook ones. * **Audio test** – `App.audio_test` / `set_test_level` / `check_audio_test` in `server.py`: entering saves the output gains (`Device.test_saved`, persisted in `config.json` so an interrupted test is undone on the next connect), lowers every output to −50 dB, flushes the queue and only then starts the generator (`0x39`); leaving switches the generator off first, then restores the gains. While `Device.test_active`, preset store/recall/import/export are refused. The state field is `state["test"] = {source, freq}`. * **`dsp/preset.py`** – preset files (`dsp-control-preset` JSON with state + raw image), validation, and the minimal command sequence for an import. Undo backups go to `backups/` next to `config.json` (last 20 per device). * **`dsp/usbhid.py`** – HID via ctypes only: Windows `hid.dll`/SetupAPI, macOS IOKit, Linux `/dev/hidraw*`. `HidStream` adapts a blocking reader thread to the asyncio stream interface `device.py` expects. * **`static/`** – single-page app in vanilla JS. `h()` builds DOM, `S` is the global state, `render()` redraws the 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, 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`. * **`pi_writer.py` / `pi_image.py` / `win_disk.py`** – Windows-only tkinter tool that downloads Raspberry Pi OS Lite (official image list), writes it raw to an SD card (`\\.\PhysicalDriveN`, verify by SHA-256) and adds cloud-init files (`user-data`, `network-config`, `meta-data`) plus an `install.sh` that installs the app on first boot. ## Conventions * **Server and `dsp/` use the Python standard library only.** pywebview/PyInstaller/Pillow are only for the desktop builds. No build step for the web UI. * Source texts are English. Every new `t("…")` string needs a German entry in `static/i18n.js`; server error messages that reach the UI need one too (exact text in `DE`, or a regex in `DE_PATTERNS`). Technical terms (Gain, Threshold, Mixer, Routing, Link, Limiter) stay English in German too. * Native/desktop apps never ask for the PIN; the web UI and remote access always do. * Channel names: max 8 printable ASCII characters (umlauts are transliterated), and they must fit the mixer strip. * Keep comments sparse and factual, match the surrounding style. * `README.md` and `PROTOCOL.md` are English. The Pi Writer UI is still German. ## Testing ```bash python tests/test_protocol.py python sim.py --model 204 --port 9761 python sim.py --model 408 --port 9762 python server.py --port 8080 --config .json ``` Log in with PIN `1234`, add devices `127.0.0.1:9761` / `:9762`. Check both languages after UI changes (⚙ → Language / Sprache). For the desktop app run `python desktop.py` (needs `pywebview`). **Never change values on a real DSP permanently while testing.** Export a preset file first (File… → Export) and restore it afterwards; prefer the simulator. The DSP accepts only one connection – close other control software. ## Verified vs. unverified Verified on a real DSP 204 (firmware V0104P, USB on macOS): connect/dump/meters, set commands, link command `0x3B` and the DSP's own mirroring inside groups, limiter-active bit mask, preset import writing only differences. Not verified yet – ask for a log (`python server.py -v`) from real hardware before changing protocol code here: * **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; where the number of preset slots comes from (20 is assumed when the `0x2C` answer carries the lock state) * Master bypass commands `0x3C` / `0x49` and their bit masks – from the control software, simulator only * Test signal command `0x39` and its position in the memory image – derived from the control software, simulator only; whether the generator is pre or post input gain is unknown (the app therefore only lowers the outputs) * 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) ## Legal notes for contributors Do not add code, binaries, firmware, screenshots, manuals or internal symbol names/addresses from the manufacturer's software. Document protocol facts only as observed behaviour. Use "t.racks"/"Thomann" only to name the supported devices and keep the "not affiliated" notice in the README.