Files
BetterDSPControl/dsp/usbhid.py
T
GivouandClaude Opus 5.5 fe13f261f7 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>
2026-11-01 20:24:33 +01:00

432 lines
18 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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