Add BetterDSPControl: web UI, desktop app and Pi writer for t.racks DSP 204/408
- Python stdlib server with SSE live updates, PIN login, remote access - Vanilla JS web UI (English/German): mixer, channel, routing, links, limiter calculator - Preset file export/import with undo, settings backup, lock for the desktop app - Network (TCP 9761) and USB HID transport (Windows, macOS, Linux) - Desktop app via pywebview, Raspberry Pi SD card writer, simulator and protocol tests - README with import guide for Claude Code, CLAUDE.md, protocol documentation Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ce02ae65a9
commit
fe13f261f7
31 files changed
+6445
No files matched your search
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"version": "0.0.1",
|
||||
"configurations": [
|
||||
{"name": "sim-204", "runtimeExecutable": "python", "runtimeArgs": ["sim.py", "--model", "204", "--port", "9761"], "port": 9761},
|
||||
{"name": "sim-408", "runtimeExecutable": "python", "runtimeArgs": ["sim.py", "--model", "408", "--port", "9762"], "port": 9762},
|
||||
{"name": "webui", "runtimeExecutable": "python", "runtimeArgs": ["server.py", "--port", "8080"], "port": 8080}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
* text=auto eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.png binary
|
||||
*.ico binary
|
||||
*.icns binary
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
# local data – contains the PIN hash, logins and personal presets
|
||||
config.json
|
||||
backups/
|
||||
Sicherungen/
|
||||
|
||||
# build output and tools
|
||||
.venv/
|
||||
build/
|
||||
dist/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.DS_Store
|
||||
|
||||
# personal Claude Code settings
|
||||
.claude/settings.local.json
|
||||
@@ -0,0 +1,89 @@
|
||||
# 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=<one-time token>`; 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`).
|
||||
* **`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). Use it for all tests.
|
||||
* **`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 <some temp file>.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; payload of the
|
||||
preset-count answer (`0x2C`)
|
||||
* 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.
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
# t.racks DSP 204 / DSP 408 – control protocol
|
||||
|
||||
Documented for interoperability by observing the communication between the devices and their control software
|
||||
and by testing on real devices. Both models speak the same protocol; only the number of channels and the size
|
||||
of the memory image differ. Implementation: [`dsp/protocol.py`](dsp/protocol.py).
|
||||
|
||||
Status: the network transport and all commands below are implemented and tested against the simulator; links,
|
||||
the limiter status bits and USB were verified on a real DSP 204 (firmware V0104P). Points marked *assumed* are
|
||||
not verified yet.
|
||||
|
||||
## Transport
|
||||
|
||||
* **Network:** TCP, port **9761**. Factory default IP `192.168.1.101`.
|
||||
* **USB:** HID class device, no driver needed, **VID 0x0168 / PID 0x0821** (both models). See [USB](#usb-hid).
|
||||
* Request/response: send one command and wait for its answer before sending the next.
|
||||
* The DSP accepts only **one** connection at a time.
|
||||
|
||||
## Frame
|
||||
|
||||
```
|
||||
10 02 SRC DST LEN CMD PAYLOAD… 10 03 CHK
|
||||
```
|
||||
|
||||
| Field | Meaning |
|
||||
|-------|---------|
|
||||
| SRC/DST | PC→DSP: `00 01`, DSP→PC: `01 00` (`01` = device ID) |
|
||||
| LEN | `1 + len(PAYLOAD)` (includes CMD) |
|
||||
| CHK | XOR from `02` to `03`, i.e. `0x01 ^ SRC ^ DST ^ LEN ^ CMD ^ PAYLOAD…` |
|
||||
|
||||
There is **no byte stuffing** – a payload may contain `10 03`, so always parse by LEN.
|
||||
All 16-bit words are little endian.
|
||||
|
||||
## Read / system commands
|
||||
|
||||
| CMD | Direction | Payload | Meaning |
|
||||
|-----|-----------|---------|---------|
|
||||
| `10` | → | – | Handshake |
|
||||
| `13` | → / ← | – / ASCII | Device info, answer starts with `DSP204` or `DSP408` |
|
||||
| `2C` | → / ← | – / `[?][count]` | Number of presets (payload meaning partly *assumed*) |
|
||||
| `22`, `14` | → | – | Init queries (sent during connect, content unknown) |
|
||||
| `29` | → / ← | `[idx]` / `[idx][name…]` | Preset name (idx 0-based) |
|
||||
| `20` | → | `[idx+1]` | Recall preset |
|
||||
| `26` | → | `name[14]` | Set name for the next store |
|
||||
| `21` | → | `[idx+1]` | Store current state into preset |
|
||||
| `27` | → | `[chunk]` | Request config chunk |
|
||||
| `24` | ← | `[chunk][50 bytes]` | Config chunk; 204: chunks 0…14, 408: 0…28 |
|
||||
| `12` | → | – | Status (sent after the dump) |
|
||||
| `40` | → / ← | – / meters | Read levels (also serves as keepalive) |
|
||||
|
||||
### Meter answer
|
||||
|
||||
12 entries × 3 bytes `b0 b1 b2`, followed by 2 status bytes.
|
||||
|
||||
* Level = float32 from the bytes `00 b2 b0 b1` (little endian) → linear, dB = 20·log10.
|
||||
* Positions: 0–3 = In A–D, 4–11 = Out 1–8. The 204 uses 0, 1 and 4–7.
|
||||
* The level is measured before mute.
|
||||
* **Limiter active**: the status bytes are a bit mask of the outputs (bit 0 = Out 1). Measured on a DSP 204:
|
||||
`00 03` while Out 1+2 limit, `00 0C` for Out 3+4. That Out 5–8 of the 408 continue in the same 16-bit value
|
||||
is *assumed*.
|
||||
|
||||
## Channel numbers
|
||||
|
||||
| Device | Inputs | Outputs |
|
||||
|--------|--------|---------|
|
||||
| DSP 204 | In A=0, In B=1 | Out 1–4 = 2–5 |
|
||||
| DSP 408 | In A–D = 0–3 | Out 1–8 = 4–11 |
|
||||
|
||||
## Set commands
|
||||
|
||||
| CMD | Parameter | Payload |
|
||||
|-----|-----------|---------|
|
||||
| `34` | Gain | `[ch][u16 gain]` |
|
||||
| `35` | Mute | `[ch][0/1]` |
|
||||
| `36` | Polarity | `[ch][0/1]` |
|
||||
| `38` | Delay | `[ch][u16 delay]` |
|
||||
| `32` | High pass (low cut) | `[ch][u16 freq][slope]` |
|
||||
| `31` | Low pass (high cut) | `[ch][u16 freq][slope]` |
|
||||
| `33` | PEQ band | `[ch][band][u16 gain][u16 freq][q][type][bypass]` |
|
||||
| `48` | GEQ band (inputs) | `[ch][band 0–30][u16 gain]` |
|
||||
| `3E` | Gate (inputs) | `[ch][attack][release][hold][threshold]` (u16 each) |
|
||||
| `30` | Compressor (outputs) | `[ch][ratio][attack][release][knee][threshold]` |
|
||||
| `3F` | Limiter (outputs) | `[ch][attack][release][knee][threshold]` |
|
||||
| `3A` | Routing matrix (outputs) | `[ch][bit mask of inputs]` |
|
||||
| `41` | Mix level (outputs) | `[ch][input][u16 level]` |
|
||||
| `3D` | Channel name | `[ch][name 8]` (printable ASCII) |
|
||||
| `3B` | Link | `[ch][u16 link mask]` (see [Channel links](#channel-links)) |
|
||||
| `15` | Delay unit | `[unit]` (display only) |
|
||||
|
||||
The format of the acknowledgement the DSP sends after a set command is not fully understood yet.
|
||||
|
||||
## Value encoding
|
||||
|
||||
| Parameter | Raw | Conversion |
|
||||
|-----------|-----|------------|
|
||||
| Gain / mix level | 0–400 (mix 0–280) | `r<80: r/2−60 dB`, else `(r−280)/10 dB` → −60…+12 dB |
|
||||
| Frequency (PEQ, HP, LP) | 0–300 | `1000 · 2^((r−170)/30)` Hz → 19.7 Hz…20.16 kHz (1/30 octave) |
|
||||
| PEQ/GEQ gain | 0–240 | `(r−120)/10` dB → ±12 dB |
|
||||
| Q | 0–100 | table 0.4…128 (see `protocol.py`) |
|
||||
| PEQ type | 0–8 | Peak, Low shelf, High shelf, HPF −6, HPF −12, LPF −6, LPF −12, Allpass 1, Allpass 2 |
|
||||
| Slope | 0–20 | 0 = bypass, 1–20 = BW−6, BL−6, BW−12, BL−12, LK−12, … LK−48 |
|
||||
| Delay | 0–65280 | `r/96` ms (max 680 ms) |
|
||||
| Threshold (gate/comp/limit) | 0–220 | `(r−180)/2` dB (gate max 0 dB, comp/limit max +20 dB) |
|
||||
| Attack | 0–998 | `r+1` ms |
|
||||
| Release | 9–2999 | `r+1` ms |
|
||||
| Hold | 9–998 | `r+1` ms |
|
||||
| Ratio | 0–15 | 1.0, 1.1, 1.3, 1.5, 1.7, 2.0, 2.5, 3.0, 3.5, 4.0, 5.0, 6.0, 8.0, 10, 20, Limit |
|
||||
| Knee | 0–12 | dB |
|
||||
|
||||
The absolute output level that corresponds to 0 dB limiter threshold is not published; the app assumes 0 dBu.
|
||||
|
||||
## Channel links
|
||||
|
||||
Measured on a DSP 204 (firmware V0104P). Every channel has a u16 mask (bit = channel index within the inputs
|
||||
or within the outputs):
|
||||
|
||||
| Channel | Mask |
|
||||
|---------|------|
|
||||
| not linked | its own bit only (Out 3 = `04`) |
|
||||
| first channel of a group | bits of all members (Out 3+4 = `0C`) |
|
||||
| further members | `00` |
|
||||
|
||||
* Set with `3B [ch][mask]` – for every channel of the group (first channel first).
|
||||
* When a group is formed, the DSP copies the settings of the first channel to the others.
|
||||
* The DSP itself applies every change on a member to the whole group (gain, delay, polarity, HP/LP, PEQ, GEQ,
|
||||
gate, compressor, limiter, mute) – but **not** channel name, routing matrix and mix levels.
|
||||
* A member with mask `00` that is not part of a group ignores changes: when unlinking, give every channel its own
|
||||
bit again.
|
||||
|
||||
## Config dump = memory image
|
||||
|
||||
Chunk `n` carries bytes `n·50 … n·50+49` of the device memory image.
|
||||
|
||||
```
|
||||
0x00 u8[2] ?
|
||||
0x02 char[14] preset name
|
||||
0x10 Input[nIn] 140 bytes each
|
||||
+0 name[8]
|
||||
+8 gate: attack, release, hold, threshold (4×u16)
|
||||
+16 geq[31] u16
|
||||
+78 peq[8] {u16 gain, u16 freq, u8 q, u8 type}
|
||||
+126 u16 hp_freq, u16 lp_freq, u8 hp_slope, u8 lp_slope
|
||||
+132 u16 gain, u16 polarity, u16 delay, u16 link mask
|
||||
Output[nOut] 96 + 2·nIn bytes each
|
||||
+0 name[8]
|
||||
+8 u16 matrix bit mask
|
||||
+10 u16 mix[nIn]
|
||||
… u16 hp_freq, u16 lp_freq, u8 hp_slope, u8 lp_slope
|
||||
… peq[9] {u16 gain, u16 freq, u8 q, u8 type}
|
||||
… comp: ratio, attack, release, knee, threshold (5×u16)
|
||||
… limit: attack, release, knee, threshold (4×u16)
|
||||
… u16 gain, u16 polarity, u16 delay, u16 link mask
|
||||
u16 input mute bit mask, u16 output mute bit mask, then unknown fields
|
||||
```
|
||||
|
||||
Total size: DSP 204 = 724 bytes (15 chunks), DSP 408 = 1448 bytes (29 chunks).
|
||||
Where the PEQ bypass flag is stored in the image is not known yet.
|
||||
|
||||
## USB (HID)
|
||||
|
||||
* Both models: **VID 0x0168, PID 0x0821**, HID class, no driver.
|
||||
* Send: report ID `00` + one complete frame (`10 02 … 10 03 CHK`), zero-padded to the output report length.
|
||||
* Receive: every input report holds exactly one frame starting at byte 0, length = `LEN + 8`, then padding.
|
||||
* The frames are identical to TCP; the longest (config chunk, 50 data bytes) is 60 bytes and fits a 64-byte report.
|
||||
@@ -1,2 +1,216 @@
|
||||
# BetterDSPControl
|
||||
|
||||
**A modern, phone-friendly control app for the t.racks DSP 204 and DSP 408 loudspeaker processors.**
|
||||
Control both devices at the same time from your phone, tablet or computer – over the network or USB.
|
||||
|
||||
> **Unofficial project.** BetterDSPControl is an independent open-source project. It is not affiliated with,
|
||||
> endorsed by or supported by Musikhaus Thomann or the t.racks brand. "Thomann" and "t.racks" are trademarks of
|
||||
> their respective owner and are used here only to name the devices this software works with.
|
||||
> Use at your own risk – see [Disclaimer](#disclaimer).
|
||||
|
||||
* Pure Python 3.10+ standard library on the server side – no packages to install
|
||||
* Vanilla HTML/CSS/JavaScript web UI – no build tools
|
||||
* Runs on Windows, macOS, Linux and a Raspberry Pi
|
||||
* English and German user interface
|
||||
|
||||
## Features
|
||||
|
||||
* **Several devices at once** – switch with the tabs at the top; the model is detected automatically
|
||||
* **Mixer** – faders, mute and live meters for all inputs and outputs, limiter LED on every output (status read
|
||||
from the DSP)
|
||||
* **Channel** – name, gain, delay, polarity, high/low pass, 8/9-band PEQ with a draggable curve
|
||||
* **Inputs** – noise gate, 31-band GEQ · **Outputs** – compressor, limiter, input routing with mix levels
|
||||
* **Routing matrix**, recall and store presets
|
||||
* **Channel links** – link channels into groups; the DSP mirrors changes within the group, the app shows them live
|
||||
* **Preset files** – export the current DSP state to a file and import it again. An import only changes the active
|
||||
state (stored presets stay untouched), writes only what actually differs and makes an automatic backup first
|
||||
("Undo import")
|
||||
* **Limiter calculator** – enter your amplifiers' datasheet values (power at 8/4/2 Ω, sensitivity or gain), assign
|
||||
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
|
||||
* **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
|
||||
|
||||
## Supported hardware
|
||||
|
||||
| Device | Network | USB | Tested on real hardware |
|
||||
|--------|---------|-----|-------------------------|
|
||||
| t.racks DSP 204 | ✓ | ✓ | yes (firmware V0104P, USB on macOS) |
|
||||
| t.racks DSP 408 | ✓ | ✓ | not yet – frames match published captures |
|
||||
|
||||
The DSPs accept only **one** connection at a time – close any other control software first.
|
||||
|
||||
## Quick start (web UI)
|
||||
|
||||
```bash
|
||||
git clone https://git.thiemoo.at/Givou/BetterDSPControl.git
|
||||
```
|
||||
|
||||
```bash
|
||||
cd BetterDSPControl
|
||||
```
|
||||
|
||||
```bash
|
||||
python server.py
|
||||
```
|
||||
|
||||
Open `http://<IP-of-this-computer>:8080` in a browser (from a phone: same Wi-Fi/LAN).
|
||||
|
||||
1. Log in with the default PIN **`1234`**.
|
||||
2. Open ⚙ (settings), enter the IP addresses of your DSPs (or choose *USB cable*) and press *Connect*.
|
||||
3. **Change the PIN** under ⚙ → Security.
|
||||
4. Switch the language under ⚙ → *Language / Sprache* (English is the default).
|
||||
|
||||
`config.json` is created on the first start. Options: `--port 8080`, `--host 0.0.0.0`, `--config path/to/config.json`,
|
||||
`-v` (debug log). On Windows you can also double-click `start.bat`.
|
||||
|
||||
**Forgot the PIN?** Stop the server, delete the `auth` entry from `config.json` and start again – the PIN is `1234`
|
||||
again.
|
||||
|
||||
### Security
|
||||
|
||||
The PIN protects against accidental access in your own network, nothing more: it has 4 digits, a logged-in device
|
||||
stays logged in for 30 days, and after 5 wrong attempts the login is blocked (30 s, growing up to 15 min). The server speaks
|
||||
plain HTTP. **Do not expose it to the internet** (no port forwarding) – use a VPN if you need remote access.
|
||||
|
||||
## Desktop apps (Windows, macOS)
|
||||
|
||||
The desktop app runs the server and the UI in its own window – **no PIN needed** in the app window.
|
||||
Under ⚙ → *Remote access* you can turn on a web server for phones and tablets (port selectable); other devices
|
||||
then log in with the PIN. The lock icon (top right) locks the app window (view only); unlock with the PIN.
|
||||
|
||||
Build it yourself (pre-built binaries are not part of the repository):
|
||||
|
||||
```bash
|
||||
python -m pip install pyinstaller pywebview pillow
|
||||
```
|
||||
|
||||
```bash
|
||||
python packaging/build.py
|
||||
```
|
||||
|
||||
* **Windows** → `dist/DSP Control.exe` and `dist/DSP Control Pi Writer.exe`. Data: `%APPDATA%\DSP Control`.
|
||||
* **macOS** → `dist/DSP Control.app` and `dist/DSP Control.dmg` (use a venv with Python 3.10+, e.g. from Homebrew).
|
||||
The app is not signed: on the first start right-click → *Open*. Data: `~/Library/Application Support/DSP Control`.
|
||||
|
||||
## Raspberry Pi (always-on web UI)
|
||||
|
||||
`DSP Control Pi Writer.exe` (Windows, user interface currently German only) prepares an SD card for a Raspberry Pi
|
||||
(Pi 1/2/3/4/5, Zero, Zero 2 W) that serves the web UI permanently:
|
||||
|
||||
* downloads the current Raspberry Pi OS Lite from the official Raspberry Pi servers (with checksum, cached)
|
||||
* writes and verifies the card, then configures it via cloud-init: hostname, Wi-Fi, user/SSH, web UI PIN, DSP IPs
|
||||
* installs BetterDSPControl from the card (the Pi needs no internet), as a systemd service on port 80
|
||||
|
||||
After 2–5 minutes open `http://<hostname>.local`. Needs administrator rights; only USB/SD drives that are not the
|
||||
system or boot disk are offered. If Windows then asks to format the Linux partition, click **Cancel**.
|
||||
|
||||
On any other Linux machine: `python3 server.py --port 8080`. For USB access as a normal user add a udev rule for
|
||||
`hidraw` devices with VID `0168` / PID `0821` (see `INSTALL_SH` in `pi_image.py`).
|
||||
|
||||
## USB
|
||||
|
||||
Choose *USB cable* for a device under ⚙. The DSPs are USB HID devices (VID 0168 / PID 0821) – no driver needed – and
|
||||
speak the same frames as over the network. Works on Windows (hid.dll), macOS (IOKit) and Linux (hidraw). With two
|
||||
DSPs on USB, pick the right one in the drop-down.
|
||||
|
||||
## Testing without hardware
|
||||
|
||||
A simulator emulates both models:
|
||||
|
||||
```bash
|
||||
python sim.py --model 204 --port 9761
|
||||
```
|
||||
|
||||
```bash
|
||||
python sim.py --model 408 --port 9762
|
||||
```
|
||||
|
||||
```bash
|
||||
python server.py
|
||||
```
|
||||
|
||||
Then add devices with IP `127.0.0.1` and ports 9761 / 9762 in the web UI. Protocol self-test:
|
||||
|
||||
```bash
|
||||
python tests/test_protocol.py
|
||||
```
|
||||
|
||||
## Project layout
|
||||
|
||||
| Path | Contents |
|
||||
|------|----------|
|
||||
| `server.py` | Web server (HTTP + server-sent events), device management, auth, backups |
|
||||
| `dsp/protocol.py` | Frame format, commands, value scales, memory-image parser |
|
||||
| `dsp/device.py` | Client per DSP (TCP or USB): connect, command queue, meters, auto-reconnect, links |
|
||||
| `dsp/preset.py` | Preset files: export/import, validation, import command sequence |
|
||||
| `dsp/usbhid.py` | USB HID without extra packages (Windows hid.dll, macOS IOKit, Linux hidraw) |
|
||||
| `sim.py` | Simulated DSP 204/408 |
|
||||
| `desktop.py` | Desktop app (Windows/macOS): server + own window (pywebview) |
|
||||
| `pi_writer.py`, `pi_image.py`, `win_disk.py` | Raspberry Pi SD card writer: GUI, OS image + cloud-init, raw disk writes |
|
||||
| `static/` | Web UI (`app.js`, `style.css`, `index.html`), translations in `static/i18n.js` |
|
||||
| `packaging/` | Build script and icons |
|
||||
| `tests/` | Protocol tests |
|
||||
| `PROTOCOL.md` | Protocol documentation |
|
||||
| `CLAUDE.md` | Guide for AI coding assistants (architecture, conventions, open points) |
|
||||
|
||||
## How to import into your Claude
|
||||
|
||||
This project was built with [Claude Code](https://claude.com/claude-code) and is documented so you can continue
|
||||
working on it in your own Claude session. `CLAUDE.md` is read automatically by Claude Code and explains the
|
||||
architecture, conventions and what is still unverified.
|
||||
|
||||
1. Clone the repository (see [Quick start](#quick-start-web-ui)).
|
||||
2. Open the folder in Claude Code – either the **Claude desktop app** (tab *Code* → choose the folder) or in a
|
||||
terminal:
|
||||
|
||||
```bash
|
||||
cd BetterDSPControl && claude
|
||||
```
|
||||
|
||||
3. Paste this prompt as your first message:
|
||||
|
||||
```text
|
||||
This is BetterDSPControl, a control app for the t.racks DSP 204 / DSP 408 (Python stdlib server + vanilla JS web UI,
|
||||
desktop app via pywebview, Raspberry Pi SD card writer).
|
||||
|
||||
Please get familiar with the project first:
|
||||
1. Read CLAUDE.md, README.md and PROTOCOL.md completely.
|
||||
2. Look at server.py, dsp/protocol.py, dsp/device.py and static/app.js to understand the structure.
|
||||
3. Run the tests (python tests/test_protocol.py) and start the simulator test from the README
|
||||
(sim.py for both models + server.py) to see the app working.
|
||||
4. Summarise briefly how it is built and which points are still unverified on real hardware.
|
||||
|
||||
Rules: never change values on a real DSP permanently while testing (export a preset file first, use the simulator
|
||||
whenever possible), keep the server free of third-party packages, and keep English and German texts in sync
|
||||
(static/i18n.js). Ask me before pushing anything.
|
||||
|
||||
My devices: <e.g. DSP 408 over network, IP 192.168.1.50 / DSP 204 over USB>.
|
||||
What I want to do: <describe your goal>.
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
Issues and pull requests are welcome – especially captures and test results from a real **DSP 408** and anything
|
||||
listed as unverified in `CLAUDE.md`. Please test with the simulator first and run `python tests/test_protocol.py`.
|
||||
|
||||
## Disclaimer
|
||||
|
||||
This software talks to your audio hardware. Wrong settings (e.g. limiter thresholds, gain, crossover filters) can
|
||||
damage loudspeakers or amplifiers. The limiter calculator is a planning aid based on datasheet values and an assumed
|
||||
reference level – verify with a measurement before relying on it. The software is provided "as is", without
|
||||
warranty of any kind, see [LICENSE](LICENSE).
|
||||
|
||||
The protocol was documented for interoperability purposes only, by observing the communication of the devices and
|
||||
testing on real hardware. This repository contains no code, binaries, firmware, images or documentation from the
|
||||
manufacturer. Frame examples in the tests also match the DSP 408 captures published by
|
||||
[dsp-408-ui](https://github.com/Aeternitaas/dsp-408-ui); no code from that project is used.
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE) © 2026 Givou
|
||||
|
||||
The desktop builds bundle third-party components under their own licenses (Python – PSF License, pywebview – BSD,
|
||||
pythonnet – MIT, PyInstaller bootloader – GPL with exception allowing distribution). If you distribute built
|
||||
binaries, include their license notices.
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
"""DSP Control desktop app: the web server runs inside the app and the UI opens in its own window.
|
||||
|
||||
The window logs in with a one-time token (no PIN). Other devices only get access when
|
||||
"Fernzugriff" is switched on in the settings - and then they need the PIN.
|
||||
|
||||
Runs on Windows and macOS. Build: python packaging/build.py
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import ctypes
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import webview
|
||||
|
||||
import server
|
||||
|
||||
APP_NAME = "DSP Control"
|
||||
|
||||
|
||||
def data_dir() -> Path:
|
||||
if sys.platform == "darwin":
|
||||
d = Path.home() / "Library" / "Application Support" / APP_NAME
|
||||
else:
|
||||
d = Path(os.environ.get("APPDATA") or Path.home()) / APP_NAME
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
# texts of this file and pywebview's own (menus, file dialogs); the page itself is translated in static/i18n.js
|
||||
TEXTS = {
|
||||
"en": {"running": "DSP Control is already running.", "failed": "DSP Control could not start:\n{error}",
|
||||
"timeout": "timeout"},
|
||||
"de": {"running": "DSP Control läuft bereits.", "failed": "DSP Control konnte nicht starten:\n{error}",
|
||||
"timeout": "Zeitüberschreitung"},
|
||||
}
|
||||
WEBVIEW_DE = {
|
||||
"global.quitConfirmation": "Wirklich beenden?", "global.ok": "OK", "global.quit": "Beenden", "global.cancel": "Abbrechen",
|
||||
"global.saveFile": "Datei speichern", "cocoa.menu.about": "Über", "cocoa.menu.services": "Dienste",
|
||||
"cocoa.menu.view": "Darstellung", "cocoa.menu.edit": "Bearbeiten", "cocoa.menu.hide": "Ausblenden",
|
||||
"cocoa.menu.hideOthers": "Andere ausblenden", "cocoa.menu.showAll": "Alle einblenden", "cocoa.menu.quit": "Beenden",
|
||||
"cocoa.menu.fullscreen": "Vollbild", "cocoa.menu.cut": "Ausschneiden", "cocoa.menu.copy": "Kopieren",
|
||||
"cocoa.menu.paste": "Einsetzen", "cocoa.menu.selectAll": "Alles auswählen", "windows.fileFilter.allFiles": "Alle Dateien",
|
||||
"windows.fileFilter.otherFiles": "Andere Dateitypen",
|
||||
}
|
||||
|
||||
|
||||
def ui_lang() -> str:
|
||||
"""Language chosen in the app (kept in config.json by the server), English by default."""
|
||||
try:
|
||||
lang = json.loads((data_dir() / "config.json").read_text(encoding="utf-8")).get("lang")
|
||||
except (OSError, ValueError, AttributeError):
|
||||
lang = None
|
||||
return lang if lang in TEXTS else "en"
|
||||
|
||||
|
||||
def text(key: str, **kw) -> str:
|
||||
return TEXTS[ui_lang()][key].format(**kw)
|
||||
|
||||
|
||||
_lock = None
|
||||
|
||||
|
||||
def single_instance() -> bool:
|
||||
"""False if the app is already running (Windows named mutex, elsewhere a locked file)."""
|
||||
global _lock
|
||||
if sys.platform == "win32":
|
||||
ctypes.windll.kernel32.CreateMutexW(None, False, "Local\\DSPControlDesktop")
|
||||
return ctypes.windll.kernel32.GetLastError() != 183 # ERROR_ALREADY_EXISTS
|
||||
import fcntl
|
||||
_lock = open(data_dir() / ".lock", "w") # held until the process ends
|
||||
try:
|
||||
fcntl.flock(_lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except OSError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def message(text: str):
|
||||
if sys.platform == "win32":
|
||||
ctypes.windll.user32.MessageBoxW(None, text, APP_NAME, 0x40)
|
||||
elif sys.platform == "darwin":
|
||||
subprocess.run(["osascript", "-e", "on run argv", "-e",
|
||||
f'display dialog (item 1 of argv) with title "{APP_NAME}" buttons {{"OK"}} default button 1',
|
||||
"-e", "end run", text], check=False)
|
||||
else:
|
||||
print(text)
|
||||
|
||||
|
||||
class Api:
|
||||
"""Called from the page (window.pywebview.api): native save/open dialogs for backups and presets."""
|
||||
|
||||
def __init__(self):
|
||||
self._window = None # underscore: not exposed to JavaScript
|
||||
|
||||
def save_file(self, name: str, text: str) -> bool:
|
||||
res = self._window.create_file_dialog(webview.FileDialog.SAVE, save_filename=name)
|
||||
path = res[0] if isinstance(res, (list, tuple)) else res
|
||||
if not path:
|
||||
return False
|
||||
Path(path).write_text(text, encoding="utf-8")
|
||||
return True
|
||||
|
||||
def open_file(self) -> dict | None:
|
||||
res = self._window.create_file_dialog(webview.FileDialog.OPEN)
|
||||
if not res:
|
||||
return None
|
||||
path = Path(res[0] if isinstance(res, (list, tuple)) else res)
|
||||
if path.stat().st_size > 5_000_000:
|
||||
raise ValueError("File is too large")
|
||||
return {"name": path.name, "data": base64.b64encode(path.read_bytes()).decode()}
|
||||
|
||||
|
||||
def main():
|
||||
if not single_instance():
|
||||
message(text("running"))
|
||||
return
|
||||
d = data_dir()
|
||||
logging.basicConfig(filename=d / "dsp-control.log", level=logging.INFO, encoding="utf-8",
|
||||
format="%(asctime)s %(name)s %(levelname)s %(message)s")
|
||||
app = server.App(d / "config.json")
|
||||
app.app_token = secrets.token_urlsafe(24)
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
started = threading.Event()
|
||||
state: dict = {}
|
||||
|
||||
async def start():
|
||||
app.load()
|
||||
srv = await asyncio.start_server(app.handle, "127.0.0.1", 0)
|
||||
state["port"] = srv.sockets[0].getsockname()[1]
|
||||
await app.start_remote()
|
||||
|
||||
def run():
|
||||
asyncio.set_event_loop(loop)
|
||||
try:
|
||||
loop.run_until_complete(start())
|
||||
except Exception as e: # noqa: BLE001 - shown to the user below
|
||||
logging.exception("start failed")
|
||||
state["error"] = e
|
||||
started.set()
|
||||
loop.run_forever()
|
||||
|
||||
threading.Thread(target=run, daemon=True, name="server").start()
|
||||
started.wait(20)
|
||||
if "port" not in state:
|
||||
message(text("failed", error=state.get("error", text("timeout"))))
|
||||
return
|
||||
|
||||
api = Api()
|
||||
api._window = webview.create_window(APP_NAME, f"http://127.0.0.1:{state['port']}/app-login?t={app.app_token}",
|
||||
width=1280, height=840, min_size=(380, 560), background_color="#0b0c0f",
|
||||
js_api=api)
|
||||
webview.start(private_mode=False, storage_path=str(d / "webview"),
|
||||
localization=WEBVIEW_DE if ui_lang() == "de" else {})
|
||||
|
||||
# window closed: disconnect the DSPs cleanly so the next connection is accepted right away
|
||||
try:
|
||||
asyncio.run_coroutine_threadsafe(app.shutdown(), loop).result(5)
|
||||
except Exception: # noqa: BLE001
|
||||
logging.exception("shutdown")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Whitespace-only changes.
+365
@@ -0,0 +1,365 @@
|
||||
"""Async client for one t.racks DSP - over the network (TCP) or USB (HID)."""
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import logging
|
||||
import struct
|
||||
import time
|
||||
|
||||
from . import preset
|
||||
from . import protocol as P
|
||||
from . import usbhid
|
||||
|
||||
log = logging.getLogger("dsp")
|
||||
|
||||
RESPONSE_TIMEOUT = 0.6
|
||||
METER_INTERVAL = 0.15
|
||||
RECONNECT_DELAY = 5.0
|
||||
LINK_RESYNC_DELAY = 1.5 # re-read the config this long after the last change on a linked channel
|
||||
|
||||
|
||||
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 = ""):
|
||||
self.id = dev_id
|
||||
self.name = name
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.model_key = model # "auto", "204" or "408"
|
||||
self.addr = addr
|
||||
self.autoconnect = autoconnect
|
||||
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)
|
||||
|
||||
self.status = "disconnected" # disconnected | connecting | loading | online | error
|
||||
self.error = ""
|
||||
self.info = ""
|
||||
self.model: P.Model | None = P.MODELS.get(model)
|
||||
self.state: dict | None = None
|
||||
self.raw = b"" # memory image of the last config read
|
||||
self.presets: list[str] = []
|
||||
self.meters: list[float] = [0.0] * 12
|
||||
|
||||
self._reader = None
|
||||
self._writer = None
|
||||
self._parser = P.FrameParser()
|
||||
self._lock = asyncio.Lock()
|
||||
self._waiter: asyncio.Future | None = None
|
||||
self._pending: dict[tuple, tuple[int, bytes]] = {}
|
||||
self._pending_event = asyncio.Event()
|
||||
self._tasks: list[asyncio.Task] = []
|
||||
self._supervisor: asyncio.Task | None = None
|
||||
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
|
||||
|
||||
# ------------------------------------------------------------ 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}
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
return {**self.config(), "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,
|
||||
"presets": self.presets, "state": self.state}
|
||||
|
||||
def start(self):
|
||||
self._want_connected = True
|
||||
if not self._supervisor or self._supervisor.done():
|
||||
self._supervisor = asyncio.create_task(self._supervise())
|
||||
|
||||
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:
|
||||
await self._supervisor
|
||||
except (asyncio.CancelledError, Exception):
|
||||
pass
|
||||
self._supervisor = None
|
||||
await self._close()
|
||||
self._set_status("disconnected")
|
||||
|
||||
def set_param(self, kind: str, idx: int, param: str, value):
|
||||
"""Update local state and queue the command (coalesced per parameter)."""
|
||||
if not self.state or not self.model:
|
||||
raise RuntimeError("device not loaded")
|
||||
chans = self.state["inputs" if kind == "in" else "outputs"]
|
||||
ch = chans[idx]
|
||||
if param == "name":
|
||||
value = P.clean_name(value)
|
||||
P.apply_param(ch, param, value)
|
||||
cmd, payload = P.param_command(self.model, kind, idx, ch, param)
|
||||
key = (cmd, payload[0]) + ((payload[1],) if cmd in (P.CMD_PEQ, P.CMD_GEQ, P.CMD_MIX) else ())
|
||||
self._pending[key] = (cmd, payload)
|
||||
self._pending_event.set()
|
||||
self._changes += 1
|
||||
# the DSP applies the change to linked channels itself: show that right away
|
||||
group = [idx] if param.split(".")[0] in P.LINK_EXCLUDED else P.link_group(chans, idx)
|
||||
for i in group:
|
||||
if i != idx:
|
||||
P.apply_param(chans[i], param, copy.deepcopy(value))
|
||||
self.on_event({"type": "param", "device": self.id, "kind": kind, "idx": i,
|
||||
"param": param, "value": value})
|
||||
if len(group) > 1:
|
||||
self._schedule_resync()
|
||||
|
||||
async def set_links(self, kind: str, groups: list[list[int]]):
|
||||
"""Link channels of one kind. The DSP copies the first channel's settings to the others."""
|
||||
if not self.state or not self.model:
|
||||
raise RuntimeError("device not loaded")
|
||||
n = self.model.n_in if kind == "in" else self.model.n_out
|
||||
for i, mask in enumerate(P.link_masks(n, groups)):
|
||||
await self._request(P.CMD_LINK, bytes([self.model.channel(kind, i)]) + struct.pack("<H", mask))
|
||||
await asyncio.sleep(0.3)
|
||||
await self.refresh()
|
||||
|
||||
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)."""
|
||||
if self._resync:
|
||||
self._resync.cancel()
|
||||
self._resync = asyncio.get_running_loop().call_later(
|
||||
LINK_RESYNC_DELAY, lambda: asyncio.create_task(self._do_resync()))
|
||||
|
||||
async def _do_resync(self):
|
||||
if self.status != "online":
|
||||
return
|
||||
if self._pending:
|
||||
return self._schedule_resync()
|
||||
seq = self._changes
|
||||
try:
|
||||
state = await self._read_config()
|
||||
except Exception as e: # noqa: BLE001 - the next change schedules another try
|
||||
log.info("%s: resync failed: %s", self.name, e)
|
||||
return
|
||||
if seq != self._changes:
|
||||
return self._schedule_resync()
|
||||
if state != self.state:
|
||||
self.state = state
|
||||
self._emit_state()
|
||||
|
||||
async def recall_preset(self, index: int):
|
||||
await self._request(P.CMD_PRESET_RECALL, bytes([index + 1]), timeout=2.0)
|
||||
await asyncio.sleep(0.3)
|
||||
await self._load_config()
|
||||
self._emit_state()
|
||||
|
||||
async def store_preset(self, index: int, name: str):
|
||||
await self._request(P.CMD_PRESET_STORE_NAME, name.encode("latin1")[:14].ljust(14, b" "))
|
||||
await self._request(P.CMD_PRESET_STORE, bytes([index + 1]), timeout=2.0)
|
||||
await self._request(P.CMD_STATUS)
|
||||
if index < len(self.presets):
|
||||
self.presets[index] = name
|
||||
if self.state:
|
||||
self.state["preset_name"] = name
|
||||
self._emit_state()
|
||||
|
||||
@property
|
||||
def model_name(self) -> str:
|
||||
return next((k for k, m in P.MODELS.items() if m is self.model), "")
|
||||
|
||||
async def export_preset(self) -> dict:
|
||||
"""The DSP's current state, read fresh from the device."""
|
||||
await self.refresh()
|
||||
return preset.export_doc(self.model_name, self.info, self.state, self.raw)
|
||||
|
||||
async def import_preset(self, state: dict) -> list[str]:
|
||||
"""Put the DSP into `state` (working state only). Returns the paths that did not take."""
|
||||
if self.status != "online":
|
||||
raise RuntimeError("DSP is not connected")
|
||||
if self._resync:
|
||||
self._resync.cancel()
|
||||
failed = 0
|
||||
for cmd, payload in preset.import_commands(self.model, state, self.state):
|
||||
if await self._request(cmd, payload) is None:
|
||||
failed += 1
|
||||
await asyncio.sleep(0.3)
|
||||
await self.refresh()
|
||||
diffs = preset.differences(state, self.state)
|
||||
if failed:
|
||||
log.warning("%s: %d import commands unanswered", self.name, failed)
|
||||
return diffs
|
||||
|
||||
async def refresh(self):
|
||||
await self._load_config()
|
||||
self._emit_state()
|
||||
|
||||
# ------------------------------------------------------------ connection
|
||||
|
||||
async def _supervise(self):
|
||||
while self._want_connected:
|
||||
try:
|
||||
await self._connect_and_run()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as e: # noqa: BLE001 - keep reconnecting on any failure
|
||||
log.warning("%s: %s", self.name, e)
|
||||
self.error = str(e) or e.__class__.__name__
|
||||
self._set_status("error")
|
||||
await self._close()
|
||||
if not self._want_connected:
|
||||
break
|
||||
await asyncio.sleep(RECONNECT_DELAY)
|
||||
|
||||
async def _connect_and_run(self):
|
||||
self._set_status("connecting")
|
||||
self.error = ""
|
||||
if self.transport == "usb":
|
||||
self._reader, self._writer = await asyncio.wait_for(usbhid.open_stream(self.usb), timeout=5)
|
||||
else:
|
||||
self._reader, self._writer = await asyncio.wait_for(
|
||||
asyncio.open_connection(self.host, self.port), timeout=5)
|
||||
self._parser = P.FrameParser()
|
||||
reader_task = asyncio.create_task(self._read_loop())
|
||||
self._tasks = [reader_task]
|
||||
self._set_status("loading")
|
||||
await self._initialise()
|
||||
self._set_status("online")
|
||||
self._emit_state()
|
||||
self._tasks += [asyncio.create_task(self._write_loop()), asyncio.create_task(self._meter_loop())]
|
||||
done, _ = await asyncio.wait(self._tasks, return_when=asyncio.FIRST_COMPLETED)
|
||||
for t in done:
|
||||
if t.exception():
|
||||
raise t.exception()
|
||||
raise ConnectionError("connection closed")
|
||||
|
||||
async def _close(self):
|
||||
if self._resync:
|
||||
self._resync.cancel()
|
||||
self._resync = None
|
||||
for t in self._tasks:
|
||||
t.cancel()
|
||||
self._tasks = []
|
||||
if self._writer:
|
||||
try:
|
||||
self._writer.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
self._reader = self._writer = None
|
||||
if self._waiter and not self._waiter.done():
|
||||
self._waiter.cancel()
|
||||
|
||||
async def _read_loop(self):
|
||||
while True:
|
||||
data = await self._reader.read(4096)
|
||||
if not data:
|
||||
raise ConnectionError("DSP closed the connection")
|
||||
for frame in self._parser.feed(data):
|
||||
if self._waiter and not self._waiter.done():
|
||||
self._waiter.set_result(frame)
|
||||
|
||||
async def _request(self, cmd: int, payload: bytes = b"", timeout: float = RESPONSE_TIMEOUT,
|
||||
expect: int | None = None) -> P.Frame | None:
|
||||
"""Send one command and wait for its answer (the DSP is strictly request/response)."""
|
||||
if not self._writer:
|
||||
raise ConnectionError("not connected")
|
||||
async with self._lock:
|
||||
deadline = time.monotonic() + timeout
|
||||
self._writer.write(P.build_frame(cmd, payload, self.addr))
|
||||
await self._writer.drain()
|
||||
while True:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
return None
|
||||
self._waiter = asyncio.get_running_loop().create_future()
|
||||
try:
|
||||
frame = await asyncio.wait_for(self._waiter, remaining)
|
||||
except asyncio.TimeoutError:
|
||||
return None
|
||||
if expect is None or frame.cmd == expect:
|
||||
return frame
|
||||
|
||||
# ------------------------------------------------------------ init / dump
|
||||
|
||||
async def _initialise(self):
|
||||
await self._request(P.CMD_HANDSHAKE)
|
||||
info = await self._request(P.CMD_DEVICE_INFO, expect=P.CMD_DEVICE_INFO)
|
||||
self.info = info.payload.split(b"\x00")[0].decode("latin1", "replace").strip() if info else ""
|
||||
detected = P.detect_model(self.info)
|
||||
if self.model_key == "auto":
|
||||
if not detected:
|
||||
raise RuntimeError(f"unknown device '{self.info}' - set the model manually")
|
||||
self.model = P.MODELS[detected]
|
||||
else:
|
||||
self.model = P.MODELS[self.model_key]
|
||||
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
|
||||
count = count if 0 < count <= 60 else 20
|
||||
await self._request(P.CMD_INIT_22)
|
||||
await self._request(P.CMD_INIT_14)
|
||||
presets = []
|
||||
for i in range(count):
|
||||
f = await self._request(P.CMD_PRESET_NAME, bytes([i]), expect=P.CMD_PRESET_NAME)
|
||||
presets.append(f.payload[1:].split(b"\x00")[0].decode("latin1", "replace").strip() if f else "")
|
||||
self.presets = presets
|
||||
await self._load_config()
|
||||
|
||||
async def _load_config(self):
|
||||
self.state = await self._read_config()
|
||||
|
||||
async def _read_config(self) -> dict:
|
||||
model = self.model
|
||||
buf = bytearray(model.chunks * P.CHUNK_SIZE)
|
||||
for n in range(model.chunks):
|
||||
for _attempt in range(3):
|
||||
f = await self._request(P.CMD_CONFIG_REQUEST, bytes([n]), expect=P.CMD_CONFIG_CHUNK)
|
||||
if f and f.payload and f.payload[0] == n:
|
||||
data = f.payload[1 : 1 + P.CHUNK_SIZE]
|
||||
buf[n * P.CHUNK_SIZE : n * P.CHUNK_SIZE + len(data)] = data
|
||||
break
|
||||
else:
|
||||
raise RuntimeError(f"config chunk {n} not received")
|
||||
await self._request(P.CMD_STATUS)
|
||||
self.raw = bytes(buf[: model.size])
|
||||
return P.parse_state(model, bytes(buf))
|
||||
|
||||
# ------------------------------------------------------------ background loops
|
||||
|
||||
async def _write_loop(self):
|
||||
while True:
|
||||
await self._pending_event.wait()
|
||||
while self._pending:
|
||||
key = next(iter(self._pending))
|
||||
cmd, payload = self._pending.pop(key)
|
||||
await self._request(cmd, payload)
|
||||
self._pending_event.clear()
|
||||
|
||||
async def _meter_loop(self):
|
||||
misses = 0
|
||||
while True:
|
||||
await asyncio.sleep(METER_INTERVAL)
|
||||
if self._pending:
|
||||
continue
|
||||
f = await self._request(P.CMD_METER, expect=P.CMD_METER)
|
||||
if f is None:
|
||||
misses += 1
|
||||
if misses >= 10:
|
||||
raise ConnectionError("DSP not responding")
|
||||
continue
|
||||
misses = 0
|
||||
self.meters = P.decode_meters(f.payload)
|
||||
m = self.model
|
||||
self.on_event({"type": "meters", "device": self.id,
|
||||
"in": [self.meters[m.meter_index("in", i)] for i in range(m.n_in)],
|
||||
"out": [self.meters[m.meter_index("out", i)] for i in range(m.n_out)],
|
||||
"limit": P.decode_limit_flags(f.payload, m.n_out)})
|
||||
|
||||
# ------------------------------------------------------------ events
|
||||
|
||||
def _set_status(self, status: str):
|
||||
self.status = status
|
||||
self.on_event({"type": "status", "device": self.id, "status": status, "error": self.error,
|
||||
"info": self.info})
|
||||
|
||||
def _emit_state(self):
|
||||
self.on_event({"type": "device", "device": self.id, "data": copy.deepcopy(self.snapshot())})
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
"""Preset files: export the DSP's current state and import it again.
|
||||
|
||||
A file holds the decoded state (readable, see protocol.parse_state) plus the raw memory image.
|
||||
Importing only changes the DSP's working state - the stored presets (U01...) stay untouched.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import time
|
||||
|
||||
from . import protocol as P
|
||||
|
||||
FORMAT = "dsp-control-preset"
|
||||
|
||||
# valid raw ranges (PROTOCOL.md, "Werte-Kodierung")
|
||||
_GATE = {"attack": (0, 998), "release": (9, 2999), "hold": (9, 998), "threshold": (0, 180)}
|
||||
_COMP = {"ratio": (0, 15), "attack": (0, 998), "release": (9, 2999), "knee": (0, 12), "threshold": (0, 220)}
|
||||
_LIMIT = {"attack": (0, 998), "release": (9, 2999), "knee": (0, 12), "threshold": (0, 220)}
|
||||
|
||||
|
||||
def export_doc(model_key: str, info: str, state: dict, raw: bytes) -> dict:
|
||||
return {"format": FORMAT, "version": 1, "model": model_key, "device": info,
|
||||
"preset_name": state.get("preset_name", ""),
|
||||
"exported": time.strftime("%Y-%m-%dT%H:%M:%S"), "state": state, "raw": raw.hex()}
|
||||
|
||||
|
||||
def _int(v, lo: int, hi: int, default: int) -> int:
|
||||
try:
|
||||
v = int(v)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return min(hi, max(lo, v))
|
||||
|
||||
|
||||
def _filter(src, cur: dict) -> dict:
|
||||
src = src if isinstance(src, dict) else {}
|
||||
return {"freq": _int(src.get("freq"), 0, 300, cur["freq"]), "slope": _int(src.get("slope"), 0, 20, cur["slope"])}
|
||||
|
||||
|
||||
def _peq(src, cur: list) -> list:
|
||||
src = src if isinstance(src, list) else []
|
||||
out = []
|
||||
for i, c in enumerate(cur):
|
||||
b = src[i] if i < len(src) and isinstance(src[i], dict) else {}
|
||||
out.append({"gain": _int(b.get("gain"), 0, 240, c["gain"]), "freq": _int(b.get("freq"), 0, 300, c["freq"]),
|
||||
"q": _int(b.get("q"), 0, 100, c["q"]), "type": _int(b.get("type"), 0, 8, c["type"]),
|
||||
"bypass": bool(b.get("bypass", c["bypass"]))})
|
||||
return out
|
||||
|
||||
|
||||
def _group(src, cur: dict, ranges: dict) -> dict:
|
||||
src = src if isinstance(src, dict) else {}
|
||||
return {k: _int(src.get(k), lo, hi, cur[k]) for k, (lo, hi) in ranges.items()}
|
||||
|
||||
|
||||
def _common(s: dict, c: dict) -> dict:
|
||||
name = s.get("name", c["name"])
|
||||
return {"name": P.clean_name(name).strip(),
|
||||
"hp": _filter(s.get("hp"), c["hp"]), "lp": _filter(s.get("lp"), c["lp"]),
|
||||
"gain": _int(s.get("gain"), 0, 400, c["gain"]), "polarity": bool(s.get("polarity", c["polarity"])),
|
||||
"delay": _int(s.get("delay"), 0, 65280, c["delay"]), "link": _int(s.get("link"), 0, 0xFFFF, c["link"]),
|
||||
"mute": bool(s.get("mute", c["mute"]))}
|
||||
|
||||
|
||||
def clean_state(model: P.Model, src: dict, base: dict) -> dict:
|
||||
"""`src` limited to valid values; anything missing or broken is taken from `base`."""
|
||||
st = copy.deepcopy(base)
|
||||
ins = src.get("inputs") if isinstance(src.get("inputs"), list) else []
|
||||
outs = src.get("outputs") if isinstance(src.get("outputs"), list) else []
|
||||
for i, c in enumerate(st["inputs"]):
|
||||
s = ins[i] if i < len(ins) and isinstance(ins[i], dict) else {}
|
||||
geq = s.get("geq") if isinstance(s.get("geq"), list) else []
|
||||
c.update(_common(s, c), peq=_peq(s.get("peq"), c["peq"]), gate=_group(s.get("gate"), c["gate"], _GATE),
|
||||
geq=[_int(geq[b], 0, 240, v) if b < len(geq) else v for b, v in enumerate(c["geq"])])
|
||||
for i, c in enumerate(st["outputs"]):
|
||||
s = outs[i] if i < len(outs) and isinstance(outs[i], dict) else {}
|
||||
mix = s.get("mix") if isinstance(s.get("mix"), list) else []
|
||||
c.update(_common(s, c), peq=_peq(s.get("peq"), c["peq"]),
|
||||
comp=_group(s.get("comp"), c["comp"], _COMP), limit=_group(s.get("limit"), c["limit"], _LIMIT),
|
||||
matrix=_int(s.get("matrix"), 0, (1 << model.n_in) - 1, c["matrix"]),
|
||||
mix=[_int(mix[k], 0, 400, v) if k < len(mix) else v for k, v in enumerate(c["mix"])])
|
||||
if isinstance(src.get("preset_name"), str):
|
||||
st["preset_name"] = src["preset_name"][:14]
|
||||
return st
|
||||
|
||||
|
||||
def read_file(model_key: str, model: P.Model, current: dict, doc: dict | None = None,
|
||||
raw: bytes | None = None) -> dict:
|
||||
"""The state to import from an uploaded file: our JSON (`doc`) or a bare memory image (`raw`)."""
|
||||
if raw is not None:
|
||||
if len(raw) not in (model.size, model.chunks * P.CHUNK_SIZE):
|
||||
raise ValueError(f"Unknown file format ({len(raw)} bytes) – expected a DSP Control preset file "
|
||||
f"or a memory image of the {model.name} ({model.size} bytes)")
|
||||
return _linked_alike(clean_state(model, P.parse_state(model, raw.ljust(model.chunks * P.CHUNK_SIZE, b"\0")), current))
|
||||
if not isinstance(doc, dict) or doc.get("format") != FORMAT:
|
||||
raise ValueError("Not a DSP Control preset file")
|
||||
if str(doc.get("model")) != model_key:
|
||||
raise ValueError(f"The file is for a DSP {doc.get('model')}, the connected device is a {model.name}")
|
||||
base = current
|
||||
try: # the raw image fills in anything the readable part lacks
|
||||
img = bytes.fromhex(doc.get("raw") or "")
|
||||
if len(img) in (model.size, model.chunks * P.CHUNK_SIZE):
|
||||
base = clean_state(model, P.parse_state(model, img.ljust(model.chunks * P.CHUNK_SIZE, b"\0")), current)
|
||||
except ValueError:
|
||||
pass
|
||||
return _linked_alike(clean_state(model, doc.get("state") if isinstance(doc.get("state"), dict) else {}, base))
|
||||
|
||||
|
||||
def _linked_alike(st: dict) -> dict:
|
||||
"""Linked channels share their settings on the DSP: take them from each group's first channel."""
|
||||
for chans in (st["inputs"], st["outputs"]):
|
||||
for g in P.link_groups(chans):
|
||||
for i in g[1:]:
|
||||
P.copy_linked(chans, g[0], i)
|
||||
return st
|
||||
|
||||
|
||||
def import_commands(model: P.Model, st: dict, current: dict) -> list[tuple[int, bytes]]:
|
||||
"""Commands that take the DSP from `current` to `st` - only values that actually change.
|
||||
|
||||
If the links change, they are dissolved first (otherwise the DSP would copy every value onto
|
||||
the whole group), then the parameters are set, then the new links are formed. Forming a group
|
||||
copies the first channel's settings to the others, so names, routing and mix levels (which
|
||||
links don't share) are sent once more at the end.
|
||||
"""
|
||||
kinds = (("in", "inputs"), ("out", "outputs"))
|
||||
relink = any(P.link_groups(st[key]) != P.link_groups(current[key]) for _, key in kinds)
|
||||
cmds = []
|
||||
if relink:
|
||||
for kind, key in kinds:
|
||||
for i in range(len(st[key])):
|
||||
cmds.append((P.CMD_LINK, bytes([model.channel(kind, i)]) + (1 << i).to_bytes(2, "little")))
|
||||
for kind, key in kinds:
|
||||
for i, ch in enumerate(st[key]):
|
||||
params = ["name", "gain", "polarity", "delay", "hp", "lp"] + [f"peq.{b}" for b in range(len(ch["peq"]))]
|
||||
if kind == "in":
|
||||
params += [f"geq.{b}" for b in range(len(ch["geq"]))] + ["gate"]
|
||||
else:
|
||||
params += ["comp", "limit", "matrix"] + [f"mix.{k}" for k in range(len(ch["mix"]))]
|
||||
for p in params + ["mute"]:
|
||||
cmd = P.param_command(model, kind, i, ch, p)
|
||||
if relink or cmd != P.param_command(model, kind, i, current[key][i], p):
|
||||
cmds.append(cmd)
|
||||
if relink:
|
||||
for kind, key in kinds:
|
||||
chans = st[key]
|
||||
groups = P.link_groups(chans)
|
||||
for i, mask in enumerate(P.link_masks(len(chans), groups)):
|
||||
if mask != 1 << i:
|
||||
cmds.append((P.CMD_LINK, bytes([model.channel(kind, i)]) + mask.to_bytes(2, "little")))
|
||||
for g in groups:
|
||||
for i in g[1:]:
|
||||
extra = ["name"] + (["matrix"] + [f"mix.{k}" for k in range(len(chans[i]["mix"]))] if kind == "out" else [])
|
||||
cmds += [P.param_command(model, kind, i, chans[i], p) for p in extra]
|
||||
return cmds
|
||||
|
||||
|
||||
def differences(target: dict, actual: dict) -> list[str]:
|
||||
"""Paths where the DSP's state differs from the imported one (the preset name is not settable)."""
|
||||
diffs = []
|
||||
|
||||
def walk(a, b, path):
|
||||
if isinstance(a, dict):
|
||||
for k in a:
|
||||
walk(a[k], b.get(k) if isinstance(b, dict) else None, f"{path}.{k}" if path else k)
|
||||
elif isinstance(a, list):
|
||||
for i, v in enumerate(a):
|
||||
walk(v, b[i] if isinstance(b, list) and i < len(b) else None, f"{path}.{i}")
|
||||
elif a != b:
|
||||
diffs.append(path)
|
||||
|
||||
walk({k: v for k, v in target.items() if k != "preset_name"}, actual, "")
|
||||
return diffs
|
||||
+536
@@ -0,0 +1,536 @@
|
||||
"""t.racks DSP 204 / DSP 408 wire protocol (see PROTOCOL.md)."""
|
||||
|
||||
import copy
|
||||
import math
|
||||
import struct
|
||||
from dataclasses import dataclass
|
||||
|
||||
PORT = 9761
|
||||
|
||||
# Read / system commands
|
||||
CMD_ACK = 0x01
|
||||
CMD_HANDSHAKE = 0x10
|
||||
CMD_STATUS = 0x12
|
||||
CMD_DEVICE_INFO = 0x13
|
||||
CMD_INIT_14 = 0x14
|
||||
CMD_PRESET_RECALL = 0x20
|
||||
CMD_PRESET_STORE = 0x21
|
||||
CMD_INIT_22 = 0x22
|
||||
CMD_CONFIG_CHUNK = 0x24
|
||||
CMD_PRESET_STORE_NAME = 0x26
|
||||
CMD_CONFIG_REQUEST = 0x27
|
||||
CMD_PRESET_NAME = 0x29
|
||||
CMD_PRESET_COUNT = 0x2C
|
||||
CMD_METER = 0x40
|
||||
|
||||
# Parameter commands
|
||||
CMD_COMP = 0x30
|
||||
CMD_LOW_PASS = 0x31
|
||||
CMD_HIGH_PASS = 0x32
|
||||
CMD_PEQ = 0x33
|
||||
CMD_GAIN = 0x34
|
||||
CMD_MUTE = 0x35
|
||||
CMD_POLARITY = 0x36
|
||||
CMD_DELAY = 0x38
|
||||
CMD_MATRIX = 0x3A
|
||||
CMD_CHANNEL_NAME = 0x3D
|
||||
CMD_GATE = 0x3E
|
||||
CMD_LIMIT = 0x3F
|
||||
CMD_MIX = 0x41
|
||||
CMD_GEQ = 0x48
|
||||
CMD_LINK = 0x3B # [ch][u16 link mask], see link_masks()
|
||||
|
||||
CHUNK_SIZE = 50
|
||||
|
||||
|
||||
def checksum(data: bytes) -> int:
|
||||
"""XOR over 02 .. 03 of the frame; the 02 and 03 bytes fold into the initial 0x01."""
|
||||
c = 0x01
|
||||
for b in data:
|
||||
c ^= b
|
||||
return c
|
||||
|
||||
|
||||
def build_frame(cmd: int, payload: bytes = b"", addr: int = 1, src: int = 0) -> bytes:
|
||||
body = bytes([src, addr, len(payload) + 1, cmd]) + bytes(payload)
|
||||
return b"\x10\x02" + body + b"\x10\x03" + bytes([checksum(body)])
|
||||
|
||||
|
||||
@dataclass
|
||||
class Frame:
|
||||
src: int
|
||||
dst: int
|
||||
cmd: int
|
||||
payload: bytes
|
||||
checksum_ok: bool = True
|
||||
|
||||
|
||||
class FrameParser:
|
||||
"""Reassembles frames from a TCP byte stream (length based, no byte stuffing)."""
|
||||
|
||||
def __init__(self):
|
||||
self.buf = bytearray()
|
||||
|
||||
def feed(self, data: bytes) -> list[Frame]:
|
||||
self.buf += data
|
||||
frames = []
|
||||
while True:
|
||||
start = self.buf.find(b"\x10\x02")
|
||||
if start < 0:
|
||||
# keep a trailing 0x10 that might start the next header
|
||||
del self.buf[: max(0, len(self.buf) - 1)]
|
||||
return frames
|
||||
if start:
|
||||
del self.buf[:start]
|
||||
if len(self.buf) < 6:
|
||||
return frames
|
||||
length = self.buf[4]
|
||||
total = 5 + length + 3
|
||||
if len(self.buf) < total:
|
||||
return frames
|
||||
if self.buf[5 + length] != 0x10 or self.buf[6 + length] != 0x03 or length == 0:
|
||||
del self.buf[:2] # not a real header, resync
|
||||
continue
|
||||
body = bytes(self.buf[2 : 5 + length])
|
||||
frames.append(
|
||||
Frame(
|
||||
src=body[0],
|
||||
dst=body[1],
|
||||
cmd=body[3],
|
||||
payload=body[4:],
|
||||
checksum_ok=checksum(body) == self.buf[7 + length],
|
||||
)
|
||||
)
|
||||
del self.buf[:total]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- value scales
|
||||
|
||||
Q_TABLE = [
|
||||
0.4, 0.42, 0.45, 0.47, 0.5, 0.53, 0.56, 0.59, 0.63, 0.67, 0.71, 0.75, 0.79, 0.84, 0.89,
|
||||
0.94, 1.0, 1.06, 1.12, 1.19, 1.26, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.4,
|
||||
2.5, 2.7, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.2, 4.5, 4.8, 5.0, 5.3, 5.7, 6.0, 6.3, 6.7,
|
||||
7.1, 7.6, 8.0, 8.5, 9.0, 9.5, 10.1, 10.7, 11.3, 12.0, 12.7, 13.5, 14.0, 15.0, 16.0, 17.0,
|
||||
18.0, 19.0, 20.0, 21.0, 23.0, 24.0, 25.0, 27.0, 29.0, 30.0, 32.0, 34.0, 36.0, 38.0, 40.0,
|
||||
43.0, 45.0, 48.0, 51.0, 54.0, 57.0, 60.0, 64.0, 68.0, 72.0, 76.0, 81.0, 85.0, 91.0, 96.0,
|
||||
102.0, 108.0, 114.0, 121.0, 128.0,
|
||||
]
|
||||
RATIO_NAMES = ["1.0", "1.1", "1.3", "1.5", "1.7", "2.0", "2.5", "3.0", "3.5", "4.0", "5.0",
|
||||
"6.0", "8.0", "10", "20", "Limit"]
|
||||
PEQ_TYPES = ["Peak", "Low Shelf", "High Shelf", "HPF -6", "HPF -12", "LPF -6", "LPF -12",
|
||||
"Allpass 1", "Allpass 2"]
|
||||
SLOPES = ["Bypass", "BW -6", "BL -6", "BW -12", "BL -12", "LK -12", "BW -18", "BL -18", "BW -24",
|
||||
"BL -24", "LK -24", "BW -30", "BL -30", "BW -36", "BL -36", "LK -36", "BW -42", "BL -42",
|
||||
"BW -48", "BL -48", "LK -48"]
|
||||
|
||||
|
||||
def gain_to_db(raw: int) -> float:
|
||||
return raw / 2 - 60 if raw < 80 else (raw - 280) / 10
|
||||
|
||||
|
||||
def db_to_gain(db: float) -> int:
|
||||
raw = round((db + 60) * 2) if db < -20 else round(db * 10 + 280)
|
||||
return max(0, min(400, raw))
|
||||
|
||||
|
||||
def freq_to_hz(raw: int) -> float:
|
||||
return 1000.0 * 2 ** ((raw - 170) / 30)
|
||||
|
||||
|
||||
def hz_to_freq(hz: float) -> int:
|
||||
return max(0, min(300, round(170 + 30 * math.log2(max(hz, 1.0) / 1000.0))))
|
||||
|
||||
|
||||
def eq_gain_to_db(raw: int) -> float:
|
||||
return (raw - 120) / 10
|
||||
|
||||
|
||||
def threshold_to_db(raw: int) -> float:
|
||||
return (raw - 180) / 2
|
||||
|
||||
|
||||
def delay_to_ms(raw: int) -> float:
|
||||
return raw / 96
|
||||
|
||||
|
||||
def decode_meters(payload: bytes) -> list[float]:
|
||||
"""12 linear levels (In A-D, Out 1-8) from a 0x40 response payload."""
|
||||
levels = []
|
||||
for i in range(12):
|
||||
b = payload[i * 3 : i * 3 + 3]
|
||||
if len(b) < 3:
|
||||
levels.append(0.0)
|
||||
continue
|
||||
v = struct.unpack("<f", bytes([0, b[2], b[0], b[1]]))[0]
|
||||
levels.append(v if math.isfinite(v) and v > 0 else 0.0)
|
||||
return levels
|
||||
|
||||
|
||||
def decode_limit_flags(payload: bytes, n_out: int) -> list[bool]:
|
||||
"""Limiter active per output, from the 2 status bytes after the levels (bit i = output i).
|
||||
|
||||
Seen on a DSP 204: 00 03 while Out 1+2 limit, 00 0C for Out 3+4. That outputs 5-8 of the 408
|
||||
continue in the same 16-bit value is an assumption.
|
||||
"""
|
||||
if len(payload) < 38:
|
||||
return [False] * n_out
|
||||
flags = payload[36] << 8 | payload[37]
|
||||
return [bool(flags >> i & 1) for i in range(n_out)]
|
||||
|
||||
|
||||
def encode_meters(levels: list[float], limit_flags: int = 0) -> bytes:
|
||||
"""Inverse of decode_meters / decode_limit_flags (used by the simulator)."""
|
||||
out = bytearray()
|
||||
for v in levels:
|
||||
raw = struct.pack("<f", v)
|
||||
out += bytes([raw[2], raw[3], raw[1]])
|
||||
return bytes(out) + bytes([limit_flags >> 8 & 0xFF, limit_flags & 0xFF])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- device models
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Model:
|
||||
name: str
|
||||
n_in: int
|
||||
n_out: int
|
||||
|
||||
@property
|
||||
def in_size(self) -> int:
|
||||
return 140
|
||||
|
||||
@property
|
||||
def out_size(self) -> int:
|
||||
return 96 + 2 * self.n_in
|
||||
|
||||
@property
|
||||
def out_base(self) -> int:
|
||||
return 0x10 + self.n_in * self.in_size
|
||||
|
||||
@property
|
||||
def globals_base(self) -> int:
|
||||
return self.out_base + self.n_out * self.out_size
|
||||
|
||||
@property
|
||||
def size(self) -> int:
|
||||
return self.globals_base + 4 + 2 * self.n_in + 2 * self.n_out + 12
|
||||
|
||||
@property
|
||||
def chunks(self) -> int:
|
||||
return -(-self.size // CHUNK_SIZE)
|
||||
|
||||
def channel(self, kind: str, idx: int) -> int:
|
||||
"""Wire channel number for input/output index."""
|
||||
return idx if kind == "in" else self.n_in + idx
|
||||
|
||||
def meter_index(self, kind: str, idx: int) -> int:
|
||||
return idx if kind == "in" else 4 + idx
|
||||
|
||||
|
||||
MODELS = {"204": Model("DSP 204", 2, 4), "408": Model("DSP 408", 4, 8)}
|
||||
|
||||
|
||||
def detect_model(info: str) -> str | None:
|
||||
for key in MODELS:
|
||||
if f"DSP{key}" in info.replace(" ", ""):
|
||||
return key
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- state (de)serialisation
|
||||
|
||||
|
||||
_UMLAUTS = str.maketrans({"ä": "ae", "ö": "oe", "ü": "ue", "Ä": "Ae", "Ö": "Oe", "Ü": "Ue", "ß": "ss"})
|
||||
|
||||
|
||||
def clean_name(name) -> str:
|
||||
"""Channel name as the DSP stores it: printable ASCII, at most 8 characters."""
|
||||
s = str(name or "").translate(_UMLAUTS)
|
||||
return "".join(c for c in s if " " <= c <= "~")[:8]
|
||||
|
||||
|
||||
def _name(b: bytes) -> str:
|
||||
return b.split(b"\x00")[0].decode("latin1").strip()
|
||||
|
||||
|
||||
def _peq(buf: bytes, off: int, n: int) -> list[dict]:
|
||||
bands = []
|
||||
for i in range(n):
|
||||
gain, freq, q, typ = struct.unpack_from("<HHBB", buf, off + i * 6)
|
||||
bands.append({"gain": gain, "freq": freq, "q": q, "type": typ % 9, "bypass": typ >= 9})
|
||||
return bands
|
||||
|
||||
|
||||
def parse_state(model: Model, buf: bytes) -> dict:
|
||||
"""Decode the reassembled config dump into a JSON friendly dict (raw values)."""
|
||||
u16 = lambda off: struct.unpack_from("<H", buf, off)[0]
|
||||
g = model.globals_base
|
||||
in_mute, out_mute = u16(g), u16(g + 2)
|
||||
inputs = []
|
||||
for i in range(model.n_in):
|
||||
o = 0x10 + i * model.in_size
|
||||
inputs.append({
|
||||
"name": _name(buf[o : o + 8]),
|
||||
"gate": dict(zip(("attack", "release", "hold", "threshold"),
|
||||
struct.unpack_from("<4H", buf, o + 8))),
|
||||
"geq": list(struct.unpack_from("<31H", buf, o + 16)),
|
||||
"peq": _peq(buf, o + 78, 8),
|
||||
"hp": {"freq": u16(o + 126), "slope": buf[o + 130]},
|
||||
"lp": {"freq": u16(o + 128), "slope": buf[o + 131]},
|
||||
"gain": u16(o + 132),
|
||||
"polarity": u16(o + 134) != 0,
|
||||
"delay": u16(o + 136),
|
||||
"link": u16(o + 138),
|
||||
"mute": bool(in_mute >> i & 1),
|
||||
})
|
||||
outputs = []
|
||||
for i in range(model.n_out):
|
||||
o = model.out_base + i * model.out_size
|
||||
p = o + 10 + 2 * model.n_in
|
||||
outputs.append({
|
||||
"name": _name(buf[o : o + 8]),
|
||||
"matrix": u16(o + 8),
|
||||
"mix": list(struct.unpack_from(f"<{model.n_in}H", buf, o + 10)),
|
||||
"hp": {"freq": u16(p), "slope": buf[p + 4]},
|
||||
"lp": {"freq": u16(p + 2), "slope": buf[p + 5]},
|
||||
"peq": _peq(buf, p + 6, 9),
|
||||
"comp": dict(zip(("ratio", "attack", "release", "knee", "threshold"),
|
||||
struct.unpack_from("<5H", buf, p + 60))),
|
||||
"limit": dict(zip(("attack", "release", "knee", "threshold"),
|
||||
struct.unpack_from("<4H", buf, p + 70))),
|
||||
"gain": u16(p + 78),
|
||||
"polarity": u16(p + 80) != 0,
|
||||
"delay": u16(p + 82),
|
||||
"link": u16(p + 84),
|
||||
"mute": bool(out_mute >> i & 1),
|
||||
})
|
||||
return {"preset_name": _name(buf[2:16]), "inputs": inputs, "outputs": outputs}
|
||||
|
||||
|
||||
def build_state_buffer(model: Model, state: dict) -> bytearray:
|
||||
"""Inverse of parse_state (used by the simulator)."""
|
||||
buf = bytearray(model.chunks * CHUNK_SIZE)
|
||||
pad = lambda s, n: s.encode("latin1")[:n].ljust(n, b" ")
|
||||
buf[0:2] = b"\xff\xff"
|
||||
buf[2:16] = pad(state["preset_name"], 14)
|
||||
|
||||
def put_peq(off, bands):
|
||||
for i, b in enumerate(bands):
|
||||
struct.pack_into("<HHBB", buf, off + i * 6, b["gain"], b["freq"], b["q"],
|
||||
b["type"] + (9 if b.get("bypass") else 0))
|
||||
|
||||
in_mute = out_mute = 0
|
||||
for i, ch in enumerate(state["inputs"]):
|
||||
o = 0x10 + i * model.in_size
|
||||
buf[o : o + 8] = pad(ch["name"], 8)
|
||||
gt = ch["gate"]
|
||||
struct.pack_into("<4H", buf, o + 8, gt["attack"], gt["release"], gt["hold"], gt["threshold"])
|
||||
struct.pack_into("<31H", buf, o + 16, *ch["geq"])
|
||||
put_peq(o + 78, ch["peq"])
|
||||
struct.pack_into("<HHBB", buf, o + 126, ch["hp"]["freq"], ch["lp"]["freq"],
|
||||
ch["hp"]["slope"], ch["lp"]["slope"])
|
||||
struct.pack_into("<4H", buf, o + 132, ch["gain"], int(ch["polarity"]), ch["delay"], ch.get("link", 1 << i))
|
||||
in_mute |= int(ch["mute"]) << i
|
||||
for i, ch in enumerate(state["outputs"]):
|
||||
o = model.out_base + i * model.out_size
|
||||
p = o + 10 + 2 * model.n_in
|
||||
buf[o : o + 8] = pad(ch["name"], 8)
|
||||
struct.pack_into("<H", buf, o + 8, ch["matrix"])
|
||||
struct.pack_into(f"<{model.n_in}H", buf, o + 10, *ch["mix"])
|
||||
struct.pack_into("<HHBB", buf, p, ch["hp"]["freq"], ch["lp"]["freq"],
|
||||
ch["hp"]["slope"], ch["lp"]["slope"])
|
||||
put_peq(p + 6, ch["peq"])
|
||||
c, lim = ch["comp"], ch["limit"]
|
||||
struct.pack_into("<5H", buf, p + 60, c["ratio"], c["attack"], c["release"], c["knee"],
|
||||
c["threshold"])
|
||||
struct.pack_into("<4H", buf, p + 70, lim["attack"], lim["release"], lim["knee"],
|
||||
lim["threshold"])
|
||||
struct.pack_into("<4H", buf, p + 78, ch["gain"], int(ch["polarity"]), ch["delay"], ch.get("link", 1 << i))
|
||||
out_mute |= int(ch["mute"]) << i
|
||||
struct.pack_into("<HH", buf, model.globals_base, in_mute, out_mute)
|
||||
return buf
|
||||
|
||||
|
||||
def default_state(model: Model) -> dict:
|
||||
peq = lambda n: [{"gain": 120, "freq": 50 + i * 25, "q": 32, "type": 0, "bypass": False}
|
||||
for i in range(n)]
|
||||
return {
|
||||
"preset_name": "Default",
|
||||
"inputs": [{
|
||||
"name": f"In{chr(65 + i)}", "gate": {"attack": 0, "release": 99, "hold": 99, "threshold": 0},
|
||||
"geq": [120] * 31, "peq": peq(8), "hp": {"freq": 0, "slope": 0},
|
||||
"lp": {"freq": 300, "slope": 0}, "gain": 280, "polarity": False, "delay": 0, "mute": False,
|
||||
"link": 1 << i,
|
||||
} for i in range(model.n_in)],
|
||||
"outputs": [{
|
||||
"name": f"Out{i + 1}", "matrix": 1 << (i % model.n_in), "mix": [280] * model.n_in,
|
||||
"hp": {"freq": 0, "slope": 0}, "lp": {"freq": 300, "slope": 0}, "peq": peq(9),
|
||||
"comp": {"ratio": 0, "attack": 49, "release": 499, "knee": 0, "threshold": 220},
|
||||
"limit": {"attack": 49, "release": 499, "knee": 0, "threshold": 220},
|
||||
"gain": 280, "polarity": False, "delay": 0, "mute": False, "link": 1 << i,
|
||||
} for i in range(model.n_out)],
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- channel links
|
||||
#
|
||||
# Every channel stores a u16 link mask (bit = channel index within inputs resp. outputs):
|
||||
# a free channel has only its own bit, the first channel of a group the bits of all members,
|
||||
# the other members 0. The DSP itself applies a change on any member to the whole group
|
||||
# (except name, routing and mix levels) and copies the first channel's settings when a group is formed.
|
||||
|
||||
LINK_EXCLUDED = ("name", "mix", "matrix", "link") # per channel even when linked (e.g. Out 1 <- A, Out 2 <- B)
|
||||
|
||||
|
||||
def link_groups(chans: list[dict]) -> list[list[int]]:
|
||||
"""Channel indices grouped by link (single channels included), in channel order."""
|
||||
seen: set[int] = set()
|
||||
groups = []
|
||||
for i, ch in enumerate(chans):
|
||||
if i in seen:
|
||||
continue
|
||||
mask = ch.get("link", 1 << i)
|
||||
g = [j for j in range(len(chans)) if (j == i or mask >> j & 1) and j not in seen]
|
||||
seen.update(g)
|
||||
groups.append(g)
|
||||
return groups
|
||||
|
||||
|
||||
def link_group(chans: list[dict], idx: int) -> list[int]:
|
||||
return next(g for g in link_groups(chans) if idx in g)
|
||||
|
||||
|
||||
def link_masks(n: int, groups: list[list[int]]) -> list[int]:
|
||||
"""Per-channel link masks for the given groups (channels not mentioned stay free)."""
|
||||
masks = [1 << i for i in range(n)]
|
||||
for g in groups:
|
||||
g = sorted({i for i in g if 0 <= i < n})
|
||||
if len(g) < 2:
|
||||
continue
|
||||
masks[g[0]] = sum(1 << i for i in g)
|
||||
for i in g[1:]:
|
||||
masks[i] = 0
|
||||
return masks
|
||||
|
||||
|
||||
def copy_linked(chans: list[dict], src: int, dst: int):
|
||||
for k, v in chans[src].items():
|
||||
if k not in LINK_EXCLUDED:
|
||||
chans[dst][k] = copy.deepcopy(v)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- parameter -> command
|
||||
|
||||
|
||||
def _w(v: int) -> bytes:
|
||||
return struct.pack("<H", int(v) & 0xFFFF)
|
||||
|
||||
|
||||
def param_command(model: Model, kind: str, idx: int, ch: dict, param: str) -> tuple[int, bytes]:
|
||||
"""Build (cmd, payload) for a changed parameter. `ch` is the already-updated channel dict.
|
||||
|
||||
`param` is a dotted path like "gain", "hp.freq", "peq.3.gain", "geq.10", "mix.1".
|
||||
"""
|
||||
c = model.channel(kind, idx)
|
||||
top, *rest = param.split(".")
|
||||
if top == "gain":
|
||||
return CMD_GAIN, bytes([c]) + _w(ch["gain"])
|
||||
if top == "mute":
|
||||
return CMD_MUTE, bytes([c, int(ch["mute"])])
|
||||
if top == "polarity":
|
||||
return CMD_POLARITY, bytes([c, int(ch["polarity"])])
|
||||
if top == "delay":
|
||||
return CMD_DELAY, bytes([c]) + _w(ch["delay"])
|
||||
if top == "name":
|
||||
return CMD_CHANNEL_NAME, bytes([c]) + clean_name(ch["name"]).encode("ascii").ljust(8, b" ")
|
||||
if top in ("hp", "lp"):
|
||||
f = ch[top]
|
||||
return (CMD_HIGH_PASS if top == "hp" else CMD_LOW_PASS), bytes([c]) + _w(f["freq"]) + bytes([f["slope"]])
|
||||
if top == "peq":
|
||||
band = int(rest[0])
|
||||
b = ch["peq"][band]
|
||||
return CMD_PEQ, bytes([c, band]) + _w(b["gain"]) + _w(b["freq"]) + bytes(
|
||||
[b["q"], b["type"], int(b["bypass"])])
|
||||
if top == "geq" and kind == "in":
|
||||
band = int(rest[0])
|
||||
return CMD_GEQ, bytes([c, band]) + _w(ch["geq"][band])
|
||||
if top == "gate" and kind == "in":
|
||||
g = ch["gate"]
|
||||
return CMD_GATE, bytes([c]) + b"".join(_w(g[k]) for k in ("attack", "release", "hold", "threshold"))
|
||||
if top == "comp" and kind == "out":
|
||||
g = ch["comp"]
|
||||
return CMD_COMP, bytes([c]) + b"".join(
|
||||
_w(g[k]) for k in ("ratio", "attack", "release", "knee", "threshold"))
|
||||
if top == "limit" and kind == "out":
|
||||
g = ch["limit"]
|
||||
return CMD_LIMIT, bytes([c]) + b"".join(_w(g[k]) for k in ("attack", "release", "knee", "threshold"))
|
||||
if top == "matrix" and kind == "out":
|
||||
return CMD_MATRIX, bytes([c, ch["matrix"] & 0xFF])
|
||||
if top == "mix" and kind == "out":
|
||||
i = int(rest[0])
|
||||
return CMD_MIX, bytes([c, i]) + _w(ch["mix"][i])
|
||||
raise ValueError(f"unknown parameter {kind}.{param}")
|
||||
|
||||
|
||||
def apply_param(state_ch: dict, param: str, value):
|
||||
"""Write `value` into the channel dict at the dotted `param` path."""
|
||||
keys = param.split(".")
|
||||
node = state_ch
|
||||
for k in keys[:-1]:
|
||||
node = node[int(k)] if isinstance(node, list) else node[k]
|
||||
last = keys[-1]
|
||||
if isinstance(node, list):
|
||||
node[int(last)] = value
|
||||
else:
|
||||
node[last] = value
|
||||
|
||||
|
||||
def apply_command(model: Model, state: dict, cmd: int, p: bytes):
|
||||
"""Update state from an incoming set command (used by the simulator)."""
|
||||
if not p:
|
||||
return
|
||||
c = p[0]
|
||||
kind, idx = ("in", c) if c < model.n_in else ("out", c - model.n_in)
|
||||
chans = state["inputs" if kind == "in" else "outputs"]
|
||||
if idx >= len(chans):
|
||||
return
|
||||
ch = chans[idx]
|
||||
w = lambda o: struct.unpack_from("<H", p, o)[0]
|
||||
if cmd == CMD_GAIN:
|
||||
ch["gain"] = w(1)
|
||||
elif cmd == CMD_MUTE:
|
||||
ch["mute"] = bool(p[1])
|
||||
elif cmd == CMD_POLARITY:
|
||||
ch["polarity"] = bool(p[1])
|
||||
elif cmd == CMD_DELAY:
|
||||
ch["delay"] = w(1)
|
||||
elif cmd == CMD_CHANNEL_NAME:
|
||||
ch["name"] = _name(p[1:9])
|
||||
elif cmd in (CMD_HIGH_PASS, CMD_LOW_PASS):
|
||||
ch["hp" if cmd == CMD_HIGH_PASS else "lp"] = {"freq": w(1), "slope": p[3]}
|
||||
elif cmd == CMD_PEQ:
|
||||
ch["peq"][p[1]] = {"gain": w(2), "freq": w(4), "q": p[6], "type": p[7], "bypass": bool(p[8])}
|
||||
elif cmd == CMD_GEQ:
|
||||
ch["geq"][p[1]] = w(2)
|
||||
elif cmd == CMD_GATE:
|
||||
ch["gate"] = dict(zip(("attack", "release", "hold", "threshold"), struct.unpack_from("<4H", p, 1)))
|
||||
elif cmd == CMD_COMP:
|
||||
ch["comp"] = dict(zip(("ratio", "attack", "release", "knee", "threshold"),
|
||||
struct.unpack_from("<5H", p, 1)))
|
||||
elif cmd == CMD_LIMIT:
|
||||
ch["limit"] = dict(zip(("attack", "release", "knee", "threshold"), struct.unpack_from("<4H", p, 1)))
|
||||
elif cmd == CMD_MATRIX:
|
||||
ch["matrix"] = p[1]
|
||||
elif cmd == CMD_MIX:
|
||||
ch["mix"][p[1]] = w(2)
|
||||
elif cmd == CMD_LINK:
|
||||
ch["link"] = w(1)
|
||||
for j in range(len(chans)): # forming a group copies the first channel's settings
|
||||
if j != idx and ch["link"] >> j & 1:
|
||||
copy_linked(chans, idx, j)
|
||||
return
|
||||
# like the real DSP: a change on a linked channel applies to the whole group
|
||||
for j in link_group(chans, idx):
|
||||
if j != idx:
|
||||
copy_linked(chans, idx, j)
|
||||
+431
@@ -0,0 +1,431 @@
|
||||
"""USB connection to the DSPs (USB HID, no driver needed).
|
||||
|
||||
Both models enumerate as VID 0x0168 / PID 0x0821.
|
||||
Every HID report carries exactly one protocol frame starting at byte 0 (the same frames as on TCP,
|
||||
length = LEN + 8), sent with report ID 0 and zero-padded to the report length.
|
||||
|
||||
Windows uses hid.dll via ctypes, macOS IOKit via ctypes, Linux /dev/hidraw* (Raspberry Pi). No extra packages.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
|
||||
VID, PID = 0x0168, 0x0821
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ Windows (hid.dll)
|
||||
|
||||
if sys.platform == "win32":
|
||||
import ctypes
|
||||
from ctypes import wintypes as W
|
||||
|
||||
_hid = ctypes.WinDLL("hid")
|
||||
_setup = ctypes.WinDLL("setupapi")
|
||||
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
|
||||
class _GUID(ctypes.Structure):
|
||||
_fields_ = [("d1", W.DWORD), ("d2", W.WORD), ("d3", W.WORD), ("d4", ctypes.c_ubyte * 8)]
|
||||
|
||||
class _IFDATA(ctypes.Structure):
|
||||
_fields_ = [("cbSize", W.DWORD), ("guid", _GUID), ("flags", W.DWORD), ("reserved", ctypes.c_void_p)]
|
||||
|
||||
class _ATTR(ctypes.Structure):
|
||||
_fields_ = [("Size", W.ULONG), ("VendorID", W.USHORT), ("ProductID", W.USHORT), ("Version", W.USHORT)]
|
||||
|
||||
class _CAPS(ctypes.Structure):
|
||||
_fields_ = [("Usage", W.USHORT), ("UsagePage", W.USHORT), ("InputReportByteLength", W.USHORT),
|
||||
("OutputReportByteLength", W.USHORT), ("FeatureReportByteLength", W.USHORT),
|
||||
("Reserved", W.USHORT * 17), ("rest", W.USHORT * 10)]
|
||||
|
||||
_k32.CreateFileW.restype = W.HANDLE
|
||||
_k32.CreateFileW.argtypes = [W.LPCWSTR, W.DWORD, W.DWORD, ctypes.c_void_p, W.DWORD, W.DWORD, W.HANDLE]
|
||||
_k32.ReadFile.argtypes = [W.HANDLE, ctypes.c_void_p, W.DWORD, ctypes.POINTER(W.DWORD), ctypes.c_void_p]
|
||||
_k32.WriteFile.argtypes = [W.HANDLE, ctypes.c_void_p, W.DWORD, ctypes.POINTER(W.DWORD), ctypes.c_void_p]
|
||||
_k32.CloseHandle.argtypes = [W.HANDLE]
|
||||
_k32.CancelIoEx.argtypes = [W.HANDLE, ctypes.c_void_p]
|
||||
_setup.SetupDiGetClassDevsW.restype = W.HANDLE
|
||||
_setup.SetupDiGetClassDevsW.argtypes = [ctypes.POINTER(_GUID), W.LPCWSTR, W.HWND, W.DWORD]
|
||||
_setup.SetupDiEnumDeviceInterfaces.argtypes = [W.HANDLE, ctypes.c_void_p, ctypes.POINTER(_GUID), W.DWORD,
|
||||
ctypes.POINTER(_IFDATA)]
|
||||
_setup.SetupDiGetDeviceInterfaceDetailW.argtypes = [W.HANDLE, ctypes.POINTER(_IFDATA), ctypes.c_void_p, W.DWORD,
|
||||
ctypes.POINTER(W.DWORD), ctypes.c_void_p]
|
||||
_setup.SetupDiDestroyDeviceInfoList.argtypes = [W.HANDLE]
|
||||
_hid.HidD_GetAttributes.argtypes = [W.HANDLE, ctypes.POINTER(_ATTR)]
|
||||
_hid.HidD_GetProductString.argtypes = [W.HANDLE, ctypes.c_void_p, W.ULONG]
|
||||
_hid.HidD_GetSerialNumberString.argtypes = [W.HANDLE, ctypes.c_void_p, W.ULONG]
|
||||
_hid.HidD_GetPreparsedData.argtypes = [W.HANDLE, ctypes.POINTER(ctypes.c_void_p)]
|
||||
_hid.HidD_FreePreparsedData.argtypes = [ctypes.c_void_p]
|
||||
_hid.HidP_GetCaps.argtypes = [ctypes.c_void_p, ctypes.POINTER(_CAPS)]
|
||||
|
||||
_INVALID = W.HANDLE(-1).value
|
||||
_GENERIC_RW, _SHARE_RW, _OPEN_EXISTING = 0xC0000000, 0x3, 3
|
||||
|
||||
def _open(path: str, access: int = _GENERIC_RW):
|
||||
h = _k32.CreateFileW(path, access, _SHARE_RW, None, _OPEN_EXISTING, 0, None)
|
||||
if h in (None, _INVALID):
|
||||
raise OSError(ctypes.get_last_error(), f"Cannot open USB device (error {ctypes.get_last_error()})")
|
||||
return h
|
||||
|
||||
def _string(fn, h) -> str:
|
||||
buf = ctypes.create_unicode_buffer(128)
|
||||
return buf.value if fn(h, buf, ctypes.sizeof(buf)) else ""
|
||||
|
||||
def _paths() -> list[str]:
|
||||
guid = _GUID()
|
||||
_hid.HidD_GetHidGuid(ctypes.byref(guid))
|
||||
info = _setup.SetupDiGetClassDevsW(ctypes.byref(guid), None, None, 0x12) # PRESENT | DEVICEINTERFACE
|
||||
paths = []
|
||||
try:
|
||||
i = 0
|
||||
while True:
|
||||
ifd = _IFDATA(cbSize=ctypes.sizeof(_IFDATA))
|
||||
if not _setup.SetupDiEnumDeviceInterfaces(info, None, ctypes.byref(guid), i, ctypes.byref(ifd)):
|
||||
break
|
||||
i += 1
|
||||
need = W.DWORD()
|
||||
_setup.SetupDiGetDeviceInterfaceDetailW(info, ctypes.byref(ifd), None, 0, ctypes.byref(need), None)
|
||||
buf = ctypes.create_string_buffer(need.value)
|
||||
ctypes.cast(buf, ctypes.POINTER(W.DWORD))[0] = 8 if ctypes.sizeof(ctypes.c_void_p) == 8 else 6
|
||||
if _setup.SetupDiGetDeviceInterfaceDetailW(info, ctypes.byref(ifd), buf, need, None, None):
|
||||
paths.append(ctypes.wstring_at(ctypes.addressof(buf) + 4))
|
||||
finally:
|
||||
_setup.SetupDiDestroyDeviceInfoList(info)
|
||||
return paths
|
||||
|
||||
def list_devices() -> list[dict]:
|
||||
found = []
|
||||
for path in _paths():
|
||||
try:
|
||||
h = _open(path, 0) # attributes only: works even while another program has it open
|
||||
except OSError:
|
||||
continue
|
||||
try:
|
||||
a = _ATTR(Size=ctypes.sizeof(_ATTR))
|
||||
if _hid.HidD_GetAttributes(h, ctypes.byref(a)) and (a.VendorID, a.ProductID) == (VID, PID):
|
||||
found.append({"path": path, "product": _string(_hid.HidD_GetProductString, h),
|
||||
"serial": _string(_hid.HidD_GetSerialNumberString, h)})
|
||||
finally:
|
||||
_k32.CloseHandle(h)
|
||||
return found
|
||||
|
||||
class HidDevice:
|
||||
"""One opened DSP. Separate read and write handles: a blocking ReadFile would otherwise
|
||||
serialise every WriteFile behind it on a synchronous handle."""
|
||||
|
||||
def __init__(self, path: str):
|
||||
self.rh = _open(path)
|
||||
try:
|
||||
self.wh = _open(path)
|
||||
pp = ctypes.c_void_p()
|
||||
caps = _CAPS()
|
||||
if _hid.HidD_GetPreparsedData(self.rh, ctypes.byref(pp)):
|
||||
_hid.HidP_GetCaps(pp, ctypes.byref(caps))
|
||||
_hid.HidD_FreePreparsedData(pp)
|
||||
self.in_len = caps.InputReportByteLength or 65
|
||||
self.out_len = caps.OutputReportByteLength or 65
|
||||
except OSError:
|
||||
_k32.CloseHandle(self.rh)
|
||||
raise
|
||||
|
||||
def read_report(self) -> bytes:
|
||||
buf = ctypes.create_string_buffer(self.in_len)
|
||||
n = W.DWORD()
|
||||
if not _k32.ReadFile(self.rh, buf, self.in_len, ctypes.byref(n), None):
|
||||
raise OSError(ctypes.get_last_error(), "USB connection lost")
|
||||
return buf.raw[1:n.value] # drop the report ID
|
||||
|
||||
def write_report(self, data: bytes):
|
||||
report = (b"\x00" + data).ljust(self.out_len, b"\x00")[: self.out_len]
|
||||
n = W.DWORD()
|
||||
if not _k32.WriteFile(self.wh, report, len(report), ctypes.byref(n), None):
|
||||
raise OSError(ctypes.get_last_error(), "USB write error")
|
||||
|
||||
def close(self):
|
||||
_k32.CancelIoEx(self.rh, None) # wakes up the blocked reader thread
|
||||
for h in (self.rh, self.wh):
|
||||
_k32.CloseHandle(h)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ Linux (hidraw)
|
||||
|
||||
elif sys.platform.startswith("linux"):
|
||||
|
||||
def list_devices() -> list[dict]:
|
||||
found = []
|
||||
base = "/sys/class/hidraw"
|
||||
for name in sorted(os.listdir(base)) if os.path.isdir(base) else []:
|
||||
try:
|
||||
with open(f"{base}/{name}/device/uevent") as f:
|
||||
ev = dict(line.strip().split("=", 1) for line in f if "=" in line)
|
||||
except OSError:
|
||||
continue
|
||||
ids = ev.get("HID_ID", "").split(":")
|
||||
if len(ids) == 3 and int(ids[1], 16) == VID and int(ids[2], 16) == PID:
|
||||
found.append({"path": f"/dev/{name}", "product": ev.get("HID_NAME", ""), "serial": ev.get("HID_UNIQ", "")})
|
||||
return found
|
||||
|
||||
class HidDevice:
|
||||
def __init__(self, path: str):
|
||||
self.fd = os.open(path, os.O_RDWR)
|
||||
self.in_len = self.out_len = 65
|
||||
|
||||
def read_report(self) -> bytes:
|
||||
data = os.read(self.fd, 64) # hidraw returns the report without a report ID
|
||||
if not data:
|
||||
raise OSError("USB connection lost")
|
||||
return data
|
||||
|
||||
def write_report(self, data: bytes):
|
||||
os.write(self.fd, (b"\x00" + data).ljust(self.out_len, b"\x00"))
|
||||
|
||||
def close(self):
|
||||
try:
|
||||
os.close(self.fd)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# ------------------------------------------------------------------ macOS (IOKit IOHIDDevice)
|
||||
|
||||
elif sys.platform == "darwin":
|
||||
import ctypes
|
||||
import queue
|
||||
|
||||
_iokit = ctypes.cdll.LoadLibrary("/System/Library/Frameworks/IOKit.framework/IOKit")
|
||||
_cf = ctypes.cdll.LoadLibrary("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")
|
||||
_vp, _i32 = ctypes.c_void_p, ctypes.c_int32
|
||||
|
||||
_UTF8, _SINT32, _SINT64 = 0x08000100, 3, 4
|
||||
_REPORT_OUTPUT = 1
|
||||
_ReportCB = ctypes.CFUNCTYPE(None, _vp, _i32, _vp, ctypes.c_int, ctypes.c_uint32,
|
||||
ctypes.POINTER(ctypes.c_uint8), ctypes.c_long)
|
||||
_RemovalCB = ctypes.CFUNCTYPE(None, _vp, _i32, _vp)
|
||||
|
||||
for _name, _res, _args in (
|
||||
("CFStringCreateWithCString", _vp, [_vp, ctypes.c_char_p, ctypes.c_uint32]),
|
||||
("CFStringGetCString", ctypes.c_bool, [_vp, ctypes.c_char_p, ctypes.c_long, ctypes.c_uint32]),
|
||||
("CFNumberCreate", _vp, [_vp, ctypes.c_int, _vp]),
|
||||
("CFNumberGetValue", ctypes.c_bool, [_vp, ctypes.c_int, _vp]),
|
||||
("CFGetTypeID", ctypes.c_ulong, [_vp]),
|
||||
("CFStringGetTypeID", ctypes.c_ulong, []),
|
||||
("CFNumberGetTypeID", ctypes.c_ulong, []),
|
||||
("CFDictionaryCreateMutable", _vp, [_vp, ctypes.c_long, _vp, _vp]),
|
||||
("CFDictionarySetValue", None, [_vp, _vp, _vp]),
|
||||
("CFSetGetCount", ctypes.c_long, [_vp]),
|
||||
("CFSetGetValues", None, [_vp, _vp]),
|
||||
("CFRetain", _vp, [_vp]),
|
||||
("CFRelease", None, [_vp]),
|
||||
("CFRunLoopGetCurrent", _vp, []),
|
||||
("CFRunLoopRunInMode", _i32, [_vp, ctypes.c_double, ctypes.c_bool]),
|
||||
("CFRunLoopStop", None, [_vp]),
|
||||
):
|
||||
getattr(_cf, _name).restype, getattr(_cf, _name).argtypes = _res, _args
|
||||
for _name, _res, _args in (
|
||||
("IOHIDManagerCreate", _vp, [_vp, ctypes.c_uint32]),
|
||||
("IOHIDManagerSetDeviceMatching", None, [_vp, _vp]),
|
||||
("IOHIDManagerCopyDevices", _vp, [_vp]),
|
||||
("IOHIDDeviceGetProperty", _vp, [_vp, _vp]),
|
||||
("IOHIDDeviceOpen", _i32, [_vp, ctypes.c_uint32]),
|
||||
("IOHIDDeviceClose", _i32, [_vp, ctypes.c_uint32]),
|
||||
("IOHIDDeviceSetReport", _i32, [_vp, ctypes.c_int, ctypes.c_long, _vp, ctypes.c_long]),
|
||||
("IOHIDDeviceRegisterInputReportCallback", None, [_vp, _vp, ctypes.c_long, _ReportCB, _vp]),
|
||||
("IOHIDDeviceRegisterRemovalCallback", None, [_vp, _RemovalCB, _vp]),
|
||||
("IOHIDDeviceScheduleWithRunLoop", None, [_vp, _vp, _vp]),
|
||||
("IOHIDDeviceUnscheduleFromRunLoop", None, [_vp, _vp, _vp]),
|
||||
):
|
||||
getattr(_iokit, _name).restype, getattr(_iokit, _name).argtypes = _res, _args
|
||||
|
||||
_MODE = _vp.in_dll(_cf, "kCFRunLoopDefaultMode")
|
||||
_KEY_CB = _vp.in_dll(_cf, "kCFTypeDictionaryKeyCallBacks")
|
||||
_VAL_CB = _vp.in_dll(_cf, "kCFTypeDictionaryValueCallBacks")
|
||||
|
||||
def _cfstr(s: str):
|
||||
return _cf.CFStringCreateWithCString(None, s.encode(), _UTF8)
|
||||
|
||||
def _prop(dev, key: str):
|
||||
k = _cfstr(key)
|
||||
try:
|
||||
v = _iokit.IOHIDDeviceGetProperty(dev, k)
|
||||
finally:
|
||||
_cf.CFRelease(k)
|
||||
if not v:
|
||||
return None
|
||||
if _cf.CFGetTypeID(v) == _cf.CFNumberGetTypeID():
|
||||
n = ctypes.c_int64()
|
||||
_cf.CFNumberGetValue(v, _SINT64, ctypes.byref(n))
|
||||
return n.value
|
||||
if _cf.CFGetTypeID(v) == _cf.CFStringGetTypeID():
|
||||
buf = ctypes.create_string_buffer(256)
|
||||
return buf.value.decode(errors="replace") if _cf.CFStringGetCString(v, buf, 256, _UTF8) else ""
|
||||
return None
|
||||
|
||||
def _path(dev) -> str:
|
||||
# LocationID identifies the USB port, so a saved device is found again after replugging
|
||||
return f"usb-loc:{(_prop(dev, 'LocationID') or 0) & 0xFFFFFFFF:08x}"
|
||||
|
||||
def _devices() -> list:
|
||||
"""Retained IOHIDDeviceRefs of all connected DSPs (caller releases them)."""
|
||||
mgr = _iokit.IOHIDManagerCreate(None, 0)
|
||||
match = _cf.CFDictionaryCreateMutable(None, 0, ctypes.byref(_KEY_CB), ctypes.byref(_VAL_CB))
|
||||
try:
|
||||
for key, val in (("VendorID", VID), ("ProductID", PID)):
|
||||
k, n = _cfstr(key), ctypes.c_int32(val)
|
||||
v = _cf.CFNumberCreate(None, _SINT32, ctypes.byref(n))
|
||||
_cf.CFDictionarySetValue(match, k, v)
|
||||
_cf.CFRelease(k)
|
||||
_cf.CFRelease(v)
|
||||
_iokit.IOHIDManagerSetDeviceMatching(mgr, match)
|
||||
devset = _iokit.IOHIDManagerCopyDevices(mgr)
|
||||
if not devset:
|
||||
return []
|
||||
count = _cf.CFSetGetCount(devset)
|
||||
arr = (_vp * count)()
|
||||
_cf.CFSetGetValues(devset, arr)
|
||||
devs = [_cf.CFRetain(d) for d in arr]
|
||||
_cf.CFRelease(devset)
|
||||
return sorted(devs, key=_path)
|
||||
finally:
|
||||
_cf.CFRelease(match)
|
||||
_cf.CFRelease(mgr)
|
||||
|
||||
def list_devices() -> list[dict]:
|
||||
found = []
|
||||
for dev in _devices():
|
||||
found.append({"path": _path(dev), "product": _prop(dev, "Product") or "",
|
||||
"serial": _prop(dev, "SerialNumber") or ""})
|
||||
_cf.CFRelease(dev)
|
||||
return found
|
||||
|
||||
class HidDevice:
|
||||
"""One opened DSP. IOKit delivers input reports through a run loop, so a private thread
|
||||
runs one and hands the reports to read_report() through a queue."""
|
||||
|
||||
def __init__(self, path: str):
|
||||
devs = _devices()
|
||||
self.dev = next((d for d in devs if _path(d) == path), None)
|
||||
for d in devs:
|
||||
if d != self.dev:
|
||||
_cf.CFRelease(d)
|
||||
if not self.dev:
|
||||
raise OSError("USB device not found – check the cable")
|
||||
ret = _iokit.IOHIDDeviceOpen(self.dev, 0) & 0xFFFFFFFF
|
||||
if ret:
|
||||
_cf.CFRelease(self.dev)
|
||||
raise OSError(ret, "USB device is in use by another program" if ret == 0xE00002C5
|
||||
else f"Cannot open USB device (error 0x{ret:08x})")
|
||||
self.in_len = _prop(self.dev, "MaxInputReportSize") or 64
|
||||
self.out_len = _prop(self.dev, "MaxOutputReportSize") or 64
|
||||
self.reports: queue.Queue = queue.Queue()
|
||||
self.closed = False
|
||||
self.runloop = None
|
||||
self.buf = (ctypes.c_uint8 * self.in_len)()
|
||||
self._on_report = _ReportCB(lambda _c, _r, _s, _t, _id, data, n: self.reports.put(ctypes.string_at(data, n)))
|
||||
self._on_removal = _RemovalCB(lambda _c, _r, _s: self.reports.put(None))
|
||||
ready = threading.Event()
|
||||
threading.Thread(target=self._run, args=(ready,), daemon=True, name="usb-runloop").start()
|
||||
ready.wait(5)
|
||||
|
||||
def _run(self, ready: threading.Event):
|
||||
self.runloop = _cf.CFRunLoopGetCurrent()
|
||||
_iokit.IOHIDDeviceRegisterInputReportCallback(self.dev, self.buf, self.in_len, self._on_report, None)
|
||||
_iokit.IOHIDDeviceRegisterRemovalCallback(self.dev, self._on_removal, None)
|
||||
_iokit.IOHIDDeviceScheduleWithRunLoop(self.dev, self.runloop, _MODE)
|
||||
ready.set()
|
||||
while not self.closed:
|
||||
_cf.CFRunLoopRunInMode(_MODE, 0.5, False)
|
||||
_iokit.IOHIDDeviceUnscheduleFromRunLoop(self.dev, self.runloop, _MODE)
|
||||
_iokit.IOHIDDeviceClose(self.dev, 0)
|
||||
_cf.CFRelease(self.dev)
|
||||
|
||||
def read_report(self) -> bytes:
|
||||
data = self.reports.get()
|
||||
if data is None:
|
||||
raise OSError("USB connection lost")
|
||||
return data # IOKit delivers the report without a report ID
|
||||
|
||||
def write_report(self, data: bytes):
|
||||
report = data.ljust(self.out_len, b"\x00")[: self.out_len]
|
||||
ret = _iokit.IOHIDDeviceSetReport(self.dev, _REPORT_OUTPUT, 0, report, len(report)) & 0xFFFFFFFF
|
||||
if ret:
|
||||
raise OSError(ret, f"USB write error (0x{ret:08x})")
|
||||
|
||||
def close(self):
|
||||
if not self.closed:
|
||||
self.closed = True
|
||||
self.reports.put(None) # wakes up the blocked reader thread
|
||||
if self.runloop:
|
||||
_cf.CFRunLoopStop(self.runloop)
|
||||
|
||||
else:
|
||||
def list_devices() -> list[dict]:
|
||||
return []
|
||||
|
||||
class HidDevice:
|
||||
def __init__(self, path: str):
|
||||
raise OSError("USB is not supported on this system")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ asyncio stream adapter
|
||||
|
||||
def frame_bytes(report: bytes, carry: list) -> bytes:
|
||||
"""The protocol bytes in one input report (strips the zero padding after the frame).
|
||||
`carry` holds the bytes still missing from a frame longer than one report."""
|
||||
if carry[0] > 0:
|
||||
take = report[: carry[0]]
|
||||
carry[0] -= len(take)
|
||||
return take
|
||||
if report[:2] != b"\x10\x02" or len(report) < 5:
|
||||
return b""
|
||||
need = report[4] + 8
|
||||
take = report[:need]
|
||||
carry[0] = need - len(take)
|
||||
return take
|
||||
|
||||
|
||||
class HidStream:
|
||||
"""Gives a HID device the reader/writer interface Device uses for TCP."""
|
||||
|
||||
def __init__(self, dev):
|
||||
self.dev = dev
|
||||
self.loop = asyncio.get_running_loop()
|
||||
self.queue: asyncio.Queue = asyncio.Queue()
|
||||
self.closed = False
|
||||
threading.Thread(target=self._reader, daemon=True, name="usb-read").start()
|
||||
|
||||
def _reader(self):
|
||||
carry = [0]
|
||||
try:
|
||||
while not self.closed:
|
||||
data = frame_bytes(self.dev.read_report(), carry)
|
||||
if data:
|
||||
self.loop.call_soon_threadsafe(self.queue.put_nowait, data)
|
||||
except OSError:
|
||||
pass
|
||||
self.loop.call_soon_threadsafe(self.queue.put_nowait, b"") # EOF
|
||||
|
||||
async def read(self, _n: int = -1) -> bytes:
|
||||
return await self.queue.get()
|
||||
|
||||
def write(self, data: bytes):
|
||||
self.dev.write_report(data)
|
||||
|
||||
async def drain(self):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
if not self.closed:
|
||||
self.closed = True
|
||||
self.dev.close()
|
||||
|
||||
|
||||
async def open_stream(path: str = "") -> tuple[HidStream, HidStream]:
|
||||
"""Open the DSP at `path` (empty = the first one found)."""
|
||||
if not path:
|
||||
devs = await asyncio.to_thread(list_devices)
|
||||
if not devs:
|
||||
raise ConnectionError("No DSP found via USB – check the cable")
|
||||
path = devs[0]["path"]
|
||||
dev = await asyncio.to_thread(HidDevice, path)
|
||||
s = HidStream(dev)
|
||||
return s, s
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Builds the desktop programs into dist/:
|
||||
|
||||
python -m pip install pyinstaller pywebview pillow
|
||||
python packaging/build.py
|
||||
|
||||
Windows:
|
||||
dist/DSP Control.exe desktop app (own window, no PIN; optional remote access with PIN)
|
||||
dist/DSP Control Pi Writer.exe SD card writer for a Raspberry Pi running the WebUI
|
||||
macOS:
|
||||
dist/DSP Control.app the same desktop app
|
||||
dist/DSP Control.dmg disk image with the app and a link to /Applications
|
||||
"""
|
||||
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SEP = ";" if sys.platform == "win32" else ":"
|
||||
|
||||
|
||||
def pyinstaller(*args, onefile=True):
|
||||
cmd = [sys.executable, "-m", "PyInstaller", "--noconfirm", "--onefile" if onefile else "--onedir", "--windowed",
|
||||
"--distpath", str(ROOT / "dist"), "--workpath", str(ROOT / "build"), "--specpath", str(ROOT / "build"), *args]
|
||||
print(">", " ".join(cmd))
|
||||
subprocess.run(cmd, cwd=ROOT, check=True)
|
||||
|
||||
|
||||
def data(src, dest="."):
|
||||
return ["--add-data", f"{ROOT / src}{SEP}{dest}"]
|
||||
|
||||
|
||||
def build_mac():
|
||||
app = ROOT / "dist" / "DSP Control.app"
|
||||
pyinstaller("--name", "DSP Control", "--icon", str(ROOT / "packaging" / "dsp-control.icns"),
|
||||
"--osx-bundle-identifier", "at.thiemoo.dspcontrol", *data("static", "static"),
|
||||
str(ROOT / "desktop.py"), onefile=False) # a .app bundle is always a folder
|
||||
shutil.rmtree(ROOT / "dist" / "DSP Control", ignore_errors=True) # the loose onedir copy next to the .app
|
||||
dmg = ROOT / "dist" / "DSP Control.dmg"
|
||||
dmg.unlink(missing_ok=True)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
shutil.copytree(app, Path(tmp) / app.name, symlinks=True)
|
||||
(Path(tmp) / "Applications").symlink_to("/Applications")
|
||||
subprocess.run(["hdiutil", "create", "-volname", "DSP Control", "-srcfolder", tmp, "-ov",
|
||||
"-format", "UDZO", str(dmg)], check=True)
|
||||
print("\nDone:", app.name, dmg.name, sep="\n ")
|
||||
|
||||
|
||||
subprocess.run([sys.executable, str(ROOT / "packaging" / "make_icons.py")], check=True)
|
||||
|
||||
if sys.platform == "darwin":
|
||||
build_mac()
|
||||
sys.exit()
|
||||
|
||||
pyinstaller("--name", "DSP Control", "--icon", str(ROOT / "packaging" / "dsp-control.ico"),
|
||||
*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"))
|
||||
|
||||
print("\nDone:", *(p.name for p in (ROOT / "dist").glob("*.exe")), sep="\n ")
|
||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 10 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,53 @@
|
||||
"""Draws the two app icons (.ico, .icns) with Pillow: python packaging/make_icons.py"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
S = 256
|
||||
|
||||
|
||||
def base(bg="#161a20"):
|
||||
im = Image.new("RGBA", (S, S), (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(im)
|
||||
d.rounded_rectangle((8, 8, S - 8, S - 8), radius=52, fill=bg)
|
||||
return im, d
|
||||
|
||||
|
||||
def bars(d, x0, y0, scale, color="#38bdf8"):
|
||||
# the WebUI logo: four level bars
|
||||
for x, top in ((7, 10), (13, 6), (19, 14), (25, 9)):
|
||||
d.line(((x0 + x * scale, y0 + 22 * scale), (x0 + x * scale, y0 + top * scale)), fill=color, width=int(3 * scale))
|
||||
d.ellipse((x0 + x * scale - 1.5 * scale, y0 + top * scale - 1.5 * scale,
|
||||
x0 + x * scale + 1.5 * scale, y0 + top * scale + 1.5 * scale), fill=color)
|
||||
d.ellipse((x0 + x * scale - 1.5 * scale, y0 + 22 * scale - 1.5 * scale,
|
||||
x0 + x * scale + 1.5 * scale, y0 + 22 * scale + 1.5 * scale), fill=color)
|
||||
|
||||
|
||||
def app_icon():
|
||||
im, d = base()
|
||||
bars(d, 0, 12, 8)
|
||||
return im
|
||||
|
||||
|
||||
def writer_icon():
|
||||
im, d = base()
|
||||
# SD card outline with cut corner
|
||||
d.polygon([(70, 40), (160, 40), (190, 70), (190, 216), (70, 216)], fill="#e8edf3")
|
||||
for i in range(5):
|
||||
d.rectangle((86 + i * 19, 52, 96 + i * 19, 82), fill="#c0841a")
|
||||
bars(d, 74, 98, 3.6, color="#0284c7")
|
||||
# Raspberry-red write arrow
|
||||
d.polygon([(196, 150), (232, 150), (214, 182)], fill="#e11d48")
|
||||
d.rectangle((207, 112, 221, 152), fill="#e11d48")
|
||||
return im
|
||||
|
||||
|
||||
for name, im in (("dsp-control.ico", app_icon()), ("pi-writer.ico", writer_icon())):
|
||||
im.save(HERE / name, sizes=[(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)])
|
||||
im.save(HERE / name.replace(".ico", ".png"))
|
||||
if sys.platform == "darwin": # the macOS app icon, only needed (and built) there
|
||||
im.resize((1024, 1024), Image.LANCZOS).save(HERE / name.replace(".ico", ".icns"))
|
||||
print("wrote", name)
|
||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.7 KiB |
+304
@@ -0,0 +1,304 @@
|
||||
"""Raspberry Pi OS images and first-boot setup for the DSP Control SD card writer.
|
||||
|
||||
The current Raspberry Pi OS Lite images are configured with cloud-init: files in the FAT boot
|
||||
partition (user-data, network-config, meta-data) plus a NoCloud entry in cmdline.txt - the same
|
||||
layout Raspberry Pi Imager writes. Our user-data then installs DSP Control from the boot partition
|
||||
as a systemd service on port 80, so the Pi needs no internet connection.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
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
|
||||
USER_AGENT = "DSP-Control-Pi-Writer/1.0"
|
||||
|
||||
# Pi models offered in the writer: (name, description, os bits)
|
||||
MODELS = [
|
||||
("Raspberry Pi 5", "Pi 5, Pi 500, CM5", 64),
|
||||
("Raspberry Pi 4", "Pi 4 B, Pi 400, CM4", 64),
|
||||
("Raspberry Pi 3", "Pi 3 A+/B/B+, CM3", 64),
|
||||
("Raspberry Pi Zero 2 W", "Zero 2 W", 64),
|
||||
("Raspberry Pi 2", "Pi 2 B", 32),
|
||||
("Raspberry Pi 1", "Pi 1 A/A+/B/B+", 32),
|
||||
("Raspberry Pi Zero", "Zero, Zero W, Zero WH", 32),
|
||||
]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ OS list / download
|
||||
|
||||
def fetch_os_list() -> dict:
|
||||
req = urllib.request.Request(OS_LIST_URL, headers={"User-Agent": USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=30) as r:
|
||||
return json.loads(r.read())
|
||||
|
||||
|
||||
def find_image(os_list: dict, bits: int) -> dict:
|
||||
"""The Raspberry Pi OS Lite entry for 32 or 64 bit."""
|
||||
want = IMAGE_NAMES[bits]
|
||||
|
||||
def walk(items):
|
||||
for it in items:
|
||||
if it.get("name") == want and it.get("url"):
|
||||
return it
|
||||
found = walk(it.get("subitems") or [])
|
||||
if found:
|
||||
return found
|
||||
return None
|
||||
|
||||
img = walk(os_list.get("os_list", []))
|
||||
if not img:
|
||||
raise RuntimeError(f"„{want}“ nicht in der Raspberry-Pi-Liste gefunden")
|
||||
if img.get("init_format") not in ("cloudinit", "cloudinit-rpi"):
|
||||
raise RuntimeError(f"Unbekanntes Einrichtungsformat „{img.get('init_format')}“ – Writer aktualisieren")
|
||||
return img
|
||||
|
||||
|
||||
def download(img: dict, cache_dir: Path, progress) -> Path:
|
||||
"""Download (or reuse) the compressed image and check its SHA-256. progress(done, total)."""
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
name = img["url"].rsplit("/", 1)[-1]
|
||||
dest = cache_dir / name
|
||||
want = (img.get("image_download_sha256") or "").lower()
|
||||
if dest.exists() and want and sha256_file(dest) == want:
|
||||
return dest
|
||||
for old in cache_dir.glob("*.img.xz"): # keep only the current image
|
||||
old.unlink(missing_ok=True)
|
||||
tmp = dest.with_suffix(dest.suffix + ".part")
|
||||
req = urllib.request.Request(img["url"], headers={"User-Agent": USER_AGENT})
|
||||
h = hashlib.sha256()
|
||||
with urllib.request.urlopen(req, timeout=60) as r, open(tmp, "wb") as f:
|
||||
total = int(r.headers.get("Content-Length") or img.get("image_download_size") or 0)
|
||||
done = 0
|
||||
while chunk := r.read(1 << 20):
|
||||
f.write(chunk)
|
||||
h.update(chunk)
|
||||
done += len(chunk)
|
||||
progress(done, total)
|
||||
if want and h.hexdigest() != want:
|
||||
tmp.unlink(missing_ok=True)
|
||||
raise RuntimeError("Download beschädigt (Prüfsumme stimmt nicht) – bitte nochmal versuchen")
|
||||
tmp.replace(dest)
|
||||
return dest
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
while chunk := f.read(1 << 20):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ password hash
|
||||
|
||||
_ITOA = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
||||
|
||||
|
||||
def sha512_crypt(password: str, salt: str | None = None, rounds: int = 5000) -> str:
|
||||
"""glibc SHA-512 crypt ("$6$..."), accepted by Linux login/PAM. Python has no crypt module on Windows."""
|
||||
if salt is None:
|
||||
salt = "".join(secrets.choice(_ITOA) for _ in range(16))
|
||||
p, s = password.encode(), salt.encode()[:16]
|
||||
rep = lambda block, n: (block * (n // len(block) + 1))[:n]
|
||||
b = hashlib.sha512(p + s + p).digest()
|
||||
a = hashlib.sha512(p + s + rep(b, len(p)))
|
||||
i = len(p)
|
||||
while i:
|
||||
a.update(b if i & 1 else p)
|
||||
i >>= 1
|
||||
c = a.digest()
|
||||
pp = rep(hashlib.sha512(p * len(p)).digest(), len(p))
|
||||
ss = rep(hashlib.sha512(s * (16 + c[0])).digest(), len(s))
|
||||
for r in range(rounds):
|
||||
d = hashlib.sha512(pp if r & 1 else c)
|
||||
if r % 3:
|
||||
d.update(ss)
|
||||
if r % 7:
|
||||
d.update(pp)
|
||||
d.update(c if r & 1 else pp)
|
||||
c = d.digest()
|
||||
out = []
|
||||
|
||||
def b64(v, n):
|
||||
for _ in range(n):
|
||||
out.append(_ITOA[v & 63])
|
||||
v >>= 6
|
||||
|
||||
for x, y, z in ((0, 21, 42), (22, 43, 1), (44, 2, 23), (3, 24, 45), (25, 46, 4), (47, 5, 26), (6, 27, 48),
|
||||
(28, 49, 7), (50, 8, 29), (9, 30, 51), (31, 52, 10), (53, 11, 32), (12, 33, 54), (34, 55, 13),
|
||||
(56, 14, 35), (15, 36, 57), (37, 58, 16), (59, 17, 38), (18, 39, 60), (40, 61, 19), (62, 20, 41)):
|
||||
b64(c[x] << 16 | c[y] << 8 | c[z], 4)
|
||||
b64(c[63], 2)
|
||||
return "$6$" + ("" if rounds == 5000 else f"rounds={rounds}$") + s.decode() + "$" + "".join(out)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ first-boot files
|
||||
|
||||
def yq(v: str) -> str:
|
||||
"""YAML double-quoted scalar."""
|
||||
return '"' + str(v).replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n").replace("\r", "") + '"'
|
||||
|
||||
|
||||
def validate(cfg: dict) -> list[str]:
|
||||
errs = []
|
||||
if not re.fullmatch(r"[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?", cfg["hostname"]):
|
||||
errs.append("Hostname: nur Kleinbuchstaben, Ziffern und „-“")
|
||||
if not re.fullmatch(r"[a-z_][a-z0-9_-]{0,31}", cfg["user"]) or cfg["user"] in ("root", "dspctl"):
|
||||
errs.append("Benutzername: Kleinbuchstaben/Ziffern, nicht „root“")
|
||||
if len(cfg["password"]) < 4:
|
||||
errs.append("Passwort: mindestens 4 Zeichen")
|
||||
if cfg["ssid"] and cfg["wifi_password"] and not 8 <= len(cfg["wifi_password"]) <= 63:
|
||||
errs.append("WLAN-Passwort: 8 bis 63 Zeichen (leer = offenes WLAN)")
|
||||
if cfg["ssid"] and not re.fullmatch(r"[A-Za-z]{2}", cfg["country"]):
|
||||
errs.append("WLAN-Land: zweistelliger Code, z. B. AT")
|
||||
if not re.fullmatch(r"\d{4}", cfg["pin"]):
|
||||
errs.append("PIN: 4 Ziffern")
|
||||
for k in ("dsp204", "dsp408"):
|
||||
if cfg.get(k) and not re.fullmatch(r"\d{1,3}(\.\d{1,3}){3}", cfg[k]):
|
||||
errs.append(f"IP-Adresse {k[3:]}: ungültig")
|
||||
return errs
|
||||
|
||||
|
||||
def user_data(cfg: dict) -> str:
|
||||
lines = [
|
||||
"#cloud-config",
|
||||
"manage_resolv_conf: false",
|
||||
"",
|
||||
f"hostname: {yq(cfg['hostname'])}",
|
||||
"manage_etc_hosts: true",
|
||||
f"timezone: {yq(cfg.get('timezone') or 'Europe/Vienna')}",
|
||||
"",
|
||||
"user:",
|
||||
f" name: {yq(cfg['user'])}",
|
||||
" shell: /bin/bash",
|
||||
" lock_passwd: false",
|
||||
f" passwd: {yq(sha512_crypt(cfg['password']))}",
|
||||
" sudo: null",
|
||||
"",
|
||||
]
|
||||
if cfg.get("ssh"):
|
||||
lines += ["ssh_pwauth: true", ""]
|
||||
lines.append("runcmd:")
|
||||
if cfg.get("ssh"):
|
||||
lines.append(" - [ systemctl, enable, --now, ssh ]")
|
||||
if not cfg["ssid"] and cfg.get("country"):
|
||||
lines.append(" - [ rfkill, unblock, wifi ]")
|
||||
lines.append(" - [ sh, /boot/firmware/dsp-control/install.sh ]")
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def network_config(cfg: dict) -> str | None:
|
||||
if not cfg["ssid"]:
|
||||
return None # Ethernet works by default
|
||||
lines = [
|
||||
"network:",
|
||||
" version: 2",
|
||||
" ethernets:",
|
||||
" eth0:",
|
||||
" dhcp4: true",
|
||||
" dhcp6: true",
|
||||
" optional: true",
|
||||
" wifis:",
|
||||
" wlan0:",
|
||||
" dhcp4: true",
|
||||
f" regulatory-domain: {yq(cfg['country'].upper())}",
|
||||
" access-points:",
|
||||
f" {yq(cfg['ssid'])}:",
|
||||
]
|
||||
if cfg["wifi_password"]:
|
||||
lines.append(f" password: {yq(cfg['wifi_password'])}")
|
||||
else:
|
||||
lines += [" auth:", " key-management: none"]
|
||||
lines.append(" optional: true")
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
INSTALL_SH = """#!/bin/sh
|
||||
# DSP Control first-boot install (run once by cloud-init)
|
||||
set -e
|
||||
SRC=/boot/firmware/dsp-control
|
||||
id dspctl >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin dspctl
|
||||
mkdir -p /opt/dsp-control
|
||||
cp -r "$SRC/app/." /opt/dsp-control/
|
||||
install -d -o dspctl -g dspctl -m 700 /var/lib/dsp-control
|
||||
if [ -f "$SRC/config.json" ]; then
|
||||
[ -f /var/lib/dsp-control/config.json ] || install -o dspctl -g dspctl -m 600 "$SRC/config.json" /var/lib/dsp-control/config.json
|
||||
rm -f "$SRC/config.json"
|
||||
fi
|
||||
# DSPs on USB (HID, VID 0168 / PID 0821): let the service user open them
|
||||
echo 'SUBSYSTEM=="hidraw", ATTRS{idVendor}=="0168", ATTRS{idProduct}=="0821", MODE="0666"' > /etc/udev/rules.d/60-dsp-control.rules
|
||||
udevadm control --reload-rules || true
|
||||
udevadm trigger --subsystem-match=hidraw || true
|
||||
install -m 644 "$SRC/dsp-control.service" /etc/systemd/system/dsp-control.service
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now dsp-control.service
|
||||
"""
|
||||
|
||||
SERVICE = """[Unit]
|
||||
Description=DSP Control WebUI for t.racks DSP 204/408
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
User=dspctl
|
||||
ExecStart=/usr/bin/python3 /opt/dsp-control/server.py --port 80 --config /var/lib/dsp-control/config.json
|
||||
AmbientCapabilities=CAP_NET_BIND_SERVICE
|
||||
Restart=always
|
||||
RestartSec=3
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
"""
|
||||
|
||||
|
||||
def initial_config(cfg: dict) -> dict:
|
||||
salt = secrets.token_hex(16)
|
||||
devices = []
|
||||
for key, name, model in (("dsp204", "DSP 204", "204"), ("dsp408", "DSP 408", "408")):
|
||||
if cfg.get(key):
|
||||
devices.append({"id": key, "name": name, "host": cfg[key], "port": 9761, "model": model,
|
||||
"addr": 1, "autoconnect": True})
|
||||
return {"devices": devices, "auth": {"salt": salt, "hash": server.hash_pin(cfg["pin"], salt)}, "sessions": {}}
|
||||
|
||||
|
||||
def write_boot_files(boot: Path, cfg: dict, app_root: Path):
|
||||
"""Put the first-boot setup and the DSP Control files onto the mounted boot partition."""
|
||||
if not (boot / "cmdline.txt").exists():
|
||||
raise RuntimeError(f"{boot} ist keine Raspberry-Pi-Bootpartition (cmdline.txt fehlt)")
|
||||
target = boot / "dsp-control"
|
||||
if target.exists():
|
||||
shutil.rmtree(target)
|
||||
(target / "app").mkdir(parents=True)
|
||||
for name in APP_FILES:
|
||||
src = app_root / name
|
||||
if src.is_dir():
|
||||
shutil.copytree(src, target / "app" / name, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
|
||||
else:
|
||||
shutil.copy2(src, target / "app" / name)
|
||||
lf = lambda p, text: p.write_text(text, encoding="utf-8", newline="\n")
|
||||
lf(target / "install.sh", INSTALL_SH)
|
||||
lf(target / "dsp-control.service", SERVICE)
|
||||
lf(target / "config.json", json.dumps(initial_config(cfg), indent=2))
|
||||
|
||||
instance = f"dsp-control-{int(time.time() * 1000)}"
|
||||
lf(boot / "meta-data", f"instance-id: {instance}\n")
|
||||
lf(boot / "user-data", user_data(cfg))
|
||||
net = network_config(cfg)
|
||||
if net:
|
||||
lf(boot / "network-config", net)
|
||||
cmdline = (boot / "cmdline.txt").read_text(encoding="utf-8").strip()
|
||||
cmdline = re.sub(r"\s*ds=nocloud;i=\S+", "", cmdline)
|
||||
cmdline += f" ds=nocloud;i={instance}"
|
||||
if not cfg["ssid"] and cfg.get("country") and "cfg80211.ieee80211_regdom" not in cmdline:
|
||||
cmdline += f" cfg80211.ieee80211_regdom={cfg['country'].upper()}"
|
||||
lf(boot / "cmdline.txt", cmdline + "\n")
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
"""DSP Control Pi Writer: prepares a bootable SD card with Raspberry Pi OS Lite + DSP Control.
|
||||
|
||||
After the first boot (2-5 minutes) the WebUI is at http://<hostname>.local - no monitor,
|
||||
keyboard or internet needed on the Pi.
|
||||
|
||||
Build: pyinstaller packaging/pi-writer.spec
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
import sys
|
||||
import threading
|
||||
import tkinter as tk
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
from tkinter import messagebox, ttk
|
||||
|
||||
import pi_image
|
||||
import win_disk
|
||||
|
||||
APP = "DSP Control Pi Writer"
|
||||
ROOT = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent)) # bundled app files
|
||||
SETTINGS = Path(os.environ.get("APPDATA") or Path.home()) / "DSP Control" / "pi-writer.json"
|
||||
CACHE = Path(os.environ.get("LOCALAPPDATA") or Path.home()) / "DSP Control" / "pi-images"
|
||||
REMEMBER = ("model", "hostname", "ssid", "country", "user", "ssh", "dsp204", "dsp408", "verify")
|
||||
|
||||
|
||||
class Writer(tk.Tk):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.title(APP)
|
||||
self.minsize(560, 640)
|
||||
self.events: queue.Queue = queue.Queue()
|
||||
self.busy = False
|
||||
self.disks: list[dict] = []
|
||||
saved = self.load_settings()
|
||||
|
||||
self.v = {
|
||||
"model": tk.StringVar(value=saved.get("model", pi_image.MODELS[1][0])),
|
||||
"disk": tk.StringVar(),
|
||||
"hostname": tk.StringVar(value=saved.get("hostname", "dsp-control")),
|
||||
"ssid": tk.StringVar(value=saved.get("ssid", "")),
|
||||
"wifi_password": tk.StringVar(),
|
||||
"country": tk.StringVar(value=saved.get("country", "AT")),
|
||||
"user": tk.StringVar(value=saved.get("user", "dsp")),
|
||||
"password": tk.StringVar(),
|
||||
"ssh": tk.BooleanVar(value=saved.get("ssh", True)),
|
||||
"pin": tk.StringVar(value="1234"),
|
||||
"dsp204": tk.StringVar(value=saved.get("dsp204", "")),
|
||||
"dsp408": tk.StringVar(value=saved.get("dsp408", "")),
|
||||
"verify": tk.BooleanVar(value=saved.get("verify", True)),
|
||||
}
|
||||
self.build()
|
||||
self.after(100, self.poll)
|
||||
self.after(200, self.refresh_disks)
|
||||
|
||||
# ------------------------------------------------------------ layout
|
||||
|
||||
def build(self):
|
||||
pad = {"padx": 12, "pady": 4}
|
||||
root = ttk.Frame(self, padding=(8, 8))
|
||||
root.pack(fill="both", expand=True)
|
||||
root.columnconfigure(0, weight=1)
|
||||
|
||||
ttk.Label(root, text="Raspberry Pi für DSP Control", font=("Segoe UI", 14, "bold")).grid(sticky="w", **pad)
|
||||
ttk.Label(root, text="Schreibt Raspberry Pi OS Lite mit vorinstallierter DSP-Control-WebUI auf eine SD-Karte.",
|
||||
foreground="#555").grid(sticky="w", padx=12)
|
||||
|
||||
def section(title):
|
||||
f = ttk.LabelFrame(root, text=title, padding=(10, 6))
|
||||
f.grid(sticky="ew", padx=12, pady=6)
|
||||
f.columnconfigure(0, minsize=110)
|
||||
f.columnconfigure(1, weight=1)
|
||||
return f
|
||||
|
||||
def row(f, r, label, widget, hint=None):
|
||||
ttk.Label(f, text=label).grid(row=r, column=0, sticky="w", pady=3, padx=(0, 10))
|
||||
widget.grid(row=r, column=1, sticky="ew", pady=3)
|
||||
if hint:
|
||||
ttk.Label(f, text=hint, foreground="#777").grid(row=r, column=2, sticky="w", padx=(8, 0))
|
||||
|
||||
f = section("1 · Gerät")
|
||||
models = [f"{n} ({d})" for n, d, _ in pi_image.MODELS]
|
||||
cur = next((m for m in models if m.startswith(self.v["model"].get())), models[1])
|
||||
self.model_box = ttk.Combobox(f, values=models, state="readonly")
|
||||
self.model_box.set(cur)
|
||||
row(f, 0, "Raspberry Pi", self.model_box)
|
||||
disk_row = ttk.Frame(f)
|
||||
disk_row.columnconfigure(0, weight=1)
|
||||
self.disk_box = ttk.Combobox(disk_row, textvariable=self.v["disk"], state="readonly")
|
||||
self.disk_box.grid(row=0, column=0, sticky="ew")
|
||||
ttk.Button(disk_row, text="↻", width=3, command=self.refresh_disks).grid(row=0, column=1, padx=(6, 0))
|
||||
row(f, 1, "SD-Karte", disk_row)
|
||||
|
||||
f = section("2 · Netzwerk")
|
||||
row(f, 0, "Hostname", ttk.Entry(f, textvariable=self.v["hostname"]), ".local")
|
||||
row(f, 1, "WLAN-Name", ttk.Entry(f, textvariable=self.v["ssid"]), "leer = nur LAN-Kabel")
|
||||
row(f, 2, "WLAN-Passwort", ttk.Entry(f, textvariable=self.v["wifi_password"], show="•"))
|
||||
row(f, 3, "Land", ttk.Entry(f, textvariable=self.v["country"], width=6), "z. B. AT, DE, CH")
|
||||
|
||||
f = section("3 · Zugang")
|
||||
row(f, 0, "Benutzer", ttk.Entry(f, textvariable=self.v["user"]), "für SSH / Wartung")
|
||||
row(f, 1, "Passwort", ttk.Entry(f, textvariable=self.v["password"], show="•"))
|
||||
ttk.Checkbutton(f, text="SSH aktivieren", variable=self.v["ssh"]).grid(row=2, column=1, sticky="w", pady=3)
|
||||
row(f, 3, "WebUI-PIN", ttk.Entry(f, textvariable=self.v["pin"], width=8), "4 Ziffern, später änderbar")
|
||||
|
||||
f = section("4 · DSPs (optional, später in der WebUI änderbar)")
|
||||
row(f, 0, "IP DSP 204", ttk.Entry(f, textvariable=self.v["dsp204"]), "z. B. 192.168.1.101")
|
||||
row(f, 1, "IP DSP 408", ttk.Entry(f, textvariable=self.v["dsp408"]))
|
||||
|
||||
bottom = ttk.Frame(root)
|
||||
bottom.grid(sticky="ew", padx=12, pady=(8, 4))
|
||||
bottom.columnconfigure(0, weight=1)
|
||||
ttk.Checkbutton(bottom, text="Nach dem Schreiben überprüfen", variable=self.v["verify"]).grid(row=0, column=0, sticky="w")
|
||||
self.go = ttk.Button(bottom, text="SD-Karte schreiben", command=self.start)
|
||||
self.go.grid(row=0, column=1, sticky="e")
|
||||
self.bar = ttk.Progressbar(root, maximum=1000)
|
||||
self.bar.grid(sticky="ew", padx=12, pady=(6, 2))
|
||||
self.status = ttk.Label(root, text="Bereit.", foreground="#333")
|
||||
self.status.grid(sticky="w", padx=12, pady=(0, 8))
|
||||
|
||||
# ------------------------------------------------------------ settings
|
||||
|
||||
def load_settings(self) -> dict:
|
||||
try:
|
||||
return json.loads(SETTINGS.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
def save_settings(self, cfg: dict):
|
||||
try:
|
||||
SETTINGS.parent.mkdir(parents=True, exist_ok=True)
|
||||
SETTINGS.write_text(json.dumps({k: cfg[k] for k in REMEMBER if k in cfg}, indent=2), encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# ------------------------------------------------------------ disks
|
||||
|
||||
def refresh_disks(self):
|
||||
if self.busy:
|
||||
return
|
||||
self.status.config(text="Suche SD-Karten…")
|
||||
threading.Thread(target=self._list_disks, daemon=True).start()
|
||||
|
||||
def _list_disks(self):
|
||||
try:
|
||||
self.events.put(("disks", win_disk.list_disks()))
|
||||
except Exception as e: # noqa: BLE001
|
||||
self.events.put(("disks_err", str(e)))
|
||||
|
||||
# ------------------------------------------------------------ run
|
||||
|
||||
def collect(self) -> dict:
|
||||
cfg = {k: (v.get().strip() if isinstance(v, tk.StringVar) and k not in ("password", "wifi_password") else v.get())
|
||||
for k, v in self.v.items()}
|
||||
cfg["hostname"] = cfg["hostname"].lower()
|
||||
cfg["user"] = cfg["user"].lower()
|
||||
idx = self.model_box.current()
|
||||
cfg["model"], _, cfg["bits"] = pi_image.MODELS[max(0, idx)]
|
||||
return cfg
|
||||
|
||||
def start(self):
|
||||
if self.busy:
|
||||
return
|
||||
cfg = self.collect()
|
||||
errs = pi_image.validate(cfg)
|
||||
disk = next((d for d in self.disks if win_disk.describe(d) == cfg["disk"]), None)
|
||||
if not disk:
|
||||
errs.insert(0, "Bitte eine SD-Karte wählen")
|
||||
if errs:
|
||||
messagebox.showerror(APP, "\n".join(errs))
|
||||
return
|
||||
if not messagebox.askyesno(APP, f"ALLE Daten auf\n\n{win_disk.describe(disk)}\n\nwerden gelöscht. Fortfahren?",
|
||||
icon="warning"):
|
||||
return
|
||||
self.save_settings(cfg)
|
||||
self.busy = True
|
||||
self.go.config(state="disabled")
|
||||
threading.Thread(target=self.job, args=(cfg, disk), daemon=True).start()
|
||||
|
||||
def job(self, cfg: dict, disk: dict):
|
||||
ev = self.events.put
|
||||
try:
|
||||
ev(("status", "Lade Raspberry-Pi-OS-Liste…", None))
|
||||
img = pi_image.find_image(pi_image.fetch_os_list(), cfg["bits"])
|
||||
ev(("status", f"{img['name']} vom {img.get('release_date', '?')}", None))
|
||||
path = pi_image.download(img, CACHE, lambda d, t: ev(("progress", f"Download {d / 1e6:.0f} / {t / 1e6:.0f} MB", d, t)))
|
||||
phases = {"write": "Schreibe", "verify": "Überprüfe"}
|
||||
win_disk.write_image(disk["Number"], path, int(img.get("extract_size") or 0),
|
||||
lambda ph, d, t: ev(("progress", f"{phases[ph]} {d / 1e9:.2f} / {t / 1e9:.2f} GB", d, t)),
|
||||
verify=cfg["verify"])
|
||||
ev(("status", "Richte DSP Control ein…", None))
|
||||
boot = win_disk.mount_boot_partition(disk["Number"])
|
||||
pi_image.write_boot_files(boot, cfg, ROOT)
|
||||
win_disk.eject(boot)
|
||||
ev(("done", cfg))
|
||||
except Exception as e: # noqa: BLE001 - every failure is shown to the user
|
||||
traceback.print_exc()
|
||||
ev(("error", str(e)))
|
||||
|
||||
def poll(self):
|
||||
try:
|
||||
while True:
|
||||
kind, *a = self.events.get_nowait()
|
||||
if kind == "disks":
|
||||
self.disks = a[0]
|
||||
names = [win_disk.describe(d) for d in self.disks]
|
||||
self.disk_box.config(values=names)
|
||||
if self.v["disk"].get() not in names:
|
||||
self.v["disk"].set(names[0] if len(names) == 1 else "")
|
||||
self.status.config(text=f"{len(names)} SD-Karte(n) gefunden." if names
|
||||
else "Keine SD-Karte gefunden – einstecken und ↻ drücken.")
|
||||
elif kind == "disks_err":
|
||||
self.status.config(text="Fehler beim Suchen: " + a[0])
|
||||
elif kind == "status":
|
||||
self.status.config(text=a[0])
|
||||
self.bar.config(mode="indeterminate")
|
||||
self.bar.start(15)
|
||||
elif kind == "progress":
|
||||
text, done, total = a
|
||||
self.bar.stop()
|
||||
self.bar.config(mode="determinate", value=1000 * done / total if total else 0)
|
||||
self.status.config(text=text)
|
||||
elif kind in ("done", "error"):
|
||||
self.busy = False
|
||||
self.go.config(state="normal")
|
||||
self.bar.stop()
|
||||
self.bar.config(mode="determinate", value=1000 if kind == "done" else 0)
|
||||
if kind == "done":
|
||||
cfg = a[0]
|
||||
self.status.config(text="Fertig.")
|
||||
messagebox.showinfo(APP, "Fertig! Die SD-Karte kann entnommen werden.\n\n"
|
||||
"Karte in den Raspberry Pi stecken, Netzwerk (LAN oder WLAN) und Strom anschließen. "
|
||||
"Der erste Start dauert 2–5 Minuten.\n\n"
|
||||
f"Dann im Browser öffnen: http://{cfg['hostname']}.local\n"
|
||||
f"PIN: {cfg['pin']}")
|
||||
else:
|
||||
self.status.config(text="Fehler: " + a[0])
|
||||
messagebox.showerror(APP, a[0])
|
||||
self.refresh_disks()
|
||||
except queue.Empty:
|
||||
pass
|
||||
self.after(100, self.poll)
|
||||
|
||||
|
||||
def main():
|
||||
if sys.platform == "win32" and not win_disk.is_admin():
|
||||
if win_disk.relaunch_as_admin():
|
||||
return
|
||||
messagebox.showerror(APP, "Zum Beschreiben von SD-Karten werden Administratorrechte benötigt.")
|
||||
return
|
||||
try:
|
||||
import ctypes
|
||||
ctypes.windll.shcore.SetProcessDpiAwareness(1) # sharp text on high-DPI screens
|
||||
except (AttributeError, OSError):
|
||||
pass
|
||||
Writer().mainloop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,646 @@
|
||||
"""DSP Control - web server for t.racks DSP 204 / DSP 408.
|
||||
|
||||
Usage: python server.py [--host 0.0.0.0] [--port 8080] [--config config.json]
|
||||
Then open http://<this-computer>:8080 on your phone.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import base64
|
||||
import errno
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import mimetypes
|
||||
import re
|
||||
import secrets
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from dsp import preset, usbhid
|
||||
from dsp.device import Device
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
STATIC = (ROOT / "static").resolve() # resolved: in the macOS .app bundle it is a symlink
|
||||
log = logging.getLogger("server")
|
||||
|
||||
DEFAULT_PIN = "1234"
|
||||
SESSION_TTL = 30 * 24 * 3600 # stay logged in for 30 days
|
||||
MAX_SESSIONS = 50
|
||||
COOKIE = "dspsess"
|
||||
CONFIG_FORMAT = "dsp-control-config"
|
||||
MAX_UNDO = 20 # automatic backups kept per DSP before each import
|
||||
|
||||
|
||||
def _num(v, lo: float, hi: float, default: float = 0.0) -> float:
|
||||
try:
|
||||
v = float(v)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return min(hi, max(lo, v)) if v == v else default
|
||||
|
||||
|
||||
def local_ips() -> list[str]:
|
||||
"""IPv4 addresses other devices on the LAN can reach this computer at."""
|
||||
ips = []
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
|
||||
s.connect(("192.0.2.1", 9)) # no packet is sent; just picks the outgoing interface
|
||||
ips.append(s.getsockname()[0])
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET):
|
||||
ip = info[4][0]
|
||||
if ip not in ips and not ip.startswith(("127.", "169.254.")):
|
||||
ips.append(ip)
|
||||
except OSError:
|
||||
pass
|
||||
return ips
|
||||
|
||||
|
||||
def clean_limiter(data: dict) -> dict:
|
||||
"""Validate the limiter calculator data (amplifier profiles + output assignments)."""
|
||||
amps = []
|
||||
for a in (data.get("amps") or [])[:100]:
|
||||
amps.append({
|
||||
"id": re.sub(r"[^\w-]", "", str(a.get("id") or uuid.uuid4().hex[:8]))[:16] or uuid.uuid4().hex[:8],
|
||||
"name": str(a.get("name") or "Amplifier")[:40],
|
||||
"mode": "gain" if a.get("mode") == "gain" else "sens",
|
||||
"sens": _num(a.get("sens"), 0.05, 20, 1.4),
|
||||
"gain": _num(a.get("gain"), 0, 60, 32),
|
||||
"p8": _num(a.get("p8"), 0, 100000), "p4": _num(a.get("p4"), 0, 100000), "p2": _num(a.get("p2"), 0, 100000),
|
||||
})
|
||||
ids = {a["id"] for a in amps}
|
||||
assign = {}
|
||||
for k, v in (data.get("assign") or {}).items():
|
||||
if re.fullmatch(r"[\w-]+:\d{1,2}", str(k)) and isinstance(v, dict) and v.get("amp") in ids:
|
||||
assign[k] = {"amp": v["amp"], "ohm": _num(v.get("ohm"), 1, 32, 8),
|
||||
"spk": _num(v.get("spk"), 0, 100000)}
|
||||
ref = {str(k)[:32]: _num(v, -20, 30) for k, v in (data.get("ref") or {}).items()}
|
||||
return {"amps": amps, "assign": assign, "ref": ref}
|
||||
|
||||
|
||||
def hash_pin(pin: str, salt: str) -> str:
|
||||
return hashlib.pbkdf2_hmac("sha256", pin.encode(), bytes.fromhex(salt), 100_000).hex()
|
||||
|
||||
|
||||
def token_id(token: str) -> str:
|
||||
"""Sessions are stored hashed so config.json never contains a usable cookie."""
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
|
||||
class App:
|
||||
def __init__(self, config_path: Path):
|
||||
self.config_path = config_path
|
||||
self.devices: dict[str, Device] = {}
|
||||
self.clients: set[asyncio.Queue] = set()
|
||||
self.auth: dict = {}
|
||||
self.sessions: dict[str, float] = {} # token hash -> expiry
|
||||
self.failures: dict[str, tuple[int, float]] = {} # ip -> (failed attempts, locked until)
|
||||
self.limiter: dict = clean_limiter({})
|
||||
# desktop app: its own window logs in with a one-time token, other devices need the PIN
|
||||
self.app_token: str | None = None
|
||||
self.app_sessions: set[str] = set()
|
||||
self.remote = {"enabled": False, "port": 8080}
|
||||
self.remote_server: asyncio.Server | None = None
|
||||
self.remote_writers: set[asyncio.StreamWriter] = set()
|
||||
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)
|
||||
|
||||
# ------------------------------------------------------------ config
|
||||
|
||||
def load(self):
|
||||
if self.config_path.exists():
|
||||
cfg = json.loads(self.config_path.read_text(encoding="utf-8"))
|
||||
else:
|
||||
cfg = {"devices": [
|
||||
{"id": "dsp204", "name": "DSP 204", "host": "192.168.1.101", "model": "204", "autoconnect": False},
|
||||
{"id": "dsp408", "name": "DSP 408", "host": "192.168.1.102", "model": "408", "autoconnect": False},
|
||||
]}
|
||||
now = time.time()
|
||||
self.sessions = {k: v for k, v in cfg.get("sessions", {}).items() if v > now}
|
||||
self.locked = bool(cfg.get("locked"))
|
||||
self.lang = cfg.get("lang") if cfg.get("lang") in ("en", "de") else ""
|
||||
self.apply_config(cfg)
|
||||
|
||||
def apply_config(self, cfg: dict):
|
||||
"""Devices, PIN, limiter data and remote settings from a config dict (file or backup)."""
|
||||
auth = cfg.get("auth") or {}
|
||||
if re.fullmatch(r"[0-9a-f]{32}", str(auth.get("salt", ""))) and re.fullmatch(r"[0-9a-f]{64}", str(auth.get("hash", ""))):
|
||||
self.auth = {"salt": auth["salt"], "hash": auth["hash"]}
|
||||
elif not self.auth: # first start (a backup without PIN keeps the current one)
|
||||
self.set_pin(DEFAULT_PIN, save=False)
|
||||
self.limiter = clean_limiter(cfg.get("limiter") or {})
|
||||
r = cfg.get("remote") or {}
|
||||
self.remote = {"enabled": bool(r.get("enabled")), "port": int(_num(r.get("port"), 1, 65535, 8080))}
|
||||
for d in cfg.get("devices", [])[:20]:
|
||||
if isinstance(d, dict):
|
||||
self.add_device(d, save=False)
|
||||
self.save()
|
||||
|
||||
# ------------------------------------------------------------ backups
|
||||
|
||||
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,
|
||||
"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()):
|
||||
await dev.stop()
|
||||
del self.devices[dev.id]
|
||||
self.broadcast({"type": "removed", "device": dev.id})
|
||||
old_auth = self.auth
|
||||
self.apply_config(doc)
|
||||
if self.auth != old_auth: # new PIN: other devices have to log in again
|
||||
self.sessions = {k: v for k, v in self.sessions.items() if k == session or k in self.app_sessions}
|
||||
self.save()
|
||||
for dev in self.devices.values():
|
||||
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
|
||||
self.broadcast({"type": "limiter", "data": self.limiter})
|
||||
if self.app_token: # desktop app: (re)start or stop the LAN listener as restored
|
||||
await self.start_remote()
|
||||
|
||||
@property
|
||||
def undo_dir(self) -> Path:
|
||||
return self.config_path.parent / "backups"
|
||||
|
||||
def undo_files(self, dev_id: str) -> list[Path]:
|
||||
return sorted(self.undo_dir.glob(f"{dev_id}-*.json"), reverse=True)
|
||||
|
||||
async def import_preset(self, dev: Device, body: dict) -> dict:
|
||||
if dev.status != "online" or not dev.state:
|
||||
raise RuntimeError("DSP is not connected")
|
||||
raw = base64.b64decode(body["raw"]) if body.get("raw") else None
|
||||
state = preset.read_file(dev.model_name, dev.model, dev.state, doc=body.get("doc"), raw=raw)
|
||||
# safety copy of the current state first, so the import can be undone
|
||||
current = await dev.export_preset()
|
||||
self.undo_dir.mkdir(exist_ok=True)
|
||||
stamp = time.strftime("%Y%m%d-%H%M%S")
|
||||
(self.undo_dir / f"{dev.id}-{stamp}.json").write_text(json.dumps(current), encoding="utf-8")
|
||||
for old in self.undo_files(dev.id)[MAX_UNDO:]:
|
||||
old.unlink(missing_ok=True)
|
||||
diffs = await dev.import_preset(state)
|
||||
return {"ok": not diffs, "differences": diffs[:20], "name": state.get("preset_name", "")}
|
||||
|
||||
async def undo_import(self, dev: Device) -> dict:
|
||||
files = self.undo_files(dev.id)
|
||||
if not files:
|
||||
raise RuntimeError("No backup available")
|
||||
doc = json.loads(files[0].read_text(encoding="utf-8"))
|
||||
state = preset.read_file(dev.model_name, dev.model, dev.state, doc=doc)
|
||||
diffs = await dev.import_preset(state)
|
||||
files[0].unlink()
|
||||
return {"ok": not diffs, "differences": diffs[:20]}
|
||||
|
||||
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,
|
||||
"sessions": sessions, "limiter": self.limiter, "remote": self.remote, "locked": self.locked}
|
||||
if self.lang:
|
||||
cfg["lang"] = self.lang
|
||||
self.config_path.write_text(json.dumps(cfg, indent=2), encoding="utf-8")
|
||||
|
||||
def add_device(self, d: dict, save=True) -> Device:
|
||||
dev_id = d.get("id") or uuid.uuid4().hex[:8]
|
||||
usb = d.get("transport") == "usb"
|
||||
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 ""))
|
||||
self.devices[dev_id] = dev
|
||||
if dev.autoconnect:
|
||||
dev.start()
|
||||
if save:
|
||||
self.save()
|
||||
return dev
|
||||
|
||||
# ------------------------------------------------------------ auth
|
||||
|
||||
def set_pin(self, pin: str, save=True):
|
||||
salt = secrets.token_hex(16)
|
||||
self.auth = {"salt": salt, "hash": hash_pin(pin, salt)}
|
||||
if save:
|
||||
self.save()
|
||||
|
||||
def check_pin(self, pin: str) -> bool:
|
||||
return secrets.compare_digest(hash_pin(str(pin), self.auth["salt"]), self.auth["hash"])
|
||||
|
||||
def session_of(self, headers: dict) -> str | None:
|
||||
"""Hashed session id of a valid login cookie, else None."""
|
||||
for part in headers.get("cookie", "").split(";"):
|
||||
k, _, v = part.strip().partition("=")
|
||||
if k == COOKIE and v:
|
||||
tid = token_id(v)
|
||||
if self.sessions.get(tid, 0) > time.time():
|
||||
return tid
|
||||
return None
|
||||
|
||||
def new_session(self) -> str:
|
||||
token = secrets.token_urlsafe(32)
|
||||
self.sessions[token_id(token)] = time.time() + SESSION_TTL
|
||||
if len(self.sessions) > MAX_SESSIONS:
|
||||
for k in sorted(self.sessions, key=self.sessions.get)[: len(self.sessions) - MAX_SESSIONS]:
|
||||
del self.sessions[k]
|
||||
self.save()
|
||||
return token
|
||||
|
||||
@staticmethod
|
||||
def cookie(token: str, max_age: int) -> str:
|
||||
return f"Set-Cookie: {COOKIE}={token}; Path=/; Max-Age={max_age}; HttpOnly; SameSite=Strict\r\n"
|
||||
|
||||
async def guarded_pin(self, who: str, pin) -> tuple[int, dict]:
|
||||
"""Check a PIN with brute-force protection per client: 200 if right, else 401/429."""
|
||||
count, until = self.failures.get(who, (0, 0.0))
|
||||
if until > time.time():
|
||||
return 429, {"error": "locked", "retry": round(until - time.time())}
|
||||
if self.check_pin(str(pin or "")):
|
||||
self.failures.pop(who, None)
|
||||
return 200, {"ok": True}
|
||||
await asyncio.sleep(0.4) # slow down guessing
|
||||
count += 1
|
||||
# 5 tries, then a 30 s lock that doubles with every further 5 failures (max 15 min)
|
||||
lock = min(900, 30 * 2 ** (count // 5 - 1)) if count % 5 == 0 else 0
|
||||
self.failures[who] = (count, time.time() + lock)
|
||||
return 401, {"error": "wrong pin", "retry": lock, "left": 5 - count % 5}
|
||||
|
||||
async def login(self, ip: str, body: dict) -> tuple[int, dict, str]:
|
||||
status, result = await self.guarded_pin(ip, body.get("pin"))
|
||||
return status, result, self.cookie(self.new_session(), SESSION_TTL) if status == 200 else ""
|
||||
|
||||
async def change_pin(self, session: str, body: dict) -> tuple[int, dict]:
|
||||
new = str(body.get("new", ""))
|
||||
# the desktop app window belongs to the owner of this computer: no current PIN needed (forgotten PIN)
|
||||
if session not in self.app_sessions and not self.check_pin(str(body.get("current", ""))):
|
||||
return 400, {"error": "Current PIN is wrong"}
|
||||
if not re.fullmatch(r"\d{4}", new):
|
||||
return 400, {"error": "The PIN must be 4 digits"}
|
||||
self.set_pin(new, save=False)
|
||||
# log out all other devices (the app window stays)
|
||||
self.sessions = {k: v for k, v in self.sessions.items() if k == session or k in self.app_sessions}
|
||||
self.save()
|
||||
return 200, {"ok": True}
|
||||
|
||||
# ------------------------------------------------------------ desktop app
|
||||
|
||||
def app_login(self, token: str) -> str | None:
|
||||
"""Session cookie value for the app window, if the one-time token matches."""
|
||||
if not self.app_token or not secrets.compare_digest(token, self.app_token):
|
||||
return None
|
||||
cookie = secrets.token_urlsafe(32)
|
||||
self.sessions[token_id(cookie)] = time.time() + SESSION_TTL
|
||||
self.app_sessions.add(token_id(cookie))
|
||||
return cookie
|
||||
|
||||
def set_locked(self, locked: bool):
|
||||
self.locked = locked
|
||||
self.save()
|
||||
self.broadcast({"type": "lock", "locked": locked})
|
||||
|
||||
@staticmethod
|
||||
def allowed_while_locked(method: str, path: str) -> bool:
|
||||
"""What the locked app window may still do: look at everything, export presets."""
|
||||
if path in ("/api/unlock", "/api/events", "/api/lang"):
|
||||
return True
|
||||
if method == "GET":
|
||||
return path != "/api/backup" # holds the PIN hash
|
||||
return method == "POST" and re.fullmatch(r"/api/devices/[\w-]+/(export|backups)", path) is not None
|
||||
|
||||
def remote_info(self) -> dict:
|
||||
return {**self.remote, "running": self.remote_server is not None, "error": self.remote_error,
|
||||
"platform": sys.platform,
|
||||
# only the main address: the others are usually virtual adapters (WSL, Hyper-V, VPN)
|
||||
"urls": [f"http://{ip}:{self.remote['port']}" for ip in local_ips()[:1]]}
|
||||
|
||||
async def start_remote(self):
|
||||
"""(Re)start the LAN listener for other devices according to self.remote."""
|
||||
self.stop_remote()
|
||||
self.remote_error = ""
|
||||
if not self.remote["enabled"]:
|
||||
return
|
||||
try:
|
||||
self.remote_server = await asyncio.start_server(
|
||||
lambda r, w: self.handle(r, w, remote=True), "0.0.0.0", self.remote["port"])
|
||||
log.info("Remote access on port %d", self.remote["port"])
|
||||
except OSError as e:
|
||||
in_use = e.errno in (errno.EADDRINUSE, 98, 10048) or getattr(e, "winerror", None) == 10048
|
||||
self.remote_error = (f"Port {self.remote['port']} is already in use – please choose another port" if in_use
|
||||
else f"Port {self.remote['port']} is not available ({e.strerror or e})")
|
||||
log.warning("Remote access failed: %s", e)
|
||||
|
||||
def stop_remote(self):
|
||||
if self.remote_server:
|
||||
self.remote_server.close()
|
||||
self.remote_server = None
|
||||
for w in list(self.remote_writers): # also end open connections (live event streams)
|
||||
w.close()
|
||||
self.remote_writers.clear()
|
||||
|
||||
async def set_remote(self, body: dict) -> dict:
|
||||
if "enabled" in body:
|
||||
self.remote["enabled"] = bool(body["enabled"])
|
||||
if "port" in body:
|
||||
self.remote["port"] = int(_num(body["port"], 1, 65535, 8080))
|
||||
self.save()
|
||||
await self.start_remote()
|
||||
return self.remote_info()
|
||||
|
||||
async def shutdown(self):
|
||||
self.stop_remote()
|
||||
for d in self.devices.values():
|
||||
await d.stop()
|
||||
|
||||
# ------------------------------------------------------------ events
|
||||
|
||||
def broadcast(self, ev: dict):
|
||||
msg = json.dumps(ev, separators=(",", ":"))
|
||||
for q in list(self.clients):
|
||||
if ev["type"] == "meters" and q.qsize() > 50:
|
||||
continue # slow client: drop meter frames, never state changes
|
||||
q.put_nowait(msg)
|
||||
|
||||
# ------------------------------------------------------------ API
|
||||
|
||||
async def api(self, method: str, path: str, body: dict):
|
||||
if path == "/api/devices" and method == "GET":
|
||||
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/usb" and method == "GET":
|
||||
return await asyncio.to_thread(usbhid.list_devices)
|
||||
if path == "/api/limiter" and method == "GET":
|
||||
return self.limiter
|
||||
if path == "/api/limiter" and method == "PUT":
|
||||
self.limiter = clean_limiter(body)
|
||||
self.save()
|
||||
self.broadcast({"type": "limiter", "data": self.limiter})
|
||||
return self.limiter
|
||||
m = re.fullmatch(r"/api/devices/([\w-]+)(?:/(\w+))?(?:/(\w+))?", path)
|
||||
if not m or m.group(1) not in self.devices:
|
||||
raise KeyError(path)
|
||||
dev = self.devices[m.group(1)]
|
||||
action = "/".join(g for g in m.groups()[1:] if g)
|
||||
if method == "DELETE" and not action:
|
||||
await dev.stop()
|
||||
del self.devices[dev.id]
|
||||
self.save()
|
||||
self.broadcast({"type": "removed", "device": dev.id})
|
||||
return {"ok": True}
|
||||
if method == "PUT" and not action:
|
||||
was_running = dev._want_connected
|
||||
await dev.stop()
|
||||
for k in ("name", "host", "model", "usb"):
|
||||
if k in body:
|
||||
setattr(dev, "model_key" if k == "model" else k, str(body[k]))
|
||||
if "transport" in body:
|
||||
dev.transport = "usb" if body["transport"] == "usb" else "tcp"
|
||||
for k in ("port", "addr"):
|
||||
if k in body:
|
||||
setattr(dev, k, int(body[k]))
|
||||
if "autoconnect" in body:
|
||||
dev.autoconnect = bool(body["autoconnect"])
|
||||
self.save()
|
||||
if was_running:
|
||||
dev.start()
|
||||
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
|
||||
return dev.snapshot()
|
||||
if method != "POST":
|
||||
raise KeyError(path)
|
||||
if action == "connect":
|
||||
dev.start()
|
||||
return {"ok": True}
|
||||
if action == "disconnect":
|
||||
await dev.stop()
|
||||
return {"ok": True}
|
||||
if action == "set":
|
||||
dev.set_param(body["kind"], int(body["idx"]), body["param"], body["value"])
|
||||
return {"ok": True}
|
||||
if action == "preset/recall":
|
||||
await dev.recall_preset(int(body["index"]))
|
||||
return {"ok": True}
|
||||
if action == "preset/store":
|
||||
await dev.store_preset(int(body["index"]), str(body["name"]))
|
||||
return {"ok": True}
|
||||
if action == "export":
|
||||
return await dev.export_preset()
|
||||
if action == "import":
|
||||
return await self.import_preset(dev, body)
|
||||
if action == "undo":
|
||||
return await self.undo_import(dev)
|
||||
if action == "backups":
|
||||
return [{"file": f.name, "time": f.stat().st_mtime} for f in self.undo_files(dev.id)]
|
||||
if action == "link":
|
||||
kind = "in" if body.get("kind") == "in" else "out"
|
||||
groups = [[int(i) for i in g] for g in body.get("groups") or [] if isinstance(g, list)]
|
||||
await dev.set_links(kind, groups)
|
||||
return {"ok": True}
|
||||
if action == "refresh":
|
||||
await dev.refresh()
|
||||
return {"ok": True}
|
||||
raise KeyError(path)
|
||||
|
||||
# ------------------------------------------------------------ HTTP
|
||||
|
||||
async def handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, remote=False):
|
||||
if remote:
|
||||
self.remote_writers.add(writer)
|
||||
try:
|
||||
await self._handle(reader, writer, remote)
|
||||
finally:
|
||||
self.remote_writers.discard(writer)
|
||||
|
||||
async def _handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, remote: bool):
|
||||
try:
|
||||
head = await reader.readuntil(b"\r\n\r\n")
|
||||
except (asyncio.IncompleteReadError, asyncio.LimitOverrunError, ConnectionError):
|
||||
writer.close()
|
||||
return
|
||||
lines = head.decode("latin1").split("\r\n")
|
||||
try:
|
||||
method, target, _ = lines[0].split(" ", 2)
|
||||
except ValueError:
|
||||
writer.close()
|
||||
return
|
||||
headers = {k.lower(): v.strip() for k, _, v in (l.partition(":") for l in lines[1:] if l)}
|
||||
url = urlsplit(target)
|
||||
path = url.path
|
||||
body = b""
|
||||
if int(headers.get("content-length", 0)):
|
||||
body = await reader.readexactly(int(headers["content-length"]))
|
||||
try:
|
||||
if path == "/app-login" and not remote:
|
||||
cookie = self.app_login(parse_qs(url.query).get("t", [""])[0])
|
||||
if cookie:
|
||||
await self.respond(writer, 302, b"", "text/plain",
|
||||
"Location: /\r\n" + self.cookie(cookie, SESSION_TTL))
|
||||
else:
|
||||
await self.respond(writer, 401, b"invalid app token", "text/plain")
|
||||
return
|
||||
if path.startswith("/api/"):
|
||||
try:
|
||||
data = json.loads(body) if body else {}
|
||||
except ValueError:
|
||||
data = {}
|
||||
session = self.session_of(headers)
|
||||
if session in self.app_sessions and remote:
|
||||
session = None # the window's session never counts on the LAN listener
|
||||
is_app = session in self.app_sessions
|
||||
if path == "/api/auth":
|
||||
await self.respond_json(writer, 200, {"authenticated": bool(session), "app": is_app,
|
||||
"locked": is_app and self.locked,
|
||||
"lang": self.lang if is_app else ""})
|
||||
return
|
||||
if path == "/api/login" and method == "POST":
|
||||
ip = (writer.get_extra_info("peername") or ("?",))[0]
|
||||
status, result, cookie = await self.login(ip, data)
|
||||
await self.respond_json(writer, status, result, cookie)
|
||||
return
|
||||
if path == "/api/logout" and method == "POST":
|
||||
if self.sessions.pop(session, None):
|
||||
self.save()
|
||||
await self.respond_json(writer, 200, {"ok": True}, self.cookie("", 0))
|
||||
return
|
||||
if not session:
|
||||
await self.respond_json(writer, 401, {"error": "login required"})
|
||||
return
|
||||
if is_app and self.locked and not self.allowed_while_locked(method, path):
|
||||
await self.respond_json(writer, 423, {"error": "Locked – unlock with the PIN to make changes"})
|
||||
return
|
||||
if path == "/api/lang" and method == "PUT":
|
||||
if is_app and data.get("lang") in ("en", "de"):
|
||||
self.lang = data["lang"]
|
||||
self.save()
|
||||
await self.respond_json(writer, 200, {"lang": self.lang})
|
||||
return
|
||||
if path in ("/api/lock", "/api/unlock") and method == "POST":
|
||||
if not is_app:
|
||||
await self.respond_json(writer, 403, {"error": "desktop app only"})
|
||||
elif path == "/api/lock":
|
||||
self.set_locked(True)
|
||||
await self.respond_json(writer, 200, {"locked": True})
|
||||
else:
|
||||
status, result = await self.guarded_pin("app-unlock", data.get("pin"))
|
||||
if status == 200:
|
||||
self.set_locked(False)
|
||||
# not 401: the page would take that for "logged out"
|
||||
await self.respond_json(writer, 400 if status == 401 else status, result)
|
||||
return
|
||||
if path == "/api/pin" and method == "POST":
|
||||
await self.respond_json(writer, *await self.change_pin(session, data))
|
||||
return
|
||||
if path == "/api/backup":
|
||||
if method == "GET":
|
||||
await self.respond_json(writer, 200, self.export_config())
|
||||
elif not is_app and not self.check_pin(str(data.get("pin", ""))):
|
||||
# on the LAN only with the PIN: a backup can replace it
|
||||
await self.respond_json(writer, 400, {"error": "Wrong PIN"})
|
||||
else:
|
||||
try:
|
||||
await self.restore_config(data.get("doc"), session)
|
||||
await self.respond_json(writer, 200, {"ok": True})
|
||||
except ValueError as e:
|
||||
await self.respond_json(writer, 400, {"error": str(e)})
|
||||
return
|
||||
if path == "/api/remote":
|
||||
if not is_app:
|
||||
await self.respond_json(writer, 403, {"error": "desktop app only"})
|
||||
elif method == "PUT":
|
||||
await self.respond_json(writer, 200, await self.set_remote(data))
|
||||
else:
|
||||
await self.respond_json(writer, 200, self.remote_info())
|
||||
return
|
||||
if path == "/api/events":
|
||||
await self.sse(writer)
|
||||
return
|
||||
if path.startswith("/api/"):
|
||||
try:
|
||||
result = await self.api(method, path, json.loads(body) if body else {})
|
||||
await self.respond(writer, 200, json.dumps(result).encode(), "application/json")
|
||||
except KeyError as e:
|
||||
await self.respond(writer, 404, json.dumps({"error": f"not found: {e}"}).encode(),
|
||||
"application/json")
|
||||
except Exception as e: # noqa: BLE001 - report any API error to the client
|
||||
log.exception("API error")
|
||||
await self.respond(writer, 400, json.dumps({"error": str(e)}).encode(), "application/json")
|
||||
return
|
||||
await self.static(writer, path)
|
||||
except (ConnectionError, asyncio.CancelledError):
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
writer.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
async def respond(self, writer, status: int, data: bytes, ctype: str, extra: str = ""):
|
||||
reason = {200: "OK", 302: "Found", 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden",
|
||||
404: "Not Found", 423: "Locked", 429: "Too Many Requests"}.get(status, "OK")
|
||||
writer.write(f"HTTP/1.1 {status} {reason}\r\nContent-Type: {ctype}\r\nContent-Length: {len(data)}\r\n"
|
||||
f"Cache-Control: no-cache\r\n{extra}Connection: close\r\n\r\n".encode() + data)
|
||||
await writer.drain()
|
||||
|
||||
async def respond_json(self, writer, status: int, obj, extra: str = ""):
|
||||
await self.respond(writer, status, json.dumps(obj).encode(), "application/json", extra)
|
||||
|
||||
async def static(self, writer, path: str):
|
||||
rel = "index.html" if path in ("/", "") else path.lstrip("/")
|
||||
f = (STATIC / rel).resolve()
|
||||
if STATIC not in f.parents or not f.is_file():
|
||||
await self.respond(writer, 404, b"not found", "text/plain")
|
||||
return
|
||||
ctype = mimetypes.guess_type(f.name)[0] or "application/octet-stream"
|
||||
if ctype.startswith("text/") or ctype.endswith("javascript"):
|
||||
ctype += "; charset=utf-8"
|
||||
await self.respond(writer, 200, f.read_bytes(), ctype)
|
||||
|
||||
async def sse(self, writer):
|
||||
writer.write(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\n"
|
||||
b"Connection: keep-alive\r\nX-Accel-Buffering: no\r\n\r\n")
|
||||
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}
|
||||
writer.write(f"data: {json.dumps(hello)}\n\n".encode())
|
||||
await writer.drain()
|
||||
while True:
|
||||
try:
|
||||
msg = await asyncio.wait_for(q.get(), timeout=15)
|
||||
writer.write(f"data: {msg}\n\n".encode())
|
||||
except asyncio.TimeoutError:
|
||||
writer.write(b": ping\n\n")
|
||||
await writer.drain()
|
||||
finally:
|
||||
self.clients.discard(q)
|
||||
|
||||
|
||||
async def main():
|
||||
ap = argparse.ArgumentParser(description="Web control for t.racks DSP 204/408")
|
||||
ap.add_argument("--host", default="0.0.0.0")
|
||||
ap.add_argument("--port", type=int, default=8080)
|
||||
ap.add_argument("--config", default=str(ROOT / "config.json"))
|
||||
ap.add_argument("-v", "--verbose", action="store_true")
|
||||
args = ap.parse_args()
|
||||
logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO,
|
||||
format="%(asctime)s %(name)s %(levelname)s %(message)s")
|
||||
app = App(Path(args.config))
|
||||
app.load()
|
||||
server = await asyncio.start_server(app.handle, args.host, args.port)
|
||||
log.info("DSP Control running on http://%s:%d", "localhost" if args.host == "0.0.0.0" else args.host, args.port)
|
||||
async with server:
|
||||
await server.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(main())
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Simulated t.racks DSP for testing without hardware.
|
||||
|
||||
Usage: python sim.py --model 204 --port 9761
|
||||
python sim.py --model 408 --port 9762
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import copy
|
||||
import logging
|
||||
import math
|
||||
import time
|
||||
|
||||
from dsp import protocol as P
|
||||
|
||||
log = logging.getLogger("sim")
|
||||
|
||||
|
||||
class SimDSP:
|
||||
def __init__(self, model_key: str):
|
||||
self.key = model_key
|
||||
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)]
|
||||
self.presets[0]["preset_name"] = "Default"
|
||||
self.pending_name = ""
|
||||
|
||||
def preset_names(self) -> list[str]:
|
||||
return [p["preset_name"] if p else "" for p in self.presets]
|
||||
|
||||
def handle(self, cmd: int, p: bytes) -> tuple[int, bytes]:
|
||||
m = self.model
|
||||
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)])
|
||||
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:
|
||||
buf = P.build_state_buffer(m, self.state)
|
||||
n = p[0]
|
||||
return P.CMD_CONFIG_CHUNK, bytes([n]) + bytes(buf[n * P.CHUNK_SIZE:(n + 1) * P.CHUNK_SIZE])
|
||||
if cmd == P.CMD_METER:
|
||||
t = time.monotonic()
|
||||
levels = [0.0] * 12
|
||||
for i in range(m.n_in):
|
||||
ch = self.state["inputs"][i]
|
||||
lv = 0.0 if ch["mute"] else 0.25 * (1 + math.sin(t * (1.3 + i))) * 10 ** (P.gain_to_db(ch["gain"]) / 20)
|
||||
levels[m.meter_index("in", i)] = lv
|
||||
flags = 0
|
||||
for o in range(m.n_out):
|
||||
ch = self.state["outputs"][o]
|
||||
src = sum(levels[m.meter_index("in", i)] for i in range(m.n_in) if ch["matrix"] >> i & 1)
|
||||
lv = 0.0 if ch["mute"] else min(1.5, src * 10 ** (P.gain_to_db(ch["gain"]) / 20))
|
||||
levels[m.meter_index("out", o)] = lv
|
||||
if lv > 0 and 20 * math.log10(lv) > P.threshold_to_db(ch["limit"]["threshold"]):
|
||||
flags |= 1 << o
|
||||
return cmd, P.encode_meters(levels, flags)
|
||||
if cmd == P.CMD_PRESET_RECALL:
|
||||
preset = self.presets[p[0] - 1]
|
||||
if preset:
|
||||
self.state = copy.deepcopy(preset)
|
||||
elif cmd == P.CMD_PRESET_STORE_NAME:
|
||||
self.pending_name = p.decode("latin1").strip()
|
||||
elif cmd == P.CMD_PRESET_STORE:
|
||||
self.state["preset_name"] = self.pending_name or f"Preset {p[0]}"
|
||||
self.presets[p[0] - 1] = copy.deepcopy(self.state)
|
||||
else:
|
||||
P.apply_command(m, self.state, cmd, p)
|
||||
return P.CMD_ACK, b"\x00"
|
||||
|
||||
async def serve(self, reader, writer):
|
||||
peer = writer.get_extra_info("peername")
|
||||
log.info("client %s connected", peer)
|
||||
parser = P.FrameParser()
|
||||
try:
|
||||
while data := await reader.read(4096):
|
||||
for f in parser.feed(data):
|
||||
if f.cmd != P.CMD_METER:
|
||||
log.info("rx cmd=0x%02x payload=%s", f.cmd, f.payload.hex(" "))
|
||||
cmd, payload = self.handle(f.cmd, f.payload)
|
||||
writer.write(P.build_frame(cmd, payload, addr=0, src=1))
|
||||
await writer.drain()
|
||||
except ConnectionError:
|
||||
pass
|
||||
log.info("client %s disconnected", peer)
|
||||
writer.close()
|
||||
|
||||
|
||||
async def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
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")
|
||||
args = ap.parse_args()
|
||||
logging.basicConfig(level=logging.INFO, format=f"%(asctime)s sim{args.model} %(message)s")
|
||||
sim = SimDSP(args.model)
|
||||
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:
|
||||
await server.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(main())
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
+1729
File diff suppressed because it is too large.
Load diff
+323
@@ -0,0 +1,323 @@
|
||||
"use strict";
|
||||
// UI language. English is the default and the language of the source; DE holds the German texts.
|
||||
// t("Text with {name}", { name }) translates and fills placeholders; trMsg() does the same for
|
||||
// messages coming from the server or the DSP connection (some of which contain variable parts).
|
||||
// Chosen per device under ⚙ → Language (stored in the browser); the desktop app also tells the server.
|
||||
|
||||
const LANGS = { en: "English", de: "Deutsch" };
|
||||
const LANG = (() => { try { return localStorage.getItem("dsp.lang") === "de" ? "de" : "en"; } catch { return "en"; } })();
|
||||
const LOCALE = LANG === "de" ? "de-AT" : "en-GB";
|
||||
|
||||
const DE = {
|
||||
" (end of range reached)": " (Bereichsende erreicht)",
|
||||
" Log out": " Abmelden",
|
||||
"+ Add amplifier": "+ Verstärker hinzufügen",
|
||||
"+ New amplifier…": "+ Neuer Verstärker…",
|
||||
"20 Hz … 20 kHz, e.g. 1.2k": "20 Hz … 20 kHz, z. B. 1.2k",
|
||||
"A backup is made automatically before every import. Last backup: {last}.": "Vor jedem Import wird automatisch gesichert. Letzte Sicherung: {last}.",
|
||||
"a change on one channel applies to the whole group. Name, routing and mix levels stay per channel. ": "eine Änderung an einem Kanal gilt für die ganze Gruppe. Name, Routing und Mix-Pegel bleiben je Kanal. ",
|
||||
"Access (PIN)": "Zugang (PIN)",
|
||||
"Add": "Hinzufügen",
|
||||
"Added": "Hinzugefügt",
|
||||
"All bands flat": "Alle Bänder flach",
|
||||
"All flat": "Alle flach",
|
||||
"Allow phones & tablets": "Handy & Tablet erlauben",
|
||||
"Amplifier": "Verstärker",
|
||||
"Amplifier clips – the limiter engages {db} dB too late": "Verstärker clippt – Limiter greift {db} dB zu spät",
|
||||
"Amplifier is not rated for {ohm} Ω": "Verstärker ist für {ohm} Ω nicht spezifiziert",
|
||||
"Amplifier −1 dB": "Verstärker −1 dB",
|
||||
"Amplifiers": "Verstärker",
|
||||
"App settings": "App-Einstellungen",
|
||||
"Apply": "Übernehmen",
|
||||
"Assign an amplifier first": "Erst Verstärker zuordnen",
|
||||
"Assumes the amplifier’s gain control turned fully up (or as entered).": "Voraussetzung: Gain-Regler am Verstärker auf Rechtsanschlag (bzw. so wie eingetragen).",
|
||||
"At least one power rating is missing.": "Mindestens eine Leistungsangabe fehlt.",
|
||||
"Automatic": "Automatisch",
|
||||
"Back up…": "Sichern…",
|
||||
"Backup": "Sicherung",
|
||||
"Both DSPs can be connected at the same time – switch between them at the top. ": "Beide DSPs können gleichzeitig verbunden sein – oben zwischen ihnen umschalten. ",
|
||||
"Calibration": "Kalibrierung",
|
||||
"Cancel": "Abbrechen",
|
||||
"Change PIN": "PIN ändern",
|
||||
"Channel": "Kanal",
|
||||
"Channel name": "Kanalname",
|
||||
"Choose channel": "Kanal wählen",
|
||||
"Close": "Schließen",
|
||||
"Compressor": "Kompressor",
|
||||
"Connect": "Verbinden",
|
||||
"Connect automatically": "Automatisch verbinden",
|
||||
"Connecting to {where}…": "Verbinde mit {where}…",
|
||||
"Connecting…": "Verbinde…",
|
||||
"Connection": "Verbindung",
|
||||
"connection closed": "Verbindung beendet",
|
||||
"Current PIN": "Aktuelle PIN",
|
||||
"Current PIN is wrong": "Aktuelle PIN ist falsch",
|
||||
"dBu = 20 · log₁₀(U / 0.775 V).": "dBu = 20 · log₁₀(U / 0,775 V).",
|
||||
"Decrease": "Verringern",
|
||||
"Delete": "Löschen",
|
||||
"Delete amplifier": "Verstärker löschen",
|
||||
"Delete {name}?": "{name} löschen?",
|
||||
"desktop app only": "nur in der Desktop-App",
|
||||
"device not loaded": "Gerät nicht geladen",
|
||||
"Device reports: ": "Gerät meldet: ",
|
||||
"Devices": "Geräte",
|
||||
"Devices ({n}), amplifier and limiter data, PIN and remote access will be replaced by the backup from {when}. The presets inside the DSPs stay unchanged.": "Geräte ({n}), Verstärker- und Limiter-Daten, PIN und Fernzugriff werden durch die Sicherung vom {when} ersetzt. Die Presets in den DSPs bleiben unverändert.",
|
||||
"Disconnect": "Trennen",
|
||||
"Disconnected": "Getrennt",
|
||||
"Drag a fader by its knob · snaps at 0 dB · double-tap the knob = 0 dB · tap the dB value to type one · tap the name = edit channel": "Fader am Knopf ziehen · rastet bei 0 dB ein · Doppeltipp auf den Knopf = 0 dB · dB-Wert antippen zum Eintippen · Name antippen = Kanal bearbeiten",
|
||||
"Drag the points in the curve · gain snaps at 0 dB": "Punkte in der Kurve ziehen · Gain rastet bei 0 dB ein",
|
||||
"DSP closed the connection": "DSP hat die Verbindung beendet",
|
||||
"DSP is not connected": "DSP ist nicht verbunden",
|
||||
"DSP not responding": "DSP antwortet nicht",
|
||||
"e.g. 1.4": "z. B. 1.4",
|
||||
"e.g. 32": "z. B. 32",
|
||||
"e.g. 4.0": "z. B. 4.0",
|
||||
"e.g. Crown XLS 1502": "z. B. Crown XLS 1502",
|
||||
"e.g. DSP 204 stage": "z. B. DSP 204 Bühne",
|
||||
"Edit": "Bearbeiten",
|
||||
"Edit amplifier": "Verstärker bearbeiten",
|
||||
"Edit channel": "Kanal bearbeiten",
|
||||
"Enter PIN": "PIN eingeben",
|
||||
"Enter value": "Wert eingeben",
|
||||
"EQ curve – drag the points": "EQ-Kurve – Punkte ziehen",
|
||||
"Error": "Fehler",
|
||||
"Error: ": "Fehler: ",
|
||||
"Export": "Exportieren",
|
||||
"Export / import preset": "Preset exportieren / importieren",
|
||||
"Export saves the DSP’s current state ({name}) to a file. Import loads a file into the active state – stored presets (U01 …) stay unchanged.": "Exportieren speichert den aktuellen Zustand des DSP ({name}) als Datei. Importieren lädt eine Datei in den aktiven Zustand – gespeicherte Presets (U01 …) bleiben unverändert.",
|
||||
"exported": "exportiert",
|
||||
"File is too large": "Datei ist zu groß",
|
||||
"File…": "Datei…",
|
||||
"Filter type": "Filtertyp",
|
||||
"First device found": "Erstes gefundenes Gerät",
|
||||
"Frequency": "Frequenz",
|
||||
"Gain": "Verstärkung",
|
||||
"Gain (dB)": "Verstärkung (dB)",
|
||||
"Gain {v} dB": "Verstärkung {v} dB",
|
||||
"Graphic EQ · 31 bands": "Grafischer EQ · 31 Bänder",
|
||||
"High- / low-pass": "Hoch- / Tiefpass",
|
||||
"High-pass": "Hochpass",
|
||||
"Highs": "Hochton",
|
||||
"If the amplifier has a gain control, the value applies with it turned fully up.": "Hat der Verstärker einen Gain-Regler, gilt der Wert bei Rechtsanschlag.",
|
||||
"If the macOS firewall is on, it asks the first time – choose “Allow”.": "Ist die macOS-Firewall aktiv, fragt sie beim ersten Einschalten – dort „Erlauben“ wählen.",
|
||||
"Impedance": "Impedanz",
|
||||
"Import": "Importieren",
|
||||
"Import incomplete": "Import unvollständig",
|
||||
"Import preset": "Preset importieren",
|
||||
"Importing… (a few seconds)": "Importiere… (einige Sekunden)",
|
||||
"Import…": "Importieren…",
|
||||
"in ms, or metres with “m” (e.g. 2.5m)": "in ms, oder Meter mit „m“ (z. B. 2.5m)",
|
||||
"Increase": "Erhöhen",
|
||||
"Input": "Eingang",
|
||||
"Input sensitivity (V RMS)": "Eingangsempfindlichkeit (V RMS)",
|
||||
"Input →": "Eingang →",
|
||||
"Inputs": "Eingänge",
|
||||
"into 2 Ω": "an 2 Ω",
|
||||
"into 4 Ω": "an 4 Ω",
|
||||
"into 8 Ω": "an 8 Ω",
|
||||
"IP address": "IP-Adresse",
|
||||
"IP address missing": "IP-Adresse fehlt",
|
||||
"IP of this computer": "IP dieses PCs",
|
||||
"Its assignments will be removed.": "Die Zuordnungen werden entfernt.",
|
||||
"Language": "Sprache",
|
||||
"Level": "Pegel",
|
||||
"Level for {ch}": "Pegel für {ch}",
|
||||
"Limit to": "Limiter auf",
|
||||
"Limiter 0 dB equals at the output": "Limiter 0 dB entspricht am Ausgang",
|
||||
"Limiter active": "Limiter aktiv",
|
||||
"Limiter tab": "Limiter-Tab",
|
||||
"Link": "Verknüpfen",
|
||||
"Link channels": "Kanäle verknüpfen",
|
||||
"Link {names}? They all take over the settings of {first} (names and routing stay).": "{names} verknüpfen? Alle übernehmen dabei die Einstellungen von {first} (Namen und Routing bleiben).",
|
||||
"Link {names}? They all take over the settings of {first} (names stay).": "{names} verknüpfen? Alle übernehmen dabei die Einstellungen von {first} (Namen bleiben).",
|
||||
"Linked channels share all settings (gain, delay, filters, EQ, dynamics, mute) – ": "Verknüpfte Kanäle teilen sich alle Einstellungen (Gain, Delay, Filter, EQ, Dynamik, Mute) – ",
|
||||
"Linked with {list} – changes apply to all of them (except name, routing and mix levels).": "Verknüpft mit {list} – Änderungen gelten für alle (außer Name, Routing und Mix-Pegel).",
|
||||
"Linked with {list} – changes apply to all of them (except the name).": "Verknüpft mit {list} – Änderungen gelten für alle (außer Name).",
|
||||
"Linked: ": "Verknüpft: ",
|
||||
"Load on channel": "Last am Kanal",
|
||||
"Load {what} into the active state? The current state is backed up automatically first and can be brought back via File → “Undo import”. Stored presets stay unchanged – to keep it, store it into a memory slot with “Save” afterwards.": "{what} in den aktiven Zustand laden? Der aktuelle Zustand wird vorher automatisch gesichert und lässt sich über Datei → „Import rückgängig“ zurückholen. Gespeicherte Presets bleiben unverändert – zum Behalten danach mit „Speichern“ in einen Speicherplatz schreiben.",
|
||||
"Loading configuration…": "Lade Konfiguration…",
|
||||
"Loading the configuration from the DSP…": "Lade Konfiguration vom DSP…",
|
||||
"Lock": "Sperren",
|
||||
"Lock (view only)": "Sperren (nur noch ansehen)",
|
||||
"Locked": "Gesperrt",
|
||||
"Locked – click to unlock": "Gesperrt – zum Entsperren klicken",
|
||||
"Locked – unlock at the top right to make changes": "Gesperrt – zum Ändern oben rechts entsperren",
|
||||
"Locked – unlock with the PIN to make changes": "Gesperrt – zum Ändern mit der PIN entsperren",
|
||||
"Locked – values are view-only": "Gesperrt – Werte nur noch ansehen",
|
||||
"login required": "Anmeldung erforderlich",
|
||||
"Low-pass": "Tiefpass",
|
||||
"Lower value": "Kleinerer Wert",
|
||||
"Memory slot": "Speicherplatz",
|
||||
"Mids": "Mitten",
|
||||
"Model": "Modell",
|
||||
"Name (max. 14 characters)": "Name (max. 14 Zeichen)",
|
||||
"Name is full (max. 8 characters, wide letters count more)": "Name ist voll (max. 8 Zeichen, breite Buchstaben zählen mehr)",
|
||||
"Network": "Netzwerk",
|
||||
"New amplifier": "Neuer Verstärker",
|
||||
"New device": "Neues Gerät",
|
||||
"New PIN": "Neue PIN",
|
||||
"Next channel": "Nächster Kanal",
|
||||
"No amplifier assigned": "Kein Verstärker zugeordnet",
|
||||
"No backup available": "Keine Sicherung vorhanden",
|
||||
"No channels linked.": "Keine Kanäle verknüpft.",
|
||||
"no crossover": "ohne Weiche",
|
||||
"No DSP found via USB": "Kein DSP per USB gefunden",
|
||||
"No DSP found via USB – check the cable": "Kein DSP per USB gefunden – Kabel prüfen",
|
||||
"no HP": "ohne HP",
|
||||
"Not a DSP Control preset file": "Keine Preset-Datei von DSP Control",
|
||||
"Not a DSP Control settings backup": "Keine Einstellungs-Sicherung von DSP Control",
|
||||
"Not assigned to any output": "Keinem Ausgang zugeordnet",
|
||||
"not connected": "nicht verbunden",
|
||||
"Not connected.": "Nicht verbunden.",
|
||||
"Off": "Aus",
|
||||
"Off (bypass)": "Aus (Bypass)",
|
||||
"Off – only this window has access.": "Aus – nur dieses Fenster hat Zugriff.",
|
||||
"On": "Ein",
|
||||
"Open channel": "Kanal öffnen",
|
||||
"Open on a phone in the same Wi-Fi:": "Am Handy im selben WLAN öffnen:",
|
||||
"Other devices log in with the PIN (changeable below). Only runs while this app is open. ": "Andere Geräte melden sich mit der PIN an (unten änderbar). Läuft nur, solange diese App offen ist. ",
|
||||
"Output ↓": "Ausgang ↓",
|
||||
"Outputs": "Ausgänge",
|
||||
"Overwrites the selected memory slot in the DSP.": "Überschreibt den gewählten Speicherplatz im DSP.",
|
||||
"Parametric EQ": "Parametrischer EQ",
|
||||
"PIN (same as on the phone)": "PIN (wie am Handy)",
|
||||
"PIN changed – other devices were logged out": "PIN geändert – andere Geräte wurden abgemeldet",
|
||||
"PIN for remote access": "PIN für Fernzugriff",
|
||||
"Please log in": "Bitte anmelden",
|
||||
"Preset exported": "Preset exportiert",
|
||||
"Preset file": "Preset-Datei",
|
||||
"Preset imported": "Preset importiert",
|
||||
"Preset U{n} recalled": "Preset U{n} geladen",
|
||||
"Preset {name} imported": "Preset {name} importiert",
|
||||
"Previous channel": "Vorheriger Kanal",
|
||||
"Previous state restored": "Vorheriger Zustand wiederhergestellt",
|
||||
"Rated RMS power per channel (datasheet, empty = not specified)": "Nennleistung RMS pro Kanal (Datenblatt, leer = nicht angegeben)",
|
||||
"Reading the state from the DSP…": "Lese Zustand vom DSP…",
|
||||
"Recall": "Laden",
|
||||
"Recall preset": "Preset laden",
|
||||
"Recall preset…": "Preset laden…",
|
||||
"Recall {name} (U{n})? Unsaved changes will be lost.": "{name} (U{n}) laden? Nicht gespeicherte Änderungen gehen verloren.",
|
||||
"Reference level in dBu": "Referenzpegel in dBu",
|
||||
"Reference level · ": "Bezugspegel · ",
|
||||
"release ≈ 16 × attack (shorter pumps). “Auto” picks the band preset matching this channel’s high-pass.": "Release ≈ 16 × Attack (zu kurz pumpt). „Auto“ wählt das Band-Preset passend zum Hochpass dieses Kanals.",
|
||||
"Remote access": "Fernzugriff",
|
||||
"Remote access (web server)": "Fernzugriff (Webserver)",
|
||||
"Remove": "Entfernen",
|
||||
"Remove device": "Gerät entfernen",
|
||||
"Remove {name} from the list?": "{name} aus der Liste entfernen?",
|
||||
"Repeat": "Wiederholen",
|
||||
"Reset": "Zurücksetzen",
|
||||
"Reset EQ": "EQ zurücksetzen",
|
||||
"Reset GEQ": "GEQ zurücksetzen",
|
||||
"Restore": "Wiederherstellen",
|
||||
"Restore settings": "Einstellungen wiederherstellen",
|
||||
"Restore the state from {last}?": "Den Zustand vom {last} wiederherstellen?",
|
||||
"Restore…": "Wiederherstellen…",
|
||||
"Restoring…": "Stelle wieder her…",
|
||||
"Routing matrix": "Routing-Matrix",
|
||||
"Rule of thumb: attack ≈ one period of the lowest frequency (faster distorts the bass), ": "Faustregel: Attack ≈ eine Schwingung der tiefsten Frequenz (zu schnell verzerrt Bässe), ",
|
||||
"Save": "Speichern",
|
||||
"Saved": "Gespeichert",
|
||||
"Saved device (not plugged in)": "Gespeichertes Gerät (nicht angesteckt)",
|
||||
"Saves devices, amplifiers & limiter calculator, PIN and remote access to a file. ": "Sichert Geräte, Verstärker & Limiter-Rechner, PIN und Fernzugriff in eine Datei. ",
|
||||
"Search again": "Neu suchen",
|
||||
"Security": "Sicherheit",
|
||||
"Sensitivity": "Empfindlichkeit",
|
||||
"Sensitivity = input voltage for full power (e.g. 0.775 V or 1.4 V). ": "Empfindlichkeit = Eingangsspannung für volle Leistung (z. B. 0.775 V oder 1.4 V). ",
|
||||
"Sensitivity is missing.": "Empfindlichkeit fehlt.",
|
||||
"Sensitivity {v} V": "Empfindlichkeit {v} V",
|
||||
"Server not reachable": "Server nicht erreichbar",
|
||||
"Set": "setzen",
|
||||
"Set all 31 bands to 0 dB?": "Alle 31 Bänder auf 0 dB setzen?",
|
||||
"Set all PEQ bands of this channel to 0 dB and clear bypass?": "Alle PEQ-Bänder dieses Kanals auf 0 dB setzen und Bypass aufheben?",
|
||||
"set the threshold to 0 dB, turn up until the limiter engages and measure the output voltage with a multimeter (AC). ": "Threshold 0 dB, Pegel hochdrehen bis der Limiter greift und die Ausgangsspannung mit einem Multimeter (AC) messen. ",
|
||||
"Settings": "Einstellungen",
|
||||
"Settings backed up": "Einstellungen gesichert",
|
||||
"Settings restored": "Einstellungen wiederhergestellt",
|
||||
"Shown is the continuous sine power (RMS) once the limiter engages – music is well below that on average. ": "Angezeigt wird die Sinus-Dauerleistung (RMS), sobald der Limiter greift – Musik liegt im Mittel deutlich darunter. ",
|
||||
"Snaps at 0 dB · double-tap the knob = 0 dB": "Rastet bei 0 dB ein · Doppeltipp = 0 dB",
|
||||
"Sources → ": "Quellen → ",
|
||||
"Speaker ": "Lautsprecher ",
|
||||
"Speaker at {pct} % of its rating ({w} RMS)": "Lautsprecher zu {pct} % belastet ({w} RMS)",
|
||||
"Speaker RMS": "Lautsprecher RMS",
|
||||
"Speaker RMS (W)": "Lautsprecher RMS (W)",
|
||||
"Store preset": "Preset speichern",
|
||||
"Stored in U{n}": "In U{n} gespeichert",
|
||||
"Tap a crosspoint = connect/disconnect · tap an output = level per input": "Kreuzungspunkt antippen = verbinden/trennen · Ausgang antippen = Pegel pro Eingang",
|
||||
"Tap at least two channels": "Mindestens zwei Kanäle antippen",
|
||||
"Target power": "Ziel-Leistung",
|
||||
"The default PIN is 1234. After changing it only this device stays logged in.": "Standard-PIN ist 1234. Nach dem Ändern bleibt nur dieses Gerät angemeldet.",
|
||||
"The DSP did not take these values:": "Diese Werte hat der DSP nicht übernommen:",
|
||||
"The DSPs accept only one connection: close the Thomann editor first.": "Die DSPs erlauben nur eine Verbindung: den Thomann-Editor vorher schließen.",
|
||||
"The first time, Windows Firewall asks – choose “Allow” for private networks.": "Beim ersten Einschalten fragt die Windows-Firewall – dort „Zulassen“ für private Netzwerke wählen.",
|
||||
"The link is stored in the DSP and also applies in the Thomann editor.": "Die Verknüpfung wird im DSP gespeichert und gilt auch für den Thomann-Editor.",
|
||||
"The new PIN must be 4 digits.": "Die neue PIN muss aus 4 Ziffern bestehen.",
|
||||
"The new PINs do not match.": "Die neuen PINs stimmen nicht überein.",
|
||||
"The PIN must be 4 digits": "Die PIN muss aus 4 Ziffern bestehen",
|
||||
"The settings inside the DSPs are saved per device via “File…” at the top.": "Die Einstellungen in den DSPs sichert man pro Gerät oben über „Datei…“.",
|
||||
"This app needs no PIN. The default is 1234; changing it logs out all phones.": "Diese App braucht keine PIN. Standard ist 1234; nach dem Ändern werden alle Handys abgemeldet.",
|
||||
"Thomann does not specify the reference level – 0 dBu (0.775 V) is assumed. To measure: feed a 1 kHz sine, ": "Thomann gibt den Bezugspegel nicht an – angenommen sind 0 dBu (0,775 V). Nachmessen: Sinus 1 kHz einspeisen, ",
|
||||
"TimeoutError": "Zeitüberschreitung",
|
||||
"Too many attempts – locked for {s} s": "Zu viele Versuche – noch {s} s gesperrt",
|
||||
"Too many attempts – please wait a moment": "Zu viele Versuche – bitte kurz warten",
|
||||
"Type": "Typ",
|
||||
"Undo import": "Import rückgängig",
|
||||
"Unlink": "Trennen",
|
||||
"Unlock": "Entsperren",
|
||||
"Unlocked": "Entsperrt",
|
||||
"USB cable": "USB-Kabel",
|
||||
"USB connection lost": "USB-Verbindung getrennt",
|
||||
"USB device": "USB-Gerät",
|
||||
"USB device is in use by another program": "USB-Gerät ist von einem anderen Programm belegt",
|
||||
"USB device not found – check the cable": "USB-Gerät nicht gefunden – Kabel prüfen",
|
||||
"USB is not supported on this system": "USB wird auf diesem System nicht unterstützt",
|
||||
"USB write error": "USB-Schreibfehler",
|
||||
"Used by: ": "Belegt: ",
|
||||
"View": "Ansicht",
|
||||
"Watts": "Watt",
|
||||
"Wrong PIN": "Falsche PIN",
|
||||
"Wrong PIN – {n} attempts left": "Falsche PIN – noch {n} Versuche",
|
||||
"{db} dB headroom to amplifier clipping": "{db} dB Reserve bis Verstärker-Clipping",
|
||||
"{names} linked": "{names} verknüpft",
|
||||
"{names} unlinked": "{names} getrennt",
|
||||
"{n} channels selected": "{n} Kanäle gewählt",
|
||||
"{pct} % of the speaker rating ({w} RMS)": "{pct} % der Lautsprecher-Belastbarkeit ({w} RMS)",
|
||||
"{pct} % of {rated}": "{pct} % von {rated}",
|
||||
"— empty —": "— leer —",
|
||||
"— no amplifier —": "— kein Verstärker —",
|
||||
"“{s}”": "„{s}“"
|
||||
};
|
||||
|
||||
const DE_PATTERNS = [
|
||||
[/^Port (\d+) is already in use – please choose another port$/, "Port $1 ist schon belegt – bitte einen anderen Port wählen"],
|
||||
[/^Port (\d+) is not available \((.*)\)$/, "Port $1 ist nicht verfügbar ($2)"],
|
||||
[/^Cannot open USB device \(error (.*)\)$/, "USB-Gerät lässt sich nicht öffnen (Fehler $1)"],
|
||||
[/^USB write error \((.*)\)$/, "USB-Schreibfehler ($1)"],
|
||||
[/^The file is for a DSP (\w+), the connected device is a (.*)$/, "Die Datei ist für den DSP $1, verbunden ist ein $2"],
|
||||
[/^Unknown file format \((\d+) bytes\) – expected a DSP Control preset file or a memory image of the (.*) \((\d+) bytes\)$/,
|
||||
"Unbekanntes Dateiformat ($1 Bytes) – erwartet wird eine Preset-Datei dieser App oder ein Speicherabbild des $2 ($3 Bytes)"],
|
||||
[/^unknown device '(.*)' - set the model manually$/, "Unbekanntes Gerät „$1“ – Modell bitte manuell einstellen"],
|
||||
[/^config chunk (\d+) not received$/, "Konfigurations-Teil $1 nicht empfangen"],
|
||||
];
|
||||
|
||||
function t(s, vars) {
|
||||
const text = LANG === "de" && DE[s] != null ? DE[s] : s;
|
||||
return vars ? text.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? vars[k] : m)) : text;
|
||||
}
|
||||
function trMsg(msg) {
|
||||
msg = String(msg ?? "");
|
||||
if (LANG !== "de") return msg;
|
||||
if (DE[msg] != null) return DE[msg];
|
||||
for (const [re, de] of DE_PATTERNS) if (re.test(msg)) return msg.replace(re, de);
|
||||
return msg;
|
||||
}
|
||||
const q = s => t("“{s}”", { s }); // quoted name: “x” / „x“
|
||||
|
||||
// static texts in index.html
|
||||
document.documentElement.lang = LANG;
|
||||
document.querySelectorAll("[data-t]").forEach(el => (el.textContent = t(el.dataset.t)));
|
||||
document.querySelectorAll("[data-t-label]").forEach(el => {
|
||||
el.setAttribute("aria-label", t(el.dataset.tLabel));
|
||||
if (el.title) el.title = t(el.dataset.tLabel);
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="theme-color" content="#0b0c0f">
|
||||
<meta name="mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||
<title>DSP Control</title>
|
||||
<link rel="stylesheet" href="/style.css">
|
||||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='6' fill='%23111418'/%3E%3Cpath d='M7 22V10M13 22V6M19 22V14M25 22V9' stroke='%2338bdf8' stroke-width='3' stroke-linecap='round'/%3E%3C/svg%3E">
|
||||
</head>
|
||||
<body>
|
||||
<div id="login" hidden></div>
|
||||
<div id="app" hidden>
|
||||
<header id="top">
|
||||
<div class="brand" aria-hidden="true">
|
||||
<svg viewBox="0 0 32 32" width="26" height="26"><rect width="32" height="32" rx="7" fill="#161a20"/><path d="M7 22V10M13 22V6M19 22V14M25 22V9" stroke="#38bdf8" stroke-width="3" stroke-linecap="round"/></svg>
|
||||
</div>
|
||||
<div id="devtabs"></div>
|
||||
<nav id="viewtabs" aria-label="View" data-t-label="View">
|
||||
<button data-view="mixer"><svg viewBox="0 0 24 24"><path d="M6 3v18M12 3v18M18 3v18"/><rect x="3.5" y="13" width="5" height="3" rx="1"/><rect x="9.5" y="7" width="5" height="3" rx="1"/><rect x="15.5" y="10" width="5" height="3" rx="1"/></svg><span>Mixer</span></button>
|
||||
<button data-view="channel"><svg viewBox="0 0 24 24"><path d="M2 14c3 0 3-7 6-7s3 10 6 10 3-6 6-6h2"/></svg><span data-t="Channel">Channel</span></button>
|
||||
<button data-view="routing"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h16M8 3v18M16 3v18"/><circle cx="8" cy="6" r="2.2" class="f"/><circle cx="16" cy="12" r="2.2" class="f"/><circle cx="8" cy="18" r="2.2" class="f"/></svg><span>Routing</span></button>
|
||||
<button data-view="link"><svg viewBox="0 0 24 24"><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/></svg><span>Link</span></button>
|
||||
<button data-view="limiter"><svg viewBox="0 0 24 24"><path d="M2 7h20" stroke-dasharray="2.5 2.5"/><path d="M2 14c2 0 3-7 5-7h3c2 0 3 11 6 11s3-5 6-5"/></svg><span>Limiter</span></button>
|
||||
</nav>
|
||||
<button id="btn-lock" class="icon" hidden aria-label="Lock" title="Lock"></button>
|
||||
<button id="btn-settings" class="icon" aria-label="Settings" title="Settings" data-t-label="Settings">
|
||||
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>
|
||||
</button>
|
||||
</header>
|
||||
<div id="statusbar"></div>
|
||||
<main id="main"></main>
|
||||
</div>
|
||||
<div id="modal" hidden></div>
|
||||
<div id="toast" hidden></div>
|
||||
<script src="/i18n.js"></script>
|
||||
<script src="/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,444 @@
|
||||
:root {
|
||||
--bg: #0b0c0f;
|
||||
--bg2: #101216;
|
||||
--panel: #15181d;
|
||||
--panel2: #1c2027;
|
||||
--panel3: #232831;
|
||||
--line: #2a303a;
|
||||
--line2: #3a4250;
|
||||
--text: #e8edf3;
|
||||
--dim: #8a95a3;
|
||||
--dim2: #5d6773;
|
||||
--accent: #38bdf8;
|
||||
--accent2: #0284c7;
|
||||
--ok: #22c55e;
|
||||
--warn: #f59e0b;
|
||||
--bad: #ef4444;
|
||||
--mute: #dc2626;
|
||||
--led-g: #2bff6b;
|
||||
--led-o: #ffa31a;
|
||||
--led-r: #ff3030;
|
||||
--radius: 12px;
|
||||
--hdr: 56px;
|
||||
--bnav: 0px;
|
||||
--sb: 70px;
|
||||
color-scheme: dark;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; background: var(--bg); color: var(--text); }
|
||||
body {
|
||||
font: 15px/1.35 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
overscroll-behavior-y: contain;
|
||||
min-height: 100dvh;
|
||||
}
|
||||
[hidden] { display: none !important; }
|
||||
button, input, select { font: inherit; color: inherit; }
|
||||
button {
|
||||
background: var(--panel2); border: 1px solid var(--line); border-radius: 9px;
|
||||
padding: 8px 12px; min-height: 40px; cursor: pointer; touch-action: manipulation;
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: 6px;
|
||||
transition: background .12s, border-color .12s, color .12s;
|
||||
}
|
||||
button:hover { border-color: var(--line2); }
|
||||
button:active { filter: brightness(1.25); }
|
||||
button:focus-visible, select:focus-visible, input:focus-visible, .fader:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
button.on { background: var(--accent2); border-color: var(--accent); color: #fff; }
|
||||
button:disabled { opacity: .45; cursor: default; }
|
||||
button.danger { color: #fca5a5; }
|
||||
button.danger-on { background: #991b1b; border-color: #ef4444; color: #fff; }
|
||||
button.small { min-height: 32px; padding: 4px 10px; font-size: 13px; text-transform: none; letter-spacing: 0; }
|
||||
button.icon { background: none; border-color: transparent; padding: 8px; min-width: 44px; }
|
||||
button.icon:hover { background: var(--panel2); }
|
||||
button svg, .icon svg { width: 22px; height: 22px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
|
||||
select, input[type=text], input[type=number], input[type=password] {
|
||||
background: var(--panel2); border: 1px solid var(--line); border-radius: 9px;
|
||||
padding: 8px 10px; min-height: 40px; width: 100%; min-width: 0;
|
||||
}
|
||||
select { cursor: pointer; }
|
||||
input.bad { border-color: var(--bad); }
|
||||
label.inline { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--dim); }
|
||||
|
||||
/* ------------------------------------------------------------- header */
|
||||
#top {
|
||||
position: sticky; top: 0; z-index: 20; display: flex; align-items: center; gap: 8px;
|
||||
padding: calc(6px + env(safe-area-inset-top)) max(8px, env(safe-area-inset-right)) 6px max(8px, env(safe-area-inset-left));
|
||||
background: rgba(11, 12, 15, .92); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.brand { display: flex; flex: none; }
|
||||
#devtabs { display: flex; gap: 6px; overflow-x: auto; flex: 1; min-width: 0; scrollbar-width: none; }
|
||||
#devtabs::-webkit-scrollbar { display: none; }
|
||||
.devtab { white-space: nowrap; flex: none; max-width: 220px; background: var(--panel); }
|
||||
.devtab .dn { overflow: hidden; text-overflow: ellipsis; }
|
||||
.devtab small { font-size: 11px; color: var(--dim); background: var(--panel3); border-radius: 5px; padding: 1px 5px; }
|
||||
.devtab.active { background: var(--panel3); border-color: var(--accent); }
|
||||
.dot { width: 9px; height: 9px; border-radius: 50%; background: var(--dim2); flex: none; }
|
||||
.dot.online { background: var(--ok); box-shadow: 0 0 6px var(--ok); }
|
||||
.dot.connecting, .dot.loading { background: var(--warn); animation: blink 1s infinite; }
|
||||
.dot.error { background: var(--bad); }
|
||||
@keyframes blink { 50% { opacity: .3; } }
|
||||
|
||||
#viewtabs { display: flex; gap: 4px; background: var(--panel); border: 1px solid var(--line); border-radius: 11px; padding: 3px; flex: none; }
|
||||
#viewtabs button { border: 0; background: none; min-height: 36px; padding: 6px 14px; color: var(--dim); border-radius: 8px; }
|
||||
#viewtabs button svg { width: 18px; height: 18px; }
|
||||
#viewtabs button svg .f { fill: currentColor; stroke: none; }
|
||||
#viewtabs button.active { background: var(--panel3); color: var(--accent); }
|
||||
body[data-view=settings] #viewtabs button.active { background: none; color: var(--dim); }
|
||||
|
||||
#statusbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; padding: 10px max(10px, env(safe-area-inset-right)) 6px max(10px, env(safe-area-inset-left)); }
|
||||
#statusbar:empty { display: none; }
|
||||
#statusbar .preset { flex: 1 1 180px; min-width: 0; }
|
||||
#statusbar .preset b { display: block; font-size: 18px; letter-spacing: .01em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
#statusbar .preset small { color: var(--dim); font-size: 12px; }
|
||||
#statusbar .presetrow { flex: 0 1 380px; display: flex; gap: 8px; min-width: 0; }
|
||||
#statusbar .presetrow select { flex: 1; min-width: 0; }
|
||||
#statusbar .presetrow button { flex: none; }
|
||||
|
||||
#main { padding: 4px max(10px, env(safe-area-inset-right)) calc(24px + var(--bnav)) max(10px, env(safe-area-inset-left)); max-width: 1500px; margin: 0 auto; }
|
||||
|
||||
/* phones: view switcher becomes a bottom navigation bar */
|
||||
@media (max-width: 759px) {
|
||||
:root { --bnav: calc(62px + env(safe-area-inset-bottom)); }
|
||||
.brand { display: none; }
|
||||
/* backdrop-filter would make the header the containing block of the fixed bottom bar */
|
||||
#top { backdrop-filter: none; -webkit-backdrop-filter: none; background: var(--bg); }
|
||||
#viewtabs {
|
||||
position: fixed; left: 0; right: 0; bottom: 0; z-index: 30; border-radius: 0; border: 0; border-top: 1px solid var(--line);
|
||||
padding: 4px 6px env(safe-area-inset-bottom); background: rgba(16, 18, 22, .96); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
|
||||
}
|
||||
#viewtabs button { flex: 1; flex-direction: column; gap: 2px; font-size: 11px; min-height: 54px; padding: 4px; }
|
||||
#viewtabs button svg { width: 22px; height: 22px; }
|
||||
#toast { bottom: calc(var(--bnav) + 12px) !important; }
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- generic blocks */
|
||||
.card { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px; min-width: 0; }
|
||||
.card h3 { margin: 0 0 12px; font-size: 12px; text-transform: uppercase; letter-spacing: .08em; color: var(--dim);
|
||||
display: flex; align-items: center; gap: 8px; min-height: 22px; }
|
||||
.grow { flex: 1; }
|
||||
.cards { display: grid; gap: 10px; grid-template-columns: repeat(auto-fit, minmax(min(100%, 340px), 1fr)); align-items: start; margin-bottom: 10px; }
|
||||
.cards .wide { grid-column: 1 / -1; }
|
||||
h2.section { font-size: 13px; text-transform: uppercase; letter-spacing: .08em; color: var(--dim); margin: 14px 2px 8px; }
|
||||
.empty { color: var(--dim); text-align: center; padding: 60px 16px; display: flex; flex-direction: column; align-items: center; gap: 16px; }
|
||||
.spinner { width: 28px; height: 28px; border-radius: 50%; border: 3px solid var(--line); border-top-color: var(--accent); animation: spin .9s linear infinite; }
|
||||
.spinner.off { display: none; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
|
||||
.row > * { flex: 1 1 auto; }
|
||||
.row > button { flex: 0 0 auto; }
|
||||
.grow2 { flex: 1 1 160px !important; }
|
||||
.info { font-size: 12px; color: var(--dim); margin: 8px 2px 0; }
|
||||
.info.off { margin: 4px 0 6px; }
|
||||
.hint { text-align: center; }
|
||||
.err { color: #fca5a5; font-size: 13px; }
|
||||
|
||||
/* ------------------------------------------------------------- parameter rows */
|
||||
.param { margin: 10px 0 4px; }
|
||||
.param .lbl { display: flex; justify-content: space-between; align-items: center; gap: 8px; font-size: 13px; color: var(--dim); margin-bottom: 2px; }
|
||||
.valbox { display: flex; align-items: center; gap: 4px; }
|
||||
.valbox .val { min-width: 104px; min-height: 32px; padding: 3px 8px; background: var(--bg2); border-color: var(--line);
|
||||
font-variant-numeric: tabular-nums; font-size: 14px; color: var(--text); }
|
||||
.valbox .step { width: 34px; min-width: 34px; min-height: 32px; padding: 0; font-size: 18px; line-height: 1; color: var(--dim); background: var(--panel2); }
|
||||
.valbox .step:hover { color: var(--text); }
|
||||
.param.atzero .val { color: var(--ok); border-color: #1f5f36; }
|
||||
.rangewrap { position: relative; }
|
||||
.rangewrap .zmark { position: absolute; top: 6px; bottom: 6px; width: 2px; margin-left: -1px; border-radius: 1px; background: var(--line2);
|
||||
left: calc(13px + (100% - 26px) * var(--f)); pointer-events: none; }
|
||||
.param.atzero .zmark { background: var(--ok); }
|
||||
input[type=range] { position: relative; width: 100%; height: 36px; background: transparent; -webkit-appearance: none; appearance: none; margin: 0; cursor: pointer; touch-action: pan-y; }
|
||||
input[type=range]::-webkit-slider-runnable-track { height: 6px; background: var(--line); border-radius: 3px; }
|
||||
input[type=range]::-moz-range-track { height: 6px; background: var(--line); border-radius: 3px; }
|
||||
input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; width: 26px; height: 26px; margin-top: -10px; border-radius: 50%;
|
||||
background: radial-gradient(circle at 50% 40%, #e2e8f0, #94a3b8); border: 2px solid #0b0c0f; box-shadow: 0 1px 4px #000c; }
|
||||
input[type=range]::-moz-range-thumb { width: 22px; height: 22px; border-radius: 50%; background: radial-gradient(circle at 50% 40%, #e2e8f0, #94a3b8); border: 2px solid #0b0c0f; }
|
||||
.param.atzero input[type=range]::-webkit-slider-thumb { box-shadow: 0 0 0 3px #22c55e55, 0 1px 4px #000c; }
|
||||
|
||||
/* ------------------------------------------------------------- LED meters (segment bars) */
|
||||
.led { display: flex; gap: 2px; flex: none; }
|
||||
.led > i { flex: 1; border-radius: 1.5px; background: var(--c); opacity: .13; }
|
||||
.led > i.g { --c: var(--led-g); }
|
||||
.led > i.o { --c: var(--led-o); }
|
||||
.led > i.r { --c: var(--led-r); }
|
||||
.led.v { flex-direction: column-reverse; width: 12px; height: 100%; padding: 12px 0; }
|
||||
.led.h { flex-direction: row; height: 10px; width: 120px; }
|
||||
.muted .led > i { filter: saturate(.25); }
|
||||
|
||||
/* ------------------------------------------------------------- fader */
|
||||
/* only the cap grabs: a swipe anywhere else on the fader scrolls the page / the mixer sideways */
|
||||
.fader { --tx: 50%; position: relative; touch-action: pan-x pan-y; user-select: none; -webkit-user-select: none; border-radius: 8px; }
|
||||
.fader .track { position: absolute; left: var(--tx); top: 12px; bottom: 12px; width: 6px; margin-left: -3px; background: #07080a;
|
||||
border-radius: 3px; box-shadow: inset 0 0 0 1px var(--line); }
|
||||
.fader .tick { position: absolute; left: calc(var(--tx) - 14px); width: 28px; height: 1px; background: var(--line2);
|
||||
top: calc(12px + (100% - 24px) * (1 - var(--f))); }
|
||||
.fader .tick.z { background: var(--dim); height: 2px; margin-top: -0.5px; }
|
||||
.fader .tick span { position: absolute; right: calc(100% + 3px); top: -6px; font-size: 9px; line-height: 12px; color: var(--dim2); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.fader .tick.z span { color: var(--dim); font-weight: 600; }
|
||||
.fader .cap { position: absolute; left: calc(var(--tx) - 16px); width: 32px; height: 40px; margin-top: -20px; border-radius: 5px;
|
||||
top: calc(12px + (100% - 24px) * (1 - var(--f)));
|
||||
background: linear-gradient(#3b4250, #262b34 45%, #1b1f26 55%, #2c323c); border: 1px solid #4a5260;
|
||||
box-shadow: 0 3px 8px #000c, inset 0 1px 0 #ffffff1a; }
|
||||
.fader .cap { touch-action: none; cursor: ns-resize; z-index: 1; }
|
||||
.fader .cap::before { content: ""; position: absolute; inset: -10px -8px; } /* larger grip area for fingers */
|
||||
.fader .cap::after { content: ""; position: absolute; left: 3px; right: 3px; top: 50%; height: 2px; margin-top: -1px; background: #e8edf3; border-radius: 1px; }
|
||||
.fader.atzero .cap::after { background: var(--ok); box-shadow: 0 0 6px var(--ok); }
|
||||
.fader.grab .cap { border-color: var(--accent); }
|
||||
|
||||
/* ------------------------------------------------------------- mixer */
|
||||
.mixer { display: flex; gap: 14px; overflow-x: auto; padding-bottom: 8px; scroll-snap-type: x proximity; }
|
||||
.mgroup { flex: 0 0 auto; display: flex; flex-direction: column; gap: 6px; }
|
||||
.mgroup h4 { margin: 0 2px; font-size: 11px; text-transform: uppercase; letter-spacing: .1em; color: var(--dim); font-weight: 600; }
|
||||
.strips { display: flex; gap: 6px; }
|
||||
.strip { --cc: var(--warn); flex: none; width: 92px; background: linear-gradient(var(--panel), var(--bg2)); border: 1px solid var(--line);
|
||||
border-radius: var(--radius); padding: 0 6px 8px; display: flex; flex-direction: column; align-items: stretch; gap: 8px;
|
||||
scroll-snap-align: start; position: relative; overflow: hidden; }
|
||||
.strip::before { content: ""; height: 3px; margin: 0 -6px; background: var(--cc); opacity: .9; }
|
||||
.strip-head { flex-direction: column; gap: 0; background: none; border: 0; padding: 2px 0; min-height: 38px; border-radius: 6px; }
|
||||
.strip-head:hover { background: var(--panel2); }
|
||||
.strip-head .kind { font-size: 11px; color: var(--dim); letter-spacing: .04em; }
|
||||
.strip-head .nm { font-weight: 650; font-size: 13px; max-width: 78px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.faderbox { display: flex; justify-content: center; gap: 4px;
|
||||
height: clamp(170px, calc(100dvh - var(--hdr) - var(--sb) - var(--bnav) - 196px), 560px); }
|
||||
.strip .fader { --tx: 36px; width: 56px; height: 100%; }
|
||||
.strip .db { min-height: 32px; padding: 2px; font-variant-numeric: tabular-nums; font-size: 13px; background: var(--bg2); }
|
||||
.strip .db.z { color: var(--ok); }
|
||||
.strip button.mute { min-height: 38px; font-weight: 700; font-size: 12px; letter-spacing: .06em; }
|
||||
button.mute.on { background: var(--mute); border-color: #f87171; color: #fff; box-shadow: 0 0 10px #dc262655; }
|
||||
.strip.muted { background: linear-gradient(#1f1517, var(--bg2)); }
|
||||
@media (min-width: 1200px) {
|
||||
.mgroup { flex-shrink: 1; flex-basis: 0; }
|
||||
.strip { flex: 1 1 92px; max-width: 128px; }
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- channel view */
|
||||
.chbar { position: sticky; top: var(--hdr); z-index: 10; display: flex; align-items: center; gap: 6px; margin: 0 -10px 10px; padding: 8px 10px;
|
||||
background: rgba(11, 12, 15, .94); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid var(--line); }
|
||||
.chbar .nav { flex: none; background: var(--panel2); border-color: var(--line); min-width: 44px; }
|
||||
.chselwrap { --cc: var(--warn); flex: 1 1 auto; min-width: 0; position: relative; max-width: 420px; }
|
||||
.chselwrap::before { content: ""; position: absolute; left: 0; top: 8px; bottom: 8px; width: 4px; border-radius: 2px; background: var(--cc); pointer-events: none; }
|
||||
.chsel { font-weight: 650; font-size: 16px; padding-left: 14px; min-height: 44px; background: var(--panel2); }
|
||||
.chbar .led.h { width: clamp(60px, 18vw, 200px); }
|
||||
.chbar .mute { flex: none; min-width: 70px; font-weight: 700; font-size: 12px; letter-spacing: .06em; }
|
||||
@media (max-width: 480px) { .chbar .led.h { display: none; } }
|
||||
|
||||
.sub { font-size: 13px; color: var(--text); font-weight: 600; flex: 0 0 80px !important; }
|
||||
.xo + .xo { margin-top: 14px; padding-top: 12px; border-top: 1px solid var(--line); }
|
||||
canvas.curve { width: 100%; height: clamp(200px, 32vw, 320px); display: block; background: #08090b; border: 1px solid var(--line); border-radius: 10px; touch-action: none; cursor: crosshair; }
|
||||
.bands { display: flex; gap: 6px; overflow-x: auto; padding: 10px 0 4px; scrollbar-width: thin; }
|
||||
.band { flex: 1 0 58px; flex-direction: column; gap: 0; padding: 5px 4px; min-height: 52px; line-height: 1.15; }
|
||||
.band b { font-size: 14px; }
|
||||
.band small { font-size: 10.5px; color: var(--dim); font-variant-numeric: tabular-nums; }
|
||||
.band.active:not(.on) { border-color: #3b6d8a; }
|
||||
.band.on { background: #3a2a0d; border-color: var(--warn); color: #fff; }
|
||||
.band.on small { color: #fcd9a0; }
|
||||
.band.bypassed { opacity: .45; }
|
||||
.band.bypassed b { text-decoration: line-through; }
|
||||
.bandhead { margin-top: 8px; }
|
||||
.bandhead label { flex: 1 1 200px; }
|
||||
.pgrid { display: grid; gap: 0 18px; grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr)); }
|
||||
|
||||
.geq { display: flex; gap: 2px; overflow-x: auto; padding-bottom: 6px; }
|
||||
.gb { flex: 1 0 30px; display: flex; flex-direction: column; align-items: center; gap: 4px; font-size: 10px; color: var(--dim); }
|
||||
.gb .fader { width: 30px; height: 190px; }
|
||||
.gb .fader .tick { left: 3px; width: 24px; }
|
||||
.gb .fader .cap { left: 1px; width: 28px; height: 24px; margin-top: -12px; }
|
||||
.gb .gv { font-variant-numeric: tabular-nums; }
|
||||
.gb .gv.nz { color: var(--warn); }
|
||||
.gb .gf { white-space: nowrap; }
|
||||
|
||||
.mixrow { display: grid; grid-template-columns: minmax(110px, 0.6fr) 1fr; gap: 4px 12px; align-items: center; padding: 4px 0; }
|
||||
.mixrow + .mixrow { border-top: 1px solid var(--line); }
|
||||
.mixrow .param { margin: 4px 0; }
|
||||
.mixrow .param .lbl > span:first-child { display: none; }
|
||||
.mixrow .param .lbl { justify-content: flex-end; }
|
||||
.mixrow.off .param { opacity: .45; }
|
||||
.src { --cc: var(--accent); justify-content: flex-start; text-align: left; min-height: 44px; }
|
||||
.src .sw { width: 30px; height: 18px; border-radius: 9px; background: var(--line); position: relative; flex: none; transition: background .15s; }
|
||||
.src .sw::after { content: ""; position: absolute; left: 2px; top: 2px; width: 14px; height: 14px; border-radius: 50%; background: var(--dim); transition: transform .15s, background .15s; }
|
||||
.src.on { background: var(--panel2); border-color: var(--cc); color: var(--text); }
|
||||
.src.on .sw { background: var(--cc); }
|
||||
.src.on .sw::after { transform: translateX(12px); background: #fff; }
|
||||
@media (max-width: 420px) { .mixrow { grid-template-columns: 1fr; } }
|
||||
|
||||
/* ------------------------------------------------------------- routing matrix */
|
||||
.routing { overflow-x: auto; }
|
||||
.xmatrix { display: grid; grid-template-columns: minmax(104px, 1.1fr) repeat(var(--n), minmax(58px, 1fr)); gap: 0; min-width: min-content; }
|
||||
.xcorner { display: flex; flex-direction: column; justify-content: flex-end; padding: 0 8px 8px 2px; font-size: 11px; color: var(--dim2); }
|
||||
.xin { --cc: var(--accent); display: flex; flex-direction: column; align-items: center; gap: 2px; padding: 8px 4px 10px; border-top: 3px solid var(--cc);
|
||||
background: linear-gradient(color-mix(in srgb, var(--cc) 10%, transparent), transparent); border-radius: 6px 6px 0 0; margin: 0 3px; min-width: 0; }
|
||||
.xin b { font-size: 14px; }
|
||||
.xin small { font-size: 11px; color: var(--dim); max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.xin .led.h { width: 80%; height: 6px; margin-top: 4px; }
|
||||
.xout { display: grid; grid-template-columns: 1fr auto; grid-template-rows: auto auto; justify-items: start; align-items: center; gap: 0 6px;
|
||||
text-align: left; border-radius: 9px 0 0 9px; border: 0; border-top: 1px solid var(--line); background: none; padding: 8px; min-height: 64px; }
|
||||
.xout:hover { background: var(--panel2); }
|
||||
.xout.open { background: var(--panel3); }
|
||||
.xo-t { display: flex; flex-direction: column; min-width: 0; }
|
||||
.xo-t b { font-size: 14px; }
|
||||
.xo-t small { font-size: 11px; color: var(--dim); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%; }
|
||||
.xo-s { grid-column: 1; font-size: 11px; color: var(--accent); }
|
||||
.chev { grid-column: 2; grid-row: 1 / 3; color: var(--dim); font-size: 16px; }
|
||||
.xp { --cc: var(--accent); position: relative; border: 0; border-top: 1px solid var(--line); border-radius: 0; min-height: 64px; padding: 0; background:
|
||||
linear-gradient(var(--line), var(--line)) center / 2px 100% no-repeat,
|
||||
linear-gradient(var(--line), var(--line)) center / 100% 2px no-repeat; flex-direction: column; gap: 3px; }
|
||||
.xp:hover { background-color: var(--panel2); }
|
||||
.xp .node { width: 24px; height: 24px; border-radius: 50%; background: var(--bg); border: 2px solid var(--line2); transition: transform .12s, background .12s; }
|
||||
.xp:hover .node { border-color: var(--dim); }
|
||||
.xp.on { border-color: var(--line); color: var(--text); --lc: color-mix(in srgb, var(--cc) 60%, transparent); background:
|
||||
linear-gradient(var(--lc), var(--lc)) center / 2px 100% no-repeat,
|
||||
linear-gradient(var(--lc), var(--lc)) center / 100% 2px no-repeat; }
|
||||
.xp.on .node { background: var(--cc); border-color: #fff; box-shadow: 0 0 0 4px color-mix(in srgb, var(--cc) 30%, transparent), 0 0 14px var(--cc); transform: scale(1.08); }
|
||||
.xp small { position: absolute; bottom: 3px; left: 0; right: 0; font-size: 10px; color: var(--text); background: none; font-variant-numeric: tabular-nums; }
|
||||
.xpanel { grid-column: 1 / -1; background: var(--panel3); border-radius: 0 0 10px 10px; padding: 6px 12px 10px; margin-bottom: 6px; }
|
||||
.xpanel-h { display: flex; align-items: center; justify-content: space-between; gap: 8px; font-size: 12px; color: var(--dim); text-transform: uppercase; letter-spacing: .06em; padding: 4px 0; }
|
||||
|
||||
/* ------------------------------------------------------------- settings */
|
||||
.devform { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
|
||||
.devform label { font-size: 12px; color: var(--dim); display: flex; flex-direction: column; gap: 4px; }
|
||||
.devform label.full, .devform .err { grid-column: 1 / -1; }
|
||||
.devform label.chk { flex-direction: row; align-items: center; gap: 8px; color: var(--text); font-size: 14px; }
|
||||
.devform label.chk input { width: 20px; height: 20px; }
|
||||
.devform .actions { grid-column: 1 / -1; display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.devform .actions button { flex: 1 1 auto; }
|
||||
|
||||
/* ------------------------------------------------------------- dialogs */
|
||||
#modal { position: fixed; inset: 0; z-index: 100; display: flex; align-items: center; justify-content: center; padding: 16px; }
|
||||
.backdrop { position: absolute; inset: 0; background: #000a; animation: fade .15s; }
|
||||
.dialog { position: relative; width: min(420px, 100%); background: var(--panel); border: 1px solid var(--line2); border-radius: 16px;
|
||||
padding: 18px; box-shadow: 0 20px 60px #000c; animation: pop .15s ease-out; }
|
||||
.dialog h2 { margin: 0 0 12px; font-size: 17px; }
|
||||
.dlg-text { margin: 0 0 4px; color: var(--dim); }
|
||||
.dlg-actions { display: flex; flex-wrap: wrap; gap: 8px; justify-content: flex-end; margin-top: 16px; }
|
||||
.dlg-actions button { min-width: 110px; }
|
||||
.dialog .row input { flex: 1 1 140px; font-size: 18px; font-variant-numeric: tabular-nums; }
|
||||
.dialog .chip { flex: none; }
|
||||
.form { display: flex; flex-direction: column; gap: 10px; }
|
||||
.form label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--dim); }
|
||||
@keyframes fade { from { opacity: 0; } }
|
||||
@keyframes pop { from { opacity: 0; transform: scale(.96) translateY(6px); } }
|
||||
@media (max-width: 520px) {
|
||||
#modal { align-items: flex-end; padding: 0; }
|
||||
.dialog { width: 100%; border-radius: 18px 18px 0 0; padding-bottom: calc(18px + env(safe-area-inset-bottom)); animation: slideup .18s ease-out; }
|
||||
.dlg-actions button { flex: 1; }
|
||||
}
|
||||
@keyframes slideup { from { transform: translateY(40px); opacity: 0; } }
|
||||
|
||||
#toast { position: fixed; left: 50%; bottom: calc(20px + env(safe-area-inset-bottom)); transform: translateX(-50%);
|
||||
background: #1f2937; border: 1px solid var(--line2); padding: 10px 16px; border-radius: 10px; z-index: 120; max-width: 90vw; box-shadow: 0 8px 24px #000a; }
|
||||
|
||||
/* ------------------------------------------------------------- login */
|
||||
#login { position: fixed; inset: 0; z-index: 200; display: flex; align-items: center; justify-content: center; overflow-y: auto;
|
||||
background: radial-gradient(ellipse at 50% 0%, #13253a 0%, var(--bg) 60%); padding: 20px; }
|
||||
.loginbox { display: flex; flex-direction: column; align-items: center; width: min(320px, 100%); }
|
||||
.loginbox .logo svg { width: 56px; height: 56px; }
|
||||
.loginbox h1 { margin: 12px 0 2px; font-size: 22px; letter-spacing: .02em; }
|
||||
.loginbox p { margin: 0 0 22px; color: var(--dim); }
|
||||
.pindots { display: flex; gap: 18px; margin-bottom: 10px; }
|
||||
.pindots i { width: 16px; height: 16px; border-radius: 50%; border: 2px solid var(--line2); transition: background .1s, border-color .1s, transform .1s; }
|
||||
.pindots i.on { background: var(--accent); border-color: var(--accent); transform: scale(1.1); box-shadow: 0 0 10px #38bdf888; }
|
||||
.pindots.shake { animation: shake .4s; }
|
||||
.pindots.shake i { border-color: var(--bad); }
|
||||
@keyframes shake { 20%, 60% { transform: translateX(-10px); } 40%, 80% { transform: translateX(10px); } }
|
||||
.pinmsg { min-height: 20px; font-size: 13px; color: #fca5a5; margin-bottom: 14px; text-align: center; }
|
||||
.pinpad { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; width: 100%; max-width: 280px; }
|
||||
.pinpad.locked { opacity: .35; pointer-events: none; }
|
||||
.pk { aspect-ratio: 1; border-radius: 50%; font-size: 26px; font-weight: 500; background: var(--panel); border: 1px solid var(--line); min-height: 0; }
|
||||
.pk:active { background: var(--accent2); border-color: var(--accent); filter: none; }
|
||||
.pk.del { font-size: 22px; background: none; border-color: transparent; color: var(--dim); }
|
||||
@media (max-height: 560px) { .pk { aspect-ratio: auto; height: 52px; border-radius: 14px; } .pinpad { gap: 8px; } .loginbox p { margin-bottom: 10px; } }
|
||||
|
||||
/* ------------------------------------------------------------- limiter calculator */
|
||||
.limcard h3 .led.h { width: clamp(50px, 14vw, 110px); height: 8px; }
|
||||
.lres { --c: var(--ok); border: 1px solid var(--line); border-left: 4px solid var(--c); border-radius: 10px; padding: 10px 12px; margin-bottom: 12px;
|
||||
background: linear-gradient(90deg, color-mix(in srgb, var(--c) 10%, transparent), transparent 70%); }
|
||||
.lres.warn { --c: var(--warn); }
|
||||
.lres.bad { --c: var(--bad); }
|
||||
.lres.none { --c: var(--line2); background: none; }
|
||||
.lw { font-size: 30px; font-weight: 700; font-variant-numeric: tabular-nums; line-height: 1.1; }
|
||||
.lw small { font-size: 14px; font-weight: 500; color: var(--dim); }
|
||||
.lsub { font-size: 13px; color: var(--dim); margin-top: 2px; }
|
||||
.lbar { position: relative; height: 8px; border-radius: 4px; background: var(--panel3); margin: 10px 0 4px; }
|
||||
.lres.none .lbar { display: none; }
|
||||
.lbar i { position: absolute; inset: 0 auto 0 0; width: calc(var(--p) * 100%); border-radius: 4px; background: var(--c); transition: width .15s; }
|
||||
.lbar b, .lbar::after { position: absolute; top: -4px; bottom: -4px; width: 2px; background: var(--text); left: calc(var(--a) * 100% - 1px); }
|
||||
.lbar::after { content: ""; display: none; background: var(--warn); left: calc(var(--s) * 100% - 1px); }
|
||||
.lbar.hasspk::after { display: block; }
|
||||
.lnotes { display: grid; gap: 2px; margin-top: 6px; font-size: 12.5px; }
|
||||
.lnotes .ok { color: #86efac; } .lnotes .warn { color: #fcd34d; } .lnotes .bad { color: #fca5a5; }
|
||||
.lnotes div::before { content: "● "; font-size: 9px; vertical-align: 2px; }
|
||||
.limgrid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 8px; }
|
||||
.limgrid label { font-size: 12px; color: var(--dim); display: flex; flex-direction: column; gap: 4px; min-width: 0; }
|
||||
.limgrid label.full { grid-column: 1 / -1; }
|
||||
.target { border-top: 1px solid var(--line); margin-top: 10px; padding-top: 10px; }
|
||||
.target .row input { flex: 1 1 80px; min-width: 0; }
|
||||
.target .sub { flex: 0 0 auto !important; }
|
||||
.chips { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 8px; }
|
||||
button.chip { min-height: 30px; padding: 3px 10px; font-size: 12.5px; text-transform: none; letter-spacing: 0; border-radius: 15px; }
|
||||
details.more { margin-top: 8px; }
|
||||
details.more summary { cursor: pointer; font-size: 13px; color: var(--dim); padding: 6px 0; user-select: none; }
|
||||
.amp .ampspec { font-size: 15px; font-weight: 600; font-variant-numeric: tabular-nums; }
|
||||
.amp .actions { display: flex; justify-content: flex-end; margin-top: 8px; }
|
||||
.addcard { min-height: 90px; border-style: dashed; color: var(--dim); background: none; font-size: 14px; }
|
||||
.addcard:hover { color: var(--accent); border-color: var(--accent); }
|
||||
input.short { flex: 0 0 72px !important; width: 72px; text-align: right; }
|
||||
.seg { display: flex; gap: 0; }
|
||||
.seg button { flex: 1; border-radius: 0; text-transform: none; letter-spacing: 0; }
|
||||
.seg button:first-child { border-radius: 8px 0 0 8px; }
|
||||
.seg button:last-child { border-radius: 0 8px 8px 0; margin-left: -1px; }
|
||||
.ampform { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
.ampform .full { grid-column: 1 / -1; }
|
||||
.ampform input { min-width: 0; width: 100%; }
|
||||
.ampform .sub { margin-top: 4px; }
|
||||
.ampform .full > label { font-size: 12px; color: var(--dim); display: flex; flex-direction: column; gap: 4px; }
|
||||
.ampform label[hidden] { display: none; }
|
||||
.chips.presets { display: grid; grid-template-columns: repeat(auto-fill, minmax(104px, 1fr)); margin: 6px 0 10px; }
|
||||
button.chip.preset { flex-direction: column; align-items: flex-start; gap: 0; border-radius: 9px; padding: 5px 9px; min-height: 42px; text-align: left; }
|
||||
button.chip.preset b { font-size: 13px; }
|
||||
button.chip.preset small { font-size: 10.5px; color: var(--dim); font-weight: 400; }
|
||||
button.chip.preset.on small { color: #e0f2fe; }
|
||||
details.more summary .tag { margin-left: 8px; font-size: 11px; padding: 1px 7px; border-radius: 9px; background: var(--panel3); color: var(--accent); }
|
||||
|
||||
/* ------------------------------------------------------------- desktop app: remote access */
|
||||
.remote-urls { display: flex; flex-direction: column; gap: 4px; margin-top: 8px; }
|
||||
.remote-urls code { font: 600 15px ui-monospace, Consolas, monospace; color: var(--accent); background: var(--panel2);
|
||||
border: 1px solid var(--line); border-radius: 8px; padding: 6px 10px; user-select: all; }
|
||||
|
||||
/* ------------------------------------------------------------- device form: network / USB */
|
||||
.devform .full { grid-column: 1 / -1; }
|
||||
.devform [hidden] { display: none !important; }
|
||||
.devform .sub { margin-top: 2px; color: var(--dim); font-weight: 500; font-size: 12px; }
|
||||
.devform .row { flex-wrap: nowrap; }
|
||||
.devform .row select { flex: 1 1 auto; min-width: 0; }
|
||||
|
||||
/* channel links */
|
||||
.lnk { --lc: var(--warn); display: inline-flex; vertical-align: -2px; margin-left: 4px; color: var(--lc); }
|
||||
.lnk svg, .linknote svg, .lkgroup svg, .lkmark svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2.2; stroke-linecap: round; }
|
||||
.linknote { --lc: var(--warn); color: var(--lc); margin: -4px 0 10px; }
|
||||
.linknote svg { vertical-align: -2px; }
|
||||
.lkgrid { display: grid; grid-template-columns: repeat(auto-fill, minmax(96px, 1fr)); gap: 6px; }
|
||||
.lkch { --lc: var(--line); position: relative; flex-direction: column; gap: 0; min-height: 58px; border-top: 3px solid var(--lc); }
|
||||
.lkch small { color: var(--dim); max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.lkch .lkmark { position: absolute; top: 4px; right: 5px; color: var(--lc); }
|
||||
.lkch.sel { background: var(--accent2); border-color: var(--accent); color: #fff; }
|
||||
.lkch.sel small { color: #dbeafe; }
|
||||
.lkactions { margin-top: 10px; }
|
||||
.lkgroups { display: flex; flex-direction: column; gap: 6px; margin-top: 12px; }
|
||||
.lkgroup { --lc: var(--warn); border-left: 3px solid var(--lc); padding: 4px 0 4px 10px; background: var(--panel2); border-radius: 6px; }
|
||||
.lkgroup svg { flex: none; color: var(--lc); }
|
||||
|
||||
/* lock (desktop app) */
|
||||
#btn-lock { display: inline-flex; align-items: center; gap: 6px; }
|
||||
#btn-lock[hidden] { display: none; }
|
||||
#btn-lock.on { background: #3a2a0d; border-color: var(--warn); color: #fcd9a0; padding: 8px 12px; }
|
||||
#btn-lock span { font-size: 13px; font-weight: 600; }
|
||||
body.locked #main :is(button, input, select, .fader, canvas):not(.chsel, .nav, .strip-head, .xout, .band, [data-view-ok]),
|
||||
body.locked #statusbar :is(button, select):not([data-view-ok]) { cursor: not-allowed; }
|
||||
|
||||
/* limiter LED (outputs): orange bar under the channel name, lit while the DSP reports the limiter active */
|
||||
.limled { flex: none; display: block; width: 34px; height: 4px; margin-top: 3px; border-radius: 1px;
|
||||
background: color-mix(in srgb, var(--led-o) 16%, transparent); transition: background .08s, box-shadow .08s; }
|
||||
.limled.ph { visibility: hidden; }
|
||||
.limled.on { background: var(--led-o); box-shadow: 0 0 6px var(--led-o), 0 0 2px var(--led-o); }
|
||||
.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; }
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Protocol self test: python tests/test_protocol.py"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from dsp import protocol as P # noqa: E402
|
||||
|
||||
|
||||
def test_frames_match_known_captures():
|
||||
# Known-good frames as sent to the devices (they also match the DSP 408 captures published by dsp-408-ui)
|
||||
assert P.build_frame(0x10) == bytes.fromhex("10 02 00 01 01 10 10 03 11")
|
||||
assert P.build_frame(0x40) == bytes.fromhex("10 02 00 01 01 40 10 03 41")
|
||||
assert P.build_frame(0x29, b"\x13") == bytes.fromhex("10 02 00 01 02 29 13 10 03 38")
|
||||
assert P.build_frame(0x35, b"\x0b\x01") == bytes.fromhex("10 02 00 01 03 35 0b 01 10 03 3c")
|
||||
|
||||
|
||||
def test_parser_handles_split_and_embedded_dle():
|
||||
payload = bytes([5]) + b"\x10\x03\x10\x02" + bytes(46)
|
||||
frame = P.build_frame(P.CMD_CONFIG_CHUNK, payload, addr=0, src=1)
|
||||
parser = P.FrameParser()
|
||||
out = parser.feed(b"\x00garbage" + frame[:7]) + parser.feed(frame[7:] + P.build_frame(0x01, b"\x00"))
|
||||
assert [f.cmd for f in out] == [P.CMD_CONFIG_CHUNK, 0x01]
|
||||
assert out[0].payload == payload and out[0].checksum_ok
|
||||
|
||||
|
||||
def test_layout_matches_devices():
|
||||
m204, m408 = P.MODELS["204"], P.MODELS["408"]
|
||||
assert (m204.size, m204.chunks) == (724, 15)
|
||||
assert (m408.size, m408.chunks) == (1448, 29)
|
||||
assert m204.out_base == 0x128 and m204.globals_base == 0x2B8
|
||||
assert m408.out_base == 0x240 and m408.globals_base == 0x580
|
||||
assert m204.channel("out", 0) == 2 and m408.channel("out", 0) == 4
|
||||
|
||||
|
||||
def test_state_roundtrip():
|
||||
for m in P.MODELS.values():
|
||||
st = P.default_state(m)
|
||||
st["outputs"][-1]["comp"]["threshold"] = 123
|
||||
st["inputs"][0]["geq"][30] = 7
|
||||
st["inputs"][-1]["mute"] = True
|
||||
assert P.parse_state(m, bytes(P.build_state_buffer(m, st))) == st
|
||||
|
||||
|
||||
def test_scales():
|
||||
assert P.gain_to_db(0) == -60 and P.gain_to_db(80) == -20 and P.gain_to_db(280) == 0 and P.gain_to_db(400) == 12
|
||||
for raw in (0, 37, 80, 150, 280, 400):
|
||||
assert P.db_to_gain(P.gain_to_db(raw)) == raw
|
||||
assert round(P.freq_to_hz(0), 1) == 19.7 and round(P.freq_to_hz(300)) == 20159
|
||||
assert P.hz_to_freq(1000) == 170
|
||||
assert len(P.Q_TABLE) == 101 and len(P.SLOPES) == 21
|
||||
lv = [0.5, 0.0, 1.0, 0.001] + [0.25] * 8
|
||||
dec = P.decode_meters(P.encode_meters(lv))
|
||||
assert all(abs(a - b) < 1e-3 * max(a, 1e-3) for a, b in zip(lv, dec))
|
||||
|
||||
|
||||
def test_param_commands():
|
||||
m = P.MODELS["204"]
|
||||
st = P.default_state(m)
|
||||
out = st["outputs"][1]
|
||||
P.apply_param(out, "peq.3.gain", 150)
|
||||
assert P.param_command(m, "out", 1, out, "peq.3.gain") == (0x33, bytes([3, 3, 150, 0, 125, 0, 32, 0, 0]))
|
||||
P.apply_param(out, "mix.1", 200)
|
||||
assert P.param_command(m, "out", 1, out, "mix.1") == (0x41, bytes([3, 1, 200, 0]))
|
||||
inp = st["inputs"][1]
|
||||
assert P.param_command(m, "in", 1, inp, "gate.hold") == (0x3E, bytes([1, 0, 0, 99, 0, 99, 0, 0, 0]))
|
||||
|
||||
|
||||
def test_links():
|
||||
# masks as read from a real DSP 204: In A+B, Out 1+2 and Out 3+4 linked
|
||||
m = P.MODELS["204"]
|
||||
st = P.default_state(m)
|
||||
for ch, mask in zip(st["inputs"] + st["outputs"], [3, 0, 3, 0, 12, 0]):
|
||||
ch["link"] = mask
|
||||
st = P.parse_state(m, bytes(P.build_state_buffer(m, st)))
|
||||
assert P.link_groups(st["inputs"]) == [[0, 1]]
|
||||
assert P.link_groups(st["outputs"]) == [[0, 1], [2, 3]]
|
||||
assert P.link_groups(P.default_state(m)["outputs"]) == [[0], [1], [2], [3]]
|
||||
assert P.link_masks(4, [[0, 1], [2, 3]]) == [3, 0, 12, 0]
|
||||
assert P.link_masks(4, [[3, 1]]) == [1, 10, 4, 0]
|
||||
# the DSP applies a change on any member to the whole group, but not names
|
||||
P.apply_command(m, st, P.CMD_GAIN, bytes([5, 100, 0]))
|
||||
P.apply_command(m, st, P.CMD_CHANNEL_NAME, bytes([4]) + b"Sub ")
|
||||
assert st["outputs"][2]["gain"] == 100 and st["outputs"][3]["name"] != "Sub"
|
||||
|
||||
|
||||
def test_preset_import_commands():
|
||||
from dsp import preset
|
||||
m = P.MODELS["204"]
|
||||
cur = P.default_state(m)
|
||||
assert preset.import_commands(m, cur, cur) == [] # identical: nothing is written
|
||||
tgt = P.default_state(m)
|
||||
tgt["outputs"][1]["gain"] = 300
|
||||
assert preset.import_commands(m, tgt, cur) == [(0x34, bytes([3]) + (300).to_bytes(2, "little"))]
|
||||
tgt["outputs"][0]["link"], tgt["outputs"][1]["link"] = 3, 0 # new link: dissolve, set, relink
|
||||
cmds = preset.import_commands(m, tgt, cur)
|
||||
assert cmds[0][0] == P.CMD_LINK and (P.CMD_LINK, bytes([2, 3, 0])) in cmds
|
||||
# a file is read with linked channels made alike, like the DSP keeps them
|
||||
doc = preset.export_doc("204", "DSP204", tgt, bytes(P.build_state_buffer(m, tgt))[: m.size])
|
||||
st = preset.read_file("204", m, cur, doc=doc)
|
||||
assert st["outputs"][1]["gain"] == st["outputs"][0]["gain"] == 280
|
||||
assert st["outputs"][1]["matrix"] == tgt["outputs"][1]["matrix"] # routing stays per channel
|
||||
|
||||
|
||||
|
||||
def test_limit_flags():
|
||||
# status bytes after the 12 levels, captured on a DSP 204 while forcing the limiters
|
||||
assert P.decode_limit_flags(bytes(36) + bytes([0x00, 0x03]), 4) == [True, True, False, False]
|
||||
assert P.decode_limit_flags(bytes(36) + bytes([0x00, 0x0C]), 4) == [False, False, True, True]
|
||||
assert P.decode_limit_flags(bytes(36), 4) == [False] * 4
|
||||
assert P.decode_limit_flags(P.encode_meters([0.0] * 12, 0x05), 4) == [True, False, True, False]
|
||||
|
||||
|
||||
|
||||
def test_channel_names():
|
||||
# the DSP keeps 8 ASCII characters; umlauts are spelled out, anything else is dropped
|
||||
assert P.clean_name("Bühne€ Links") == "Buehne L"
|
||||
m = P.MODELS["204"]
|
||||
assert P.param_command(m, "in", 0, {"name": "Süd"}, "name") == (0x3D, b"\x00Sued ")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
for name, fn in list(globals().items()):
|
||||
if name.startswith("test_"):
|
||||
fn()
|
||||
print("ok", name)
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
"""Raw SD card writing on Windows (needs administrator rights).
|
||||
|
||||
Safety: only removable USB/SD/MMC disks that are neither the boot nor the system disk are offered.
|
||||
The first MiB (partition table) is written last, so Windows does not mount half-written
|
||||
partitions in the middle of the job - the same trick Raspberry Pi Imager uses.
|
||||
"""
|
||||
|
||||
import ctypes
|
||||
import hashlib
|
||||
import json
|
||||
import lzma
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
CHUNK = 4 << 20 # write size (multiple of the sector size)
|
||||
HEAD = 1 << 20 # held back and written last
|
||||
MAX_SIZE = 512 << 30 # larger "removable" disks are most likely not an SD card
|
||||
NO_WINDOW = 0x08000000 if sys.platform == "win32" else 0
|
||||
|
||||
|
||||
def is_admin() -> bool:
|
||||
try:
|
||||
return bool(ctypes.windll.shell32.IsUserAnAdmin())
|
||||
except (AttributeError, OSError):
|
||||
return False
|
||||
|
||||
|
||||
def relaunch_as_admin() -> bool:
|
||||
"""Restart this program elevated (UAC prompt). True if the elevated copy was started."""
|
||||
argv = sys.argv[1:] if getattr(sys, "frozen", False) else sys.argv # script: python <script> ...
|
||||
args = " ".join(f'"{a}"' for a in argv)
|
||||
return ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, args, None, 1) > 32
|
||||
|
||||
|
||||
def powershell(script: str, timeout=60) -> str:
|
||||
r = subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", script],
|
||||
capture_output=True, text=True, timeout=timeout, creationflags=NO_WINDOW)
|
||||
if r.returncode:
|
||||
raise RuntimeError(r.stderr.strip() or r.stdout.strip() or "PowerShell-Fehler")
|
||||
return r.stdout
|
||||
|
||||
|
||||
def list_disks() -> list[dict]:
|
||||
out = powershell(
|
||||
"@(Get-Disk | Where-Object { $_.BusType -in 'USB','SD','MMC' -and -not $_.IsBoot -and -not $_.IsSystem "
|
||||
"-and $_.Size -gt 0 } | Select-Object Number,FriendlyName,Size,BusType) | ConvertTo-Json -Compress")
|
||||
out = out.strip()
|
||||
disks = json.loads(out) if out else []
|
||||
if isinstance(disks, dict):
|
||||
disks = [disks]
|
||||
for d in disks:
|
||||
d["Letters"] = drive_letters(d["Number"])
|
||||
return [d for d in disks if 0 < d["Size"] <= MAX_SIZE]
|
||||
|
||||
|
||||
def drive_letters(number: int) -> list[str]:
|
||||
try:
|
||||
out = powershell(f"@(Get-Partition -DiskNumber {int(number)} -ErrorAction SilentlyContinue | "
|
||||
"Where-Object DriveLetter | ForEach-Object {{ [string]$_.DriveLetter }}) -join ','")
|
||||
return [x for x in out.strip().split(",") if x]
|
||||
except RuntimeError:
|
||||
return []
|
||||
|
||||
|
||||
def describe(d: dict) -> str:
|
||||
letters = f" [{', '.join(l + ':' for l in d['Letters'])}]" if d.get("Letters") else ""
|
||||
return f"Datenträger {d['Number']}: {d['FriendlyName']} – {d['Size'] / 1e9:.1f} GB ({d['BusType']}){letters}"
|
||||
|
||||
|
||||
def diskpart(lines: list[str]):
|
||||
r = subprocess.run(["diskpart"], input="\n".join(lines) + "\nexit\n", capture_output=True, text=True,
|
||||
timeout=120, creationflags=NO_WINDOW)
|
||||
if r.returncode:
|
||||
raise RuntimeError("diskpart: " + (r.stdout.strip().splitlines() or ["Fehler"])[-1])
|
||||
|
||||
|
||||
def write_image(number: int, xz_path: Path, total: int, progress, verify=True, target: Path | None = None):
|
||||
"""Decompress xz_path straight onto the disk; total = image size for the progress bar.
|
||||
progress(phase, done, total). `target` writes into a plain file instead (testing without a card)."""
|
||||
if target is None:
|
||||
diskpart([f"select disk {int(number)}", "clean"]) # drops partitions, Windows unmounts them
|
||||
time.sleep(1)
|
||||
dev = rf"\\.\PhysicalDrive{int(number)}"
|
||||
else:
|
||||
dev = str(target)
|
||||
open(dev, "wb").close()
|
||||
h = hashlib.sha256()
|
||||
head = b""
|
||||
written = 0
|
||||
with lzma.open(xz_path) as src, open(dev, "r+b", buffering=0) as out:
|
||||
buf = bytearray()
|
||||
while True:
|
||||
data = src.read(CHUNK)
|
||||
if data:
|
||||
h.update(data)
|
||||
if len(head) < HEAD:
|
||||
take = HEAD - len(head)
|
||||
head += data[:take]
|
||||
data = data[take:]
|
||||
if len(head) == HEAD:
|
||||
out.seek(HEAD)
|
||||
buf += data
|
||||
while len(buf) >= CHUNK or (not data and buf):
|
||||
piece = bytes(buf[:CHUNK])
|
||||
del buf[:CHUNK]
|
||||
if len(piece) % 512:
|
||||
piece += b"\0" * (512 - len(piece) % 512)
|
||||
out.write(piece)
|
||||
written += len(piece)
|
||||
progress("write", written + len(head), total)
|
||||
if not data:
|
||||
break
|
||||
out.seek(0)
|
||||
out.write(head + b"\0" * (-len(head) % 512))
|
||||
out.flush()
|
||||
size = written + len(head)
|
||||
if verify:
|
||||
progress("verify", 0, size)
|
||||
v = hashlib.sha256()
|
||||
with open(dev, "rb", buffering=0) as f:
|
||||
left = size
|
||||
while left > 0:
|
||||
n = min(CHUNK, left)
|
||||
block = f.read(n + (-n % 512))[:n]
|
||||
if not block:
|
||||
break
|
||||
v.update(block)
|
||||
left -= len(block)
|
||||
progress("verify", size - left, size)
|
||||
if v.digest() != h.digest():
|
||||
raise RuntimeError("Überprüfung fehlgeschlagen – die SD-Karte ist evtl. defekt oder gefälscht")
|
||||
|
||||
|
||||
def mount_boot_partition(number: int, timeout=40) -> Path:
|
||||
"""Make Windows pick up the new partition table and return the boot partition's drive root."""
|
||||
try:
|
||||
diskpart([f"select disk {int(number)}", "rescan"])
|
||||
except RuntimeError:
|
||||
pass
|
||||
deadline = time.time() + timeout
|
||||
assigned = False
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
letter = powershell(f"(Get-Partition -DiskNumber {int(number)} -PartitionNumber 1 "
|
||||
"-ErrorAction Stop).DriveLetter").strip()
|
||||
except RuntimeError:
|
||||
letter = ""
|
||||
if letter and letter != "\0":
|
||||
root = Path(f"{letter}:\\")
|
||||
if (root / "cmdline.txt").exists():
|
||||
return root
|
||||
elif not assigned and time.time() > deadline - timeout + 6:
|
||||
try:
|
||||
powershell(f"Add-PartitionAccessPath -DiskNumber {int(number)} -PartitionNumber 1 -AssignDriveLetter")
|
||||
assigned = True
|
||||
except RuntimeError:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise RuntimeError("Bootpartition wurde von Windows nicht eingebunden – Karte neu einstecken und erneut versuchen")
|
||||
|
||||
|
||||
def eject(root: Path):
|
||||
"""Ask Windows to safely remove the card (best effort)."""
|
||||
try:
|
||||
powershell(f"(New-Object -ComObject Shell.Application).Namespace(17).ParseName('{str(root)[:2]}')"
|
||||
".InvokeVerb('Eject')", timeout=20)
|
||||
except (RuntimeError, subprocess.TimeoutExpired):
|
||||
pass
|
||||
Reference in new issue
Block a user