2012-09-22 73 views
4

的USB設備我想與溝通,併發送數據到USB設備。我能找到設備,但同時用它給USB Error: Resource Busy內核驅動程序安裝該設備。下面是我的代碼:通信在Python

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

給我們更多的細節 - 平臺,PyUSB版本,USB後端庫。什麼是'界面'?爲什麼你真的試圖連接內核驅動程序? –

+0

還有一個想法:有問題的設備是FTDI232 USB轉RS232轉換器。爲什麼不使用內核驅動程序和pySerial模塊?這將(理論上)使您的代碼跨各種串行端口類型(包括真實的RS232和USB加密狗)移植。 –

回答

7

假設你使用Linux和libusb-1.0PyUSB的後端庫。

按照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)