在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;
}