libusb / hidapi

A Simple cross-platform library for communicating with HID devices
https://libusb.info/hidapi/
Other
1.66k stars 397 forks source link

HID connection status? #103

Closed JacoFourie closed 3 years ago

JacoFourie commented 5 years ago

Hi, this is more a question than an issue. I am new to HID over USB. I found the lib. I use it via Lazarus / free pascal binding. All seems to be working but I have some questions. How do I detect the connection status? Let's say you pull out the USB device and push it back in. Or you lose connection to the device and want to retry the connection. I only see an Open and Close API.

todbot commented 5 years ago

Not directly with hidapi. You can try sending a report and if it does not error out, the OS still believes the device is connected. With your device, there may be a "get status" or "get version" command you can periodically send to determine device plugged in.

To determine device insertion, you can periodically use hid_open() or hid_enumerate() and check for any devices returned. Be careful doing this too often though, as USB enumeration can be expensive on some OSes.

Alternatively, there may be a "usb detection" library for your language. For instance, in Node.js, there's the node-hid wrapper on hidapi but there's also node-usb-detection that is specifically for providing plug/unplug events.

Youw commented 5 years ago

On Linux I'd suggest using udev library to monitor plug/unplug events.

JacoFourie commented 5 years ago

Can I use libusb with hidapi. libusb has hotplug events. So my plan is to use libusb to monitor the status of the usb device and use hidapi to send and receive data.

z3ntu commented 5 years ago

I've implemented something like this (with Qt signals/slots - using libudev on Linux and using IOService notifications on macOS) in my project: https://github.com/z3ntu/razer_test/tree/master/src/devnotifier

But I agree it would be nice if there was a proper easy cross platform solution for that.

todbot commented 5 years ago

Yes, I believe you can use libusb with hidapi, but the preferred method is udev.

Youw commented 5 years ago

libusb is a great choice, if you target linux only (it uses udev under the hood anyway), since hotplug support is not yet implemented on Windows (last time I check it wasn't).

@z3ntu 's implementation is very practical - I did the same way, whan I needed this in one of my own projects.

xakod commented 4 years ago

Is there any way for windows?

Youw commented 4 years ago

Yes, this is possible, but you need a Windows even loop, and a window handle (can be a dummy window). I don't have a complete sample for HID devices notification, but there is a similar sample on MSDN: https://docs.microsoft.com/en-us/windows/win32/devio/registering-for-device-notification , where you probably need to use GUID_DEVINTERFACE_HID.