Tweak the second keyboard robot recipe so it detects keyboards and
doesn't throw exceptions on unknown keys. Also add a note to the recipe
that it won't work over remote connections like SSH.
This commit is contained in:
Dave Jones
2016-08-29 22:18:04 +01:00
parent c51f447800
commit 07c95598d1
2 changed files with 24 additions and 4 deletions

View File

@@ -3,8 +3,23 @@ from evdev import InputDevice, list_devices, ecodes
robot = Robot(left=(4, 14), right=(17, 18))
# Get the list of available input devices
devices = [InputDevice(device) for device in list_devices()]
keyboard = devices[0] # this may vary
# Filter out everything that's not a keyboard. Keyboards are defined as any
# device which has keys, and which specifically has keys 1..31 (roughly Esc,
# the numeric keys, the first row of QWERTY plus a few more) and which does
# *not* have key 0 (reserved)
must_have = {i for i in range(1, 32)}
must_not_have = {0}
devices = [
device
for device in devices
for keys in (set(device.capabilities().get(ecodes.EV_KEY, [])),)
if must_have.issubset(keys)
and must_not_have.isdisjoint(keys)
]
# Pick the first keyboard
keyboard = devices[0]
keypress_actions = {
ecodes.KEY_UP: robot.forward,
@@ -14,7 +29,7 @@ keypress_actions = {
}
for event in keyboard.read_loop():
if event.type == ecodes.EV_KEY:
if event.type == ecodes.EV_KEY and event.code in keypress_actions:
if event.value == 1: # key down
keypress_actions[event.code]()
if event.value == 0: # key up