Fix hang on ARM platforms
[pub/pl2303-ft232-gpio.git] / usb.c
1
2 #include <stdio.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <errno.h>
6 #include <libusb.h>
7
8
9
10
11 static int ncusb_match_string(libusb_device_handle *dev, int index, const char* string)
12 {
13 unsigned char tmp[256];
14 libusb_get_string_descriptor_ascii(dev, index, tmp, 256);
15 if (string == NULL)
16 return 1; /* NULL matches anything */
17 return (strcmp(string, (char*) tmp)==0);
18 }
19
20
21 struct libusb_device_handle *ncusb_find_and_open(struct libusb_context *ctx,
22 int vendor, int product,
23 const char *vendor_name,
24 const char *product_name,
25 const char *serial)
26 {
27 libusb_device_handle *found = NULL;
28 libusb_device **list;
29 ssize_t cnt = libusb_get_device_list(ctx, &list);
30 ssize_t i = 0;
31
32 if (cnt < 0){
33 return NULL;
34 }
35
36 for(i = 0; i < cnt; i++) {
37 int err = 0;
38 libusb_device *device = list[i];
39 struct libusb_device_descriptor desc;
40 libusb_device_handle *handle;
41 err = libusb_open(device, &handle);
42 if (err)
43 continue;
44
45 int r = libusb_get_device_descriptor( device, &desc );
46 if (r) {
47 libusb_close(handle);
48 continue;
49 }
50
51 if ( desc.idVendor == vendor && desc.idProduct == product &&
52 ncusb_match_string(handle, desc.iManufacturer, vendor_name) &&
53 ncusb_match_string(handle, desc.iProduct, product_name) &&
54 ncusb_match_string(handle, desc.iSerialNumber, serial)
55 )
56 {
57 found = handle;
58 }
59
60 if (found)
61 break;
62
63 }
64 libusb_free_device_list(list, 1);
65
66 return found;
67 }
68
69
70 void check_handle(libusb_device_handle **h, int vid, int pid, const char* manuf, const char* product, const char* serial)
71 {
72 if (*h)
73 return;
74 libusb_init(NULL);
75 libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
76 *h = ncusb_find_and_open(NULL, vid, pid, manuf, product, serial);
77 if (!(*h)) {
78 fprintf(stderr, "No PL2303 USB device %04x:%04x found ;(\n", vid, pid);
79 exit(1);
80 }
81 }