在libusb开源的源码当中,有根据VID和PID来打开设备的接口。但是这对于设备来说并不唯一。因为有很多设备的VID和PID都是一样的,比如iPhone。
但是设备的序列号就是唯一的,所以根据参照VID和PID打开的源码,如下就是打开一个指定serialnumber的设备。
libusb_device_handle* libusb_open_device_with_serialnumber(
libusb_context* ctx, const char* serial_number) {
struct libusb_device** devs;
struct libusb_device* dev;
struct libusb_device_handle* handle = NULL;
char string[128];
char serialnumber[128] = “”;
uint8_t string_index[3];
size_t i = 0;
int r = 0;
if (serial_number)
strcpy(serialnumber, serial_number);
if (libusb_get_device_list(ctx, &devs) < 0)
return NULL;
while ((dev = devs[i++]) != NULL) {
struct libusb_device_descriptor desc;
r = libusb_get_device_descriptor(dev, &desc);
if (r < 0)
goto out;
string_index[2] = desc.iSerialNumber;
r = libusb_open(dev, &handle);
if (r < 0) {
handle = NULL;
break;
}
if (libusb_get_string_descriptor_ascii(handle, string_index[2], (unsigned char*)string, 128) >= 0) {
if (!strcmp(serialnumber, string))
break;
}
libusb_close(handle);
handle = NULL;
}
out:
libusb_free_device_list(devs, 1);
return handle;
}