0
# Event Codes and Constants
1
2
Comprehensive mapping of Linux input subsystem constants and utilities for resolving event codes to human-readable names. The ecodes module provides access to all kernel-defined constants for event types, key codes, and device properties.
3
4
## Capabilities
5
6
### Event Type Constants
7
8
Primary event type classifications from the Linux input subsystem.
9
10
```python { .api }
11
# Core event types
12
EV_SYN: int # Synchronization events
13
EV_KEY: int # Key/button events
14
EV_REL: int # Relative axis events (mouse movement)
15
EV_ABS: int # Absolute axis events (touchscreen, joystick)
16
EV_MSC: int # Miscellaneous events
17
EV_SW: int # Switch events
18
EV_LED: int # LED events
19
EV_SND: int # Sound events
20
EV_REP: int # Repeat events
21
EV_FF: int # Force feedback events
22
EV_PWR: int # Power button events
23
EV_FF_STATUS: int # Force feedback status
24
25
# Event type mapping dictionary
26
EV: Dict[int, str] # Maps event type codes to names
27
```
28
29
### Key and Button Codes
30
31
Constants for keyboard keys and button identifiers.
32
33
```python { .api }
34
# Keyboard key constants (examples - hundreds available)
35
KEY_A: int # 'A' key
36
KEY_B: int # 'B' key
37
KEY_SPACE: int # Space bar
38
KEY_ENTER: int # Enter key
39
KEY_ESC: int # Escape key
40
KEY_BACKSPACE: int # Backspace key
41
KEY_TAB: int # Tab key
42
KEY_LEFTSHIFT: int # Left shift key
43
KEY_RIGHTCTRL: int # Right control key
44
KEY_LEFTALT: int # Left alt key
45
46
# Function keys
47
KEY_F1: int # F1 key
48
KEY_F2: int # F2 key
49
# ... F1-F24
50
51
# Arrow keys
52
KEY_UP: int # Up arrow
53
KEY_DOWN: int # Down arrow
54
KEY_LEFT: int # Left arrow
55
KEY_RIGHT: int # Right arrow
56
57
# Numeric keypad
58
KEY_KP0: int # Keypad 0
59
KEY_KP1: int # Keypad 1
60
# ... KP0-KP9
61
62
# Button constants
63
BTN_LEFT: int # Left mouse button
64
BTN_RIGHT: int # Right mouse button
65
BTN_MIDDLE: int # Middle mouse button
66
BTN_SIDE: int # Side mouse button
67
BTN_EXTRA: int # Extra mouse button
68
69
# Gamepad buttons
70
BTN_A: int # Gamepad A button
71
BTN_B: int # Gamepad B button
72
BTN_X: int # Gamepad X button
73
BTN_Y: int # Gamepad Y button
74
BTN_START: int # Start button
75
BTN_SELECT: int # Select button
76
77
# Key/button mapping dictionaries
78
KEY: Dict[int, str] # Maps key codes to names
79
BTN: Dict[int, str] # Maps button codes to names
80
keys: Dict[int, str] # Combined KEY and BTN mappings
81
```
82
83
### Relative Axis Codes
84
85
Constants for relative positioning devices (mice, trackballs).
86
87
```python { .api }
88
# Relative axis constants
89
REL_X: int # X-axis movement
90
REL_Y: int # Y-axis movement
91
REL_Z: int # Z-axis movement
92
REL_RX: int # X-axis rotation
93
REL_RY: int # Y-axis rotation
94
REL_RZ: int # Z-axis rotation
95
REL_HWHEEL: int # Horizontal wheel
96
REL_DIAL: int # Dial rotation
97
REL_WHEEL: int # Vertical wheel
98
REL_MISC: int # Miscellaneous
99
100
# Relative axis mapping dictionary
101
REL: Dict[int, str] # Maps relative axis codes to names
102
```
103
104
### Absolute Axis Codes
105
106
Constants for absolute positioning devices (touchscreens, joysticks, tablets).
107
108
```python { .api }
109
# Absolute axis constants
110
ABS_X: int # X-axis position
111
ABS_Y: int # Y-axis position
112
ABS_Z: int # Z-axis position
113
ABS_RX: int # X-axis rotation
114
ABS_RY: int # Y-axis rotation
115
ABS_RZ: int # Z-axis rotation
116
ABS_THROTTLE: int # Throttle
117
ABS_RUDDER: int # Rudder
118
ABS_WHEEL: int # Wheel
119
ABS_GAS: int # Gas pedal
120
ABS_BRAKE: int # Brake pedal
121
122
# Multi-touch constants
123
ABS_MT_SLOT: int # Multi-touch slot
124
ABS_MT_TOUCH_MAJOR: int # Touch major axis
125
ABS_MT_TOUCH_MINOR: int # Touch minor axis
126
ABS_MT_WIDTH_MAJOR: int # Width major axis
127
ABS_MT_WIDTH_MINOR: int # Width minor axis
128
ABS_MT_ORIENTATION: int # Touch orientation
129
ABS_MT_POSITION_X: int # Multi-touch X position
130
ABS_MT_POSITION_Y: int # Multi-touch Y position
131
ABS_MT_TOOL_TYPE: int # Tool type
132
ABS_MT_BLOB_ID: int # Blob identifier
133
ABS_MT_TRACKING_ID: int # Tracking identifier
134
ABS_MT_PRESSURE: int # Touch pressure
135
ABS_MT_DISTANCE: int # Distance from surface
136
137
# Absolute axis mapping dictionary
138
ABS: Dict[int, str] # Maps absolute axis codes to names
139
```
140
141
### Synchronization Codes
142
143
Constants for event synchronization and timing.
144
145
```python { .api }
146
# Sync event constants
147
SYN_REPORT: int # Synchronization report
148
SYN_CONFIG: int # Configuration sync
149
SYN_MT_REPORT: int # Multi-touch report
150
SYN_DROPPED: int # Events dropped
151
152
# Sync mapping dictionary
153
SYN: Dict[int, str] # Maps sync codes to names
154
```
155
156
### LED Codes
157
158
Constants for LED indicators on devices.
159
160
```python { .api }
161
# LED constants
162
LED_NUML: int # Num Lock LED
163
LED_CAPSL: int # Caps Lock LED
164
LED_SCROLLL: int # Scroll Lock LED
165
LED_COMPOSE: int # Compose LED
166
LED_KANA: int # Kana LED
167
LED_SLEEP: int # Sleep LED
168
LED_SUSPEND: int # Suspend LED
169
LED_MUTE: int # Mute LED
170
LED_MISC: int # Miscellaneous LED
171
172
# LED mapping dictionary
173
LED: Dict[int, str] # Maps LED codes to names
174
```
175
176
### Switch Codes
177
178
Constants for switch events (lid switches, tablet mode, etc.).
179
180
```python { .api }
181
# Switch constants
182
SW_LID: int # Lid switch
183
SW_TABLET_MODE: int # Tablet mode
184
SW_HEADPHONE_INSERT: int # Headphone insertion
185
SW_RFKILL_ALL: int # RF kill switch
186
SW_RADIO: int # Radio switch
187
SW_MICROPHONE_INSERT: int # Microphone insertion
188
SW_DOCK: int # Dock switch
189
SW_LINEOUT_INSERT: int # Line out insertion
190
SW_JACK_PHYSICAL_INSERT: int # Physical jack insertion
191
192
# Switch mapping dictionary
193
SW: Dict[int, str] # Maps switch codes to names
194
```
195
196
### Force Feedback Codes
197
198
Constants for force feedback effects and status.
199
200
```python { .api }
201
# Force feedback effect types
202
FF_RUMBLE: int # Rumble effect
203
FF_PERIODIC: int # Periodic effect
204
FF_CONSTANT: int # Constant force effect
205
FF_SPRING: int # Spring effect
206
FF_FRICTION: int # Friction effect
207
FF_DAMPER: int # Damper effect
208
FF_INERTIA: int # Inertia effect
209
FF_RAMP: int # Ramp effect
210
211
# Periodic waveforms
212
FF_SQUARE: int # Square wave
213
FF_TRIANGLE: int # Triangle wave
214
FF_SINE: int # Sine wave
215
FF_SAW_UP: int # Sawtooth up
216
FF_SAW_DOWN: int # Sawtooth down
217
FF_CUSTOM: int # Custom waveform
218
219
# Force feedback mapping dictionaries
220
FF: Dict[int, str] # Maps FF codes to names
221
FF_STATUS: Dict[int, str] # Maps FF status codes to names
222
```
223
224
### Bus Type Codes
225
226
Constants for device bus types.
227
228
```python { .api }
229
# Bus type constants
230
BUS_PCI: int # PCI bus
231
BUS_ISAPNP: int # ISA Plug and Play
232
BUS_USB: int # USB bus
233
BUS_HIL: int # HIL bus
234
BUS_BLUETOOTH: int # Bluetooth
235
BUS_VIRTUAL: int # Virtual bus
236
BUS_ISA: int # ISA bus
237
BUS_I8042: int # i8042 controller
238
BUS_XTKBD: int # XT keyboard
239
BUS_RS232: int # RS232 serial
240
BUS_GAMEPORT: int # Gameport
241
BUS_PARPORT: int # Parallel port
242
BUS_AMIGA: int # Amiga bus
243
BUS_ADB: int # Apple Desktop Bus
244
BUS_I2C: int # I2C bus
245
BUS_HOST: int # Host bus
246
BUS_GSC: int # GSC bus
247
BUS_ATARI: int # Atari bus
248
BUS_SPI: int # SPI bus
249
250
# Bus type mapping dictionary
251
BUS: Dict[int, str] # Maps bus type codes to names
252
```
253
254
### Input Properties
255
256
Constants for device input properties and quirks.
257
258
```python { .api }
259
# Input property constants
260
INPUT_PROP_POINTER: int # Device is a pointer
261
INPUT_PROP_DIRECT: int # Direct input device
262
INPUT_PROP_BUTTONPAD: int # Device is a buttonpad
263
INPUT_PROP_SEMI_MT: int # Semi-multitouch device
264
INPUT_PROP_TOPBUTTONPAD: int # Top button pad
265
INPUT_PROP_POINTING_STICK: int # Pointing stick
266
INPUT_PROP_ACCELEROMETER: int # Accelerometer
267
268
# Input properties mapping dictionary
269
INPUT_PROP: Dict[int, str] # Maps property codes to names
270
```
271
272
### Code Resolution Utilities
273
274
Functions for converting between numeric codes and human-readable names.
275
276
```python { .api }
277
def resolve_ecodes(ecode_dict: Dict, ecode_list: List, unknown: str = "?") -> List:
278
"""
279
Resolve event codes to their verbose names.
280
281
Parameters:
282
- ecode_dict: Dictionary mapping codes to names (e.g., ecodes.KEY)
283
- ecode_list: List of numeric codes to resolve
284
- unknown: String to use for unknown codes
285
286
Returns:
287
List of resolved code names or tuples for complex cases
288
289
Example:
290
>>> resolve_ecodes(ecodes.KEY, [30, 48, 46])
291
[('KEY_A', 30), ('KEY_B', 48), ('KEY_C', 46)]
292
"""
293
294
def resolve_ecodes_dict(typecodemap: Dict, unknown: str = "?") -> Iterator:
295
"""
296
Resolve event types and codes to verbose names.
297
298
Parameters:
299
- typecodemap: Dictionary mapping event types to code lists
300
{1: [272, 273], 3: [(0, AbsInfo(...))]}
301
- unknown: String to use for unknown types/codes
302
303
Yields:
304
Tuples of ((type_name, type_code), resolved_codes)
305
306
Example:
307
>>> resolve_ecodes_dict({1: [272, 273, 274]})
308
(('EV_KEY', 1), [('BTN_MOUSE', 272), ('BTN_RIGHT', 273), ('BTN_MIDDLE', 274)])
309
"""
310
311
def find_ecodes_by_regex(regex) -> Dict[int, List[int]]:
312
"""
313
Find ecodes matching a regex pattern and return mapping of event type to event codes.
314
315
Parameters:
316
- regex: Pattern string or compiled regular expression object
317
318
Returns:
319
Dictionary mapping event type codes to lists of matching event codes
320
321
Example:
322
>>> find_ecodes_by_regex(r'(ABS|KEY)_BR(AKE|EAK)')
323
{1: [411], 3: [10]}
324
>>> res = find_ecodes_by_regex(r'BTN_(A|B|X|Y)')
325
>>> resolve_ecodes_dict(res)
326
(('EV_KEY', 1), [('BTN_A', 304), ('BTN_B', 305), ('BTN_X', 307), ('BTN_Y', 308)])
327
"""
328
```
329
330
### Master Code Dictionary
331
332
Central mapping of all constant names to their numeric values.
333
334
```python { .api }
335
ecodes: Dict[str, int] # Maps all constant names to values
336
# Example: ecodes['KEY_A'] == 30, ecodes['EV_KEY'] == 1
337
338
# Reverse mappings by event type
339
bytype: Dict[int, Dict[int, str]] # Maps event types to their code dictionaries
340
# Example: bytype[EV_KEY] == KEY dictionary, bytype[EV_REL] == REL dictionary
341
```
342
343
## Usage Examples
344
345
### Basic Code Resolution
346
347
```python
348
from evdev import ecodes
349
350
# Access constants directly
351
print(f"KEY_A code: {ecodes.KEY_A}")
352
print(f"EV_KEY type: {ecodes.EV_KEY}")
353
354
# Resolve code to name
355
key_name = ecodes.KEY[ecodes.KEY_A]
356
print(f"Code {ecodes.KEY_A} is: {key_name}")
357
358
# Check if code exists
359
if ecodes.KEY_SPACE in ecodes.KEY:
360
print(f"Space key name: {ecodes.KEY[ecodes.KEY_SPACE]}")
361
```
362
363
### Event Code Resolution
364
365
```python
366
from evdev import ecodes, resolve_ecodes, resolve_ecodes_dict
367
368
# Resolve multiple key codes
369
key_codes = [ecodes.KEY_A, ecodes.KEY_B, ecodes.KEY_C]
370
resolved = resolve_ecodes(ecodes.KEY, key_codes)
371
print("Resolved keys:", resolved)
372
373
# Resolve device capabilities
374
capabilities = {
375
ecodes.EV_KEY: [ecodes.KEY_A, ecodes.KEY_B, ecodes.BTN_LEFT],
376
ecodes.EV_REL: [ecodes.REL_X, ecodes.REL_Y, ecodes.REL_WHEEL]
377
}
378
379
for (type_name, type_code), codes in resolve_ecodes_dict(capabilities):
380
print(f"Event type {type_name} ({type_code}):")
381
for code_info in codes:
382
if isinstance(code_info, tuple):
383
code_name, code_num = code_info
384
print(f" {code_name} ({code_num})")
385
else:
386
print(f" {code_info}")
387
```
388
389
### Finding Codes by Pattern
390
391
```python
392
from evdev import ecodes
393
import re
394
395
# Find all function key constants
396
function_keys = [name for name in dir(ecodes) if name.startswith('KEY_F')]
397
print("Function keys:", function_keys)
398
399
# Find mouse button constants
400
mouse_buttons = [name for name in dir(ecodes) if 'BTN' in name and 'MOUSE' in name]
401
print("Mouse buttons:", mouse_buttons)
402
403
# Using regex search (if available)
404
try:
405
from evdev.util import find_ecodes_by_regex
406
gamepad_codes = find_ecodes_by_regex(r'BTN_(A|B|X|Y|START|SELECT)')
407
print("Gamepad buttons:", gamepad_codes)
408
except ImportError:
409
# Alternative manual search
410
gamepad_buttons = [name for name in dir(ecodes)
411
if any(btn in name for btn in ['BTN_A', 'BTN_B', 'BTN_X', 'BTN_Y'])]
412
print("Gamepad buttons:", gamepad_buttons)
413
```
414
415
### Working with Multi-Touch Constants
416
417
```python
418
from evdev import ecodes
419
420
# Multi-touch axis codes
421
mt_axes = [
422
ecodes.ABS_MT_POSITION_X,
423
ecodes.ABS_MT_POSITION_Y,
424
ecodes.ABS_MT_PRESSURE,
425
ecodes.ABS_MT_TRACKING_ID
426
]
427
428
print("Multi-touch axes:")
429
for axis in mt_axes:
430
axis_name = ecodes.ABS[axis]
431
print(f" {axis_name}: {axis}")
432
```
433
434
### Device Type Detection
435
436
```python
437
from evdev import InputDevice, ecodes
438
439
def analyze_device_type(device_path):
440
device = InputDevice(device_path)
441
caps = device.capabilities()
442
443
device_types = []
444
445
# Check for keyboard
446
if ecodes.EV_KEY in caps:
447
key_codes = caps[ecodes.EV_KEY]
448
if any(code in key_codes for code in [ecodes.KEY_A, ecodes.KEY_SPACE]):
449
device_types.append("keyboard")
450
if any(code in key_codes for code in [ecodes.BTN_LEFT, ecodes.BTN_RIGHT]):
451
device_types.append("mouse")
452
if any(code in key_codes for code in [ecodes.BTN_A, ecodes.BTN_B]):
453
device_types.append("gamepad")
454
455
# Check for mouse movement
456
if ecodes.EV_REL in caps:
457
rel_codes = caps[ecodes.EV_REL]
458
if ecodes.REL_X in rel_codes and ecodes.REL_Y in rel_codes:
459
device_types.append("pointer")
460
461
# Check for touchscreen/tablet
462
if ecodes.EV_ABS in caps:
463
abs_codes = [code[0] if isinstance(code, tuple) else code
464
for code in caps[ecodes.EV_ABS]]
465
if ecodes.ABS_X in abs_codes and ecodes.ABS_Y in abs_codes:
466
if any(code in abs_codes for code in [ecodes.ABS_MT_POSITION_X]):
467
device_types.append("touchscreen")
468
else:
469
device_types.append("tablet/joystick")
470
471
print(f"Device: {device.name}")
472
print(f"Types: {', '.join(device_types) if device_types else 'unknown'}")
473
474
device.close()
475
return device_types
476
477
# Analyze all devices
478
from evdev import list_devices
479
for device_path in list_devices():
480
analyze_device_type(device_path)
481
```
482
483
### Custom Code Mapping
484
485
```python
486
from evdev import ecodes
487
488
# Create custom mappings for specific use cases
489
WASD_KEYS = {
490
'w': ecodes.KEY_W,
491
'a': ecodes.KEY_A,
492
's': ecodes.KEY_S,
493
'd': ecodes.KEY_D
494
}
495
496
ARROW_KEYS = {
497
'up': ecodes.KEY_UP,
498
'down': ecodes.KEY_DOWN,
499
'left': ecodes.KEY_LEFT,
500
'right': ecodes.KEY_RIGHT
501
}
502
503
# Function to get key code by name
504
def get_key_code(key_name):
505
# Try direct lookup
506
attr_name = f'KEY_{key_name.upper()}'
507
if hasattr(ecodes, attr_name):
508
return getattr(ecodes, attr_name)
509
510
# Try custom mappings
511
if key_name.lower() in WASD_KEYS:
512
return WASD_KEYS[key_name.lower()]
513
514
if key_name.lower() in ARROW_KEYS:
515
return ARROW_KEYS[key_name.lower()]
516
517
raise ValueError(f"Unknown key: {key_name}")
518
519
# Usage
520
try:
521
code = get_key_code('a')
522
print(f"Key 'a' has code: {code}")
523
except ValueError as e:
524
print(e)
525
```