Files
MrBlakeandClaude Opus 5.5 7e276912da K65 Studio: Linux control app for the Corsair K65 PLUS Wireless
Bragi protocol over hidraw, device service with heartbeat and
notifications, PySide6 UI with animated preview, profiles, tray,
autostart, udev rule and installer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 21:02:59 +02:00

91 lines
2.7 KiB
Python

"""Minimal hidraw transport and device discovery (Linux only, no external deps)."""
from __future__ import annotations
import os
import re
import select
from dataclasses import dataclass
from pathlib import Path
REPORT_SIZE = 64
SYSFS_HIDRAW = Path("/sys/class/hidraw")
@dataclass(frozen=True)
class HidrawInfo:
path: str # /dev/hidrawN
vendor_id: int
product_id: int
interface: int # USB bInterfaceNumber, -1 if unknown (e.g. Bluetooth)
name: str
bus: int # 3 = USB, 5 = Bluetooth
def enumerate_hidraw(vendor_id: int | None = None) -> list[HidrawInfo]:
devices: list[HidrawInfo] = []
if not SYSFS_HIDRAW.exists():
return devices
for entry in sorted(SYSFS_HIDRAW.iterdir()):
try:
uevent = (entry / "device" / "uevent").read_text()
except OSError:
continue
fields = dict(line.split("=", 1) for line in uevent.splitlines() if "=" in line)
hid_id = fields.get("HID_ID", "")
m = re.fullmatch(r"([0-9A-Fa-f]+):([0-9A-Fa-f]+):([0-9A-Fa-f]+)", hid_id)
if not m:
continue
bus, vid, pid = (int(x, 16) for x in m.groups())
if vendor_id is not None and vid != vendor_id:
continue
# .../1-2:1.1/0003:1B1C:2B07.0002 -> interface 1
real = os.path.realpath(entry / "device")
im = re.search(r":\d+\.(\d+)/[^/]+$", real)
devices.append(HidrawInfo(
path=f"/dev/{entry.name}",
vendor_id=vid,
product_id=pid,
interface=int(im.group(1)) if im else -1,
name=fields.get("HID_NAME", ""),
bus=bus,
))
return devices
class Hidraw:
"""A raw HID device without numbered reports (report id byte 0 is stripped by the kernel)."""
def __init__(self, path: str):
self.path = path
self.fd = os.open(path, os.O_RDWR | os.O_NONBLOCK)
def close(self) -> None:
if self.fd >= 0:
os.close(self.fd)
self.fd = -1
def write(self, data: bytes) -> None:
if len(data) > REPORT_SIZE:
raise ValueError(f"report too long: {len(data)} > {REPORT_SIZE}")
os.write(self.fd, b"\x00" + data.ljust(REPORT_SIZE, b"\x00"))
def read(self, timeout: float) -> bytes | None:
ready, _, _ = select.select([self.fd], [], [], timeout)
if not ready:
return None
try:
return os.read(self.fd, REPORT_SIZE)
except BlockingIOError:
return None
def drain(self) -> None:
while self.read(0) is not None:
pass
def __enter__(self) -> "Hidraw":
return self
def __exit__(self, *exc) -> None:
self.close()