Sending data via USB using PyUSB

Bibix picture Bibix · Jul 3, 2012 · Viewed 18.7k times · Source

I need to send data via USB using Python, I'm using PyUSB (http://sourceforge.net/apps/trac/pyusb/) I look for any USB port available, and I tried to send a message:

devList = usb.core.find(find_all=True)
for dev in devList:
    for cfg in dev:
        for intf in cfg:
            sys.stdout.write('\t' + str(intf.bInterfaceNumber) + ',' + str(intf.bAlternateSetting) + '\n')
            for ep in intf:
                sys.stdout.write('\t\t' + str(ep.bEndpointAddress) + '\n')
                if ep.bEndpointAddress:
                    try:
                        dev.write(ep.bEndpointAddress, 'test', intf.bInterfaceNumber)
                    except Exception:
                        print "\t\terror : dev.write("+str(ep.bEndpointAddress)+", 'test', "+str(intf.bInterfaceNumber)+")"

The result is :

    0,0
            129
            error : dev.write(129, 'test', 0)
    0,1
            129
            error : dev.write(129, 'test', 0)
    0,0
            136
            error : dev.write(136, 'test', 0)
            10
            error : dev.write(10, 'test', 0)
    1,0
            139
            error : dev.write(139, 'test', 1)
            13
            error : dev.write(13, 'test', 1)

without try catch it gives:

usb.core.USBError: [Errno None] usb_claim_interface: could not claim interface 0, invalid configuration 0

What is wrong? Is there a best way to communicate via usb with python? because I just have found this lib

Answer

Paulo Santos picture Paulo Santos · Nov 23, 2012

As stated in the tutorial:

[...] a device does not work without setting a configuration, even if it has just one! [...]

Apparently most of the times there is only one configuration. Assuming all those configurations are from different devices, you can do something like:

for dev in devList:
    for cfg in dev:

        cfg.set()

        for intf in cfg:

If you can't set a configuration due to "resource busy", you'll need to unload its interface kernel driver:

dev.detatch_kernel_driver(interface)