libusb
Device hotplug event notification

Introduction

Releases of libusb 1.0 newer than 1.X have added support for hotplug events. This interface allows you to request notification for the arrival and departure of matching USB devices.

To receive hotplug notification you prepare a callback by calling libusb_hotplug_prepare_callback() and registering it with libusb_hotplug_register_callback(),

As of 1.X there are two supported hotplug events:

A hotplug event can listen for either or both of these events.

Note: If you receive notification that a device has left and you have any a libusb_device_handles for the device it is up to you to call libusb_close() on each handle to free up any remaining resources associated with the device. Once a device has left any libusb_device_handle associated with the device are invalid and will remain so even if the device comes back.

When handling a LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED event it is considered safe to call any libusb function that takes a libusb_device. On the other hand, when handling a LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT event the only safe function is libusb_get_device_descriptor().

The following code provides an example of the usage of the hotplug interface:

static int count = 0;
void hotplug_callback(struct libusb_context *ctx, struct libusb_device *dev,
static libusb_device_handle *handle = NULL;
int rc;
(void)libusb_get_device_descriptor(dev, &desc);
rc = libusb_open(dev, &handle);
if (LIBUSB_SUCCESS != rc) {
printf("Could not open USB device\n");
}
} else if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == event) {
if (handle) {
libusb_close(handle);
handle = NULL;
}
} else {
printf("Unhandled event %d\n", event);
}
count++;
}
int main (void) {
libusb_init(NULL);
LIBUSB_HOTPLUG_CLASS_ANY, hotplug_callback, NULL);
while (count < 2) {
usleep(10000);
}
libusb_exit(NULL);
return 0;
}