Add BetterDSPControl: web UI, desktop app and Pi writer for t.racks DSP 204/408
- Python stdlib server with SSE live updates, PIN login, remote access - Vanilla JS web UI (English/German): mixer, channel, routing, links, limiter calculator - Preset file export/import with undo, settings backup, lock for the desktop app - Network (TCP 9761) and USB HID transport (Windows, macOS, Linux) - Desktop app via pywebview, Raspberry Pi SD card writer, simulator and protocol tests - README with import guide for Claude Code, CLAUDE.md, protocol documentation Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ce02ae65a9
commit
fe13f261f7
31 files changed
+6445
No files matched your search
+365
@@ -0,0 +1,365 @@
|
||||
"""Async client for one t.racks DSP - over the network (TCP) or USB (HID)."""
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import logging
|
||||
import struct
|
||||
import time
|
||||
|
||||
from . import preset
|
||||
from . import protocol as P
|
||||
from . import usbhid
|
||||
|
||||
log = logging.getLogger("dsp")
|
||||
|
||||
RESPONSE_TIMEOUT = 0.6
|
||||
METER_INTERVAL = 0.15
|
||||
RECONNECT_DELAY = 5.0
|
||||
LINK_RESYNC_DELAY = 1.5 # re-read the config this long after the last change on a linked channel
|
||||
|
||||
|
||||
class Device:
|
||||
def __init__(self, dev_id: str, name: str, host: str, port: int = P.PORT, model: str = "auto",
|
||||
addr: int = 1, autoconnect: bool = True, on_event=None, transport: str = "tcp", usb: str = ""):
|
||||
self.id = dev_id
|
||||
self.name = name
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.model_key = model # "auto", "204" or "408"
|
||||
self.addr = addr
|
||||
self.autoconnect = autoconnect
|
||||
self.transport = "usb" if transport == "usb" else "tcp"
|
||||
self.usb = usb # HID device path, "" = first DSP found
|
||||
self.on_event = on_event or (lambda ev: None)
|
||||
|
||||
self.status = "disconnected" # disconnected | connecting | loading | online | error
|
||||
self.error = ""
|
||||
self.info = ""
|
||||
self.model: P.Model | None = P.MODELS.get(model)
|
||||
self.state: dict | None = None
|
||||
self.raw = b"" # memory image of the last config read
|
||||
self.presets: list[str] = []
|
||||
self.meters: list[float] = [0.0] * 12
|
||||
|
||||
self._reader = None
|
||||
self._writer = None
|
||||
self._parser = P.FrameParser()
|
||||
self._lock = asyncio.Lock()
|
||||
self._waiter: asyncio.Future | None = None
|
||||
self._pending: dict[tuple, tuple[int, bytes]] = {}
|
||||
self._pending_event = asyncio.Event()
|
||||
self._tasks: list[asyncio.Task] = []
|
||||
self._supervisor: asyncio.Task | None = None
|
||||
self._want_connected = False
|
||||
self._resync: asyncio.TimerHandle | None = None
|
||||
self._changes = 0 # bumped on every local change, so a resync never overwrites newer edits
|
||||
|
||||
# ------------------------------------------------------------ public API
|
||||
|
||||
def config(self) -> dict:
|
||||
return {"id": self.id, "name": self.name, "host": self.host, "port": self.port,
|
||||
"model": self.model_key, "addr": self.addr, "autoconnect": self.autoconnect,
|
||||
"transport": self.transport, "usb": self.usb}
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
return {**self.config(), "status": self.status, "error": self.error, "info": self.info,
|
||||
"detected_model": self.model_name or None,
|
||||
"n_in": self.model.n_in if self.model else 0,
|
||||
"n_out": self.model.n_out if self.model else 0,
|
||||
"presets": self.presets, "state": self.state}
|
||||
|
||||
def start(self):
|
||||
self._want_connected = True
|
||||
if not self._supervisor or self._supervisor.done():
|
||||
self._supervisor = asyncio.create_task(self._supervise())
|
||||
|
||||
async def stop(self):
|
||||
self._want_connected = False
|
||||
self._resync: asyncio.TimerHandle | None = None
|
||||
self._changes = 0 # bumped on every local change, so a resync never overwrites newer edits
|
||||
if self._supervisor:
|
||||
self._supervisor.cancel()
|
||||
try:
|
||||
await self._supervisor
|
||||
except (asyncio.CancelledError, Exception):
|
||||
pass
|
||||
self._supervisor = None
|
||||
await self._close()
|
||||
self._set_status("disconnected")
|
||||
|
||||
def set_param(self, kind: str, idx: int, param: str, value):
|
||||
"""Update local state and queue the command (coalesced per parameter)."""
|
||||
if not self.state or not self.model:
|
||||
raise RuntimeError("device not loaded")
|
||||
chans = self.state["inputs" if kind == "in" else "outputs"]
|
||||
ch = chans[idx]
|
||||
if param == "name":
|
||||
value = P.clean_name(value)
|
||||
P.apply_param(ch, param, value)
|
||||
cmd, payload = P.param_command(self.model, kind, idx, ch, param)
|
||||
key = (cmd, payload[0]) + ((payload[1],) if cmd in (P.CMD_PEQ, P.CMD_GEQ, P.CMD_MIX) else ())
|
||||
self._pending[key] = (cmd, payload)
|
||||
self._pending_event.set()
|
||||
self._changes += 1
|
||||
# the DSP applies the change to linked channels itself: show that right away
|
||||
group = [idx] if param.split(".")[0] in P.LINK_EXCLUDED else P.link_group(chans, idx)
|
||||
for i in group:
|
||||
if i != idx:
|
||||
P.apply_param(chans[i], param, copy.deepcopy(value))
|
||||
self.on_event({"type": "param", "device": self.id, "kind": kind, "idx": i,
|
||||
"param": param, "value": value})
|
||||
if len(group) > 1:
|
||||
self._schedule_resync()
|
||||
|
||||
async def set_links(self, kind: str, groups: list[list[int]]):
|
||||
"""Link channels of one kind. The DSP copies the first channel's settings to the others."""
|
||||
if not self.state or not self.model:
|
||||
raise RuntimeError("device not loaded")
|
||||
n = self.model.n_in if kind == "in" else self.model.n_out
|
||||
for i, mask in enumerate(P.link_masks(n, groups)):
|
||||
await self._request(P.CMD_LINK, bytes([self.model.channel(kind, i)]) + struct.pack("<H", mask))
|
||||
await asyncio.sleep(0.3)
|
||||
await self.refresh()
|
||||
|
||||
def _schedule_resync(self):
|
||||
"""Re-read the config shortly after edits on linked channels, so the app shows exactly
|
||||
what the DSP applied to the group (e.g. mute, which we don't mirror for certain)."""
|
||||
if self._resync:
|
||||
self._resync.cancel()
|
||||
self._resync = asyncio.get_running_loop().call_later(
|
||||
LINK_RESYNC_DELAY, lambda: asyncio.create_task(self._do_resync()))
|
||||
|
||||
async def _do_resync(self):
|
||||
if self.status != "online":
|
||||
return
|
||||
if self._pending:
|
||||
return self._schedule_resync()
|
||||
seq = self._changes
|
||||
try:
|
||||
state = await self._read_config()
|
||||
except Exception as e: # noqa: BLE001 - the next change schedules another try
|
||||
log.info("%s: resync failed: %s", self.name, e)
|
||||
return
|
||||
if seq != self._changes:
|
||||
return self._schedule_resync()
|
||||
if state != self.state:
|
||||
self.state = state
|
||||
self._emit_state()
|
||||
|
||||
async def recall_preset(self, index: int):
|
||||
await self._request(P.CMD_PRESET_RECALL, bytes([index + 1]), timeout=2.0)
|
||||
await asyncio.sleep(0.3)
|
||||
await self._load_config()
|
||||
self._emit_state()
|
||||
|
||||
async def store_preset(self, index: int, name: str):
|
||||
await self._request(P.CMD_PRESET_STORE_NAME, name.encode("latin1")[:14].ljust(14, b" "))
|
||||
await self._request(P.CMD_PRESET_STORE, bytes([index + 1]), timeout=2.0)
|
||||
await self._request(P.CMD_STATUS)
|
||||
if index < len(self.presets):
|
||||
self.presets[index] = name
|
||||
if self.state:
|
||||
self.state["preset_name"] = name
|
||||
self._emit_state()
|
||||
|
||||
@property
|
||||
def model_name(self) -> str:
|
||||
return next((k for k, m in P.MODELS.items() if m is self.model), "")
|
||||
|
||||
async def export_preset(self) -> dict:
|
||||
"""The DSP's current state, read fresh from the device."""
|
||||
await self.refresh()
|
||||
return preset.export_doc(self.model_name, self.info, self.state, self.raw)
|
||||
|
||||
async def import_preset(self, state: dict) -> list[str]:
|
||||
"""Put the DSP into `state` (working state only). Returns the paths that did not take."""
|
||||
if self.status != "online":
|
||||
raise RuntimeError("DSP is not connected")
|
||||
if self._resync:
|
||||
self._resync.cancel()
|
||||
failed = 0
|
||||
for cmd, payload in preset.import_commands(self.model, state, self.state):
|
||||
if await self._request(cmd, payload) is None:
|
||||
failed += 1
|
||||
await asyncio.sleep(0.3)
|
||||
await self.refresh()
|
||||
diffs = preset.differences(state, self.state)
|
||||
if failed:
|
||||
log.warning("%s: %d import commands unanswered", self.name, failed)
|
||||
return diffs
|
||||
|
||||
async def refresh(self):
|
||||
await self._load_config()
|
||||
self._emit_state()
|
||||
|
||||
# ------------------------------------------------------------ connection
|
||||
|
||||
async def _supervise(self):
|
||||
while self._want_connected:
|
||||
try:
|
||||
await self._connect_and_run()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as e: # noqa: BLE001 - keep reconnecting on any failure
|
||||
log.warning("%s: %s", self.name, e)
|
||||
self.error = str(e) or e.__class__.__name__
|
||||
self._set_status("error")
|
||||
await self._close()
|
||||
if not self._want_connected:
|
||||
break
|
||||
await asyncio.sleep(RECONNECT_DELAY)
|
||||
|
||||
async def _connect_and_run(self):
|
||||
self._set_status("connecting")
|
||||
self.error = ""
|
||||
if self.transport == "usb":
|
||||
self._reader, self._writer = await asyncio.wait_for(usbhid.open_stream(self.usb), timeout=5)
|
||||
else:
|
||||
self._reader, self._writer = await asyncio.wait_for(
|
||||
asyncio.open_connection(self.host, self.port), timeout=5)
|
||||
self._parser = P.FrameParser()
|
||||
reader_task = asyncio.create_task(self._read_loop())
|
||||
self._tasks = [reader_task]
|
||||
self._set_status("loading")
|
||||
await self._initialise()
|
||||
self._set_status("online")
|
||||
self._emit_state()
|
||||
self._tasks += [asyncio.create_task(self._write_loop()), asyncio.create_task(self._meter_loop())]
|
||||
done, _ = await asyncio.wait(self._tasks, return_when=asyncio.FIRST_COMPLETED)
|
||||
for t in done:
|
||||
if t.exception():
|
||||
raise t.exception()
|
||||
raise ConnectionError("connection closed")
|
||||
|
||||
async def _close(self):
|
||||
if self._resync:
|
||||
self._resync.cancel()
|
||||
self._resync = None
|
||||
for t in self._tasks:
|
||||
t.cancel()
|
||||
self._tasks = []
|
||||
if self._writer:
|
||||
try:
|
||||
self._writer.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
self._reader = self._writer = None
|
||||
if self._waiter and not self._waiter.done():
|
||||
self._waiter.cancel()
|
||||
|
||||
async def _read_loop(self):
|
||||
while True:
|
||||
data = await self._reader.read(4096)
|
||||
if not data:
|
||||
raise ConnectionError("DSP closed the connection")
|
||||
for frame in self._parser.feed(data):
|
||||
if self._waiter and not self._waiter.done():
|
||||
self._waiter.set_result(frame)
|
||||
|
||||
async def _request(self, cmd: int, payload: bytes = b"", timeout: float = RESPONSE_TIMEOUT,
|
||||
expect: int | None = None) -> P.Frame | None:
|
||||
"""Send one command and wait for its answer (the DSP is strictly request/response)."""
|
||||
if not self._writer:
|
||||
raise ConnectionError("not connected")
|
||||
async with self._lock:
|
||||
deadline = time.monotonic() + timeout
|
||||
self._writer.write(P.build_frame(cmd, payload, self.addr))
|
||||
await self._writer.drain()
|
||||
while True:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
return None
|
||||
self._waiter = asyncio.get_running_loop().create_future()
|
||||
try:
|
||||
frame = await asyncio.wait_for(self._waiter, remaining)
|
||||
except asyncio.TimeoutError:
|
||||
return None
|
||||
if expect is None or frame.cmd == expect:
|
||||
return frame
|
||||
|
||||
# ------------------------------------------------------------ init / dump
|
||||
|
||||
async def _initialise(self):
|
||||
await self._request(P.CMD_HANDSHAKE)
|
||||
info = await self._request(P.CMD_DEVICE_INFO, expect=P.CMD_DEVICE_INFO)
|
||||
self.info = info.payload.split(b"\x00")[0].decode("latin1", "replace").strip() if info else ""
|
||||
detected = P.detect_model(self.info)
|
||||
if self.model_key == "auto":
|
||||
if not detected:
|
||||
raise RuntimeError(f"unknown device '{self.info}' - set the model manually")
|
||||
self.model = P.MODELS[detected]
|
||||
else:
|
||||
self.model = P.MODELS[self.model_key]
|
||||
if detected and detected != self.model_key:
|
||||
log.warning("%s: configured as %s but device reports %s", self.name, self.model_key, self.info)
|
||||
count_frame = await self._request(P.CMD_PRESET_COUNT, expect=P.CMD_PRESET_COUNT)
|
||||
count = count_frame.payload[-1] if count_frame and count_frame.payload else 20
|
||||
count = count if 0 < count <= 60 else 20
|
||||
await self._request(P.CMD_INIT_22)
|
||||
await self._request(P.CMD_INIT_14)
|
||||
presets = []
|
||||
for i in range(count):
|
||||
f = await self._request(P.CMD_PRESET_NAME, bytes([i]), expect=P.CMD_PRESET_NAME)
|
||||
presets.append(f.payload[1:].split(b"\x00")[0].decode("latin1", "replace").strip() if f else "")
|
||||
self.presets = presets
|
||||
await self._load_config()
|
||||
|
||||
async def _load_config(self):
|
||||
self.state = await self._read_config()
|
||||
|
||||
async def _read_config(self) -> dict:
|
||||
model = self.model
|
||||
buf = bytearray(model.chunks * P.CHUNK_SIZE)
|
||||
for n in range(model.chunks):
|
||||
for _attempt in range(3):
|
||||
f = await self._request(P.CMD_CONFIG_REQUEST, bytes([n]), expect=P.CMD_CONFIG_CHUNK)
|
||||
if f and f.payload and f.payload[0] == n:
|
||||
data = f.payload[1 : 1 + P.CHUNK_SIZE]
|
||||
buf[n * P.CHUNK_SIZE : n * P.CHUNK_SIZE + len(data)] = data
|
||||
break
|
||||
else:
|
||||
raise RuntimeError(f"config chunk {n} not received")
|
||||
await self._request(P.CMD_STATUS)
|
||||
self.raw = bytes(buf[: model.size])
|
||||
return P.parse_state(model, bytes(buf))
|
||||
|
||||
# ------------------------------------------------------------ background loops
|
||||
|
||||
async def _write_loop(self):
|
||||
while True:
|
||||
await self._pending_event.wait()
|
||||
while self._pending:
|
||||
key = next(iter(self._pending))
|
||||
cmd, payload = self._pending.pop(key)
|
||||
await self._request(cmd, payload)
|
||||
self._pending_event.clear()
|
||||
|
||||
async def _meter_loop(self):
|
||||
misses = 0
|
||||
while True:
|
||||
await asyncio.sleep(METER_INTERVAL)
|
||||
if self._pending:
|
||||
continue
|
||||
f = await self._request(P.CMD_METER, expect=P.CMD_METER)
|
||||
if f is None:
|
||||
misses += 1
|
||||
if misses >= 10:
|
||||
raise ConnectionError("DSP not responding")
|
||||
continue
|
||||
misses = 0
|
||||
self.meters = P.decode_meters(f.payload)
|
||||
m = self.model
|
||||
self.on_event({"type": "meters", "device": self.id,
|
||||
"in": [self.meters[m.meter_index("in", i)] for i in range(m.n_in)],
|
||||
"out": [self.meters[m.meter_index("out", i)] for i in range(m.n_out)],
|
||||
"limit": P.decode_limit_flags(f.payload, m.n_out)})
|
||||
|
||||
# ------------------------------------------------------------ events
|
||||
|
||||
def _set_status(self, status: str):
|
||||
self.status = status
|
||||
self.on_event({"type": "status", "device": self.id, "status": status, "error": self.error,
|
||||
"info": self.info})
|
||||
|
||||
def _emit_state(self):
|
||||
self.on_event({"type": "device", "device": self.id, "data": copy.deepcopy(self.snapshot())})
|
||||
Reference in new issue
Block a user