c++hidsetupapi

Open and read from device using HID API


I'm writing a low level input system with the HID API.

I've gotten to the point where I can enumerate all of the devices on a system, and open them with CreateFile.

The problem I'm running into now is how to manage reading from them, there doesn't seem to be any documentation that I can find to do this properly. When I call ReadFile it halts execution until I receive input from that device, and I'd rather not create a thread for every device I want input from. I've tried using asynchronous reads, but it seems to not work, and that would still lead using more threads than necessary. I want to be able to get an 'update' from a device at an arbitrary time, I'm not concerned about getting input when it happens, at least not for now.

If anyone could point to documentation or give examples on would such a system would work, that would be much appreciated.


Solution

  • You can do async read with zero timeout - it will not block execution and return error if device is not sent anything yet. You can look at hidapi implementation for example: https://github.com/libusb/hidapi/blob/master/windows/hid.c#L1065

    Also note that hid driver have a ring buffer for each device and you can miss some reports if you read them not too fast enough due to ring buffer overflow.

    https://learn.microsoft.com/en-us/windows-hardware/drivers/hid/obtaining-hid-reports

    https://learn.microsoft.com/en-us/windows-hardware/drivers/hid/troubleshooting-hid-reports