File: tutorial.rst

package info (click to toggle)
python-evdev 1.1.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 340 kB
  • sloc: python: 1,576; ansic: 607; makefile: 141
file content (436 lines) | stat: -rw-r--r-- 12,220 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
Tutorial
--------


Listing accessible event devices
================================

::

    >>> import evdev

    >>> devices = [evdev.InputDevice(path) for path in evdev.list_devices()]
    >>> for device in devices:
    >>>     print(device.path, device.name, device.phys)
    /dev/input/event1    Dell Dell USB Keyboard   usb-0000:00:12.1-2/input0
    /dev/input/event0    Dell USB Optical Mouse   usb-0000:00:12.0-2/input0


Listing device capabilities
===========================

::

    >>> import evdev

    >>> device = evdev.InputDevice('/dev/input/event0')
    >>> print(device)
    device /dev/input/event0, name "Dell USB Optical Mouse", phys "usb-0000:00:12.0-2/input0"

    >>> device.capabilities()
    ... { 0: [0, 1, 2], 1: [272, 273, 274, 275], 2: [0, 1, 6, 8], 4: [4] }

    >>> device.capabilities(verbose=True)
    ... { ('EV_SYN', 0): [('SYN_REPORT', 0), ('SYN_CONFIG', 1), ('SYN_MT_REPORT', 2)],
    ...   ('EV_KEY', 1): [('BTN_MOUSE', 272), ('BTN_RIGHT', 273), ('BTN_MIDDLE', 274), ('BTN_SIDE', 275)], ...


Listing device capabilities (devices with absolute axes)
========================================================

::

    >>> import evdev

    >>> device = evdev.InputDevice('/dev/input/event7')
    >>> print(device)
    device /dev/input/event7, name "Wacom Bamboo 2FG 4x5 Finger", phys ""

    >>> device.capabilities()
    ... { 1: [272, 273, 277, 278, 325, 330, 333] ,
    ...   3: [(0, AbsInfo(min=0, max=15360, fuzz=128, flat=0)),
    ...       (1, AbsInfo(min=0, max=10240, fuzz=128, flat=0))] }

    >>> device.capabilities(verbose=True)
    ... { ('EV_KEY', 1): [('BTN_MOUSE', 272), ('BTN_RIGHT', 273), ...],
    ...   ('EV_ABS', 3): [(('ABS_X', 0), AbsInfo(min=0, max=15360, fuzz=128, flat=0)),
    ...                   (('ABS_Y', 1), AbsInfo(min=0, max=10240, fuzz=128, flat=0)),] }

    >>> device.capabilities(absinfo=False)
    ... { 1: [272, 273, 277, 278, 325, 330, 333],
    ...   3: [0, 1, 47, 53, 54, 57] }


Getting and setting LED states
==============================

::

    >>> dev.leds(verbose=True)
    ... [('LED_NUML', 0), ('LED_CAPSL', 1)]

    >>> dev.leds()
    ... [0, 1]

    >>> dev.set_led(ecodes.LED_NUML, 1)  # enable numlock
    >>> dev.set_led(ecodes.LED_NUML, 0)  # disable numlock


Getting currently active keys
=============================

::

    >>> dev.active_keys(verbose=True)
    ... [('KEY_3', 4), ('KEY_LEFTSHIFT', 42)]

    >>> dev.active_keys()
    ... [4, 42]


Reading events
==============

Reading events from a single device in an endless loop.

::

    >>> from evdev import InputDevice, categorize, ecodes
    >>> dev = InputDevice('/dev/input/event1')

    >>> print(dev)
    device /dev/input/event1, name "Dell Dell USB Keyboard", phys "usb-0000:00:12.1-2/input0"

    >>> for event in dev.read_loop():
    ...     if event.type == ecodes.EV_KEY:
    ...         print(categorize(event))
    ... # pressing 'a' and holding 'space'
    key event at 1337016188.396030, 30 (KEY_A), down
    key event at 1337016188.492033, 30 (KEY_A), up
    key event at 1337016189.772129, 57 (KEY_SPACE), down
    key event at 1337016190.275396, 57 (KEY_SPACE), hold
    key event at 1337016190.284160, 57 (KEY_SPACE), up


Reading events (using :mod:`asyncio`)
======================================

.. note::

   This requires Python 3.5+ for the async/await keywords.


::

    >>> import asyncio
    >>> from evdev import InputDevice, categorize, ecodes

    >>> dev = InputDevice('/dev/input/event1')

    >>> async def helper(dev):
    ...     async for ev in dev.async_read_loop():
    ...         print(repr(ev))

    >>> loop = asyncio.get_event_loop()
    >>> loop.run_until_complete(helper(dev))
    InputEvent(1527363738, 348740, 4, 4, 458792)
    InputEvent(1527363738, 348740, 1, 28, 0)
    InputEvent(1527363738, 348740, 0, 0, 0)


Reading events from multiple devices (using :mod:`select`)
==========================================================

::

    >>> from evdev import InputDevice
    >>> from select import select

    # A mapping of file descriptors (integers) to InputDevice instances.
    >>> devices = map(InputDevice, ('/dev/input/event1', '/dev/input/event2'))
    >>> devices = {dev.fd: dev for dev in devices}

    >>> for dev in devices.values(): print(dev)
    device /dev/input/event1, name "Dell Dell USB Keyboard", phys "usb-0000:00:12.1-2/input0"
    device /dev/input/event2, name "Logitech USB Laser Mouse", phys "usb-0000:00:12.0-2/input0"

    >>> while True:
    ...    r, w, x = select(devices, [], [])
    ...    for fd in r:
    ...        for event in devices[fd].read():
    ...            print(event)
    event at 1351116708.002230, code 01, type 02, val 01
    event at 1351116708.002234, code 00, type 00, val 00
    event at 1351116708.782231, code 04, type 04, val 458782
    event at 1351116708.782237, code 02, type 01, val 01


Reading events from multiple devices (using :mod:`selectors`)
=============================================================

This can also be achieved using the :mod:`selectors` module in Python 3.4:

::

   from evdev import InputDevice
   from selectors import DefaultSelector, EVENT_READ

   selector = selectors.DefaultSelector()

   mouse = evdev.InputDevice('/dev/input/event1')
   keybd = evdev.InputDevice('/dev/input/event2')

   # This works because InputDevice has a `fileno()` method.
   selector.register(mouse, selectors.EVENT_READ)
   selector.register(keybd, selectors.EVENT_READ)

   while True:
       for key, mask in selector.select():
           device = key.fileobj
           for event in device.read():
               print(event)


Reading events from multiple devices (using :mod:`asyncio`)
===========================================================

Yet another possibility is the :mod:`asyncio` module from Python 3.4:

::

    import asyncio, evdev

    @asyncio.coroutine
    def print_events(device):
        while True:
            events = yield from device.async_read()
            for event in events:
                print(device.path, evdev.categorize(event), sep=': ')

    mouse = evdev.InputDevice('/dev/input/eventX')
    keybd = evdev.InputDevice('/dev/input/eventY')

    for device in mouse, keybd:
        asyncio.async(print_events(device))

    loop = asyncio.get_event_loop()
    loop.run_forever()

Since Python 3.5, the `async/await`_ syntax makes this even simpler:

::

    import asyncio, evdev

    mouse = evdev.InputDevice('/dev/input/event4')
    keybd = evdev.InputDevice('/dev/input/event5')

    async def print_events(device):
        async for event in device.async_read_loop():
            print(device.path, evdev.categorize(event), sep=': ')

    for device in mouse, keybd:
        asyncio.ensure_future(print_events(device))

    loop = asyncio.get_event_loop()
    loop.run_forever()


Accessing evdev constants
=========================

::

    >>> from evdev import ecodes

    >>> ecodes.KEY_A, ecodes.ecodes['KEY_A']
    ... (30, 30)
    >>> ecodes.KEY[30]
    ... 'KEY_A'
    >>> ecodes.bytype[ecodes.EV_KEY][30]
    ... 'KEY_A'
    >>> ecodes.KEY[152]  # a single value may correspond to multiple codes
    ... ['KEY_COFFEE', 'KEY_SCREENLOCK']


Getting exclusive access to a device
====================================

::

    >>> dev.grab()  # become the sole recipient of all incoming input events
    >>> dev.ungrab()

This functionality is also available as a context manager.

::

    >>> with dev.grab_context():
    ...     pass


Associating classes with event types
====================================

::

    >>> from evdev import categorize, event_factory, ecodes

    >>> class SynEvent(object):
    ...     def __init__(self, event):
    ...         ...

    >>> event_factory[ecodes.EV_SYN] = SynEvent

See :mod:`events <evdev.events.event_factory>` for more information.

Injecting input
===============

::

    >>> from evdev import UInput, ecodes as e

    >>> ui = UInput()

    >>> # accepts only KEY_* events by default
    >>> ui.write(e.EV_KEY, e.KEY_A, 1)  # KEY_A down
    >>> ui.write(e.EV_KEY, e.KEY_A, 0)  # KEY_A up
    >>> ui.syn()

    >>> ui.close()


Injecting events (using a context manager)
==========================================

::

    >>> ev = InputEvent(1334414993, 274296, ecodes.EV_KEY, ecodes.KEY_A, 1)
    >>> with UInput() as ui:
    ...    ui.write_event(ev)
    ...    ui.syn()


Specifying ``uinput`` device options
====================================

::

    >>> from evdev import UInput, AbsInfo, ecodes as e

    >>> cap = {
    ...     e.EV_KEY : [e.KEY_A, e.KEY_B],
    ...     e.EV_ABS : [
    ...         (e.ABS_X, AbsInfo(value=0, min=0, max=255,
    ...                           fuzz=0, flat=0, resolution=0)),
    ...         (e.ABS_Y, AbsInfo(0, 0, 255, 0, 0, 0)),
    ...         (e.ABS_MT_POSITION_X, (0, 128, 255, 0)) ]
    ... }

    >>> ui = UInput(cap, name='example-device', version=0x3)
    >>> print(ui)
    name "example-device", bus "BUS_USB", vendor "0001", product "0001", version "0003"
    event types: EV_KEY EV_ABS EV_SYN

    >>> print(ui.capabilities())
    {0: [0, 1, 3],
     1: [30, 48],
     3: [(0,  AbsInfo(value=0, min=0, max=0,   fuzz=255, flat=0, resolution=0)),
         (1,  AbsInfo(value=0, min=0, max=0,   fuzz=255, flat=0, resolution=0)),
         (53, AbsInfo(value=0, min=0, max=255, fuzz=128, flat=0, resolution=0))]}

    >>> # move mouse cursor
    >>> ui.write(e.EV_ABS, e.ABS_X, 20)
    >>> ui.write(e.EV_ABS, e.ABS_Y, 20)
    >>> ui.syn()


Create ``uinput`` device with capabilities of another device
================================================================

::

    >>> from evdev import UInput, InputDevice

    >>> mouse = InputDevice('/dev/input/event1')
    >>> keybd = '/dev/input/event2'

    >>> ui = UInput.from_device(mouse, keybd, name='keyboard-mouse-device')
    >>> ui.capabilities(verbose=True).keys()
    dict_keys([('EV_LED', 17), ('EV_KEY', 1), ('EV_SYN', 0), ('EV_REL', 2), ('EV_MSC', 4)])


.. _`async/await`:  https://docs.python.org/3/library/asyncio-task.html

Create ``uinput`` device capable of recieving FF-effects
========================================================

::

    import asyncio
    from evdev import UInput, categorize, ecodes

    cap = {
       ecodes.EV_FF:  [ecodes.FF_RUMBLE ],
       ecodes.EV_KEY: [ecodes.KEY_A, ecodes.KEY_B]
    }

    ui = UInput(cap, name='test-controller', version=0x3)

    async def print_events(device):
        async for event in device.async_read_loop():
            print(categorize(event))

            # Wait for an EV_UINPUT event that will signal us that an
            # effect upload/erase operation is in progress.
            if event.type != ecodes.EV_UINPUT:
                pass

            if event.code == ecodes.UI_FF_UPLOAD:
                upload = device.begin_upload(event.value)
                upload.retval = 0

                print(f'[upload] effect_id: {upload.effect_id}, type: {upload.effect.type}')
                device.end_upload(upload)

            elif event.code == ecodes.UI_FF_ERASE:
                erase = device.begin_erase(event.value)
                print(f'[erase] effect_id {erase.effect_id}')

                erase.retval = 0
                device.end_erase(erase)

    asyncio.ensure_future(print_events(ui))
    loop = asyncio.get_event_loop()
    loop.run_forever()


Injecting an FF-event into first FF-capable device found
========================================================

::

    from evdev import ecodes, InputDevice, ff

    # Find first EV_FF capable event device (that we have permissions to use).
    for name in evdev.list_devices():
        dev = InputDevice(name)
        if ecodes.EV_FF in dev.capabilities():
            break

    rumble = ff.Rumble(strong_magnitude=0x0000, weak_magnitude=0xffff)
    effect_type = ff.EffectType(ff_rumble_effect=rumble)
    duration_ms = 1000

    effect = ff.Effect(
        ecodes.FF_RUMBLE, -1, 0,
        ff.Trigger(0, 0),
        ff.Replay(duration_ms, 0),
        ff.EffectType(ff_rumble_effect=rumble)
    )

    repeat_count = 1
    effect_id = dev.upload_effect(effect)
    dev.write(e.EV_FF, effect_id, repeat_count)
    dev.erase_effect(effect_id)