简体   繁体   English

如何使用 Python 获取原始 USB 键盘数据?

[英]How can I get raw USB keyboard data with Python?

I am using PyUSB in Python as I will have to listen an USB port to retrieve data from an electronic card.我在 Python 中使用 PyUSB,因为我必须监听 USB 端口才能从电子卡中检索数据。 For the moment, I have to train myself by reading direct input from a small keyboard (USB-connected) connected to a Raspberry-Pi.目前,我必须通过从连接到 Raspberry-Pi 的小键盘(USB 连接)读取直接输入来训练自己。 Of course, I do not want to read the typed String, I expect to get ASCII codes for example.当然,我不想阅读类型化的字符串,我希望得到例如 ASCII 码。 I just don't get how I could read input from my USB-keyboard.我只是不明白如何从我的 USB 键盘读取输入。

I already found some snippets :我已经找到了一些片段:

import usb.core
import usb.util

VENDOR_ID = 0x0922
PRODUCT_ID = 0x8003

# find the USB device
device = usb.core.find(idVendor=VENDOR_ID,
                       idProduct=PRODUCT_ID)

# use the first/default configuration
device.set_configuration()
# first endpoint
endpoint = device[0][(0,0)][0]

# read a data packet
attempts = 10
data = None
while data is None and attempts > 0:
    try:
        data = device.read(endpoint.bEndpointAddress,
                           endpoint.wMaxPacketSize)
    except usb.core.USBError as e:
        data = None
        if e.args == ('Operation timed out',):
            attempts -= 1
            continue

print data

Either I get the error 16 "Device is busy" or nothing at all if I uncomment the following line "device.set_configuration()" which causes the "Device is busy" exception... (I did replace VENDOR_ID and PRODUCT_ID with my keyboard's ids)如果我取消注释导致“设备正忙”异常的以下行“device.set_configuration()”,我会收到错误 16“设备正忙”或什么都没有...(我确实用我的键盘替换了 VENDOR_ID 和 PRODUCT_ID身份证)

I'm assuming that you are using Linux, as you mentioned the Raspberry Pi.我假设您使用的是 Linux,正如您提到的 Raspberry Pi。 You can use python-evdev to read data from the event devices in /dev/input/ .您可以使用python-evdev/dev/input/中的事件设备读取数据。

For example:例如:

from evdev import InputDevice, categorize, ecodes

device = InputDevice("/dev/input/event3") # my keyboard
for event in device.read_loop():
    if event.type == ecodes.EV_KEY:
        print(categorize(event))

Output:输出:

key event at 1462881252.506405, 30 (KEY_A), up
key event at 1462881252.541371, 31 (KEY_S), up
key event at 1462881252.616399, 31 (KEY_S), down
key event at 1462881252.674422, 22 (KEY_U), down
key event at 1462881252.730418, 31 (KEY_S), up
key event at 1462881252.745558, 22 (KEY_U), up
key event at 1462881252.808419, 50 (KEY_M), down
key event at 1462881252.914552, 23 (KEY_I), down
key event at 1462881252.925388, 50 (KEY_M), up
key event at 1462881253.003579, 49 (KEY_N), down
key event at 1462881253.066418, 34 (KEY_G), down

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM