Extracting USB Device ID using libusb

  • Share this:

Code introduction


This function is used to obtain the unique ID of a USB device connected to the system. It takes a libusb1.libusb_device object as a parameter and returns a combination of the vendor ID and product ID of the device.


Technology Stack : PyUSB, libusb1

Code Type : Function

Code Difficulty : Intermediate


                
                    
def find_device_id(device):
    # This function returns the unique ID of a USB device connected to the system.
    # The device parameter is an instance of the libusb1.libusb_device object.

    # Using libusb_get_device_descriptor to get the device descriptor
    device_desc = device.get_device_descriptor()

    # Using libusb_get_string_descriptor_ascii to get the ASCII string for the vendor ID
    vendor_id = device.get_string(device_desc.iManufacturer, 0)

    # Using libusb_get_string_descriptor_ascii to get the ASCII string for the product ID
    product_id = device.get_string(device_desc.iProduct, 0)

    # The unique ID is a combination of vendor ID and product ID
    device_id = f"{vendor_id}:{product_id}"

    return device_id                
              
Tags: