- logo and DSP choice on the left, menu and buttons on the right - the menu becomes a sidebar when it no longer fits in the top bar (measured, so it works for every language and device name); phones keep the bottom bar with short labels - custom logo in the settings: any PNG/JPG/WebP/SVG is scaled to a 128x128 PNG, shown top left and as the browser icon, stored by the server and in the backup Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1012 lines
47 KiB
Python
1012 lines
47 KiB
Python
"""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 mimetypes
|
||
import re
|
||
import secrets
|
||
import socket
|
||
import sys
|
||
import time
|
||
import uuid
|
||
from pathlib import Path
|
||
from urllib.parse import parse_qs, urlsplit
|
||
|
||
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,
|
||
}
|
||
|
||
|
||
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_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.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.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": [
|
||
{"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 ""
|
||
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 "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}
|
||
|
||
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)
|
||
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.real_devices()], "auth": self.auth,
|
||
"sessions": sessions, "limiter": self.limiter, "remote": self.remote, "locked": self.locked,
|
||
"soundfield": self.soundfield, "logo": self.logo,
|
||
"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")))
|
||
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", 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):
|
||
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()
|
||
|
||
# ------------------------------------------------------------ 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"] 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:
|
||
v = copy.deepcopy(self._get(sch, p))
|
||
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)
|
||
|
||
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 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/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/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/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")
|
||
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"
|
||
for k in ("port", "addr"):
|
||
if k in body:
|
||
setattr(dev, k, int(body[k]))
|
||
if "autoconnect" in body:
|
||
dev.autoconnect = bool(body["autoconnect"])
|
||
if "auto_unlock" in body:
|
||
dev.auto_unlock = bool(body["auto_unlock"])
|
||
if body.get("lock_code") == "":
|
||
dev.lock_code, dev.auto_unlock = "", False # forget the remembered code
|
||
self.save()
|
||
if was_running:
|
||
dev.start()
|
||
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}
|
||
if action == "colors": # display only, stays in the app (the DSP doesn't know colours)
|
||
dev.colors = clean_colors(body.get("colors"))
|
||
self.save()
|
||
self.broadcast({"type": "device", "device": dev.id, "data": dev.snapshot()})
|
||
return {"ok": True, "colors": dev.colors}
|
||
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",
|
||
"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,
|
||
"demo": self.demo_info(), "muteall": self.mute_all_info(), "soundfield": self.soundfield, "logo": self.logo}
|
||
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
|