我正在实现此程序,以从USB鼠标读取USB数据并显示它。程序产生正确的输出。它也适用于其他USB设备。代码如下
import sys
import usb.core
import usb.util
dev=usb.core.find(idVendor=0x1c4f, idProduct=0x0032)
interface=0
endpoint = dev[0][(0,0)][0]
if dev.is_kernel_driver_active(interface) is True:
dev.detach_kernel_driver(interface)
usb.util.claim_interface(dev,interface)
collected = 0
attempts = 50
while collected < attempts:
try:
data = dev.read(endpoint.bEndpointAddress,endpoint.wMaxPacketSize)
collected += 1
print data
except usb.core.USBError as e :
data = None
if e.args == ('Operation timed out',):
continue
usb.util.release_interface(dev,interface)
dev.attach_kernel_driver(interface)
我无法理解以下几行
interface=0
为什么需要等于零?更改它会产生错误。
下一行是做什么的?
endpoint = dev[0][(0,0)][0]
我已经从[this](http://www.usbmadesimple.co.uk/ums_3.htm)网站了解了端点的含义,但仍然不了解[0] [(0,0)[0]是什么。更改此设置也会产生错误。pyusb docs / tutorials也帮不上什么忙
编辑
正如马丁·埃文斯(Martin Evans)在下面的评论中所建议的那样,我在dev = [0] [(0,0)] [0]之后添加了print dev,并且得到了以下输出。
DEVICE ID 1c4f:0002 on Bus 002 Address 003 =================
bLength : 0x12 (18 bytes)
bDescriptorType : 0x1 Device
bcdUSB : 0x110 USB 1.1
bDeviceClass : 0x0 Specified at interface
bDeviceSubClass : 0x0
bDeviceProtocol : 0x0
bMaxPacketSize0 : 0x8 (8 bytes)
idVendor : 0x1c4f
idProduct : 0x0002
bcdDevice : 0x110 Device 1.1
iManufacturer : 0x1 SIGMACHIP
iProduct : 0x2 USB Keyboard
iSerialNumber : 0x0
bNumConfigurations : 0x1
CONFIGURATION 1: 98 mA ===================================
bLength : 0x9 (9 bytes)
bDescriptorType : 0x2 Configuration
wTotalLength : 0x3b (59 bytes)
bNumInterfaces : 0x2
bConfigurationValue : 0x1
iConfiguration : 0x0
bmAttributes : 0xa0 Bus Powered, Remote Wakeup
bMaxPower : 0x31 (98 mA)
INTERFACE 0: Human Interface Device ====================
bLength : 0x9 (9 bytes)
bDescriptorType : 0x4 Interface
bInterfaceNumber : 0x0
bAlternateSetting : 0x0
bNumEndpoints : 0x1
bInterfaceClass : 0x3 Human Interface Device
bInterfaceSubClass : 0x1
bInterfaceProtocol : 0x1
iInterface : 0x0
ENDPOINT 0x81: Interrupt IN ==========================
bLength : 0x7 (7 bytes)
bDescriptorType : 0x5 Endpoint
bEndpointAddress : 0x81 IN
bmAttributes : 0x3 Interrupt
wMaxPacketSize : 0x8 (8 bytes)
bInterval : 0xa
我还有更多行,但是由于它们是Interface 1,所以我还没有发布它,我猜因为我的代码中的interface = 0,所以上述几行才有意义。
所以我认为第一个[0]对应于bEndpointAddress,([0,0])对应于(bmAttributes,wMaxPacketSize),最后一个[0]对应于bInterval?还是我错了?
根据PyUSB教程:
您还可以使用下标运算符来随机访问描述符,如下所示:
>>> # access the second configuration
>>> cfg = dev[1]
>>> # access the first interface
>>> intf = cfg[(0,0)]
>>> # third endpoint
>>> ep = intf[2]
如您所见,索引是从零开始的。可是等等!我访问接口的方式有些奇怪...是的,是的,配置中的下标运算符接受两个项的序列,第一个是接口的索引,第二个是接口的索引环境。因此,要访问第一个接口,但要访问它的第二个备用设置,我们可以编写cfg [(0,1)]。
因此,第一个下标[0]访问第一个配置,第二个下标[0,0]选择第一个接口(具有第一个备用设置),第三个下标[0]选择第一个端点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句