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