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
Whitespace-only changes.
+365
@@ -0,0 +1,365 @@
|
||||
"""Async client for one t.racks DSP - over the network (TCP) or USB (HID)."""
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import logging
|
||||
import struct
|
||||
import time
|
||||
|
||||
from . import preset
|
||||
from . import protocol as P
|
||||
from . import usbhid
|
||||
|
||||
log = logging.getLogger("dsp")
|
||||
|
||||
RESPONSE_TIMEOUT = 0.6
|
||||
METER_INTERVAL = 0.15
|
||||
RECONNECT_DELAY = 5.0
|
||||
LINK_RESYNC_DELAY = 1.5 # re-read the config this long after the last change on a linked channel
|
||||
|
||||
|
||||
class Device:
|
||||
def __init__(self, dev_id: str, name: str, host: str, port: int = P.PORT, model: str = "auto",
|
||||
addr: int = 1, autoconnect: bool = True, on_event=None, transport: str = "tcp", usb: str = ""):
|
||||
self.id = dev_id
|
||||
self.name = name
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.model_key = model # "auto", "204" or "408"
|
||||
self.addr = addr
|
||||
self.autoconnect = autoconnect
|
||||
self.transport = "usb" if transport == "usb" else "tcp"
|
||||
self.usb = usb # HID device path, "" = first DSP found
|
||||
self.on_event = on_event or (lambda ev: None)
|
||||
|
||||
self.status = "disconnected" # disconnected | connecting | loading | online | error
|
||||
self.error = ""
|
||||
self.info = ""
|
||||
self.model: P.Model | None = P.MODELS.get(model)
|
||||
self.state: dict | None = None
|
||||
self.raw = b"" # memory image of the last config read
|
||||
self.presets: list[str] = []
|
||||
self.meters: list[float] = [0.0] * 12
|
||||
|
||||
self._reader = None
|
||||
self._writer = None
|
||||
self._parser = P.FrameParser()
|
||||
self._lock = asyncio.Lock()
|
||||
self._waiter: asyncio.Future | None = None
|
||||
self._pending: dict[tuple, tuple[int, bytes]] = {}
|
||||
self._pending_event = asyncio.Event()
|
||||
self._tasks: list[asyncio.Task] = []
|
||||
self._supervisor: asyncio.Task | None = None
|
||||
self._want_connected = False
|
||||
self._resync: asyncio.TimerHandle | None = None
|
||||
self._changes = 0 # bumped on every local change, so a resync never overwrites newer edits
|
||||
|
||||
# ------------------------------------------------------------ public API
|
||||
|
||||
def config(self) -> dict:
|
||||
return {"id": self.id, "name": self.name, "host": self.host, "port": self.port,
|
||||
"model": self.model_key, "addr": self.addr, "autoconnect": self.autoconnect,
|
||||
"transport": self.transport, "usb": self.usb}
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
return {**self.config(), "status": self.status, "error": self.error, "info": self.info,
|
||||
"detected_model": self.model_name or None,
|
||||
"n_in": self.model.n_in if self.model else 0,
|
||||
"n_out": self.model.n_out if self.model else 0,
|
||||
"presets": self.presets, "state": self.state}
|
||||
|
||||
def start(self):
|
||||
self._want_connected = True
|
||||
if not self._supervisor or self._supervisor.done():
|
||||
self._supervisor = asyncio.create_task(self._supervise())
|
||||
|
||||
async def stop(self):
|
||||
self._want_connected = False
|
||||
self._resync: asyncio.TimerHandle | None = None
|
||||
self._changes = 0 # bumped on every local change, so a resync never overwrites newer edits
|
||||
if self._supervisor:
|
||||
self._supervisor.cancel()
|
||||
try:
|
||||
await self._supervisor
|
||||
except (asyncio.CancelledError, Exception):
|
||||
pass
|
||||
self._supervisor = None
|
||||
await self._close()
|
||||
self._set_status("disconnected")
|
||||
|
||||
def set_param(self, kind: str, idx: int, param: str, value):
|
||||
"""Update local state and queue the command (coalesced per parameter)."""
|
||||
if not self.state or not self.model:
|
||||
raise RuntimeError("device not loaded")
|
||||
chans = self.state["inputs" if kind == "in" else "outputs"]
|
||||
ch = chans[idx]
|
||||
if param == "name":
|
||||
value = P.clean_name(value)
|
||||
P.apply_param(ch, param, value)
|
||||
cmd, payload = P.param_command(self.model, kind, idx, ch, param)
|
||||
key = (cmd, payload[0]) + ((payload[1],) if cmd in (P.CMD_PEQ, P.CMD_GEQ, P.CMD_MIX) else ())
|
||||
self._pending[key] = (cmd, payload)
|
||||
self._pending_event.set()
|
||||
self._changes += 1
|
||||
# the DSP applies the change to linked channels itself: show that right away
|
||||
group = [idx] if param.split(".")[0] in P.LINK_EXCLUDED else P.link_group(chans, idx)
|
||||
for i in group:
|
||||
if i != idx:
|
||||
P.apply_param(chans[i], param, copy.deepcopy(value))
|
||||
self.on_event({"type": "param", "device": self.id, "kind": kind, "idx": i,
|
||||
"param": param, "value": value})
|
||||
if len(group) > 1:
|
||||
self._schedule_resync()
|
||||
|
||||
async def set_links(self, kind: str, groups: list[list[int]]):
|
||||
"""Link channels of one kind. The DSP copies the first channel's settings to the others."""
|
||||
if not self.state or not self.model:
|
||||
raise RuntimeError("device not loaded")
|
||||
n = self.model.n_in if kind == "in" else self.model.n_out
|
||||
for i, mask in enumerate(P.link_masks(n, groups)):
|
||||
await self._request(P.CMD_LINK, bytes([self.model.channel(kind, i)]) + struct.pack("<H", mask))
|
||||
await asyncio.sleep(0.3)
|
||||
await self.refresh()
|
||||
|
||||
def _schedule_resync(self):
|
||||
"""Re-read the config shortly after edits on linked channels, so the app shows exactly
|
||||
what the DSP applied to the group (e.g. mute, which we don't mirror for certain)."""
|
||||
if self._resync:
|
||||
self._resync.cancel()
|
||||
self._resync = asyncio.get_running_loop().call_later(
|
||||
LINK_RESYNC_DELAY, lambda: asyncio.create_task(self._do_resync()))
|
||||
|
||||
async def _do_resync(self):
|
||||
if self.status != "online":
|
||||
return
|
||||
if self._pending:
|
||||
return self._schedule_resync()
|
||||
seq = self._changes
|
||||
try:
|
||||
state = await self._read_config()
|
||||
except Exception as e: # noqa: BLE001 - the next change schedules another try
|
||||
log.info("%s: resync failed: %s", self.name, e)
|
||||
return
|
||||
if seq != self._changes:
|
||||
return self._schedule_resync()
|
||||
if state != self.state:
|
||||
self.state = state
|
||||
self._emit_state()
|
||||
|
||||
async def recall_preset(self, index: int):
|
||||
await self._request(P.CMD_PRESET_RECALL, bytes([index + 1]), timeout=2.0)
|
||||
await asyncio.sleep(0.3)
|
||||
await self._load_config()
|
||||
self._emit_state()
|
||||
|
||||
async def store_preset(self, index: int, name: str):
|
||||
await self._request(P.CMD_PRESET_STORE_NAME, name.encode("latin1")[:14].ljust(14, b" "))
|
||||
await self._request(P.CMD_PRESET_STORE, bytes([index + 1]), timeout=2.0)
|
||||
await self._request(P.CMD_STATUS)
|
||||
if index < len(self.presets):
|
||||
self.presets[index] = name
|
||||
if self.state:
|
||||
self.state["preset_name"] = name
|
||||
self._emit_state()
|
||||
|
||||
@property
|
||||
def model_name(self) -> str:
|
||||
return next((k for k, m in P.MODELS.items() if m is self.model), "")
|
||||
|
||||
async def export_preset(self) -> dict:
|
||||
"""The DSP's current state, read fresh from the device."""
|
||||
await self.refresh()
|
||||
return preset.export_doc(self.model_name, self.info, self.state, self.raw)
|
||||
|
||||
async def import_preset(self, state: dict) -> list[str]:
|
||||
"""Put the DSP into `state` (working state only). Returns the paths that did not take."""
|
||||
if self.status != "online":
|
||||
raise RuntimeError("DSP is not connected")
|
||||
if self._resync:
|
||||
self._resync.cancel()
|
||||
failed = 0
|
||||
for cmd, payload in preset.import_commands(self.model, state, self.state):
|
||||
if await self._request(cmd, payload) is None:
|
||||
failed += 1
|
||||
await asyncio.sleep(0.3)
|
||||
await self.refresh()
|
||||
diffs = preset.differences(state, self.state)
|
||||
if failed:
|
||||
log.warning("%s: %d import commands unanswered", self.name, failed)
|
||||
return diffs
|
||||
|
||||
async def refresh(self):
|
||||
await self._load_config()
|
||||
self._emit_state()
|
||||
|
||||
# ------------------------------------------------------------ connection
|
||||
|
||||
async def _supervise(self):
|
||||
while self._want_connected:
|
||||
try:
|
||||
await self._connect_and_run()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as e: # noqa: BLE001 - keep reconnecting on any failure
|
||||
log.warning("%s: %s", self.name, e)
|
||||
self.error = str(e) or e.__class__.__name__
|
||||
self._set_status("error")
|
||||
await self._close()
|
||||
if not self._want_connected:
|
||||
break
|
||||
await asyncio.sleep(RECONNECT_DELAY)
|
||||
|
||||
async def _connect_and_run(self):
|
||||
self._set_status("connecting")
|
||||
self.error = ""
|
||||
if self.transport == "usb":
|
||||
self._reader, self._writer = await asyncio.wait_for(usbhid.open_stream(self.usb), timeout=5)
|
||||
else:
|
||||
self._reader, self._writer = await asyncio.wait_for(
|
||||
asyncio.open_connection(self.host, self.port), timeout=5)
|
||||
self._parser = P.FrameParser()
|
||||
reader_task = asyncio.create_task(self._read_loop())
|
||||
self._tasks = [reader_task]
|
||||
self._set_status("loading")
|
||||
await self._initialise()
|
||||
self._set_status("online")
|
||||
self._emit_state()
|
||||
self._tasks += [asyncio.create_task(self._write_loop()), asyncio.create_task(self._meter_loop())]
|
||||
done, _ = await asyncio.wait(self._tasks, return_when=asyncio.FIRST_COMPLETED)
|
||||
for t in done:
|
||||
if t.exception():
|
||||
raise t.exception()
|
||||
raise ConnectionError("connection closed")
|
||||
|
||||
async def _close(self):
|
||||
if self._resync:
|
||||
self._resync.cancel()
|
||||
self._resync = None
|
||||
for t in self._tasks:
|
||||
t.cancel()
|
||||
self._tasks = []
|
||||
if self._writer:
|
||||
try:
|
||||
self._writer.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
self._reader = self._writer = None
|
||||
if self._waiter and not self._waiter.done():
|
||||
self._waiter.cancel()
|
||||
|
||||
async def _read_loop(self):
|
||||
while True:
|
||||
data = await self._reader.read(4096)
|
||||
if not data:
|
||||
raise ConnectionError("DSP closed the connection")
|
||||
for frame in self._parser.feed(data):
|
||||
if self._waiter and not self._waiter.done():
|
||||
self._waiter.set_result(frame)
|
||||
|
||||
async def _request(self, cmd: int, payload: bytes = b"", timeout: float = RESPONSE_TIMEOUT,
|
||||
expect: int | None = None) -> P.Frame | None:
|
||||
"""Send one command and wait for its answer (the DSP is strictly request/response)."""
|
||||
if not self._writer:
|
||||
raise ConnectionError("not connected")
|
||||
async with self._lock:
|
||||
deadline = time.monotonic() + timeout
|
||||
self._writer.write(P.build_frame(cmd, payload, self.addr))
|
||||
await self._writer.drain()
|
||||
while True:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
return None
|
||||
self._waiter = asyncio.get_running_loop().create_future()
|
||||
try:
|
||||
frame = await asyncio.wait_for(self._waiter, remaining)
|
||||
except asyncio.TimeoutError:
|
||||
return None
|
||||
if expect is None or frame.cmd == expect:
|
||||
return frame
|
||||
|
||||
# ------------------------------------------------------------ init / dump
|
||||
|
||||
async def _initialise(self):
|
||||
await self._request(P.CMD_HANDSHAKE)
|
||||
info = await self._request(P.CMD_DEVICE_INFO, expect=P.CMD_DEVICE_INFO)
|
||||
self.info = info.payload.split(b"\x00")[0].decode("latin1", "replace").strip() if info else ""
|
||||
detected = P.detect_model(self.info)
|
||||
if self.model_key == "auto":
|
||||
if not detected:
|
||||
raise RuntimeError(f"unknown device '{self.info}' - set the model manually")
|
||||
self.model = P.MODELS[detected]
|
||||
else:
|
||||
self.model = P.MODELS[self.model_key]
|
||||
if detected and detected != self.model_key:
|
||||
log.warning("%s: configured as %s but device reports %s", self.name, self.model_key, self.info)
|
||||
count_frame = await self._request(P.CMD_PRESET_COUNT, expect=P.CMD_PRESET_COUNT)
|
||||
count = count_frame.payload[-1] if count_frame and count_frame.payload else 20
|
||||
count = count if 0 < count <= 60 else 20
|
||||
await self._request(P.CMD_INIT_22)
|
||||
await self._request(P.CMD_INIT_14)
|
||||
presets = []
|
||||
for i in range(count):
|
||||
f = await self._request(P.CMD_PRESET_NAME, bytes([i]), expect=P.CMD_PRESET_NAME)
|
||||
presets.append(f.payload[1:].split(b"\x00")[0].decode("latin1", "replace").strip() if f else "")
|
||||
self.presets = presets
|
||||
await self._load_config()
|
||||
|
||||
async def _load_config(self):
|
||||
self.state = await self._read_config()
|
||||
|
||||
async def _read_config(self) -> dict:
|
||||
model = self.model
|
||||
buf = bytearray(model.chunks * P.CHUNK_SIZE)
|
||||
for n in range(model.chunks):
|
||||
for _attempt in range(3):
|
||||
f = await self._request(P.CMD_CONFIG_REQUEST, bytes([n]), expect=P.CMD_CONFIG_CHUNK)
|
||||
if f and f.payload and f.payload[0] == n:
|
||||
data = f.payload[1 : 1 + P.CHUNK_SIZE]
|
||||
buf[n * P.CHUNK_SIZE : n * P.CHUNK_SIZE + len(data)] = data
|
||||
break
|
||||
else:
|
||||
raise RuntimeError(f"config chunk {n} not received")
|
||||
await self._request(P.CMD_STATUS)
|
||||
self.raw = bytes(buf[: model.size])
|
||||
return P.parse_state(model, bytes(buf))
|
||||
|
||||
# ------------------------------------------------------------ background loops
|
||||
|
||||
async def _write_loop(self):
|
||||
while True:
|
||||
await self._pending_event.wait()
|
||||
while self._pending:
|
||||
key = next(iter(self._pending))
|
||||
cmd, payload = self._pending.pop(key)
|
||||
await self._request(cmd, payload)
|
||||
self._pending_event.clear()
|
||||
|
||||
async def _meter_loop(self):
|
||||
misses = 0
|
||||
while True:
|
||||
await asyncio.sleep(METER_INTERVAL)
|
||||
if self._pending:
|
||||
continue
|
||||
f = await self._request(P.CMD_METER, expect=P.CMD_METER)
|
||||
if f is None:
|
||||
misses += 1
|
||||
if misses >= 10:
|
||||
raise ConnectionError("DSP not responding")
|
||||
continue
|
||||
misses = 0
|
||||
self.meters = P.decode_meters(f.payload)
|
||||
m = self.model
|
||||
self.on_event({"type": "meters", "device": self.id,
|
||||
"in": [self.meters[m.meter_index("in", i)] for i in range(m.n_in)],
|
||||
"out": [self.meters[m.meter_index("out", i)] for i in range(m.n_out)],
|
||||
"limit": P.decode_limit_flags(f.payload, m.n_out)})
|
||||
|
||||
# ------------------------------------------------------------ events
|
||||
|
||||
def _set_status(self, status: str):
|
||||
self.status = status
|
||||
self.on_event({"type": "status", "device": self.id, "status": status, "error": self.error,
|
||||
"info": self.info})
|
||||
|
||||
def _emit_state(self):
|
||||
self.on_event({"type": "device", "device": self.id, "data": copy.deepcopy(self.snapshot())})
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
"""Preset files: export the DSP's current state and import it again.
|
||||
|
||||
A file holds the decoded state (readable, see protocol.parse_state) plus the raw memory image.
|
||||
Importing only changes the DSP's working state - the stored presets (U01...) stay untouched.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import time
|
||||
|
||||
from . import protocol as P
|
||||
|
||||
FORMAT = "dsp-control-preset"
|
||||
|
||||
# valid raw ranges (PROTOCOL.md, "Werte-Kodierung")
|
||||
_GATE = {"attack": (0, 998), "release": (9, 2999), "hold": (9, 998), "threshold": (0, 180)}
|
||||
_COMP = {"ratio": (0, 15), "attack": (0, 998), "release": (9, 2999), "knee": (0, 12), "threshold": (0, 220)}
|
||||
_LIMIT = {"attack": (0, 998), "release": (9, 2999), "knee": (0, 12), "threshold": (0, 220)}
|
||||
|
||||
|
||||
def export_doc(model_key: str, info: str, state: dict, raw: bytes) -> dict:
|
||||
return {"format": FORMAT, "version": 1, "model": model_key, "device": info,
|
||||
"preset_name": state.get("preset_name", ""),
|
||||
"exported": time.strftime("%Y-%m-%dT%H:%M:%S"), "state": state, "raw": raw.hex()}
|
||||
|
||||
|
||||
def _int(v, lo: int, hi: int, default: int) -> int:
|
||||
try:
|
||||
v = int(v)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return min(hi, max(lo, v))
|
||||
|
||||
|
||||
def _filter(src, cur: dict) -> dict:
|
||||
src = src if isinstance(src, dict) else {}
|
||||
return {"freq": _int(src.get("freq"), 0, 300, cur["freq"]), "slope": _int(src.get("slope"), 0, 20, cur["slope"])}
|
||||
|
||||
|
||||
def _peq(src, cur: list) -> list:
|
||||
src = src if isinstance(src, list) else []
|
||||
out = []
|
||||
for i, c in enumerate(cur):
|
||||
b = src[i] if i < len(src) and isinstance(src[i], dict) else {}
|
||||
out.append({"gain": _int(b.get("gain"), 0, 240, c["gain"]), "freq": _int(b.get("freq"), 0, 300, c["freq"]),
|
||||
"q": _int(b.get("q"), 0, 100, c["q"]), "type": _int(b.get("type"), 0, 8, c["type"]),
|
||||
"bypass": bool(b.get("bypass", c["bypass"]))})
|
||||
return out
|
||||
|
||||
|
||||
def _group(src, cur: dict, ranges: dict) -> dict:
|
||||
src = src if isinstance(src, dict) else {}
|
||||
return {k: _int(src.get(k), lo, hi, cur[k]) for k, (lo, hi) in ranges.items()}
|
||||
|
||||
|
||||
def _common(s: dict, c: dict) -> dict:
|
||||
name = s.get("name", c["name"])
|
||||
return {"name": P.clean_name(name).strip(),
|
||||
"hp": _filter(s.get("hp"), c["hp"]), "lp": _filter(s.get("lp"), c["lp"]),
|
||||
"gain": _int(s.get("gain"), 0, 400, c["gain"]), "polarity": bool(s.get("polarity", c["polarity"])),
|
||||
"delay": _int(s.get("delay"), 0, 65280, c["delay"]), "link": _int(s.get("link"), 0, 0xFFFF, c["link"]),
|
||||
"mute": bool(s.get("mute", c["mute"]))}
|
||||
|
||||
|
||||
def clean_state(model: P.Model, src: dict, base: dict) -> dict:
|
||||
"""`src` limited to valid values; anything missing or broken is taken from `base`."""
|
||||
st = copy.deepcopy(base)
|
||||
ins = src.get("inputs") if isinstance(src.get("inputs"), list) else []
|
||||
outs = src.get("outputs") if isinstance(src.get("outputs"), list) else []
|
||||
for i, c in enumerate(st["inputs"]):
|
||||
s = ins[i] if i < len(ins) and isinstance(ins[i], dict) else {}
|
||||
geq = s.get("geq") if isinstance(s.get("geq"), list) else []
|
||||
c.update(_common(s, c), peq=_peq(s.get("peq"), c["peq"]), gate=_group(s.get("gate"), c["gate"], _GATE),
|
||||
geq=[_int(geq[b], 0, 240, v) if b < len(geq) else v for b, v in enumerate(c["geq"])])
|
||||
for i, c in enumerate(st["outputs"]):
|
||||
s = outs[i] if i < len(outs) and isinstance(outs[i], dict) else {}
|
||||
mix = s.get("mix") if isinstance(s.get("mix"), list) else []
|
||||
c.update(_common(s, c), peq=_peq(s.get("peq"), c["peq"]),
|
||||
comp=_group(s.get("comp"), c["comp"], _COMP), limit=_group(s.get("limit"), c["limit"], _LIMIT),
|
||||
matrix=_int(s.get("matrix"), 0, (1 << model.n_in) - 1, c["matrix"]),
|
||||
mix=[_int(mix[k], 0, 400, v) if k < len(mix) else v for k, v in enumerate(c["mix"])])
|
||||
if isinstance(src.get("preset_name"), str):
|
||||
st["preset_name"] = src["preset_name"][:14]
|
||||
return st
|
||||
|
||||
|
||||
def read_file(model_key: str, model: P.Model, current: dict, doc: dict | None = None,
|
||||
raw: bytes | None = None) -> dict:
|
||||
"""The state to import from an uploaded file: our JSON (`doc`) or a bare memory image (`raw`)."""
|
||||
if raw is not None:
|
||||
if len(raw) not in (model.size, model.chunks * P.CHUNK_SIZE):
|
||||
raise ValueError(f"Unknown file format ({len(raw)} bytes) – expected a DSP Control preset file "
|
||||
f"or a memory image of the {model.name} ({model.size} bytes)")
|
||||
return _linked_alike(clean_state(model, P.parse_state(model, raw.ljust(model.chunks * P.CHUNK_SIZE, b"\0")), current))
|
||||
if not isinstance(doc, dict) or doc.get("format") != FORMAT:
|
||||
raise ValueError("Not a DSP Control preset file")
|
||||
if str(doc.get("model")) != model_key:
|
||||
raise ValueError(f"The file is for a DSP {doc.get('model')}, the connected device is a {model.name}")
|
||||
base = current
|
||||
try: # the raw image fills in anything the readable part lacks
|
||||
img = bytes.fromhex(doc.get("raw") or "")
|
||||
if len(img) in (model.size, model.chunks * P.CHUNK_SIZE):
|
||||
base = clean_state(model, P.parse_state(model, img.ljust(model.chunks * P.CHUNK_SIZE, b"\0")), current)
|
||||
except ValueError:
|
||||
pass
|
||||
return _linked_alike(clean_state(model, doc.get("state") if isinstance(doc.get("state"), dict) else {}, base))
|
||||
|
||||
|
||||
def _linked_alike(st: dict) -> dict:
|
||||
"""Linked channels share their settings on the DSP: take them from each group's first channel."""
|
||||
for chans in (st["inputs"], st["outputs"]):
|
||||
for g in P.link_groups(chans):
|
||||
for i in g[1:]:
|
||||
P.copy_linked(chans, g[0], i)
|
||||
return st
|
||||
|
||||
|
||||
def import_commands(model: P.Model, st: dict, current: dict) -> list[tuple[int, bytes]]:
|
||||
"""Commands that take the DSP from `current` to `st` - only values that actually change.
|
||||
|
||||
If the links change, they are dissolved first (otherwise the DSP would copy every value onto
|
||||
the whole group), then the parameters are set, then the new links are formed. Forming a group
|
||||
copies the first channel's settings to the others, so names, routing and mix levels (which
|
||||
links don't share) are sent once more at the end.
|
||||
"""
|
||||
kinds = (("in", "inputs"), ("out", "outputs"))
|
||||
relink = any(P.link_groups(st[key]) != P.link_groups(current[key]) for _, key in kinds)
|
||||
cmds = []
|
||||
if relink:
|
||||
for kind, key in kinds:
|
||||
for i in range(len(st[key])):
|
||||
cmds.append((P.CMD_LINK, bytes([model.channel(kind, i)]) + (1 << i).to_bytes(2, "little")))
|
||||
for kind, key in kinds:
|
||||
for i, ch in enumerate(st[key]):
|
||||
params = ["name", "gain", "polarity", "delay", "hp", "lp"] + [f"peq.{b}" for b in range(len(ch["peq"]))]
|
||||
if kind == "in":
|
||||
params += [f"geq.{b}" for b in range(len(ch["geq"]))] + ["gate"]
|
||||
else:
|
||||
params += ["comp", "limit", "matrix"] + [f"mix.{k}" for k in range(len(ch["mix"]))]
|
||||
for p in params + ["mute"]:
|
||||
cmd = P.param_command(model, kind, i, ch, p)
|
||||
if relink or cmd != P.param_command(model, kind, i, current[key][i], p):
|
||||
cmds.append(cmd)
|
||||
if relink:
|
||||
for kind, key in kinds:
|
||||
chans = st[key]
|
||||
groups = P.link_groups(chans)
|
||||
for i, mask in enumerate(P.link_masks(len(chans), groups)):
|
||||
if mask != 1 << i:
|
||||
cmds.append((P.CMD_LINK, bytes([model.channel(kind, i)]) + mask.to_bytes(2, "little")))
|
||||
for g in groups:
|
||||
for i in g[1:]:
|
||||
extra = ["name"] + (["matrix"] + [f"mix.{k}" for k in range(len(chans[i]["mix"]))] if kind == "out" else [])
|
||||
cmds += [P.param_command(model, kind, i, chans[i], p) for p in extra]
|
||||
return cmds
|
||||
|
||||
|
||||
def differences(target: dict, actual: dict) -> list[str]:
|
||||
"""Paths where the DSP's state differs from the imported one (the preset name is not settable)."""
|
||||
diffs = []
|
||||
|
||||
def walk(a, b, path):
|
||||
if isinstance(a, dict):
|
||||
for k in a:
|
||||
walk(a[k], b.get(k) if isinstance(b, dict) else None, f"{path}.{k}" if path else k)
|
||||
elif isinstance(a, list):
|
||||
for i, v in enumerate(a):
|
||||
walk(v, b[i] if isinstance(b, list) and i < len(b) else None, f"{path}.{i}")
|
||||
elif a != b:
|
||||
diffs.append(path)
|
||||
|
||||
walk({k: v for k, v in target.items() if k != "preset_name"}, actual, "")
|
||||
return diffs
|
||||
+536
@@ -0,0 +1,536 @@
|
||||
"""t.racks DSP 204 / DSP 408 wire protocol (see PROTOCOL.md)."""
|
||||
|
||||
import copy
|
||||
import math
|
||||
import struct
|
||||
from dataclasses import dataclass
|
||||
|
||||
PORT = 9761
|
||||
|
||||
# Read / system commands
|
||||
CMD_ACK = 0x01
|
||||
CMD_HANDSHAKE = 0x10
|
||||
CMD_STATUS = 0x12
|
||||
CMD_DEVICE_INFO = 0x13
|
||||
CMD_INIT_14 = 0x14
|
||||
CMD_PRESET_RECALL = 0x20
|
||||
CMD_PRESET_STORE = 0x21
|
||||
CMD_INIT_22 = 0x22
|
||||
CMD_CONFIG_CHUNK = 0x24
|
||||
CMD_PRESET_STORE_NAME = 0x26
|
||||
CMD_CONFIG_REQUEST = 0x27
|
||||
CMD_PRESET_NAME = 0x29
|
||||
CMD_PRESET_COUNT = 0x2C
|
||||
CMD_METER = 0x40
|
||||
|
||||
# Parameter commands
|
||||
CMD_COMP = 0x30
|
||||
CMD_LOW_PASS = 0x31
|
||||
CMD_HIGH_PASS = 0x32
|
||||
CMD_PEQ = 0x33
|
||||
CMD_GAIN = 0x34
|
||||
CMD_MUTE = 0x35
|
||||
CMD_POLARITY = 0x36
|
||||
CMD_DELAY = 0x38
|
||||
CMD_MATRIX = 0x3A
|
||||
CMD_CHANNEL_NAME = 0x3D
|
||||
CMD_GATE = 0x3E
|
||||
CMD_LIMIT = 0x3F
|
||||
CMD_MIX = 0x41
|
||||
CMD_GEQ = 0x48
|
||||
CMD_LINK = 0x3B # [ch][u16 link mask], see link_masks()
|
||||
|
||||
CHUNK_SIZE = 50
|
||||
|
||||
|
||||
def checksum(data: bytes) -> int:
|
||||
"""XOR over 02 .. 03 of the frame; the 02 and 03 bytes fold into the initial 0x01."""
|
||||
c = 0x01
|
||||
for b in data:
|
||||
c ^= b
|
||||
return c
|
||||
|
||||
|
||||
def build_frame(cmd: int, payload: bytes = b"", addr: int = 1, src: int = 0) -> bytes:
|
||||
body = bytes([src, addr, len(payload) + 1, cmd]) + bytes(payload)
|
||||
return b"\x10\x02" + body + b"\x10\x03" + bytes([checksum(body)])
|
||||
|
||||
|
||||
@dataclass
|
||||
class Frame:
|
||||
src: int
|
||||
dst: int
|
||||
cmd: int
|
||||
payload: bytes
|
||||
checksum_ok: bool = True
|
||||
|
||||
|
||||
class FrameParser:
|
||||
"""Reassembles frames from a TCP byte stream (length based, no byte stuffing)."""
|
||||
|
||||
def __init__(self):
|
||||
self.buf = bytearray()
|
||||
|
||||
def feed(self, data: bytes) -> list[Frame]:
|
||||
self.buf += data
|
||||
frames = []
|
||||
while True:
|
||||
start = self.buf.find(b"\x10\x02")
|
||||
if start < 0:
|
||||
# keep a trailing 0x10 that might start the next header
|
||||
del self.buf[: max(0, len(self.buf) - 1)]
|
||||
return frames
|
||||
if start:
|
||||
del self.buf[:start]
|
||||
if len(self.buf) < 6:
|
||||
return frames
|
||||
length = self.buf[4]
|
||||
total = 5 + length + 3
|
||||
if len(self.buf) < total:
|
||||
return frames
|
||||
if self.buf[5 + length] != 0x10 or self.buf[6 + length] != 0x03 or length == 0:
|
||||
del self.buf[:2] # not a real header, resync
|
||||
continue
|
||||
body = bytes(self.buf[2 : 5 + length])
|
||||
frames.append(
|
||||
Frame(
|
||||
src=body[0],
|
||||
dst=body[1],
|
||||
cmd=body[3],
|
||||
payload=body[4:],
|
||||
checksum_ok=checksum(body) == self.buf[7 + length],
|
||||
)
|
||||
)
|
||||
del self.buf[:total]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- value scales
|
||||
|
||||
Q_TABLE = [
|
||||
0.4, 0.42, 0.45, 0.47, 0.5, 0.53, 0.56, 0.59, 0.63, 0.67, 0.71, 0.75, 0.79, 0.84, 0.89,
|
||||
0.94, 1.0, 1.06, 1.12, 1.19, 1.26, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.4,
|
||||
2.5, 2.7, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.2, 4.5, 4.8, 5.0, 5.3, 5.7, 6.0, 6.3, 6.7,
|
||||
7.1, 7.6, 8.0, 8.5, 9.0, 9.5, 10.1, 10.7, 11.3, 12.0, 12.7, 13.5, 14.0, 15.0, 16.0, 17.0,
|
||||
18.0, 19.0, 20.0, 21.0, 23.0, 24.0, 25.0, 27.0, 29.0, 30.0, 32.0, 34.0, 36.0, 38.0, 40.0,
|
||||
43.0, 45.0, 48.0, 51.0, 54.0, 57.0, 60.0, 64.0, 68.0, 72.0, 76.0, 81.0, 85.0, 91.0, 96.0,
|
||||
102.0, 108.0, 114.0, 121.0, 128.0,
|
||||
]
|
||||
RATIO_NAMES = ["1.0", "1.1", "1.3", "1.5", "1.7", "2.0", "2.5", "3.0", "3.5", "4.0", "5.0",
|
||||
"6.0", "8.0", "10", "20", "Limit"]
|
||||
PEQ_TYPES = ["Peak", "Low Shelf", "High Shelf", "HPF -6", "HPF -12", "LPF -6", "LPF -12",
|
||||
"Allpass 1", "Allpass 2"]
|
||||
SLOPES = ["Bypass", "BW -6", "BL -6", "BW -12", "BL -12", "LK -12", "BW -18", "BL -18", "BW -24",
|
||||
"BL -24", "LK -24", "BW -30", "BL -30", "BW -36", "BL -36", "LK -36", "BW -42", "BL -42",
|
||||
"BW -48", "BL -48", "LK -48"]
|
||||
|
||||
|
||||
def gain_to_db(raw: int) -> float:
|
||||
return raw / 2 - 60 if raw < 80 else (raw - 280) / 10
|
||||
|
||||
|
||||
def db_to_gain(db: float) -> int:
|
||||
raw = round((db + 60) * 2) if db < -20 else round(db * 10 + 280)
|
||||
return max(0, min(400, raw))
|
||||
|
||||
|
||||
def freq_to_hz(raw: int) -> float:
|
||||
return 1000.0 * 2 ** ((raw - 170) / 30)
|
||||
|
||||
|
||||
def hz_to_freq(hz: float) -> int:
|
||||
return max(0, min(300, round(170 + 30 * math.log2(max(hz, 1.0) / 1000.0))))
|
||||
|
||||
|
||||
def eq_gain_to_db(raw: int) -> float:
|
||||
return (raw - 120) / 10
|
||||
|
||||
|
||||
def threshold_to_db(raw: int) -> float:
|
||||
return (raw - 180) / 2
|
||||
|
||||
|
||||
def delay_to_ms(raw: int) -> float:
|
||||
return raw / 96
|
||||
|
||||
|
||||
def decode_meters(payload: bytes) -> list[float]:
|
||||
"""12 linear levels (In A-D, Out 1-8) from a 0x40 response payload."""
|
||||
levels = []
|
||||
for i in range(12):
|
||||
b = payload[i * 3 : i * 3 + 3]
|
||||
if len(b) < 3:
|
||||
levels.append(0.0)
|
||||
continue
|
||||
v = struct.unpack("<f", bytes([0, b[2], b[0], b[1]]))[0]
|
||||
levels.append(v if math.isfinite(v) and v > 0 else 0.0)
|
||||
return levels
|
||||
|
||||
|
||||
def decode_limit_flags(payload: bytes, n_out: int) -> list[bool]:
|
||||
"""Limiter active per output, from the 2 status bytes after the levels (bit i = output i).
|
||||
|
||||
Seen on a DSP 204: 00 03 while Out 1+2 limit, 00 0C for Out 3+4. That outputs 5-8 of the 408
|
||||
continue in the same 16-bit value is an assumption.
|
||||
"""
|
||||
if len(payload) < 38:
|
||||
return [False] * n_out
|
||||
flags = payload[36] << 8 | payload[37]
|
||||
return [bool(flags >> i & 1) for i in range(n_out)]
|
||||
|
||||
|
||||
def encode_meters(levels: list[float], limit_flags: int = 0) -> bytes:
|
||||
"""Inverse of decode_meters / decode_limit_flags (used by the simulator)."""
|
||||
out = bytearray()
|
||||
for v in levels:
|
||||
raw = struct.pack("<f", v)
|
||||
out += bytes([raw[2], raw[3], raw[1]])
|
||||
return bytes(out) + bytes([limit_flags >> 8 & 0xFF, limit_flags & 0xFF])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- device models
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Model:
|
||||
name: str
|
||||
n_in: int
|
||||
n_out: int
|
||||
|
||||
@property
|
||||
def in_size(self) -> int:
|
||||
return 140
|
||||
|
||||
@property
|
||||
def out_size(self) -> int:
|
||||
return 96 + 2 * self.n_in
|
||||
|
||||
@property
|
||||
def out_base(self) -> int:
|
||||
return 0x10 + self.n_in * self.in_size
|
||||
|
||||
@property
|
||||
def globals_base(self) -> int:
|
||||
return self.out_base + self.n_out * self.out_size
|
||||
|
||||
@property
|
||||
def size(self) -> int:
|
||||
return self.globals_base + 4 + 2 * self.n_in + 2 * self.n_out + 12
|
||||
|
||||
@property
|
||||
def chunks(self) -> int:
|
||||
return -(-self.size // CHUNK_SIZE)
|
||||
|
||||
def channel(self, kind: str, idx: int) -> int:
|
||||
"""Wire channel number for input/output index."""
|
||||
return idx if kind == "in" else self.n_in + idx
|
||||
|
||||
def meter_index(self, kind: str, idx: int) -> int:
|
||||
return idx if kind == "in" else 4 + idx
|
||||
|
||||
|
||||
MODELS = {"204": Model("DSP 204", 2, 4), "408": Model("DSP 408", 4, 8)}
|
||||
|
||||
|
||||
def detect_model(info: str) -> str | None:
|
||||
for key in MODELS:
|
||||
if f"DSP{key}" in info.replace(" ", ""):
|
||||
return key
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- state (de)serialisation
|
||||
|
||||
|
||||
_UMLAUTS = str.maketrans({"ä": "ae", "ö": "oe", "ü": "ue", "Ä": "Ae", "Ö": "Oe", "Ü": "Ue", "ß": "ss"})
|
||||
|
||||
|
||||
def clean_name(name) -> str:
|
||||
"""Channel name as the DSP stores it: printable ASCII, at most 8 characters."""
|
||||
s = str(name or "").translate(_UMLAUTS)
|
||||
return "".join(c for c in s if " " <= c <= "~")[:8]
|
||||
|
||||
|
||||
def _name(b: bytes) -> str:
|
||||
return b.split(b"\x00")[0].decode("latin1").strip()
|
||||
|
||||
|
||||
def _peq(buf: bytes, off: int, n: int) -> list[dict]:
|
||||
bands = []
|
||||
for i in range(n):
|
||||
gain, freq, q, typ = struct.unpack_from("<HHBB", buf, off + i * 6)
|
||||
bands.append({"gain": gain, "freq": freq, "q": q, "type": typ % 9, "bypass": typ >= 9})
|
||||
return bands
|
||||
|
||||
|
||||
def parse_state(model: Model, buf: bytes) -> dict:
|
||||
"""Decode the reassembled config dump into a JSON friendly dict (raw values)."""
|
||||
u16 = lambda off: struct.unpack_from("<H", buf, off)[0]
|
||||
g = model.globals_base
|
||||
in_mute, out_mute = u16(g), u16(g + 2)
|
||||
inputs = []
|
||||
for i in range(model.n_in):
|
||||
o = 0x10 + i * model.in_size
|
||||
inputs.append({
|
||||
"name": _name(buf[o : o + 8]),
|
||||
"gate": dict(zip(("attack", "release", "hold", "threshold"),
|
||||
struct.unpack_from("<4H", buf, o + 8))),
|
||||
"geq": list(struct.unpack_from("<31H", buf, o + 16)),
|
||||
"peq": _peq(buf, o + 78, 8),
|
||||
"hp": {"freq": u16(o + 126), "slope": buf[o + 130]},
|
||||
"lp": {"freq": u16(o + 128), "slope": buf[o + 131]},
|
||||
"gain": u16(o + 132),
|
||||
"polarity": u16(o + 134) != 0,
|
||||
"delay": u16(o + 136),
|
||||
"link": u16(o + 138),
|
||||
"mute": bool(in_mute >> i & 1),
|
||||
})
|
||||
outputs = []
|
||||
for i in range(model.n_out):
|
||||
o = model.out_base + i * model.out_size
|
||||
p = o + 10 + 2 * model.n_in
|
||||
outputs.append({
|
||||
"name": _name(buf[o : o + 8]),
|
||||
"matrix": u16(o + 8),
|
||||
"mix": list(struct.unpack_from(f"<{model.n_in}H", buf, o + 10)),
|
||||
"hp": {"freq": u16(p), "slope": buf[p + 4]},
|
||||
"lp": {"freq": u16(p + 2), "slope": buf[p + 5]},
|
||||
"peq": _peq(buf, p + 6, 9),
|
||||
"comp": dict(zip(("ratio", "attack", "release", "knee", "threshold"),
|
||||
struct.unpack_from("<5H", buf, p + 60))),
|
||||
"limit": dict(zip(("attack", "release", "knee", "threshold"),
|
||||
struct.unpack_from("<4H", buf, p + 70))),
|
||||
"gain": u16(p + 78),
|
||||
"polarity": u16(p + 80) != 0,
|
||||
"delay": u16(p + 82),
|
||||
"link": u16(p + 84),
|
||||
"mute": bool(out_mute >> i & 1),
|
||||
})
|
||||
return {"preset_name": _name(buf[2:16]), "inputs": inputs, "outputs": outputs}
|
||||
|
||||
|
||||
def build_state_buffer(model: Model, state: dict) -> bytearray:
|
||||
"""Inverse of parse_state (used by the simulator)."""
|
||||
buf = bytearray(model.chunks * CHUNK_SIZE)
|
||||
pad = lambda s, n: s.encode("latin1")[:n].ljust(n, b" ")
|
||||
buf[0:2] = b"\xff\xff"
|
||||
buf[2:16] = pad(state["preset_name"], 14)
|
||||
|
||||
def put_peq(off, bands):
|
||||
for i, b in enumerate(bands):
|
||||
struct.pack_into("<HHBB", buf, off + i * 6, b["gain"], b["freq"], b["q"],
|
||||
b["type"] + (9 if b.get("bypass") else 0))
|
||||
|
||||
in_mute = out_mute = 0
|
||||
for i, ch in enumerate(state["inputs"]):
|
||||
o = 0x10 + i * model.in_size
|
||||
buf[o : o + 8] = pad(ch["name"], 8)
|
||||
gt = ch["gate"]
|
||||
struct.pack_into("<4H", buf, o + 8, gt["attack"], gt["release"], gt["hold"], gt["threshold"])
|
||||
struct.pack_into("<31H", buf, o + 16, *ch["geq"])
|
||||
put_peq(o + 78, ch["peq"])
|
||||
struct.pack_into("<HHBB", buf, o + 126, ch["hp"]["freq"], ch["lp"]["freq"],
|
||||
ch["hp"]["slope"], ch["lp"]["slope"])
|
||||
struct.pack_into("<4H", buf, o + 132, ch["gain"], int(ch["polarity"]), ch["delay"], ch.get("link", 1 << i))
|
||||
in_mute |= int(ch["mute"]) << i
|
||||
for i, ch in enumerate(state["outputs"]):
|
||||
o = model.out_base + i * model.out_size
|
||||
p = o + 10 + 2 * model.n_in
|
||||
buf[o : o + 8] = pad(ch["name"], 8)
|
||||
struct.pack_into("<H", buf, o + 8, ch["matrix"])
|
||||
struct.pack_into(f"<{model.n_in}H", buf, o + 10, *ch["mix"])
|
||||
struct.pack_into("<HHBB", buf, p, ch["hp"]["freq"], ch["lp"]["freq"],
|
||||
ch["hp"]["slope"], ch["lp"]["slope"])
|
||||
put_peq(p + 6, ch["peq"])
|
||||
c, lim = ch["comp"], ch["limit"]
|
||||
struct.pack_into("<5H", buf, p + 60, c["ratio"], c["attack"], c["release"], c["knee"],
|
||||
c["threshold"])
|
||||
struct.pack_into("<4H", buf, p + 70, lim["attack"], lim["release"], lim["knee"],
|
||||
lim["threshold"])
|
||||
struct.pack_into("<4H", buf, p + 78, ch["gain"], int(ch["polarity"]), ch["delay"], ch.get("link", 1 << i))
|
||||
out_mute |= int(ch["mute"]) << i
|
||||
struct.pack_into("<HH", buf, model.globals_base, in_mute, out_mute)
|
||||
return buf
|
||||
|
||||
|
||||
def default_state(model: Model) -> dict:
|
||||
peq = lambda n: [{"gain": 120, "freq": 50 + i * 25, "q": 32, "type": 0, "bypass": False}
|
||||
for i in range(n)]
|
||||
return {
|
||||
"preset_name": "Default",
|
||||
"inputs": [{
|
||||
"name": f"In{chr(65 + i)}", "gate": {"attack": 0, "release": 99, "hold": 99, "threshold": 0},
|
||||
"geq": [120] * 31, "peq": peq(8), "hp": {"freq": 0, "slope": 0},
|
||||
"lp": {"freq": 300, "slope": 0}, "gain": 280, "polarity": False, "delay": 0, "mute": False,
|
||||
"link": 1 << i,
|
||||
} for i in range(model.n_in)],
|
||||
"outputs": [{
|
||||
"name": f"Out{i + 1}", "matrix": 1 << (i % model.n_in), "mix": [280] * model.n_in,
|
||||
"hp": {"freq": 0, "slope": 0}, "lp": {"freq": 300, "slope": 0}, "peq": peq(9),
|
||||
"comp": {"ratio": 0, "attack": 49, "release": 499, "knee": 0, "threshold": 220},
|
||||
"limit": {"attack": 49, "release": 499, "knee": 0, "threshold": 220},
|
||||
"gain": 280, "polarity": False, "delay": 0, "mute": False, "link": 1 << i,
|
||||
} for i in range(model.n_out)],
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- channel links
|
||||
#
|
||||
# Every channel stores a u16 link mask (bit = channel index within inputs resp. outputs):
|
||||
# a free channel has only its own bit, the first channel of a group the bits of all members,
|
||||
# the other members 0. The DSP itself applies a change on any member to the whole group
|
||||
# (except name, routing and mix levels) and copies the first channel's settings when a group is formed.
|
||||
|
||||
LINK_EXCLUDED = ("name", "mix", "matrix", "link") # per channel even when linked (e.g. Out 1 <- A, Out 2 <- B)
|
||||
|
||||
|
||||
def link_groups(chans: list[dict]) -> list[list[int]]:
|
||||
"""Channel indices grouped by link (single channels included), in channel order."""
|
||||
seen: set[int] = set()
|
||||
groups = []
|
||||
for i, ch in enumerate(chans):
|
||||
if i in seen:
|
||||
continue
|
||||
mask = ch.get("link", 1 << i)
|
||||
g = [j for j in range(len(chans)) if (j == i or mask >> j & 1) and j not in seen]
|
||||
seen.update(g)
|
||||
groups.append(g)
|
||||
return groups
|
||||
|
||||
|
||||
def link_group(chans: list[dict], idx: int) -> list[int]:
|
||||
return next(g for g in link_groups(chans) if idx in g)
|
||||
|
||||
|
||||
def link_masks(n: int, groups: list[list[int]]) -> list[int]:
|
||||
"""Per-channel link masks for the given groups (channels not mentioned stay free)."""
|
||||
masks = [1 << i for i in range(n)]
|
||||
for g in groups:
|
||||
g = sorted({i for i in g if 0 <= i < n})
|
||||
if len(g) < 2:
|
||||
continue
|
||||
masks[g[0]] = sum(1 << i for i in g)
|
||||
for i in g[1:]:
|
||||
masks[i] = 0
|
||||
return masks
|
||||
|
||||
|
||||
def copy_linked(chans: list[dict], src: int, dst: int):
|
||||
for k, v in chans[src].items():
|
||||
if k not in LINK_EXCLUDED:
|
||||
chans[dst][k] = copy.deepcopy(v)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- parameter -> command
|
||||
|
||||
|
||||
def _w(v: int) -> bytes:
|
||||
return struct.pack("<H", int(v) & 0xFFFF)
|
||||
|
||||
|
||||
def param_command(model: Model, kind: str, idx: int, ch: dict, param: str) -> tuple[int, bytes]:
|
||||
"""Build (cmd, payload) for a changed parameter. `ch` is the already-updated channel dict.
|
||||
|
||||
`param` is a dotted path like "gain", "hp.freq", "peq.3.gain", "geq.10", "mix.1".
|
||||
"""
|
||||
c = model.channel(kind, idx)
|
||||
top, *rest = param.split(".")
|
||||
if top == "gain":
|
||||
return CMD_GAIN, bytes([c]) + _w(ch["gain"])
|
||||
if top == "mute":
|
||||
return CMD_MUTE, bytes([c, int(ch["mute"])])
|
||||
if top == "polarity":
|
||||
return CMD_POLARITY, bytes([c, int(ch["polarity"])])
|
||||
if top == "delay":
|
||||
return CMD_DELAY, bytes([c]) + _w(ch["delay"])
|
||||
if top == "name":
|
||||
return CMD_CHANNEL_NAME, bytes([c]) + clean_name(ch["name"]).encode("ascii").ljust(8, b" ")
|
||||
if top in ("hp", "lp"):
|
||||
f = ch[top]
|
||||
return (CMD_HIGH_PASS if top == "hp" else CMD_LOW_PASS), bytes([c]) + _w(f["freq"]) + bytes([f["slope"]])
|
||||
if top == "peq":
|
||||
band = int(rest[0])
|
||||
b = ch["peq"][band]
|
||||
return CMD_PEQ, bytes([c, band]) + _w(b["gain"]) + _w(b["freq"]) + bytes(
|
||||
[b["q"], b["type"], int(b["bypass"])])
|
||||
if top == "geq" and kind == "in":
|
||||
band = int(rest[0])
|
||||
return CMD_GEQ, bytes([c, band]) + _w(ch["geq"][band])
|
||||
if top == "gate" and kind == "in":
|
||||
g = ch["gate"]
|
||||
return CMD_GATE, bytes([c]) + b"".join(_w(g[k]) for k in ("attack", "release", "hold", "threshold"))
|
||||
if top == "comp" and kind == "out":
|
||||
g = ch["comp"]
|
||||
return CMD_COMP, bytes([c]) + b"".join(
|
||||
_w(g[k]) for k in ("ratio", "attack", "release", "knee", "threshold"))
|
||||
if top == "limit" and kind == "out":
|
||||
g = ch["limit"]
|
||||
return CMD_LIMIT, bytes([c]) + b"".join(_w(g[k]) for k in ("attack", "release", "knee", "threshold"))
|
||||
if top == "matrix" and kind == "out":
|
||||
return CMD_MATRIX, bytes([c, ch["matrix"] & 0xFF])
|
||||
if top == "mix" and kind == "out":
|
||||
i = int(rest[0])
|
||||
return CMD_MIX, bytes([c, i]) + _w(ch["mix"][i])
|
||||
raise ValueError(f"unknown parameter {kind}.{param}")
|
||||
|
||||
|
||||
def apply_param(state_ch: dict, param: str, value):
|
||||
"""Write `value` into the channel dict at the dotted `param` path."""
|
||||
keys = param.split(".")
|
||||
node = state_ch
|
||||
for k in keys[:-1]:
|
||||
node = node[int(k)] if isinstance(node, list) else node[k]
|
||||
last = keys[-1]
|
||||
if isinstance(node, list):
|
||||
node[int(last)] = value
|
||||
else:
|
||||
node[last] = value
|
||||
|
||||
|
||||
def apply_command(model: Model, state: dict, cmd: int, p: bytes):
|
||||
"""Update state from an incoming set command (used by the simulator)."""
|
||||
if not p:
|
||||
return
|
||||
c = p[0]
|
||||
kind, idx = ("in", c) if c < model.n_in else ("out", c - model.n_in)
|
||||
chans = state["inputs" if kind == "in" else "outputs"]
|
||||
if idx >= len(chans):
|
||||
return
|
||||
ch = chans[idx]
|
||||
w = lambda o: struct.unpack_from("<H", p, o)[0]
|
||||
if cmd == CMD_GAIN:
|
||||
ch["gain"] = w(1)
|
||||
elif cmd == CMD_MUTE:
|
||||
ch["mute"] = bool(p[1])
|
||||
elif cmd == CMD_POLARITY:
|
||||
ch["polarity"] = bool(p[1])
|
||||
elif cmd == CMD_DELAY:
|
||||
ch["delay"] = w(1)
|
||||
elif cmd == CMD_CHANNEL_NAME:
|
||||
ch["name"] = _name(p[1:9])
|
||||
elif cmd in (CMD_HIGH_PASS, CMD_LOW_PASS):
|
||||
ch["hp" if cmd == CMD_HIGH_PASS else "lp"] = {"freq": w(1), "slope": p[3]}
|
||||
elif cmd == CMD_PEQ:
|
||||
ch["peq"][p[1]] = {"gain": w(2), "freq": w(4), "q": p[6], "type": p[7], "bypass": bool(p[8])}
|
||||
elif cmd == CMD_GEQ:
|
||||
ch["geq"][p[1]] = w(2)
|
||||
elif cmd == CMD_GATE:
|
||||
ch["gate"] = dict(zip(("attack", "release", "hold", "threshold"), struct.unpack_from("<4H", p, 1)))
|
||||
elif cmd == CMD_COMP:
|
||||
ch["comp"] = dict(zip(("ratio", "attack", "release", "knee", "threshold"),
|
||||
struct.unpack_from("<5H", p, 1)))
|
||||
elif cmd == CMD_LIMIT:
|
||||
ch["limit"] = dict(zip(("attack", "release", "knee", "threshold"), struct.unpack_from("<4H", p, 1)))
|
||||
elif cmd == CMD_MATRIX:
|
||||
ch["matrix"] = p[1]
|
||||
elif cmd == CMD_MIX:
|
||||
ch["mix"][p[1]] = w(2)
|
||||
elif cmd == CMD_LINK:
|
||||
ch["link"] = w(1)
|
||||
for j in range(len(chans)): # forming a group copies the first channel's settings
|
||||
if j != idx and ch["link"] >> j & 1:
|
||||
copy_linked(chans, idx, j)
|
||||
return
|
||||
# like the real DSP: a change on a linked channel applies to the whole group
|
||||
for j in link_group(chans, idx):
|
||||
if j != idx:
|
||||
copy_linked(chans, idx, j)
|
||||
+431
@@ -0,0 +1,431 @@
|
||||
"""USB connection to the DSPs (USB HID, no driver needed).
|
||||
|
||||
Both models enumerate as VID 0x0168 / PID 0x0821.
|
||||
Every HID report carries exactly one protocol frame starting at byte 0 (the same frames as on TCP,
|
||||
length = LEN + 8), sent with report ID 0 and zero-padded to the report length.
|
||||
|
||||
Windows uses hid.dll via ctypes, macOS IOKit via ctypes, Linux /dev/hidraw* (Raspberry Pi). No extra packages.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
|
||||
VID, PID = 0x0168, 0x0821
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ Windows (hid.dll)
|
||||
|
||||
if sys.platform == "win32":
|
||||
import ctypes
|
||||
from ctypes import wintypes as W
|
||||
|
||||
_hid = ctypes.WinDLL("hid")
|
||||
_setup = ctypes.WinDLL("setupapi")
|
||||
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
|
||||
class _GUID(ctypes.Structure):
|
||||
_fields_ = [("d1", W.DWORD), ("d2", W.WORD), ("d3", W.WORD), ("d4", ctypes.c_ubyte * 8)]
|
||||
|
||||
class _IFDATA(ctypes.Structure):
|
||||
_fields_ = [("cbSize", W.DWORD), ("guid", _GUID), ("flags", W.DWORD), ("reserved", ctypes.c_void_p)]
|
||||
|
||||
class _ATTR(ctypes.Structure):
|
||||
_fields_ = [("Size", W.ULONG), ("VendorID", W.USHORT), ("ProductID", W.USHORT), ("Version", W.USHORT)]
|
||||
|
||||
class _CAPS(ctypes.Structure):
|
||||
_fields_ = [("Usage", W.USHORT), ("UsagePage", W.USHORT), ("InputReportByteLength", W.USHORT),
|
||||
("OutputReportByteLength", W.USHORT), ("FeatureReportByteLength", W.USHORT),
|
||||
("Reserved", W.USHORT * 17), ("rest", W.USHORT * 10)]
|
||||
|
||||
_k32.CreateFileW.restype = W.HANDLE
|
||||
_k32.CreateFileW.argtypes = [W.LPCWSTR, W.DWORD, W.DWORD, ctypes.c_void_p, W.DWORD, W.DWORD, W.HANDLE]
|
||||
_k32.ReadFile.argtypes = [W.HANDLE, ctypes.c_void_p, W.DWORD, ctypes.POINTER(W.DWORD), ctypes.c_void_p]
|
||||
_k32.WriteFile.argtypes = [W.HANDLE, ctypes.c_void_p, W.DWORD, ctypes.POINTER(W.DWORD), ctypes.c_void_p]
|
||||
_k32.CloseHandle.argtypes = [W.HANDLE]
|
||||
_k32.CancelIoEx.argtypes = [W.HANDLE, ctypes.c_void_p]
|
||||
_setup.SetupDiGetClassDevsW.restype = W.HANDLE
|
||||
_setup.SetupDiGetClassDevsW.argtypes = [ctypes.POINTER(_GUID), W.LPCWSTR, W.HWND, W.DWORD]
|
||||
_setup.SetupDiEnumDeviceInterfaces.argtypes = [W.HANDLE, ctypes.c_void_p, ctypes.POINTER(_GUID), W.DWORD,
|
||||
ctypes.POINTER(_IFDATA)]
|
||||
_setup.SetupDiGetDeviceInterfaceDetailW.argtypes = [W.HANDLE, ctypes.POINTER(_IFDATA), ctypes.c_void_p, W.DWORD,
|
||||
ctypes.POINTER(W.DWORD), ctypes.c_void_p]
|
||||
_setup.SetupDiDestroyDeviceInfoList.argtypes = [W.HANDLE]
|
||||
_hid.HidD_GetAttributes.argtypes = [W.HANDLE, ctypes.POINTER(_ATTR)]
|
||||
_hid.HidD_GetProductString.argtypes = [W.HANDLE, ctypes.c_void_p, W.ULONG]
|
||||
_hid.HidD_GetSerialNumberString.argtypes = [W.HANDLE, ctypes.c_void_p, W.ULONG]
|
||||
_hid.HidD_GetPreparsedData.argtypes = [W.HANDLE, ctypes.POINTER(ctypes.c_void_p)]
|
||||
_hid.HidD_FreePreparsedData.argtypes = [ctypes.c_void_p]
|
||||
_hid.HidP_GetCaps.argtypes = [ctypes.c_void_p, ctypes.POINTER(_CAPS)]
|
||||
|
||||
_INVALID = W.HANDLE(-1).value
|
||||
_GENERIC_RW, _SHARE_RW, _OPEN_EXISTING = 0xC0000000, 0x3, 3
|
||||
|
||||
def _open(path: str, access: int = _GENERIC_RW):
|
||||
h = _k32.CreateFileW(path, access, _SHARE_RW, None, _OPEN_EXISTING, 0, None)
|
||||
if h in (None, _INVALID):
|
||||
raise OSError(ctypes.get_last_error(), f"Cannot open USB device (error {ctypes.get_last_error()})")
|
||||
return h
|
||||
|
||||
def _string(fn, h) -> str:
|
||||
buf = ctypes.create_unicode_buffer(128)
|
||||
return buf.value if fn(h, buf, ctypes.sizeof(buf)) else ""
|
||||
|
||||
def _paths() -> list[str]:
|
||||
guid = _GUID()
|
||||
_hid.HidD_GetHidGuid(ctypes.byref(guid))
|
||||
info = _setup.SetupDiGetClassDevsW(ctypes.byref(guid), None, None, 0x12) # PRESENT | DEVICEINTERFACE
|
||||
paths = []
|
||||
try:
|
||||
i = 0
|
||||
while True:
|
||||
ifd = _IFDATA(cbSize=ctypes.sizeof(_IFDATA))
|
||||
if not _setup.SetupDiEnumDeviceInterfaces(info, None, ctypes.byref(guid), i, ctypes.byref(ifd)):
|
||||
break
|
||||
i += 1
|
||||
need = W.DWORD()
|
||||
_setup.SetupDiGetDeviceInterfaceDetailW(info, ctypes.byref(ifd), None, 0, ctypes.byref(need), None)
|
||||
buf = ctypes.create_string_buffer(need.value)
|
||||
ctypes.cast(buf, ctypes.POINTER(W.DWORD))[0] = 8 if ctypes.sizeof(ctypes.c_void_p) == 8 else 6
|
||||
if _setup.SetupDiGetDeviceInterfaceDetailW(info, ctypes.byref(ifd), buf, need, None, None):
|
||||
paths.append(ctypes.wstring_at(ctypes.addressof(buf) + 4))
|
||||
finally:
|
||||
_setup.SetupDiDestroyDeviceInfoList(info)
|
||||
return paths
|
||||
|
||||
def list_devices() -> list[dict]:
|
||||
found = []
|
||||
for path in _paths():
|
||||
try:
|
||||
h = _open(path, 0) # attributes only: works even while another program has it open
|
||||
except OSError:
|
||||
continue
|
||||
try:
|
||||
a = _ATTR(Size=ctypes.sizeof(_ATTR))
|
||||
if _hid.HidD_GetAttributes(h, ctypes.byref(a)) and (a.VendorID, a.ProductID) == (VID, PID):
|
||||
found.append({"path": path, "product": _string(_hid.HidD_GetProductString, h),
|
||||
"serial": _string(_hid.HidD_GetSerialNumberString, h)})
|
||||
finally:
|
||||
_k32.CloseHandle(h)
|
||||
return found
|
||||
|
||||
class HidDevice:
|
||||
"""One opened DSP. Separate read and write handles: a blocking ReadFile would otherwise
|
||||
serialise every WriteFile behind it on a synchronous handle."""
|
||||
|
||||
def __init__(self, path: str):
|
||||
self.rh = _open(path)
|
||||
try:
|
||||
self.wh = _open(path)
|
||||
pp = ctypes.c_void_p()
|
||||
caps = _CAPS()
|
||||
if _hid.HidD_GetPreparsedData(self.rh, ctypes.byref(pp)):
|
||||
_hid.HidP_GetCaps(pp, ctypes.byref(caps))
|
||||
_hid.HidD_FreePreparsedData(pp)
|
||||
self.in_len = caps.InputReportByteLength or 65
|
||||
self.out_len = caps.OutputReportByteLength or 65
|
||||
except OSError:
|
||||
_k32.CloseHandle(self.rh)
|
||||
raise
|
||||
|
||||
def read_report(self) -> bytes:
|
||||
buf = ctypes.create_string_buffer(self.in_len)
|
||||
n = W.DWORD()
|
||||
if not _k32.ReadFile(self.rh, buf, self.in_len, ctypes.byref(n), None):
|
||||
raise OSError(ctypes.get_last_error(), "USB connection lost")
|
||||
return buf.raw[1:n.value] # drop the report ID
|
||||
|
||||
def write_report(self, data: bytes):
|
||||
report = (b"\x00" + data).ljust(self.out_len, b"\x00")[: self.out_len]
|
||||
n = W.DWORD()
|
||||
if not _k32.WriteFile(self.wh, report, len(report), ctypes.byref(n), None):
|
||||
raise OSError(ctypes.get_last_error(), "USB write error")
|
||||
|
||||
def close(self):
|
||||
_k32.CancelIoEx(self.rh, None) # wakes up the blocked reader thread
|
||||
for h in (self.rh, self.wh):
|
||||
_k32.CloseHandle(h)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ Linux (hidraw)
|
||||
|
||||
elif sys.platform.startswith("linux"):
|
||||
|
||||
def list_devices() -> list[dict]:
|
||||
found = []
|
||||
base = "/sys/class/hidraw"
|
||||
for name in sorted(os.listdir(base)) if os.path.isdir(base) else []:
|
||||
try:
|
||||
with open(f"{base}/{name}/device/uevent") as f:
|
||||
ev = dict(line.strip().split("=", 1) for line in f if "=" in line)
|
||||
except OSError:
|
||||
continue
|
||||
ids = ev.get("HID_ID", "").split(":")
|
||||
if len(ids) == 3 and int(ids[1], 16) == VID and int(ids[2], 16) == PID:
|
||||
found.append({"path": f"/dev/{name}", "product": ev.get("HID_NAME", ""), "serial": ev.get("HID_UNIQ", "")})
|
||||
return found
|
||||
|
||||
class HidDevice:
|
||||
def __init__(self, path: str):
|
||||
self.fd = os.open(path, os.O_RDWR)
|
||||
self.in_len = self.out_len = 65
|
||||
|
||||
def read_report(self) -> bytes:
|
||||
data = os.read(self.fd, 64) # hidraw returns the report without a report ID
|
||||
if not data:
|
||||
raise OSError("USB connection lost")
|
||||
return data
|
||||
|
||||
def write_report(self, data: bytes):
|
||||
os.write(self.fd, (b"\x00" + data).ljust(self.out_len, b"\x00"))
|
||||
|
||||
def close(self):
|
||||
try:
|
||||
os.close(self.fd)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# ------------------------------------------------------------------ macOS (IOKit IOHIDDevice)
|
||||
|
||||
elif sys.platform == "darwin":
|
||||
import ctypes
|
||||
import queue
|
||||
|
||||
_iokit = ctypes.cdll.LoadLibrary("/System/Library/Frameworks/IOKit.framework/IOKit")
|
||||
_cf = ctypes.cdll.LoadLibrary("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")
|
||||
_vp, _i32 = ctypes.c_void_p, ctypes.c_int32
|
||||
|
||||
_UTF8, _SINT32, _SINT64 = 0x08000100, 3, 4
|
||||
_REPORT_OUTPUT = 1
|
||||
_ReportCB = ctypes.CFUNCTYPE(None, _vp, _i32, _vp, ctypes.c_int, ctypes.c_uint32,
|
||||
ctypes.POINTER(ctypes.c_uint8), ctypes.c_long)
|
||||
_RemovalCB = ctypes.CFUNCTYPE(None, _vp, _i32, _vp)
|
||||
|
||||
for _name, _res, _args in (
|
||||
("CFStringCreateWithCString", _vp, [_vp, ctypes.c_char_p, ctypes.c_uint32]),
|
||||
("CFStringGetCString", ctypes.c_bool, [_vp, ctypes.c_char_p, ctypes.c_long, ctypes.c_uint32]),
|
||||
("CFNumberCreate", _vp, [_vp, ctypes.c_int, _vp]),
|
||||
("CFNumberGetValue", ctypes.c_bool, [_vp, ctypes.c_int, _vp]),
|
||||
("CFGetTypeID", ctypes.c_ulong, [_vp]),
|
||||
("CFStringGetTypeID", ctypes.c_ulong, []),
|
||||
("CFNumberGetTypeID", ctypes.c_ulong, []),
|
||||
("CFDictionaryCreateMutable", _vp, [_vp, ctypes.c_long, _vp, _vp]),
|
||||
("CFDictionarySetValue", None, [_vp, _vp, _vp]),
|
||||
("CFSetGetCount", ctypes.c_long, [_vp]),
|
||||
("CFSetGetValues", None, [_vp, _vp]),
|
||||
("CFRetain", _vp, [_vp]),
|
||||
("CFRelease", None, [_vp]),
|
||||
("CFRunLoopGetCurrent", _vp, []),
|
||||
("CFRunLoopRunInMode", _i32, [_vp, ctypes.c_double, ctypes.c_bool]),
|
||||
("CFRunLoopStop", None, [_vp]),
|
||||
):
|
||||
getattr(_cf, _name).restype, getattr(_cf, _name).argtypes = _res, _args
|
||||
for _name, _res, _args in (
|
||||
("IOHIDManagerCreate", _vp, [_vp, ctypes.c_uint32]),
|
||||
("IOHIDManagerSetDeviceMatching", None, [_vp, _vp]),
|
||||
("IOHIDManagerCopyDevices", _vp, [_vp]),
|
||||
("IOHIDDeviceGetProperty", _vp, [_vp, _vp]),
|
||||
("IOHIDDeviceOpen", _i32, [_vp, ctypes.c_uint32]),
|
||||
("IOHIDDeviceClose", _i32, [_vp, ctypes.c_uint32]),
|
||||
("IOHIDDeviceSetReport", _i32, [_vp, ctypes.c_int, ctypes.c_long, _vp, ctypes.c_long]),
|
||||
("IOHIDDeviceRegisterInputReportCallback", None, [_vp, _vp, ctypes.c_long, _ReportCB, _vp]),
|
||||
("IOHIDDeviceRegisterRemovalCallback", None, [_vp, _RemovalCB, _vp]),
|
||||
("IOHIDDeviceScheduleWithRunLoop", None, [_vp, _vp, _vp]),
|
||||
("IOHIDDeviceUnscheduleFromRunLoop", None, [_vp, _vp, _vp]),
|
||||
):
|
||||
getattr(_iokit, _name).restype, getattr(_iokit, _name).argtypes = _res, _args
|
||||
|
||||
_MODE = _vp.in_dll(_cf, "kCFRunLoopDefaultMode")
|
||||
_KEY_CB = _vp.in_dll(_cf, "kCFTypeDictionaryKeyCallBacks")
|
||||
_VAL_CB = _vp.in_dll(_cf, "kCFTypeDictionaryValueCallBacks")
|
||||
|
||||
def _cfstr(s: str):
|
||||
return _cf.CFStringCreateWithCString(None, s.encode(), _UTF8)
|
||||
|
||||
def _prop(dev, key: str):
|
||||
k = _cfstr(key)
|
||||
try:
|
||||
v = _iokit.IOHIDDeviceGetProperty(dev, k)
|
||||
finally:
|
||||
_cf.CFRelease(k)
|
||||
if not v:
|
||||
return None
|
||||
if _cf.CFGetTypeID(v) == _cf.CFNumberGetTypeID():
|
||||
n = ctypes.c_int64()
|
||||
_cf.CFNumberGetValue(v, _SINT64, ctypes.byref(n))
|
||||
return n.value
|
||||
if _cf.CFGetTypeID(v) == _cf.CFStringGetTypeID():
|
||||
buf = ctypes.create_string_buffer(256)
|
||||
return buf.value.decode(errors="replace") if _cf.CFStringGetCString(v, buf, 256, _UTF8) else ""
|
||||
return None
|
||||
|
||||
def _path(dev) -> str:
|
||||
# LocationID identifies the USB port, so a saved device is found again after replugging
|
||||
return f"usb-loc:{(_prop(dev, 'LocationID') or 0) & 0xFFFFFFFF:08x}"
|
||||
|
||||
def _devices() -> list:
|
||||
"""Retained IOHIDDeviceRefs of all connected DSPs (caller releases them)."""
|
||||
mgr = _iokit.IOHIDManagerCreate(None, 0)
|
||||
match = _cf.CFDictionaryCreateMutable(None, 0, ctypes.byref(_KEY_CB), ctypes.byref(_VAL_CB))
|
||||
try:
|
||||
for key, val in (("VendorID", VID), ("ProductID", PID)):
|
||||
k, n = _cfstr(key), ctypes.c_int32(val)
|
||||
v = _cf.CFNumberCreate(None, _SINT32, ctypes.byref(n))
|
||||
_cf.CFDictionarySetValue(match, k, v)
|
||||
_cf.CFRelease(k)
|
||||
_cf.CFRelease(v)
|
||||
_iokit.IOHIDManagerSetDeviceMatching(mgr, match)
|
||||
devset = _iokit.IOHIDManagerCopyDevices(mgr)
|
||||
if not devset:
|
||||
return []
|
||||
count = _cf.CFSetGetCount(devset)
|
||||
arr = (_vp * count)()
|
||||
_cf.CFSetGetValues(devset, arr)
|
||||
devs = [_cf.CFRetain(d) for d in arr]
|
||||
_cf.CFRelease(devset)
|
||||
return sorted(devs, key=_path)
|
||||
finally:
|
||||
_cf.CFRelease(match)
|
||||
_cf.CFRelease(mgr)
|
||||
|
||||
def list_devices() -> list[dict]:
|
||||
found = []
|
||||
for dev in _devices():
|
||||
found.append({"path": _path(dev), "product": _prop(dev, "Product") or "",
|
||||
"serial": _prop(dev, "SerialNumber") or ""})
|
||||
_cf.CFRelease(dev)
|
||||
return found
|
||||
|
||||
class HidDevice:
|
||||
"""One opened DSP. IOKit delivers input reports through a run loop, so a private thread
|
||||
runs one and hands the reports to read_report() through a queue."""
|
||||
|
||||
def __init__(self, path: str):
|
||||
devs = _devices()
|
||||
self.dev = next((d for d in devs if _path(d) == path), None)
|
||||
for d in devs:
|
||||
if d != self.dev:
|
||||
_cf.CFRelease(d)
|
||||
if not self.dev:
|
||||
raise OSError("USB device not found – check the cable")
|
||||
ret = _iokit.IOHIDDeviceOpen(self.dev, 0) & 0xFFFFFFFF
|
||||
if ret:
|
||||
_cf.CFRelease(self.dev)
|
||||
raise OSError(ret, "USB device is in use by another program" if ret == 0xE00002C5
|
||||
else f"Cannot open USB device (error 0x{ret:08x})")
|
||||
self.in_len = _prop(self.dev, "MaxInputReportSize") or 64
|
||||
self.out_len = _prop(self.dev, "MaxOutputReportSize") or 64
|
||||
self.reports: queue.Queue = queue.Queue()
|
||||
self.closed = False
|
||||
self.runloop = None
|
||||
self.buf = (ctypes.c_uint8 * self.in_len)()
|
||||
self._on_report = _ReportCB(lambda _c, _r, _s, _t, _id, data, n: self.reports.put(ctypes.string_at(data, n)))
|
||||
self._on_removal = _RemovalCB(lambda _c, _r, _s: self.reports.put(None))
|
||||
ready = threading.Event()
|
||||
threading.Thread(target=self._run, args=(ready,), daemon=True, name="usb-runloop").start()
|
||||
ready.wait(5)
|
||||
|
||||
def _run(self, ready: threading.Event):
|
||||
self.runloop = _cf.CFRunLoopGetCurrent()
|
||||
_iokit.IOHIDDeviceRegisterInputReportCallback(self.dev, self.buf, self.in_len, self._on_report, None)
|
||||
_iokit.IOHIDDeviceRegisterRemovalCallback(self.dev, self._on_removal, None)
|
||||
_iokit.IOHIDDeviceScheduleWithRunLoop(self.dev, self.runloop, _MODE)
|
||||
ready.set()
|
||||
while not self.closed:
|
||||
_cf.CFRunLoopRunInMode(_MODE, 0.5, False)
|
||||
_iokit.IOHIDDeviceUnscheduleFromRunLoop(self.dev, self.runloop, _MODE)
|
||||
_iokit.IOHIDDeviceClose(self.dev, 0)
|
||||
_cf.CFRelease(self.dev)
|
||||
|
||||
def read_report(self) -> bytes:
|
||||
data = self.reports.get()
|
||||
if data is None:
|
||||
raise OSError("USB connection lost")
|
||||
return data # IOKit delivers the report without a report ID
|
||||
|
||||
def write_report(self, data: bytes):
|
||||
report = data.ljust(self.out_len, b"\x00")[: self.out_len]
|
||||
ret = _iokit.IOHIDDeviceSetReport(self.dev, _REPORT_OUTPUT, 0, report, len(report)) & 0xFFFFFFFF
|
||||
if ret:
|
||||
raise OSError(ret, f"USB write error (0x{ret:08x})")
|
||||
|
||||
def close(self):
|
||||
if not self.closed:
|
||||
self.closed = True
|
||||
self.reports.put(None) # wakes up the blocked reader thread
|
||||
if self.runloop:
|
||||
_cf.CFRunLoopStop(self.runloop)
|
||||
|
||||
else:
|
||||
def list_devices() -> list[dict]:
|
||||
return []
|
||||
|
||||
class HidDevice:
|
||||
def __init__(self, path: str):
|
||||
raise OSError("USB is not supported on this system")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ asyncio stream adapter
|
||||
|
||||
def frame_bytes(report: bytes, carry: list) -> bytes:
|
||||
"""The protocol bytes in one input report (strips the zero padding after the frame).
|
||||
`carry` holds the bytes still missing from a frame longer than one report."""
|
||||
if carry[0] > 0:
|
||||
take = report[: carry[0]]
|
||||
carry[0] -= len(take)
|
||||
return take
|
||||
if report[:2] != b"\x10\x02" or len(report) < 5:
|
||||
return b""
|
||||
need = report[4] + 8
|
||||
take = report[:need]
|
||||
carry[0] = need - len(take)
|
||||
return take
|
||||
|
||||
|
||||
class HidStream:
|
||||
"""Gives a HID device the reader/writer interface Device uses for TCP."""
|
||||
|
||||
def __init__(self, dev):
|
||||
self.dev = dev
|
||||
self.loop = asyncio.get_running_loop()
|
||||
self.queue: asyncio.Queue = asyncio.Queue()
|
||||
self.closed = False
|
||||
threading.Thread(target=self._reader, daemon=True, name="usb-read").start()
|
||||
|
||||
def _reader(self):
|
||||
carry = [0]
|
||||
try:
|
||||
while not self.closed:
|
||||
data = frame_bytes(self.dev.read_report(), carry)
|
||||
if data:
|
||||
self.loop.call_soon_threadsafe(self.queue.put_nowait, data)
|
||||
except OSError:
|
||||
pass
|
||||
self.loop.call_soon_threadsafe(self.queue.put_nowait, b"") # EOF
|
||||
|
||||
async def read(self, _n: int = -1) -> bytes:
|
||||
return await self.queue.get()
|
||||
|
||||
def write(self, data: bytes):
|
||||
self.dev.write_report(data)
|
||||
|
||||
async def drain(self):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
if not self.closed:
|
||||
self.closed = True
|
||||
self.dev.close()
|
||||
|
||||
|
||||
async def open_stream(path: str = "") -> tuple[HidStream, HidStream]:
|
||||
"""Open the DSP at `path` (empty = the first one found)."""
|
||||
if not path:
|
||||
devs = await asyncio.to_thread(list_devices)
|
||||
if not devs:
|
||||
raise ConnectionError("No DSP found via USB – check the cable")
|
||||
path = devs[0]["path"]
|
||||
dev = await asyncio.to_thread(HidDevice, path)
|
||||
s = HidStream(dev)
|
||||
return s, s
|
||||
Reference in new issue
Block a user