我有一个游戏手柄(用于PC的Buffalo iBuffalo Classic USB Gampe),并且想在按下按钮时读取其输入值。
我正在使用,
Ubuntu 16.04
Kernel 4.15
64 bit
在我的代码中,
import sys
pipe = open("/dev/input/js0", "r", encoding="utf-8")
msg = []
while 1:
for char in pipe.read(1):
msg += [ord(char)]
if len(msg) == 8:
print(msg)
msg = []
但是,我收到unicodeDecodeError 'utf-8' codec can't decode byte 0xc8 in position 0: invalid continuation byte
。所以我使用了codec
模块,
import codec
pipe = codec.open("/dev/input/js0", "r", encoding="utf-8")
但是我仍然遇到同样的错误。我还尝试读取其他模式rb
。如何读取此输入值并将其作为8btye值并以六进制格式(例如001c)
答案 0 :(得分:6)
您可以运行以下python代码来读取事件:
#!/usr/bin/env python
import struct
infile_path = "/dev/input/js0"
EVENT_SIZE = struct.calcsize("llHHI")
file = open(infile_path, "rb")
event = file.read(EVENT_SIZE)
while event:
print(struct.unpack("llHHI", event))
(tv_sec, tv_usec, type, code, value) = struct.unpack("llHHI", event)
event = file.read(EVENT_SIZE)
输出ex:
(73324490, 142671872, 55242, 1118, 159449088)
您可以添加一个条件,以便您获得8个字节
其他
如果要更好地操纵输入序列,请根据linux/joystick.h
文件:
struct js_event {
__u32 time; /* event timestamp in milliseconds */
__s16 value; /* value */
__u8 type; /* event type */
__u8 number; /* axis/button number */
};
因此,如果您使用struct.unpack("LhBB", event)
和struct.calcsize("LhBB")
则得到(XBOX输出):
//msec, value, type, number
(2114530, 1, 1, 0) // A pressed
(2114670, 0, 1, 0) // A released
(2116490, 1, 1, 1) // B pressed
(2116620, 0, 1, 1) // B released
(2117370, 1, 1, 2) // X pressed
(2117520, 0, 1, 2) // X released
(2118220, 1, 1, 3) // Y pressed
(2118360, 0, 1, 3) // Y released
您还可以使用高级模块python-evdev https://github.com/gvalkov/python-evdev