I'm trying to implement device attach/detach events in my libusb-1.0 code from this example.
Here is how I'm using it:
void registerCallBack() {
int rc;
libusb_init(NULL);
rc = libusb_hotplug_register_callback(NULL, (libusb_hotplug_event) (LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED |
LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT), LIBUSB_HOTPLUG_ENUMERATE,
0x2047, LIBUSB_HOTPLUG_MATCH_ANY,
LIBUSB_HOTPLUG_MATCH_ANY, hotplug_callback, NULL,
&handle);
if (LIBUSB_SUCCESS != rc) {
printf("Error creating a hotplug callback\n");
libusb_exit(NULL);
return;
}
printf("Success registering callback\n");
}
Callback function itself:
int hotplug_callback(struct libusb_context *ctx, struct libusb_device *dev,
libusb_hotplug_event event, void *user_data) {
printf("EVENT! %d\n", event);
callJava(); // call java method when event fires
return 0;
}
If I run this code and device had attached - fires event, because LIBUSB_HOTPLUG_ENUMERATE set. But if I try to attach/detach device while program running nothing happens. If I'm setting flag to 0 (not LIBUSB_HOTPLUG_ENUMERATE) then no events happens.
I have Ubuntu Linux 13.10 and libusb-1.0.16-3. Callback is registered successfully.
P.S. I use libusb in C++ library for Java program.
Thanks!
I had the same problem, and from a bit of debugging, I found that the hotplug event itself was happening and getting pushed to the event pipe. However, from looking at the libusb source, I didn't see any dedicated thread which would poll for these events. The event polling (and callback invocations) seem to be done as part of the generic transaction request handling. So I suspect (have not tested this myself though) that you have to be making control or data requests to see the hotplug callbacks.
You might try spawning a thread to call libusb_handle_events_timeout_completed() with a NULL timeout parameter, maybe once a second. That might give you what you want.
If this is correct, I wish libusb would have a flag on libusb_init() to create a thread specifically for hotplug events, without depending on control/data request calls.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With