Files
CosairRGBforCachy/k65studio/device.py
T
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

382 lines
14 KiB
Python

"""K65 PLUS Wireless device service.
A background thread owns the hidraw handles. It finds the Slipstream receiver (or a wired
keyboard), keeps the keyboard in software mode with heartbeats, applies profiles and reports
state changes through a callback.
"""
from __future__ import annotations
import logging
import queue
import struct
import threading
import time
from dataclasses import dataclass, field, replace
from typing import Callable
from . import bragi, effects
from .hidraw import Hidraw, enumerate_hidraw
from .profiles import Profile
log = logging.getLogger(__name__)
HEARTBEAT_INTERVAL = 10.0
DISCOVERY_INTERVAL = 2.0
RECONNECT_DELAY = 3.0
TIMEOUT = 0.5
class DeviceError(Exception):
pass
class PermissionProblem(DeviceError):
pass
@dataclass(frozen=True)
class DeviceState:
receiver: bool = False # receiver (or wired keyboard) present and opened
keyboard: bool = False # keyboard reachable
wireless: bool = True
battery: int | None = None # percent
keyboard_firmware: str = ""
receiver_firmware: str = ""
serial: str = ""
error: str = ""
class Transport:
def __init__(self, path: str):
self.dev = Hidraw(path)
self.lock = threading.Lock()
def close(self) -> None:
self.dev.close()
def transfer(self, pkt: bytes, timeout: float = TIMEOUT) -> bytes:
with self.lock:
self.dev.drain()
self.dev.write(pkt)
deadline = time.monotonic() + timeout
while (left := deadline - time.monotonic()) > 0:
resp = self.dev.read(left)
if resp and resp[0] == pkt[0] and resp[1] == pkt[1]:
return resp
raise DeviceError(f"no response to {pkt[:4].hex(' ')}")
def command(self, pkt: bytes, timeout: float = TIMEOUT) -> bytes:
resp = self.transfer(pkt, timeout)
if resp[2] != 0:
raise DeviceError(f"status {resp[2]:#04x} for {pkt[:4].hex(' ')}")
return resp
class Keyboard:
"""Commands for the keyboard, addressed through `target` on `transport`."""
def __init__(self, transport: Transport, target: int):
self.t = transport
self.target = target
def heartbeat(self) -> None:
self.t.command(bragi.packet(self.target, bragi.CMD_HEARTBEAT))
def set_mode(self, mode: int) -> None:
self.t.command(bragi.set_property(self.target, bragi.PROP_MODE, bytes([mode])))
def battery(self) -> int:
resp = self.t.command(bragi.get_property(self.target, bragi.PROP_BATTERY))
return round(bragi.parse_u16(resp) / 10)
def firmware(self) -> str:
return bragi.parse_firmware(self.t.command(bragi.get_property(self.target, bragi.PROP_FIRMWARE)))
def brightness(self, percent: int) -> None:
value = struct.pack("<H", max(0, min(100, percent)) * 10)
self.t.command(bragi.set_property(self.target, bragi.PROP_BRIGHTNESS, value))
def sleep_timer(self, minutes: int) -> None:
value = struct.pack("<I", max(1, minutes) * 60_000)
self.t.command(bragi.set_property(self.target, bragi.PROP_SLEEP, value))
def locks(self, game_mode: bool, flags: int) -> None:
self.t.command(bragi.set_property(self.target, bragi.PROP_LOCKS, bytes([flags if game_mode else 0])))
self.t.command(bragi.set_property(self.target, bragi.PROP_GAME_MODE, bytes([int(game_mode)])))
def _close_handle(self) -> None:
self.t.transfer(bragi.packet(self.target, bragi.CMD_CLOSE, bragi.HANDLE, bragi.HANDLE))
def _write_block(self, open_args: bytes, packets: list[bytes], settle: float = 0.0) -> None:
self._close_handle()
self.t.command(bragi.packet(self.target, bragi.CMD_OPEN, bragi.HANDLE, open_args))
if settle:
time.sleep(settle)
self.t.transfer(bragi.packet(self.target, bragi.CMD_PREPARE, bragi.HANDLE))
try:
for p in packets:
self.t.command(p)
finally:
self._close_handle()
def lighting(self, packets: list[bytes]) -> None:
self._write_block(struct.pack("<H", bragi.RESOURCE_LIGHTING), packets, settle=0.5)
def keymap(self) -> None:
self._write_block(bytes([bragi.RESOURCE_KEYMAP]),
bragi.block_packets(self.target, bragi.default_keymap()))
def apply(self, p: Profile, prev: Profile | None = None) -> None:
"""Send `p`; with `prev` given, only the settings that differ from it."""
def changed(*names: str) -> bool:
return prev is None or any(getattr(p, n) != getattr(prev, n) for n in names)
if prev is None:
self.set_mode(bragi.MODE_SOFTWARE)
if changed("effect", "colors", "random_colors", "speed"):
self.lighting(effects.encode(self.target, p.effect, p.colors, p.random_colors, p.speed))
if changed("brightness"):
self.brightness(p.brightness)
if changed("sleep_minutes"):
self.sleep_timer(p.sleep_minutes)
if changed("game_mode", "lock_win", "lock_alt_tab", "lock_alt_f4", "lock_shift_tab"):
flags = ((bragi.LOCK_WIN if p.lock_win else 0) | (bragi.LOCK_ALT_TAB if p.lock_alt_tab else 0)
| (bragi.LOCK_ALT_F4 if p.lock_alt_f4 else 0)
| (bragi.LOCK_SHIFT_TAB if p.lock_shift_tab else 0))
self.locks(p.game_mode, flags)
if prev is None:
self.keymap()
@dataclass
class _Handles:
transport: Transport
notify: Hidraw | None
keyboard: Keyboard
receiver: Keyboard | None # the receiver itself, wireless only
paths: tuple[str, ...] = field(default_factory=tuple)
def close(self) -> None:
self.transport.close()
if self.notify:
self.notify.close()
def find_interfaces() -> tuple[str, str | None, bool] | None:
"""Return (command hidraw, notification hidraw, wireless) for the first K65 PLUS found."""
devs = [d for d in enumerate_hidraw(bragi.VENDOR_CORSAIR) if d.bus == 3]
for pids, wireless in (((bragi.PID_SLIPSTREAM_K65,), True), (bragi.PIDS_K65_PLUS_WIRED, False)):
cmd = next((d for d in devs if d.product_id in pids and d.interface == 1), None)
if cmd:
notify = next((d for d in devs if d.product_id == cmd.product_id and d.interface == 2), None)
return cmd.path, notify.path if notify else None, wireless
return None
class DeviceService:
"""Runs the device loop in a thread. `on_state` is called from that thread."""
def __init__(self, on_state: Callable[[DeviceState], None]):
self.on_state = on_state
self.state = DeviceState()
self._profile: Profile | None = None
self._applied: Profile | None = None # what the keyboard currently has
self._jobs: queue.Queue[tuple[str, object]] = queue.Queue()
self._stop = threading.Event()
self._restore_hardware = True
self._thread = threading.Thread(target=self._run, name="k65-device", daemon=True)
self._h: _Handles | None = None
self._reconnect_at: float | None = None
# --- public API (any thread) ---
def start(self, profile: Profile) -> None:
self._profile = replace(profile, colors=list(profile.colors))
self._thread.start()
def apply(self, profile: Profile) -> None:
self._jobs.put(("apply", replace(profile, colors=list(profile.colors))))
def stop(self, restore_hardware: bool = True, timeout: float = 3.0) -> None:
self._restore_hardware = restore_hardware
self._stop.set()
self._thread.join(timeout)
# --- device thread ---
def _set(self, **changes) -> None:
new = replace(self.state, **changes)
if new != self.state:
self.state = new
self.on_state(new)
def _run(self) -> None:
next_heartbeat = 0.0
while not self._stop.is_set():
if self._h is None:
if not self._open():
self._stop.wait(DISCOVERY_INTERVAL)
continue
next_heartbeat = time.monotonic() + HEARTBEAT_INTERVAL
try:
self._process_jobs()
self._read_notifications(0.2)
now = time.monotonic()
if self._reconnect_at is not None and now >= self._reconnect_at:
self._reconnect_at = None
self._init_keyboard()
if now >= next_heartbeat:
next_heartbeat = now + HEARTBEAT_INTERVAL
self._heartbeat()
except OSError as e:
log.warning("device lost: %s", e)
self._close()
self._set(receiver=False, keyboard=False, battery=None, error="Gerät getrennt")
self._shutdown()
def _open(self) -> bool:
found = find_interfaces()
if not found:
self._set(receiver=False, keyboard=False, error="Kein K65 PLUS gefunden")
return False
cmd_path, notify_path, wireless = found
try:
transport = Transport(cmd_path)
notify = Hidraw(notify_path) if notify_path else None
except PermissionError:
self._set(receiver=False, keyboard=False,
error=f"Keine Berechtigung für {cmd_path}. udev-Regel installieren (siehe README).")
return False
except OSError as e:
self._set(receiver=False, keyboard=False, error=str(e))
return False
target = bragi.TARGET_PAIRED if wireless else bragi.TARGET_LOCAL
receiver = Keyboard(transport, bragi.TARGET_LOCAL) if wireless else None
self._h = _Handles(transport, notify, Keyboard(transport, target), receiver)
self._set(receiver=True, wireless=wireless, error="")
if receiver:
try:
self._set(receiver_firmware=receiver.firmware(), serial=self._paired_serial())
receiver.set_mode(bragi.MODE_SOFTWARE)
except DeviceError as e:
log.warning("receiver init: %s", e)
self._init_keyboard()
return True
def _paired_serial(self) -> str:
"""Read the receiver's pairing list and return the keyboard serial."""
t = self._h.transport
res = struct.pack("<B", bragi.CMD_DEVICE_LIST)
t.transfer(bragi.packet(bragi.TARGET_LOCAL, bragi.CMD_CLOSE, bragi.HANDLE, res))
t.command(bragi.packet(bragi.TARGET_LOCAL, bragi.CMD_OPEN, 0x00, res))
t.transfer(bragi.packet(bragi.TARGET_LOCAL, bragi.CMD_PREPARE, 0x00, res))
buf = t.command(bragi.packet(bragi.TARGET_LOCAL, bragi.CMD_READ, 0x00, res))
t.transfer(bragi.packet(bragi.TARGET_LOCAL, bragi.CMD_CLOSE, bragi.HANDLE))
if buf[5] == 0:
return ""
return buf[11:11 + buf[10]].decode("ascii", "replace")
def _init_keyboard(self) -> None:
kb = self._h.keyboard
try:
kb.heartbeat()
except DeviceError:
self._set(keyboard=False, battery=None)
return
try:
kb.set_mode(bragi.MODE_SOFTWARE)
self._set(keyboard=True, keyboard_firmware=kb.firmware(), battery=self._battery(kb))
self._applied = None
if self._profile:
kb.apply(self._profile)
self._applied = self._profile
self._set(error="")
except DeviceError as e:
log.warning("keyboard init: %s", e)
self._set(error=f"Initialisierung fehlgeschlagen: {e}")
def _battery(self, kb: Keyboard) -> int | None:
if not self.state.wireless:
return None
try:
return kb.battery()
except DeviceError:
return self.state.battery
def _heartbeat(self) -> None:
if self._h.receiver:
try:
self._h.receiver.heartbeat()
except DeviceError as e:
log.debug("receiver heartbeat: %s", e)
try:
self._h.keyboard.heartbeat()
except DeviceError:
self._set(keyboard=False, battery=None)
return
if not self.state.keyboard:
self._init_keyboard()
else:
self._set(battery=self._battery(self._h.keyboard))
def _process_jobs(self) -> None:
latest = None
while True:
try:
job, arg = self._jobs.get_nowait()
except queue.Empty:
break
if job == "apply":
latest = arg
if latest is None:
return
self._profile = latest
if self.state.keyboard:
try:
self._h.keyboard.apply(latest, self._applied)
self._applied = latest
self._set(error="")
except DeviceError as e:
self._applied = None
self._set(error=f"Profil konnte nicht angewendet werden: {e}")
def _read_notifications(self, timeout: float) -> None:
notify = self._h.notify
if notify is None:
time.sleep(timeout)
return
data = notify.read(timeout)
while data:
self._handle_notification(data)
data = notify.read(0)
def _handle_notification(self, data: bytes) -> None:
if len(data) < 6:
return
if data[1] == 0x01 and data[2] == bragi.NOTIFY_CONNECTION:
if data[4] == 0x02:
self._reconnect_at = time.monotonic() + RECONNECT_DELAY
elif data[4] == 0x00:
self._set(keyboard=False, battery=None)
elif data[2] == bragi.PROP_BATTERY:
level = round(bragi.parse_u16(data, 4) / 10)
if level > 0:
self._set(battery=level)
def _close(self) -> None:
if self._h:
self._h.close()
self._h = None
def _shutdown(self) -> None:
if self._h and self._restore_hardware:
for dev in (self._h.keyboard, self._h.receiver):
if dev is None:
continue
try:
dev.set_mode(bragi.MODE_HARDWARE)
except (DeviceError, OSError) as e:
log.debug("hardware mode: %s", e)
self._close()