xinthose xinthose - 6 months ago 86
Linux Question

Get device path based on USB VID:PID in Linux

If I plug in a device, say

/dev/ttyUSB0
and I want to get the number
0
based on its VID:PID (found with
lsusb
), how could I do that in C++ Linux? I have this code to find one printer device, if it's helpful at all:

int printer_open (void)
{
char printer_location[] = "/dev/usb/lpX";
struct stat buf;

// continuously try all numbers until stat returns true for the connected printer
for (int i = 0; i < 10; i++)
{
printer_location[11] = '0' + i;
if (!stat (printer_location, &buf))
break;
}

return 0;
}

Answer

You could use libusb
apt-get install build-essential libudev-dev
Here is a good example:
http://www.dreamincode.net/forums/topic/148707-introduction-to-using-libusb-10/
and here is the lib description:
http://libusb.sourceforge.net/api-1.0/

int main() {
libusb_context *context = NULL;
libusb_device **list = NULL;
int rc = 0;
ssize_t count = 0;

rc = libusb_init(&context);
assert(rc == 0);

count = libusb_get_device_list(context, &list);
assert(count > 0);

for (size_t idx = 0; idx < count; ++idx) {
    libusb_device *device = list[idx];
    libusb_device_descriptor desc = {0};

    rc = libusb_get_device_descriptor(device, &desc);
    assert(rc == 0);

    printf("Vendor:Device = %04x:%04x\n", desc.idVendor, desc.idProduct);
}}

And if you compile your code don't forget to add the lib reference -I/usr/include/libusb-1.0/ and - lusb-1.0

Comments