Files
BetterDSPControl/server.py
T
GivouandClaude Opus 5.5 63b3c17fb7 DJ Brake: use the offset measured on a real DSP 204
Measured: limiter threshold minus output meter is about 26 dB when the limiter
starts (25.1 to 27.7, one DSP 204, one output, one piece of music), and the meter
is after the output gain. So the distance is right before the first hit.
The limiter flag also stayed on after raising a threshold, which would have
taught a false value: only limiters starting by themselves teach now.
The measuring tool no longer draws conclusions the data doesn't carry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 21:54:29 +01:00

1501 lines
74 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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 copy
import errno
import hashlib
import json
import logging
import math
import mimetypes
import re
import secrets
import shutil
import socket
import struct
import sys
import time
import uuid
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import parse_qs, urlsplit
from urllib.request import Request, urlopen
import sim
from dsp import preset, usbhid
from dsp import protocol as P
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
TEST_LEVEL = -50.0 # dB all outputs start at when an audio test begins (noise generators are loud)
TEST_MAX = 0.0 # highest level the test fader can set
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}
LOGO_MAX = 300_000 # characters of the data URL (the app sends a 128×128 PNG)
def clean_logo(v) -> str:
"""Custom logo as a PNG data URL, "" = the built-in one."""
v = str(v or "")
return v if v.startswith("data:image/png;base64,") and len(v) <= LOGO_MAX and re.fullmatch(r"[\w+/=]*", v[22:]) else ""
SF_ROLES = ("main", "sub", "delay", "fill")
def clean_soundfield(data) -> dict:
"""SoundField room plan: room, stage, reference position and speakers (positions in metres)."""
data = data if isinstance(data, dict) else {}
room = data.get("room") if isinstance(data.get("room"), dict) else {}
w, d = _num(room.get("w"), 4, 200, 20), _num(room.get("d"), 4, 300, 30)
stage = data.get("stage") if isinstance(data.get("stage"), dict) else {}
ref = data.get("ref") if isinstance(data.get("ref"), dict) else {}
speakers = []
for s in (data.get("speakers") or [])[:48]:
if not isinstance(s, dict):
continue
sid = re.sub(r"[^\w-]", "", str(s.get("id") or ""))[:16] or uuid.uuid4().hex[:8]
speakers.append({
"id": sid, "name": str(s.get("name") or "Speaker")[:24],
"role": s.get("role") if s.get("role") in SF_ROLES else "main",
"type": re.sub(r"[^\w-]", "", str(s.get("type") or "custom"))[:16],
"x": _num(s.get("x"), 0, w, w / 2), "y": _num(s.get("y"), 0, d, 1), "h": _num(s.get("h"), 0, 30, 2),
"aim": _num(s.get("aim"), -180, 180, 0), "cov": _num(s.get("cov"), 20, 360, 90),
"spl": _num(s.get("spl"), 80, 160, 128),
"tx": _num(s.get("tx"), 0, w, w / 2), "ty": _num(s.get("ty"), 0, d, d / 2),
"outs": [o for o in (s.get("outs") or [])[:8] if re.fullmatch(r"[\w-]+:\d{1,2}", str(o))],
"mount": re.sub(r"[^\w-]", "", str(s.get("mount") or ""))[:16], # id of the sub this top stands on (pole)
})
ids = {s["id"]: s for s in speakers}
for s in speakers: # a mount must be an existing sub, and the top stands exactly on it
m = ids.get(s["mount"])
if not m or m["role"] != "sub" or s["role"] == "sub":
s["mount"] = ""
else:
s["x"], s["y"] = m["x"], m["y"]
return {
"room": {"w": w, "d": d},
"stage": {"w": _num(stage.get("w"), 0, w, min(8, w)), "d": _num(stage.get("d"), 0, d / 2, 4)},
"temp": _num(data.get("temp"), -10, 45, 20),
"precedence": _num(data.get("precedence"), 0, 30, 5),
"ear": _num(data.get("ear"), 0.5, 3, 1.7),
"ref": {"x": _num(ref.get("x"), 0, w, w / 2), "y": _num(ref.get("y"), 0, d, d * 0.6)},
"speakers": speakers,
}
REW_URL = "http://127.0.0.1:4735" # REW's API only answers on its own computer
def rew_call(method: str, path: str, body=None):
"""One request to REW's API."""
data = json.dumps(body).encode() if body is not None else None
req = Request(REW_URL + path, data=data, method=method, headers={"Content-Type": "application/json"})
try:
with urlopen(req, timeout=8) as r:
raw = r.read()
except HTTPError as e:
try:
msg = json.loads(e.read()).get("message", "")
except (ValueError, AttributeError):
msg = ""
raise RuntimeError(f"REW: {msg or e.code}") from None
except (URLError, OSError):
raise RuntimeError("REW can't be reached") from None
return json.loads(raw) if raw else {}
def rew_id(body: dict) -> str:
mid = str(body.get("id") or "")
if not re.fullmatch(r"[\w-]{1,64}", mid):
raise ValueError("No measurement chosen")
return mid
def rew_filters(mid: str) -> list:
res = rew_call("GET", f"/measurements/{mid}/filters")
return res.get("filters", []) if isinstance(res, dict) else res
def rew_measurements() -> list:
res = rew_call("GET", "/measurements")
items = res.values() if isinstance(res, dict) else res
return [{"id": m.get("uuid") or "", "title": m.get("title") or "?"} for m in items if isinstance(m, dict) and m.get("uuid")]
def rew_send_filters(mid: str, filters: list):
"""Put a channel's EQ on a measurement. The generic equaliser takes all filter types and enough filters."""
rew_call("POST", f"/measurements/{mid}/equaliser", {"manufacturer": "Generic", "model": "Generic"})
filters = [f for f in filters if isinstance(f, dict)][:9]
for i, f in enumerate(filters):
f["index"] = i + 1
rest = [{"index": f.get("index"), "type": "None", "enabled": True, "isAuto": False}
for f in rew_filters(mid) if isinstance(f, dict) and f.get("index", 0) > len(filters) and f.get("type") not in (None, "None")]
rew_call("POST", f"/measurements/{mid}/filters", {"filters": filters + rest})
def rew_floats(values) -> str:
"""REW's data format: base64 of 32-bit floats, most significant byte first."""
return base64.b64encode(struct.pack(f">{len(values)}f", *[float(v) for v in values])).decode()
def rew_send_curve(body: dict):
mag, phase = body.get("magnitude"), body.get("phase")
if not isinstance(mag, list) or not isinstance(phase, list) or not 2 <= len(mag) <= 4000 or len(mag) != len(phase):
raise ValueError("No curve to send")
rew_call("POST", "/import/frequency-response-data", {
"identifier": str(body.get("identifier") or "DSP Control")[:60], "isImpedance": False,
"startFreq": _num(body.get("startFreq"), 1, 20000, 20), "ppo": int(_num(body.get("ppo"), 1, 192, 96)),
"magnitude": rew_floats(mag), "phase": rew_floats(phase)})
DJ_HOLD = 1.5 # s the light of /djbrake stays on after a limiter acted, so it doesn't flicker with the music
DJ_PEAK_HOLD = 1.5 # s the peak marker stays, then it falls ...
DJ_PEAK_FALL = 3.0 # ... this many dB/s: the display follows the music, not every single beat
DJ_AVG_TAU = 3.0 # s time constant of the average level
# dB between the limiter threshold and the output meter when a limiter starts, until real hits say otherwise. Measured with
# tools/dsp_measure.py: one DSP 204 (V0104P), one output, one piece of music: 25.1 to 27.7 in five rounds, with and without
# -6 dB gain. It holds a share of the music's peaks the meter doesn't catch, so other music can differ by a few dB.
DJ_METER_OFFSET = {"204": 26.0}
DJ_LEARN_QUIET = 6.0 # s after a jump of a threshold the limiter flag teaches nothing: it was seen on for 4 s at +20 dB
def clean_dj_margin(value) -> int:
"""dB the page puts its limit below the real one, 0-12."""
return int(max(0, min(12, value))) if type(value) in (int, float) else 0
def clean_dj_ignore(data) -> dict:
"""Outputs the DJ Brake does not watch, per device id. Everything else is watched, so new DSPs count by default."""
if not isinstance(data, dict):
return {}
out = {str(k)[:64]: sorted({i for i in v if type(i) is int and 0 <= i < 16})
for k, v in list(data.items())[:64] if isinstance(v, list)}
return {k: v for k, v in out.items() if v}
DASH_TYPES = ("status", "meters", "mixer", "curve", "channel", "limiter", "routing", "delays", "fir", "notes")
def clean_dashboard(data) -> dict | None:
"""Modules of the dashboard page; None = never edited (the app shows a default page)."""
if not isinstance(data, dict) or not isinstance(data.get("modules"), list):
return None
modules = []
for m in data["modules"][:40]:
if not isinstance(m, dict) or m.get("type") not in DASH_TYPES:
continue
src = m.get("cfg") if isinstance(m.get("cfg"), dict) else {}
cfg = {"device": str(src.get("device") or "")[:64], "title": str(src.get("title") or "")[:40],
"kind": "out" if src.get("kind") == "out" else "in", "idx": int(_num(src.get("idx"), 0, 15, 0)),
"text": str(src.get("text") or "")[:2000],
"overlays": [str(o) for o in src.get("overlays") or [] if re.fullmatch(r"(in|out)\d{1,2}", str(o))][:16]}
modules.append({"id": re.sub(r"[^\w-]", "", str(m.get("id") or ""))[:32] or uuid.uuid4().hex[:8], "type": m["type"],
"w": int(_num(m.get("w"), 2, 12, 4)), "h": int(_num(m.get("h"), 0, 20, 0)), "cfg": cfg})
return {"modules": modules}
def clean_colors(v) -> dict:
"""Channel colours: {"in0": "#rrggbb", "out3": ...}. Linked channels carry their group's colour; that a colour
belongs to one channel/group only is ensured by the colour picker (it knows the link groups)."""
out = {}
for k, c in (v.items() if isinstance(v, dict) else []):
c = str(c).lower()
if re.fullmatch(r"(in|out)\d{1,2}", str(k)) and re.fullmatch(r"#[0-9a-f]{6}", c):
out[str(k)] = c
return out
def clean_linknames(v) -> dict:
"""Names of link groups, keyed by kind and members: {"out:0,1": "Tops"}. A changed group loses its name."""
out = {}
for k, n in (v.items() if isinstance(v, dict) else []):
n = "".join(c for c in str(n) if c.isprintable()).strip()[:16]
if n and re.fullmatch(r"(in|out):\d{1,2}(,\d{1,2})+", str(k)):
out[str(k)] = n
return out
def clean_looks(v) -> dict:
"""Colours and group names per preset name: {"Party": {"colors": {...}, "linknames": {...}}}."""
out = {}
for k, look in list(v.items() if isinstance(v, dict) else [])[:64]:
if isinstance(look, dict):
out[str(k)[:14]] = {"colors": clean_colors(look.get("colors")), "linknames": clean_linknames(look.get("linknames"))}
return out
def clean_maxgain(v) -> dict:
"""Software gain limits per channel: {"in0": raw 0..399} (400 = +12 dB would be no limit)."""
out = {}
for k, g in (v.items() if isinstance(v, dict) else []):
if re.fullmatch(r"(in|out)\d{1,2}", str(k)):
g = int(_num(g, 0, 400, 400))
if g < 400:
out[str(k)] = g
return out
def clean_gains(v) -> list[int] | None:
"""Saved output gains of an interrupted audio test (from config.json)."""
if not isinstance(v, list) or not v or len(v) > 8:
return None
return [int(_num(g, 0, 400, 280)) for g in v]
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({})
self.soundfield: dict = clean_soundfield({})
self.dashboard: dict | None = None
self.djbrake = False # page /djbrake for the DJ: without PIN, shows only whether a limiter acts
self.dj_ignore: dict = {} # device id -> outputs not watched
self.dj_margin = 0 # the page warns this many dB before the real limiter, and never says so
self.dj_hint = True # short text on the page: the limiter is not the goal
self.dj_hint_en = True # that text always in English, else in the language of the browser
self.dj_hit = 0.0 # when a limiter was last seen acting
self.dj_rooms: dict = {} # device id -> dB left to the nearest watched limiter, False = nothing watched
self.dj_avgs: dict = {} # the same for the average level
self.dj_env: dict = {} # "device:output" -> peak and average of the level
self.dj_cal: dict = {} # device id -> dB the limiters sit below their threshold on the meter, learned from hits
self.dj_cal_saved = 0.0
self.dj_streams = 0
self.logo = ""
# 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.lock_dash = False # while locked the app window shows nothing but the dashboard
self.lang = "" # UI language chosen in the desktop app ("" = not chosen yet, English)
# demo mode: the real DSPs are disconnected and a simulated one runs inside the server
self.demo = {"enabled": False, "model": "408"}
self.demo_server: asyncio.Server | None = None
self.demo_resume: set[str] = set() # real devices to reconnect when the demo ends
# global mute: per device the channels that were open before, unmuted again on release
self.mute_all = {"active": False, "restore": {}}
# ------------------------------------------------------------ config
def load(self):
if self.config_path.exists():
cfg = json.loads(self.config_path.read_text(encoding="utf-8"))
else:
cfg = {"devices": []}
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.lock_dash = bool(cfg.get("lock_dash"))
self.lang = cfg.get("lang") if cfg.get("lang") in ("en", "de") else ""
m = cfg.get("mute_all") or {}
self.mute_all = {"active": bool(m.get("active")), "restore": {
str(k): [[c[0], int(c[1])] for c in v if isinstance(c, list) and len(c) == 2 and c[0] in ("in", "out")]
for k, v in (m.get("restore") or {}).items() if isinstance(v, list)}}
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 {})
if "soundfield" in cfg:
self.soundfield = clean_soundfield(cfg.get("soundfield"))
if "dashboard" in cfg:
self.dashboard = clean_dashboard(cfg.get("dashboard"))
self.djbrake = bool(cfg.get("djbrake"))
self.dj_ignore = clean_dj_ignore(cfg.get("dj_ignore"))
self.dj_margin = clean_dj_margin(cfg.get("dj_margin"))
self.dj_cal = {str(k)[:64]: float(v) for k, v in (cfg.get("dj_cal") if isinstance(cfg.get("dj_cal"), dict) else {}).items()
if type(v) in (int, float) and ":" not in str(k)}
self.dj_hint = bool(cfg.get("dj_hint", True))
self.dj_hint_en = bool(cfg.get("dj_hint_en", True))
if "logo" in cfg:
self.logo = clean_logo(cfg.get("logo"))
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.real_devices()], "auth": self.auth,
"limiter": self.limiter, "remote": self.remote, "soundfield": self.soundfield, "logo": self.logo,
"dashboard": self.dashboard, "djbrake": self.djbrake, "dj_ignore": self.dj_ignore, "dj_hint": self.dj_hint, "dj_hint_en": self.dj_hint_en, "dj_margin": self.dj_margin, "dj_cal": self.dj_cal}
async def reset_config(self):
"""Back to a fresh app. Only the app: the DSPs get disconnected first and receive nothing."""
if any(d.test_active for d in self.real_devices()):
raise ValueError("End the audio test first: the DSP would stay at the lowered level")
if self.mute_all["active"]:
raise ValueError("Release mute all first: the DSPs would stay muted")
self.demo_resume = set()
if self.demo["enabled"]:
await self.stop_demo()
for dev in self.real_devices():
await dev.stop()
del self.devices[dev.id]
self.broadcast({"type": "removed", "device": dev.id})
if self.config_path.exists(): # one way back, in case this was a mistake
shutil.copyfile(self.config_path, self.config_path.with_name("config.before-reset.json"))
sessions = {k: v for k, v in self.sessions.items() if k in self.app_sessions}
keep = {"config_path", "clients", "app_token", "app_sessions", "remote_server", "remote_writers", "failures", "dj_streams"}
for name, value in vars(App(self.config_path)).items():
if name not in keep:
setattr(self, name, value)
self.sessions = sessions
self.apply_config({})
self.save()
self.broadcast({"type": "reset"})
await asyncio.sleep(0.2) # let the phones hear it before their connection goes
if self.app_token:
await self.start_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 self.real_devices():
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})
self.broadcast({"type": "soundfield", "data": self.soundfield})
self.broadcast({"type": "logo", "data": self.logo})
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)
self.take_look(dev, body.get("doc"))
return {"ok": not diffs, "differences": diffs[:20], "name": state.get("preset_name", "")}
def take_look(self, dev: Device, doc):
"""Colours and group names that came with a preset file (older files have none)."""
look = doc.get("look") if isinstance(doc, dict) else None
if isinstance(look, dict):
dev.colors, dev.linknames = clean_colors(look.get("colors")), clean_linknames(look.get("linknames"))
dev.remember_look()
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
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)
self.take_look(dev, doc)
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.real_devices()], "auth": self.auth,
"sessions": sessions, "limiter": self.limiter, "remote": self.remote, "locked": self.locked, "lock_dash": self.lock_dash,
"soundfield": self.soundfield, "logo": self.logo, "dashboard": self.dashboard, "djbrake": self.djbrake, "dj_ignore": self.dj_ignore, "dj_hint": self.dj_hint, "dj_hint_en": self.dj_hint_en, "dj_margin": self.dj_margin, "dj_cal": self.dj_cal,
"mute_all": {"active": self.mute_all["active"],
"restore": {k: v for k, v in self.mute_all["restore"].items() if k != "demo"}}}
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 ""),
lock_code=str(d.get("lock_code") or ""), auto_unlock=bool(d.get("auto_unlock")),
test_saved=clean_gains(d.get("test_saved")), colors=clean_colors(d.get("colors")),
maxgain=clean_maxgain(d.get("maxgain")), linknames=clean_linknames(d.get("linknames")),
looks=clean_looks(d.get("looks")), look_name=str(d.get("look_name") or "")[:14])
dev.on_online = self.device_online
self.devices[dev_id] = dev
if dev.autoconnect:
if self.demo["enabled"]:
self.demo_resume.add(dev_id)
else:
dev.start()
if save:
self.save()
return dev
# ------------------------------------------------------------ audio test
def set_test_level(self, dev: Device, db: float):
"""Every output to the same level (the test fader)."""
dev.test_level = _num(db, -60, TEST_MAX, TEST_LEVEL)
raw = P.db_to_gain(dev.test_level)
for i in range(len(dev.state["outputs"])):
dev.set_param("out", i, "gain", dev.gain_cap("out", i, raw))
def restore_gains(self, dev: Device):
for i, g in enumerate((dev.test_saved or [])[: len(dev.state["outputs"])]):
dev.set_param("out", i, "gain", g)
dev.test_saved = None
async def audio_test(self, dev: Device, body: dict) -> dict:
source = int(_num(body.get("source"), 0, len(P.TEST_SOURCES) - 1, 0))
freq = int(_num(body.get("freq"), 0, 30, dev.state["test"]["freq"] if dev.state else 17))
if not dev.state or dev.status != "online":
raise RuntimeError("DSP is not connected")
if source:
if not dev.test_active: # entering: lower every output before the generator starts
if dev.test_saved is None:
dev.test_saved = [ch["gain"] for ch in dev.state["outputs"]]
self.save()
self.set_test_level(dev, TEST_LEVEL)
await dev.set_test_signal(source, freq)
else: # leaving: generator off first, then the faders go back
await dev.set_test_signal(0, freq)
if dev.test_saved is not None:
self.restore_gains(dev)
await dev.flush()
self.save()
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
return {"ok": True}
async def device_online(self, dev: Device):
if dev.model.fir and dev.test_saved is not None: # its test signal can't be read back: make sure it is off
await dev.set_test_signal(0, 0)
await self.check_audio_test(dev)
if not self.mute_all["active"] and self.mute_all["restore"].get(dev.id):
self.unmute_device(dev) # released while this DSP was offline
self.save()
# ------------------------------------------------------------ global mute
def mute_all_info(self) -> dict:
return {"active": self.mute_all["active"]}
def unmute_device(self, dev: Device):
for kind, i in self.mute_all["restore"].pop(dev.id, []):
chans = dev.state["inputs" if kind == "in" else "outputs"]
if i < len(chans) and chans[i]["mute"]:
dev.set_param(kind, i, "mute", False)
def set_mute_all(self, mute: bool) -> dict:
"""Mute every channel of every connected DSP; releasing unmutes only what was open before."""
online = [d for d in self.devices.values() if d.status == "online" and d.state]
if mute and not self.mute_all["active"]:
self.mute_all["restore"] = {}
for dev in online:
opened = [[kind, i] for kind, key in (("in", "inputs"), ("out", "outputs"))
for i, ch in enumerate(dev.state[key]) if not ch["mute"]]
for kind, i in opened:
dev.set_param(kind, i, "mute", True)
self.mute_all["restore"][dev.id] = opened
self.mute_all["active"] = True
elif not mute and self.mute_all["active"]:
self.mute_all["active"] = False
for dev in online:
self.unmute_device(dev) # offline ones follow when they connect again
self.save()
self.broadcast({"type": "muteall", "data": self.mute_all_info()})
return self.mute_all_info()
# ------------------------------------------------------------ FIR filters (FIR DSP 408)
@staticmethod
def check_fir_param(dev: Device, idx: int, value) -> dict:
value = P.clean_fir(value, dev.state["outputs"][idx]["fir"])
if value["type"] and dev.fir_taps_used(skip=("out", idx)) + 256 + 32 * value["taps"] > P.FIR_MAX_TOTAL:
raise RuntimeError("Out of FIR taps: all channels together have 4096")
return value
async def upload_fir(self, dev: Device, body: dict) -> dict:
kind = "in" if body.get("kind") == "in" else "out"
idx = int(body.get("idx", 0))
if not dev.state or not dev.model.fir or not 0 <= idx < len(dev.state["inputs" if kind == "in" else "outputs"]):
raise RuntimeError("DSP is not connected")
raw = body.get("coeffs")
limit = P.FIR_MAX_IN if kind == "in" else P.FIR_MAX_OUT
if not isinstance(raw, list) or not 1 <= len(raw) <= limit:
raise RuntimeError(f"Too many FIR coefficients: at most {limit} here")
try:
coeffs = [float(c) for c in raw]
except (TypeError, ValueError):
raise RuntimeError("Not valid FIR coefficients") from None
if not all(math.isfinite(c) for c in coeffs):
raise RuntimeError("Not valid FIR coefficients")
name = str(body.get("name") or "")
if kind == "out":
taps = max(0, -((256 - len(coeffs)) // 32)) # taps index that holds them
cur = dev.state["outputs"][idx]["fir"]
dev.set_param("out", idx, "fir", self.check_fir_param(dev, idx, {**cur, "type": 4, "taps": taps}))
elif dev.fir_taps_used(skip=("in", idx)) + len(coeffs) > P.FIR_MAX_TOTAL:
raise RuntimeError("Out of FIR taps: all channels together have 4096")
failed = await dev.upload_fir(kind, idx, coeffs, name)
if kind == "in" and dev.state["inputs"][idx]["fir"]["bypass"]:
dev.set_param("in", idx, "fir.bypass", False)
if failed:
raise RuntimeError(f"The DSP did not answer {failed} frames")
return {"ok": True, "count": len(coeffs)}
# ------------------------------------------------------------ copy channel settings
def copy_settings(self, body: dict) -> dict:
"""Copy groups of settings from one channel to channels of the same kind (any connected DSP)."""
src = self.devices.get(str(body.get("device")))
kind = "in" if body.get("kind") == "in" else "out"
key = "inputs" if kind == "in" else "outputs"
if not src or not src.state:
raise RuntimeError("DSP is not connected")
sch = src.state[key][int(body.get("idx", 0))]
groups = set(body.get("groups") or [])
changed = 0
for t in body.get("targets") or []:
dev = self.devices.get(str(t.get("device")))
if not dev or dev.status != "online" or not dev.state:
continue
if dev.test_active:
raise RuntimeError("Audio test is on – switch it off first")
idx = int(t.get("idx", -1))
if not 0 <= idx < len(dev.state[key]) or (dev is src and idx == int(body.get("idx", 0))):
continue
tch = dev.state[key][idx]
params = []
if "level" in groups:
params += ["gain", "delay", "polarity"]
if "filters" in groups:
params += ["hp", "lp"]
if "eq" in groups:
params += ["peq_bypass"] + [f"peq.{b}" for b in range(min(len(sch["peq"]), len(tch["peq"])))]
if kind == "in":
params += ["geq_bypass"] + [f"geq.{b}" for b in range(31)]
if "dynamics" in groups:
params += ["gate", "comp"] if kind == "in" else ["comp", "limit"]
if "routing" in groups and kind == "out":
params += [f"mix.{k}" for k in range(min(len(sch["mix"]), len(tch["mix"])))]
for p in params:
top = p.split(".")[0]
if top not in sch or top not in tch or (isinstance(sch[top], dict) and sch[top].keys() != tch[top].keys()):
continue # a setting only one of the two models has
v = copy.deepcopy(self._get(sch, p))
if p == "gain":
v = dev.gain_cap(kind, idx, v)
if self._get(tch, p) != v:
dev.set_param(kind, idx, p, v)
changed += 1
if "routing" in groups and kind == "out":
m = sch["matrix"] & ((1 << len(tch["mix"])) - 1)
if tch["matrix"] != m:
dev.set_param(kind, idx, "matrix", m)
changed += 1
return {"ok": True, "changed": changed}
@staticmethod
def _get(ch: dict, path: str):
node = ch
for k in path.split("."):
node = node[int(k)] if isinstance(node, list) else node[k]
return node
async def check_audio_test(self, dev: Device):
"""On connect: a DSP still playing a test signal goes straight into the audio test (outputs lowered);
one back on its analog inputs gets the faders saved by an interrupted test back."""
try:
if dev.test_active:
if dev.test_saved is None:
dev.test_saved = [ch["gain"] for ch in dev.state["outputs"]]
self.set_test_level(dev, TEST_LEVEL)
elif dev.test_saved is not None:
self.restore_gains(dev)
else:
return
await dev.flush()
if not dev.demo:
self.save()
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
except Exception as e: # noqa: BLE001 - connection lost meanwhile: checked again on the next connect
log.warning("%s: audio test check failed: %s", dev.name, e)
# ------------------------------------------------------------ network search
async def scan_network(self) -> list[dict]:
"""Look for DSPs (TCP 9761) in the local /24 networks and ask them who they are.
DSPs this app is connected to are skipped: a DSP takes only one connection."""
busy = {d.host for d in self.real_devices() if d.transport == "tcp" and d.status in ("connecting", "loading", "locked", "online")}
known = {d.host: d for d in self.real_devices() if d.transport == "tcp"}
nets = []
for ip in local_ips():
net = ip.rsplit(".", 1)[0]
if not ip.startswith("127.") and net not in nets:
nets.append(net)
sem = asyncio.Semaphore(96)
async def probe(ip: str):
if ip in busy:
d = known[ip]
return {"host": ip, "port": P.PORT, "info": d.info, "model": d.model_name or None, "known": d.name, "busy": True}
async with sem:
try:
r, w = await asyncio.wait_for(asyncio.open_connection(ip, P.PORT), 0.7)
except (OSError, asyncio.TimeoutError):
return None
info = ""
try:
w.write(P.build_frame(P.CMD_HANDSHAKE) + P.build_frame(P.CMD_DEVICE_INFO))
await w.drain()
parser, end = P.FrameParser(), time.monotonic() + 1.2
while not info and time.monotonic() < end:
data = await asyncio.wait_for(r.read(512), max(0.05, end - time.monotonic()))
if not data:
break
for f in parser.feed(data):
if f.cmd == P.CMD_DEVICE_INFO:
info = f.payload.split(b"\x00")[0].decode("latin1", "replace").strip()
except (OSError, asyncio.TimeoutError):
pass
finally:
w.close()
d = known.get(ip)
return {"host": ip, "port": P.PORT, "info": info, "model": P.detect_model(info), "known": d.name if d else "", "busy": False}
hosts = [f"{net}.{i}" for net in nets[:2] for i in range(1, 255)]
found = [x for x in await asyncio.gather(*(probe(h) for h in hosts)) if x]
return sorted(found, key=lambda x: tuple(int(p) for p in x["host"].split(".")))
def real_devices(self) -> list[Device]:
return [d for d in self.devices.values() if not d.demo]
# ------------------------------------------------------------ demo mode
def demo_info(self) -> dict:
return {**self.demo, "error": ""}
async def set_demo(self, body: dict) -> dict:
enabled = bool(body.get("enabled", self.demo["enabled"]))
model = body.get("model") if body.get("model") in ("204", "408") else self.demo["model"]
if self.demo["enabled"] and (not enabled or model != self.demo["model"]):
await self.stop_demo()
self.demo["model"] = model
if enabled and not self.demo["enabled"]:
await self.start_demo()
self.broadcast({"type": "demo", "data": self.demo_info()})
return self.demo_info()
async def start_demo(self):
"""Disconnect the real DSPs and start a simulated one inside this server."""
self.demo_resume = {d.id for d in self.real_devices() if d._want_connected}
for d in self.real_devices():
await d.stop()
model = self.demo["model"]
logging.getLogger("sim").setLevel(logging.WARNING)
dsp = sim.SimDSP(model)
dsp.presets[1] = {**dsp.presets[0], "preset_name": "Demo"}
self.demo_server = await asyncio.start_server(dsp.serve, "127.0.0.1", 0)
port = self.demo_server.sockets[0].getsockname()[1]
dev = Device("demo", f"Demo DSP {model}", "127.0.0.1", port, model, autoconnect=False, on_event=self.broadcast)
dev.demo = True
dev.on_online = self.device_online
self.devices[dev.id] = dev
self.demo["enabled"] = True
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
dev.start()
async def stop_demo(self):
dev = self.devices.pop("demo", None)
if dev:
await dev.stop()
self.broadcast({"type": "removed", "device": dev.id})
if self.demo_server:
self.demo_server.close()
self.demo_server = None
self.demo["enabled"] = False
for dev_id in self.demo_resume:
if dev_id in self.devices:
self.devices[dev_id].start()
self.demo_resume = set()
# ------------------------------------------------------------ auth
def set_pin(self, pin: str, save=True):
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", "/api/muteall"):
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()
if self.demo["enabled"]:
self.demo_resume = set()
await self.stop_demo()
for d in self.devices.values():
await d.stop()
# ------------------------------------------------------------ events
def dj_offset(self, dev) -> float:
"""Learned from this DSP's hits, else what was measured on this model. The simulator has no such offset."""
if dev.id in self.dj_cal:
return self.dj_cal[dev.id]
real = "SIM" not in getattr(dev, "info", "") and not getattr(dev, "demo", False)
return DJ_METER_OFFSET.get(getattr(dev, "model_name", ""), 0.0) if real else 0.0
def dj_track(self, dev, key: str, level: float, limit: bool, threshold: int, now: float) -> tuple:
"""One meter reading of a watched output: (dB left by the peak, dB left by the average, warn now)."""
e = self.dj_env.setdefault(key, {"peak": -120.0, "until": 0.0, "pow": 0.0, "t": now})
dt = min(now - e["t"], 1.0)
e["t"] = now
db = 20 * math.log10(level) if level > 0 else -120.0
if db >= e["peak"]:
e["peak"], e["until"] = db, now + DJ_PEAK_HOLD
elif now > e["until"]:
e["peak"] = max(db, e["peak"] - DJ_PEAK_FALL * dt)
e["pow"] += (level * level - e["pow"]) * (1 - math.exp(-dt / DJ_AVG_TAU))
thr = P.threshold_to_db(threshold)
# the moment a limiter starts is where it really sits on the meter. Later the level is what the limiter
# left of it. One DSP has one meter, so this counts for all its outputs
# only a limiter that starts by itself counts: not after a threshold jumped, up or down, and not
# while it flickers on and off in the middle of limiting
if thr > e.get("thr", thr) or thr < e.get("thr", thr) - 2:
e["jumped"] = now
e["thr"] = thr
if limit and now - e.get("last_on", -1e9) > 3 and now - e.get("jumped", -1e9) > DJ_LEARN_QUIET and e["peak"] > -70:
seen = max(-6.0, min(40.0, thr - e["peak"]))
known = self.dj_offset(dev)
self.dj_cal[dev.id] = (known * 3 + seen) / 4 if known or dev.id in self.dj_cal else seen
if limit:
e["last_on"] = now
top = thr - self.dj_offset(dev) - self.dj_margin
left = 0.0 if limit else max(0.0, top - e["peak"]) if e["peak"] > -70 else None
mean = max(0.0, top - 10 * math.log10(e["pow"])) if e["pow"] > 1e-7 else None
return left, mean, limit or bool(self.dj_margin and db >= top)
def dj_note(self, ev: dict, now: float | None = None):
"""Keeps the state of the /djbrake page. A muted output is not watched: nobody hears it."""
dev = self.devices.get(ev["device"])
if not dev or not dev.state:
return
now = time.monotonic() if now is None else now
room, avg, ignore = False, None, self.dj_ignore.get(dev.id, ())
for i, (level, limit) in enumerate(zip(ev["out"], ev["limit"])):
ch, key = dev.state["outputs"][i], f"{dev.id}:{i}"
if i in ignore or ch["mute"]:
self.dj_env.pop(key, None)
continue
left, mean, warn = self.dj_track(dev, key, level, limit, ch["limit"]["threshold"], now)
if warn:
self.dj_hit = now
room = left if room is False or room is None else room if left is None else min(room, left)
avg = mean if avg is None else avg if mean is None else min(avg, mean)
self.dj_rooms[dev.id], self.dj_avgs[dev.id] = room, avg
if self.dj_cal and now - self.dj_cal_saved > 60: # an SD card is not for writing with every beat
self.dj_cal_saved = now
self.save()
def broadcast(self, ev: dict):
if ev["type"] == "meters":
self.dj_note(ev)
elif ev["type"] == "device":
dev = self.devices.get(ev["device"])
if dev and dev.look_dirty:
dev.look_dirty = False
self.save()
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/logo" and method == "PUT":
self.logo = clean_logo(body.get("logo"))
if body.get("logo") and not self.logo:
raise ValueError("The logo could not be read")
self.save()
self.broadcast({"type": "logo", "data": self.logo})
return {"logo": self.logo}
if path == "/api/logo":
return {"logo": self.logo}
if path == "/api/djbrake" and method == "PUT":
if "enabled" in body:
self.djbrake = bool(body["enabled"])
if "ignore" in body:
self.dj_ignore = clean_dj_ignore(body["ignore"])
if body.get("relearn"):
self.dj_cal = {}
if "margin" in body:
self.dj_margin = clean_dj_margin(body["margin"])
if "hint" in body:
self.dj_hint = bool(body["hint"])
if "hint_en" in body:
self.dj_hint_en = bool(body["hint_en"])
self.save()
ans = {"enabled": self.djbrake, "ignore": self.dj_ignore, "hint": self.dj_hint, "hint_en": self.dj_hint_en,
"margin": self.dj_margin}
self.broadcast({"type": "djbrake", **ans})
return ans
if path == "/api/dashboard" and method == "PUT":
self.dashboard = clean_dashboard(body)
self.save()
self.broadcast({"type": "dashboard", "data": self.dashboard})
return self.dashboard
if path == "/api/dashboard":
return self.dashboard
if path == "/api/soundfield" and method == "PUT":
self.soundfield = clean_soundfield(body)
self.save()
self.broadcast({"type": "soundfield", "data": self.soundfield})
return self.soundfield
if path == "/api/soundfield":
return self.soundfield
if path == "/api/muteall" and method == "POST":
return self.set_mute_all(bool(body.get("mute")))
if path == "/api/muteall":
return self.mute_all_info()
if path == "/api/copy" and method == "POST":
return self.copy_settings(body)
if path == "/api/demo":
return await self.set_demo(body) if method == "PUT" else self.demo_info()
if path == "/api/scan" and method == "POST":
return await self.scan_network()
if path == "/api/rew/status" and method == "GET":
res = await asyncio.to_thread(rew_call, "GET", "/version")
return {"version": res.get("message", "") if isinstance(res, dict) else str(res)}
if path == "/api/rew/measurements" and method == "GET":
return await asyncio.to_thread(rew_measurements)
if path == "/api/rew/filters" and method == "POST":
return await asyncio.to_thread(rew_filters, rew_id(body))
if path == "/api/rew/send-filters" and method == "POST":
await asyncio.to_thread(rew_send_filters, rew_id(body), body.get("filters") or [])
return {"ok": True}
if path == "/api/rew/send-curve" and method == "POST":
await asyncio.to_thread(rew_send_curve, body)
return {"ok": True}
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 dev.demo and (method in ("DELETE", "PUT") or action in ("unlock", "lockcode")):
raise RuntimeError("Not available for the demo device")
# during the audio test only the test controls work: generator, test fader, output mutes
if dev.test_active and (action in ("preset/recall", "preset/store", "export", "import", "undo", "link", "fir")
or action == "set" and body.get("param") != "mute"):
raise RuntimeError("Audio test is on – switch it off first")
if self.demo["enabled"] and not dev.demo and action == "connect":
raise RuntimeError("Demo mode is on – switch it off to connect the real DSPs")
if method == "DELETE" and not action:
await dev.stop()
del self.devices[dev.id]
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"
if "port" in body:
dev.port = int(_num(body["port"], 1, 65535, P.PORT))
if "addr" in body: # device ID of the DSP (address byte of every frame)
dev.addr = int(_num(body["addr"], 1, 250, 1))
if "autoconnect" in body:
dev.autoconnect = bool(body["autoconnect"])
if "auto_unlock" in body:
dev.auto_unlock = bool(body["auto_unlock"])
if body.get("lock_code") == "":
dev.lock_code, dev.auto_unlock = "", False # forget the remembered code
self.save()
if was_running:
dev.start()
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":
kind, idx, value = body["kind"], int(body["idx"]), body["value"]
if body["param"] == "gain" and not body.get("force"): # force: confirmed twice in the app
value = dev.gain_cap(kind, idx, int(value)) # software max level
if body["param"] == "fir" and dev.state:
value = self.check_fir_param(dev, int(body["idx"]), value)
dev.set_param(kind, idx, body["param"], value)
return {"ok": True, "value": value}
if action == "fir":
return await self.upload_fir(dev, body)
if action == "maxgain": # app-side setting, the DSP doesn't know it
dev.maxgain = clean_maxgain(body.get("maxgain"))
self.save()
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
return {"ok": True, "maxgain": dev.maxgain}
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.flush() # e.g. settings copied to a new first channel of a group must arrive before the link
await dev.set_links(kind, groups)
return {"ok": True}
if action == "refresh":
await dev.refresh()
return {"ok": True}
if action == "colors": # display only, stays in the app (the DSP doesn't know colours)
dev.colors = clean_colors(body.get("colors"))
dev.remember_look()
self.save()
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
return {"ok": True, "colors": dev.colors}
if action == "linknames": # display only, like the colours
dev.linknames = clean_linknames(body.get("linknames"))
dev.remember_look()
self.save()
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
return {"ok": True, "linknames": dev.linknames}
if action == "test":
return await self.audio_test(dev, body)
if action == "testlevel":
if not dev.test_active:
raise RuntimeError("Audio test is off")
self.set_test_level(dev, body.get("db"))
return {"ok": True, "db": dev.test_level}
if action == "unlock": # hardware lock of the DSP, independent of the app lock
code = str(body.get("code") or "").strip().upper()
ok = await dev.unlock(code)
if ok and body.get("remember"):
dev.lock_code, dev.auto_unlock = code, True
self.save()
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
return {"ok": ok}
if action == "lockcode":
await dev.set_lock_code(body.get("code"))
self.save()
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
return {"ok": True}
raise KeyError(path)
# ------------------------------------------------------------ HTTP
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",
f"Location: /?start=app&lang={self.lang or 'en'}\r\n" + self.cookie(cookie, SESSION_TTL))
else:
await self.respond(writer, 401, b"invalid app token", "text/plain")
return
if path == "/djbrake/state":
await self.dj_stream(writer)
return
if path in ("/djbrake", "/djbrake/"):
path = "/djbrake.html"
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, "lock_dash": is_app and self.lock_dash,
"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.startswith("/api/rew/") and not is_app: # REW runs next to the desktop app
await self.respond_json(writer, 403, {"error": "desktop app only"})
return
if path == "/api/lock-dash" and method == "POST":
if not is_app:
await self.respond_json(writer, 403, {"error": "desktop app only"})
else:
self.lock_dash = bool(data.get("enabled"))
self.save()
self.broadcast({"type": "lockdash", "enabled": self.lock_dash})
await self.respond_json(writer, 200, {"enabled": self.lock_dash})
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/reset" and method == "POST":
if not is_app:
await self.respond_json(writer, 403, {"error": "desktop app only"})
else:
try:
await self.reset_config()
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/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("/")
if rel == "djbrake.html" and not self.djbrake:
await self.respond(writer, 404, b"not found", "text/plain")
return
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 dj_stream(self, writer):
"""All /djbrake may know, without a login: is a limiter acting and how far away is it. Nothing else leaves here."""
if not self.djbrake or self.dj_streams >= 20:
await self.respond(writer, 404, b"not found", "text/plain")
return
self.dj_streams += 1
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")
last, idle = None, 0.0
try:
while self.djbrake:
now = time.monotonic()
online = [d.id for d in self.devices.values() if d.status == "online"]
rooms = [r for r in (self.dj_rooms.get(i, False) for i in online) if r is not False]
known = [r for r in rooms if r is not None]
avgs = [r for r in (self.dj_avgs.get(i) for i in online) if r is not None]
state = {"on": now - self.dj_hit < DJ_HOLD, "ready": bool(rooms),
"room": round(min(known) * 2) / 2 if known else None,
"avg": round(min(avgs)) if avgs else None,
"hint": ("en" if self.dj_hint_en else "auto") if self.dj_hint else None}
if state != last:
writer.write(f"data: {json.dumps(state)}\n\n".encode())
last, idle = state, 0.0
elif idle > 15:
writer.write(b": ping\n\n")
idle = 0.0
await writer.drain()
await asyncio.sleep(0.1)
idle += 0.1
finally:
self.dj_streams -= 1
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,
"demo": self.demo_info(), "muteall": self.mute_all_info(), "soundfield": self.soundfield, "logo": self.logo,
"dashboard": self.dashboard, "djbrake": self.djbrake, "dj_ignore": self.dj_ignore, "dj_hint": self.dj_hint, "dj_hint_en": self.dj_hint_en, "dj_margin": self.dj_margin}
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