python的USB通信

手头有个用libusb-win32驱动的USB设备,idVendor= 0x5345, idProduct= 0x1234,就来测试下pyusb模块的应用,pyusb让usb编程变得简单和方便,支持 libusb 0.1.x(libusb-win32采用此库), libusb 1.x, and OpenUSB,主要测试发送和接收数据,usb设备信息如下

python的USB通信_第1张图片

代码如下:

import usb.core
import usb.util
import sys

dev =  usb.core.find(idVendor= 0x5345, idProduct= 0x1234)

cfg = dev.get_active_configuration()
intf = cfg[(0,0)]
ep = usb.util.find_descriptor(
    intf,
    # match the first OUT endpoint
    custom_match = \
    lambda e: \
        usb.util.endpoint_direction(e.bEndpointAddress) == \
        usb.util.ENDPOINT_OUT
)
print 'The length of data(write USB) is:', ep.write('WANTFORGETTXT')
ep_read = usb.util.find_descriptor(
    intf,
    # match the first IN endpoint
    custom_match = \
    lambda e: \
        usb.util.endpoint_direction(e.bEndpointAddress) == \
        usb.util.ENDPOINT_IN
)
data_len = ep_read.read(4)
print 'Get USB data:',data_len
len = (data_len[3] << 24) + (data_len[2] << 16) + (data_len[1] << 8) + data_len[0]
print 'data len is:',len
dev.reset()
结果如下:

python的USB通信_第2张图片


转载于:https://my.oschina.net/sunlimpid/blog/139059

你可能感兴趣的:(python的USB通信)