Bump LIBUSBX_API_VERSION for new hotplug API
[libusbx.git] / examples / hotplugtest.c
blob6f168279479ea85e99f367850566c4cf88c1eae0
1 /*
2 * libusb example program for hotplug API
3 * Copyright © 2012-2013 Nathan Hjelm <hjelmn@mac.ccom>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 #include <stdlib.h>
21 #include <stdio.h>
23 #include "libusb.h"
25 int done = 0;
26 libusb_device_handle *handle;
28 static int LIBUSB_CALL hotplug_callback(libusb_context *ctx, libusb_device *dev, libusb_hotplug_event event, void *user_data)
30 struct libusb_device_descriptor desc;
31 int rc;
33 rc = libusb_get_device_descriptor(dev, &desc);
34 if (LIBUSB_SUCCESS != rc) {
35 fprintf (stderr, "Error getting device descriptor\n");
38 printf ("Device attached: %04x:%04x\n", desc.idVendor, desc.idProduct);
40 libusb_open (dev, &handle);
42 done++;
44 return 0;
47 static int LIBUSB_CALL hotplug_callback_detach(libusb_context *ctx, libusb_device *dev, libusb_hotplug_event event, void *user_data)
49 printf ("Device detached\n");
51 libusb_close (handle);
53 done++;
54 return 0;
57 int main(int argc, char *argv[])
59 libusb_hotplug_callback_handle hp[2];
60 int product_id, vendor_id, class_id;
61 int rc;
63 vendor_id = (argc > 1) ? strtol (argv[1], NULL, 0) : 0x045a;
64 product_id = (argc > 2) ? strtol (argv[2], NULL, 0) : 0x5005;
65 class_id = (argc > 3) ? strtol (argv[3], NULL, 0) : LIBUSB_HOTPLUG_MATCH_ANY;
67 libusb_init (NULL);
69 if (!libusb_has_capability (LIBUSB_CAP_HAS_HOTPLUG)) {
70 printf ("Hotplug capabilites are not supported on this platform\n");
71 libusb_exit (NULL);
72 return EXIT_FAILURE;
75 rc = libusb_hotplug_register_callback (NULL, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED, 0, vendor_id,
76 product_id, class_id, hotplug_callback, NULL, &hp[0]);
77 if (LIBUSB_SUCCESS != rc) {
78 fprintf (stderr, "Error registering callback 0\n");
79 libusb_exit (NULL);
80 return EXIT_FAILURE;
83 rc = libusb_hotplug_register_callback (NULL, LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT, 0, vendor_id,
84 product_id,class_id, hotplug_callback_detach, NULL, &hp[1]);
85 if (LIBUSB_SUCCESS != rc) {
86 fprintf (stderr, "Error registering callback 1\n");
87 libusb_exit (NULL);
88 return EXIT_FAILURE;
91 while (done < 2) {
92 libusb_handle_events (NULL);
95 libusb_exit (NULL);