Skip to main content
 首页 » 编程设计

python之如何使用 PyUSB 与 USB 设备交互

2024年10月01日7exmyth

到目前为止,我已经到了找到设备的阶段,现在我准备好使用 specification 中列出的设备协议(protocol)与 USB 通信了。在第 22 页。

我的机器上安装了 libusb,PyUSB 也安装了。

import usb.core 
import usb.util 
 
# find our device 
dev = usb.core.find(idVendor=0x067b, idProduct=0x2303) 
 
# was it found? 
if dev is None: 
    raise ValueError('Device not found') 
 
# b are bytes, w are words 
 
reqType = '' 
bReq = '' 
wVal = '' 
wIndex = '' 
 
dev.ctrl_transfer(reqType, bReq, wVal, wIndex, []) 

上面的例子试图使用控制传输,我认为这是协议(protocol)所描述的。

我只是想知道我的方向是否正确,或者我是否做错了根本性的事情。

设备已找到,只是我不确定的下一部分。

请您参考如下方法:

https://github.com/walac/pyusb/blob/master/docs/tutorial.rst中有一个例子亲爱的,跟我说话

>>> msg = 'test' 
>>> assert dev.ctrl_transfer(0x40, CTRL_LOOPBACK_WRITE, 0, 0, msg) == len(msg) 
>>> ret = dev.ctrl_transfer(0xC0, CTRL_LOOPBACK_READ, 0, 0, len(msg)) 
>>> sret = ''.join([chr(x) for x in ret]) 
>>> assert sret == msg 

如果你想写入端点(批量传输等),你必须遵守 USB 树结构:-> configuration -> claim interface -> get endpoint ...

规范的第22页不是USB协议(protocol)是GNET协议(protocol)(我不知道)。关键是您不需要低级 USB 即可与设备通信。你可以在 linux 或Windows 中的一些模拟