在Python中与USB设备通信

时间:2012-09-22 10:03:21

标签: python

我想与USB设备进行通信并将数据发送到USB设备。我能够找到设备,但在使用内核驱动程序连接设备时,它会给USB Error: Resource Busy。以下是我的代码:

    dev = usb.core.find(idVendor=0x0403, idProduct=0x6001)
    dev.set_configuration() 

    cfg = dev.get_active_configuration() 

    dev.attach_kernel_driver(interface) 

    interface_number = cfg[(0,0)].bInterfaceNumber 
    alternate_settting = usb.control.get_interface(interface_number) 
    intf = usb.util.find_descriptor( 
    cfg, bInterfaceNumber = interface_number, 
    bAlternateSetting = alternate_setting) 

    ep = usb.util.find_descriptor(intf,custom_match = \
          lambda e: \
    usb.util.endpoint_direction(e.bEndpointAddress) == \
    usb.util.ENDPOINT_OUT) 

    dev.detach_kernel_driver(interface)

    ep.write("\r"+linea1[:19]+"\n\r"+" "*(20-len(linea2))+linea2)  

1 个答案:

答案 0 :(得分:8)

假设您使用Linux和libusb-1.0作为PyUSB的后端库。

根据libusb documentation

// Detach a kernel driver from an interface.
// If successful, you will then be able to claim the interface and perform I/O.
int libusb_detach_kernel_driver (libusb_device_handle *dev, 
                                 int interface_number)  

// Re-attach an interface's kernel driver, which was previously 
// detached using libusb_detach_kernel_driver().
int libusb_attach_kernel_driver(libusb_device_handle *dev,
                                int interface_number)

所以基本上,你需要先调用detach_kernel_driver 来从设备的界面分离已连接的内核驱动程序(如果有的话),这样你就可以在代码中与它通信了(它是您的代码或某些内核驱动程序与设备的接口通信)。完成后,您可能需要再次调用attach_kernel_driver重新附加内核驱动程序。

我相信如果你能确保没有为给定设备加载内核驱动程序(或在运行代码之前手动卸载它),就不需要调用任何C函数/ Python方法。

修改:

我刚刚得到这段代码(根据你的样本)工作。注意:为简单起见,我将{0}作为detach_kernel_driverattach_kernel_driver的接口编号硬编码 - 我认为你应该让它变得更聪明。

import usb

dev = usb.core.find(idVendor=0x0403, idProduct=0x6001)

reattach = False
if dev.is_kernel_driver_active(0):
    reattach = True
    dev.detach_kernel_driver(0)

dev.set_configuration() 
cfg = dev.get_active_configuration() 

interface_number = cfg[(0,0)].bInterfaceNumber 
alternate_settting = usb.control.get_interface(dev, interface_number) 
intf = usb.util.find_descriptor(cfg, bInterfaceNumber = interface_number, 
                            bAlternateSetting = alternate_settting) 

ep = usb.util.find_descriptor(intf,custom_match = \
      lambda e: \
    usb.util.endpoint_direction(e.bEndpointAddress) == \
    usb.util.ENDPOINT_OUT) 
ep.write("test\n\r")

# This is needed to release interface, otherwise attach_kernel_driver fails 
# due to "Resource busy"
usb.util.dispose_resources(dev)

# It may raise USBError if there's e.g. no kernel driver loaded at all
if reattach:
    dev.attach_kernel_driver(0)