解释HIDAPI python输出

时间:2018-05-16 02:48:34

标签: python hidapi

我想在OS X上用Python上的USB HID扫描器读取一个字符串。下面的例子是我的起点,我已经能够将代码定制到我的扫描仪:我已经能够执行命令: h.open()成功并打印出制造商和产品字符串。 scan codes were verified with EVDEV with the scanner.

挑战在于解释返回的数据并将其映射回ascii字符串。

This post provides python HIDAPI example code

 from __future__ import print_function

import hid
import time

print("Opening the device")

h = hid.device()
h.open(1118, 2048) # A Microsoft wireless combo keyboard & mouse

print("Manufacturer: %s" % h.get_manufacturer_string())
print("Product: %s" % h.get_product_string())
print("Serial No: %s" % h.get_serial_number_string())

try:
    while True:
        d = h.read(64)
        if d:
            print('read: "{}"'.format(d))
finally:
    print("Closing the device")
    h.close()

$ sudo python try.py输出:

Opening the device
Manufacturer: Microsoft
Product: Microsoft® Nano Transceiver v2.0
Serial No: None
read: "[0, 0, 0, 0, 0, 0, 0, 0]"
read: "[0, 0, 0, 0, 0, 0, 0, 0]"
read: "[0, 0, 0, 0, 0, 0, 0, 0]"

--8<-- snip lots of repeated lines --8<--

read: "[0, 0, 0, 0, 0, 0, 0, 0]"
read: "[0, 0, 0, 0, 0, 0, 0, 0]"
read: "[0, 0, 21, 0, 0, 0, 0, 0]"
read: "[0, 0, 21, 0, 0, 0, 0, 0]"
read: "[0, 0, 21, 0, 0, 0, 0, 0]"
read: "[0, 0, 21, 0, 0, 0, 0, 0]"
read: "[0, 0, 0, 0, 0, 0, 0, 0]"
read: "[0, 0, 4, 0, 0, 0, 0, 0]"
read: "[0, 0, 4, 22, 0, 0, 0, 0]"
read: "[0, 0, 4, 22, 0, 0, 0, 0]"
read: "[0, 0, 4, 22, 0, 0, 0, 0]"
read: "[0, 0, 4, 22, 0, 0, 0, 0]"
read: "[0, 0, 4, 22, 0, 0, 0, 0]"
read: "[0, 0, 4, 0, 0, 0, 0, 0]"
read: "[0, 0, 4, 0, 0, 0, 0, 0]"
read: "[0, 0, 4, 9, 0, 0, 0, 0]"
read: "[0, 0, 4, 9, 0, 0, 0, 0]"
read: "[0, 0, 4, 9, 0, 0, 0, 0]"
read: "[0, 0, 4, 9, 0, 0, 0, 0]"
read: "[0, 0, 4, 9, 7, 0, 0, 0]"
read: "[0, 0, 4, 9, 7, 0, 0, 0]"
read: "[0, 0, 7, 0, 0, 0, 0, 0]"
^Closing the device
Traceback (most recent call last):
  File "try.py", line 17, in <module>
    d = h.read(64)
KeyboardInterrupt

问题

我无法找到好的例子(like those found with EVDEV)。任何等效的链接都会非常有用。 在没有良好文档的情况下解释输出是一项挑战。 h.read()返回一个列表

  1. 为什么64选择h.read()?

    d = h.read(64)

  2. 当64用1,2,3 ... 8中的数字替换时,列表中的元素数量是相同的。 9个或更多结果列出了8个元素。

    1. 为什么变量&#39; d&#39; 8个元素的输出列表? (8未指定任何地方)

      打印(&#39;读取:&#34; {}&#34;&#39; .format(d))

    2. 每个打印输出列表代表什么? 1个打字的角色?

    3. 输出列表中的每列代表\ encode?

    4. 是否有已发布的表格将数字映射到键盘?

    5. 我期待回复:如果您有使用HIDAPI的经验(特别是使用Python),请在答案中说明。输入HID扫描仪体验的双奖励回合

2 个答案:

答案 0 :(得分:2)

HIDAPI(这是 Python 正在使用的)不检索描述符,而描述符正是您解析传入数据所需要的。 您需要的是一种转储和解码这些描述符的方法: https://github.com/todbot/mac-hid-dump https://eleccelerator.com/usbdescreqparser/

答案 1 :(得分:0)

您需要阅读并理解USB HID规范。

Hid Specs

按搜索按钮,然后查看文档。这一点最重要:“ HID 1.11的设备类定义” 另请参见“使用情况页面”文档。

每个设备都发送一个HID描述符,该描述符准确地描述了报告中的每一位。因此,为了解释报告,您的代码可以解析描述符(api),也可以手动将字节/位分配给结构(不建议这样做,因为它仅适用于知名设备)。