"""Overlapped Win32 HID access shared by every USB device The Kurgan drives (the Thermaltake LCD, the Corsair Commander PRO and the Lighting Node CORE). Uses only ctypes and the stock Windows HID driver. """ from __future__ import annotations import ctypes import ctypes.wintypes as wt class HidError(Exception): """A HID device could not be opened, written or read.""" # --------------------------------------------------------------------------- Win32 _setupapi = ctypes.WinDLL("setupapi", use_last_error=True) _hid = ctypes.WinDLL("hid", use_last_error=True) _k32 = ctypes.WinDLL("kernel32", use_last_error=True) _INVALID_HANDLE = wt.HANDLE(-1).value _DIGCF_PRESENT = 0x02 _DIGCF_DEVICEINTERFACE = 0x10 _GENERIC_READ = 0x80000000 _GENERIC_WRITE = 0x40000000 _FILE_SHARE_READ = 0x01 _FILE_SHARE_WRITE = 0x02 _OPEN_EXISTING = 3 _FILE_FLAG_OVERLAPPED = 0x40000000 _ERROR_IO_PENDING = 997 _ERROR_NO_MORE_ITEMS = 259 _WAIT_OBJECT_0 = 0 _WAIT_TIMEOUT = 0x102 # How long to wait for the driver to finish a cancelled IRP before giving up on the channel. _ABANDON_GRACE_MS = 1000 # OVERLAPPED structs and buffers of IRPs the driver never finished cancelling, kept for the life # of the process. Nothing can tell us when the driver is done with them, so freeing them (even # with their channel) could let a late completion write into reused memory. A few hundred # bytes each, and only after a wedged device. _ABANDONED: list = [] class _GUID(ctypes.Structure): _fields_ = [ ("Data1", wt.DWORD), ("Data2", wt.WORD), ("Data3", wt.WORD), ("Data4", ctypes.c_ubyte * 8), ] class _SP_DEVICE_INTERFACE_DATA(ctypes.Structure): _fields_ = [ ("cbSize", wt.DWORD), ("InterfaceClassGuid", _GUID), ("Flags", wt.DWORD), ("Reserved", ctypes.c_size_t), ] class _HIDP_CAPS(ctypes.Structure): _fields_ = [ ("Usage", wt.USHORT), ("UsagePage", wt.USHORT), ("InputReportByteLength", wt.USHORT), ("OutputReportByteLength", wt.USHORT), ("FeatureReportByteLength", wt.USHORT), ("Reserved", wt.USHORT * 17), ("Counts", wt.USHORT * 10), ] class _OVERLAPPED(ctypes.Structure): _fields_ = [ ("Internal", ctypes.c_size_t), ("InternalHigh", ctypes.c_size_t), ("Offset", wt.DWORD), ("OffsetHigh", wt.DWORD), ("hEvent", wt.HANDLE), ] _hid.HidD_GetHidGuid.argtypes = [ctypes.POINTER(_GUID)] _hid.HidD_GetHidGuid.restype = None _hid.HidD_GetPreparsedData.argtypes = [wt.HANDLE, ctypes.POINTER(ctypes.c_void_p)] _hid.HidD_GetPreparsedData.restype = wt.BOOLEAN _hid.HidD_FreePreparsedData.argtypes = [ctypes.c_void_p] _hid.HidD_FreePreparsedData.restype = wt.BOOLEAN _hid.HidP_GetCaps.argtypes = [ctypes.c_void_p, ctypes.POINTER(_HIDP_CAPS)] _hid.HidP_GetCaps.restype = ctypes.c_long _hid.HidD_FlushQueue.argtypes = [wt.HANDLE] _hid.HidD_FlushQueue.restype = wt.BOOLEAN _setupapi.SetupDiGetClassDevsW.argtypes = [ctypes.POINTER(_GUID), wt.LPCWSTR, wt.HWND, wt.DWORD] _setupapi.SetupDiGetClassDevsW.restype = wt.HANDLE _setupapi.SetupDiEnumDeviceInterfaces.argtypes = [ wt.HANDLE, ctypes.c_void_p, ctypes.POINTER(_GUID), wt.DWORD, ctypes.POINTER(_SP_DEVICE_INTERFACE_DATA), ] _setupapi.SetupDiEnumDeviceInterfaces.restype = wt.BOOL _setupapi.SetupDiGetDeviceInterfaceDetailW.argtypes = [ wt.HANDLE, ctypes.POINTER(_SP_DEVICE_INTERFACE_DATA), ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD), ctypes.c_void_p, ] _setupapi.SetupDiGetDeviceInterfaceDetailW.restype = wt.BOOL _setupapi.SetupDiDestroyDeviceInfoList.argtypes = [wt.HANDLE] _setupapi.SetupDiDestroyDeviceInfoList.restype = wt.BOOL _k32.CreateFileW.argtypes = [ wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.c_void_p, wt.DWORD, wt.DWORD, wt.HANDLE, ] _k32.CreateFileW.restype = wt.HANDLE _k32.CreateEventW.argtypes = [ctypes.c_void_p, wt.BOOL, wt.BOOL, wt.LPCWSTR] _k32.CreateEventW.restype = wt.HANDLE _k32.CloseHandle.argtypes = [wt.HANDLE] _k32.CloseHandle.restype = wt.BOOL _k32.WriteFile.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD), ctypes.POINTER(_OVERLAPPED)] _k32.WriteFile.restype = wt.BOOL _k32.ReadFile.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD), ctypes.POINTER(_OVERLAPPED)] _k32.ReadFile.restype = wt.BOOL _k32.GetOverlappedResult.argtypes = [wt.HANDLE, ctypes.POINTER(_OVERLAPPED), ctypes.POINTER(wt.DWORD), wt.BOOL] _k32.GetOverlappedResult.restype = wt.BOOL _k32.WaitForSingleObject.argtypes = [wt.HANDLE, wt.DWORD] _k32.WaitForSingleObject.restype = wt.DWORD _k32.CancelIoEx.argtypes = [wt.HANDLE, ctypes.POINTER(_OVERLAPPED)] _k32.CancelIoEx.restype = wt.BOOL _k32.ResetEvent.argtypes = [wt.HANDLE] _k32.ResetEvent.restype = wt.BOOL def _winerr(what: str) -> HidError: code = ctypes.get_last_error() return HidError(f"{what} failed: [{code}] {ctypes.FormatError(code).strip()}") def hid_device_paths(vendor_id: int, product_id: int) -> list[str]: """Device paths of every present HID interface with this USB vendor/product ID.""" guid = _GUID() _hid.HidD_GetHidGuid(ctypes.byref(guid)) hdev = _setupapi.SetupDiGetClassDevsW( ctypes.byref(guid), None, None, _DIGCF_PRESENT | _DIGCF_DEVICEINTERFACE ) if hdev == _INVALID_HANDLE: raise _winerr("SetupDiGetClassDevs") found: list[str] = [] needle = f"vid_{vendor_id:04x}&pid_{product_id:04x}" try: index = 0 while True: ifdata = _SP_DEVICE_INTERFACE_DATA() ifdata.cbSize = ctypes.sizeof(ifdata) if not _setupapi.SetupDiEnumDeviceInterfaces(hdev, None, ctypes.byref(guid), index, ctypes.byref(ifdata)): if ctypes.get_last_error() == _ERROR_NO_MORE_ITEMS: break raise _winerr("SetupDiEnumDeviceInterfaces") index += 1 required = wt.DWORD(0) _setupapi.SetupDiGetDeviceInterfaceDetailW(hdev, ctypes.byref(ifdata), None, 0, ctypes.byref(required), None) buf = ctypes.create_string_buffer(required.value + 2) # SP_DEVICE_INTERFACE_DETAIL_DATA_W.cbSize: 8 on 64-bit, 6 on 32-bit ctypes.c_uint32.from_buffer(buf).value = 8 if ctypes.sizeof(ctypes.c_void_p) == 8 else 6 if not _setupapi.SetupDiGetDeviceInterfaceDetailW(hdev, ctypes.byref(ifdata), buf, required, None, None): continue path = ctypes.wstring_at(ctypes.addressof(buf) + 4) if needle in path.lower(): found.append(path) finally: _setupapi.SetupDiDestroyDeviceInfoList(hdev) return found class HidChannel: """One HID interface opened for overlapped I/O.""" def __init__(self, path: str, payload_size: int): self.path = path self.handle = _k32.CreateFileW( path, _GENERIC_READ | _GENERIC_WRITE, _FILE_SHARE_READ | _FILE_SHARE_WRITE, None, _OPEN_EXISTING, _FILE_FLAG_OVERLAPPED, None, ) if self.handle == _INVALID_HANDLE: raise _winerr(f"Opening {path}") try: caps = _HIDP_CAPS() pp = ctypes.c_void_p() if not _hid.HidD_GetPreparsedData(self.handle, ctypes.byref(pp)): raise _winerr("HidD_GetPreparsedData") try: _hid.HidP_GetCaps(pp, ctypes.byref(caps)) finally: _hid.HidD_FreePreparsedData(pp) self.output_len = caps.OutputReportByteLength self.input_len = caps.InputReportByteLength if self.output_len != payload_size + 1: raise HidError( f"Unexpected output report length {self.output_len} on {path} " f"(expected {payload_size + 1}); is this the right device?" ) self._wevent = _k32.CreateEventW(None, True, False, None) self._revent = _k32.CreateEventW(None, True, False, None) if not self._wevent or not self._revent: raise _winerr("CreateEventW") self._broken = False except Exception: _k32.CloseHandle(self.handle) raise def close(self) -> None: for h in (getattr(self, "_wevent", None), getattr(self, "_revent", None), self.handle): if h: _k32.CloseHandle(h) self.handle = None def _cancel(self, ov, buf, event, what: str) -> None: """Cancel a timed-out IRP and give the driver a moment to finish it. If the device is wedged and the cancellation never completes, mark the channel broken: further calls fail fast instead of queueing more IRPs behind a dead one, and the caller's reconnect path closes the handle (which cancels the IRP for good). """ _k32.CancelIoEx(self.handle, ctypes.byref(ov)) if _k32.WaitForSingleObject(event, _ABANDON_GRACE_MS) == _WAIT_OBJECT_0: return self._broken = True _ABANDONED.append((ov, buf)) def send(self, payload: bytes, timeout_ms: int = 1000) -> None: if self._broken: raise HidError(f"HID write on {self.path}: channel abandoned after a timeout; reconnect it") data = bytes(1) + payload if len(data) < self.output_len: data += bytes(self.output_len - len(data)) buf = ctypes.create_string_buffer(data, self.output_len) ov = _OVERLAPPED() ov.hEvent = self._wevent _k32.ResetEvent(self._wevent) written = wt.DWORD(0) if not _k32.WriteFile(self.handle, buf, self.output_len, None, ctypes.byref(ov)): if ctypes.get_last_error() != _ERROR_IO_PENDING: raise _winerr("WriteFile") if _k32.WaitForSingleObject(self._wevent, timeout_ms) != _WAIT_OBJECT_0: self._cancel(ov, buf, self._wevent, "write") raise HidError(f"HID write timed out on {self.path}") if not _k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(written), True): raise _winerr("WriteFile (completion)") def read(self, timeout_ms: int) -> bytes | None: """Read one input report, or None on timeout.""" if self._broken: raise HidError(f"HID read on {self.path}: channel abandoned after a timeout; reconnect it") buf = ctypes.create_string_buffer(self.input_len) ov = _OVERLAPPED() ov.hEvent = self._revent _k32.ResetEvent(self._revent) got = wt.DWORD(0) if not _k32.ReadFile(self.handle, buf, self.input_len, None, ctypes.byref(ov)): if ctypes.get_last_error() != _ERROR_IO_PENDING: raise _winerr("ReadFile") if _k32.WaitForSingleObject(self._revent, timeout_ms) != _WAIT_OBJECT_0: self._cancel(ov, buf, self._revent, "read") if self._broken: raise HidError(f"HID read timed out on {self.path} and the device ignored the cancel") ok = _k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(got), True) return buf.raw[: got.value] if ok and got.value else None if not _k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(got), True): raise _winerr("ReadFile (completion)") return buf.raw[: got.value] def drain(self) -> None: _hid.HidD_FlushQueue(self.handle)