Sending data via USB using PyUSB

跟風遠走 提交于 2020-01-02 18:34:13

问题


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


回答1:


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)



回答2:


I had this problem. Got corrected by using

dev.set_configuration()

pyUSB Tutuorial



来源:https://stackoverflow.com/questions/11313008/sending-data-via-usb-using-pyusb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!