File: device.py

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 (379 lines) | stat: -rw-r--r-- 10,584 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
# encoding: utf-8

import os
import warnings
import contextlib
import collections

from evdev import _input, ecodes, util
from evdev.events import InputEvent

try:
    from evdev.eventio_async import EventIO, EvdevError
except ImportError:
    from evdev.eventio import EventIO, EvdevError


#--------------------------------------------------------------------------
_AbsInfo = collections.namedtuple(
    'AbsInfo', ['value', 'min', 'max', 'fuzz', 'flat', 'resolution'])

_KbdInfo = collections.namedtuple(
    'KbdInfo', ['repeat', 'delay'])

_DeviceInfo = collections.namedtuple(
    'DeviceInfo', ['bustype', 'vendor', 'product', 'version'])


class AbsInfo(_AbsInfo):
    '''Absolute axis information.

    A ``namedtuple`` used for storing absolute axis information -
    corresponds to the ``input_absinfo`` struct:

    Attributes
    ---------
    value
      Latest reported value for the axis.

    min
      Specifies minimum value for the axis.

    max
      Specifies maximum value for the axis.

    fuzz
      Specifies fuzz value that is used to filter noise from the
      event stream.

    flat
      Values that are within this value will be discarded by joydev
      interface and reported as 0 instead.

    resolution
      Specifies resolution for the values reported for the axis.
      Resolution for main axes (``ABS_X, ABS_Y, ABS_Z``) is reported
      in units per millimeter (units/mm), resolution for rotational
      axes (``ABS_RX, ABS_RY, ABS_RZ``) is reported in units per
      radian.

    Note
    ----
    The input core does not clamp reported values to the ``[minimum,
    maximum]`` limits, such task is left to userspace.

    '''

    def __str__(self):
        return 'val {}, min {}, max {}, fuzz {}, flat {}, res {}'.format(*self)


class KbdInfo(_KbdInfo):
    '''Keyboard repeat rate.

    Attributes
    ----------
    repeat
      Keyboard repeat rate in characters per second.

    delay
      Amount of time that a key must be depressed before it will start
      to repeat (in milliseconds).
    '''

    def __str__(self):
        return 'repeat {}, delay {}'.format(*self)


class DeviceInfo(_DeviceInfo):
    '''
    Attributes
    ----------
    bustype
    vendor
    product
    version
    '''

    def __str__(self):
        msg = 'bus: {:04x}, vendor {:04x}, product {:04x}, version {:04x}'
        return msg.format(*self)


class InputDevice(EventIO):
    '''
    A linux input device from which input events can be read.
    '''

    __slots__ = ('path', 'fd', 'info', 'name', 'phys', 'uniq', '_rawcapabilities',
                 'version', 'ff_effects_count')

    def __init__(self, dev):
        '''
        Arguments
        ---------
        dev : str|bytes|PathLike
          Path to input device
        '''

        #: Path to input device.
        self.path = dev if not hasattr(dev, '__fspath__') else dev.__fspath__()

        # Certain operations are possible only when the device is opened in
        # read-write mode.
        try:
            fd = os.open(dev, os.O_RDWR | os.O_NONBLOCK)
        except OSError:
            fd = os.open(dev, os.O_RDONLY | os.O_NONBLOCK)

        #: A non-blocking file descriptor to the device file.
        self.fd = fd

        # Returns (bustype, vendor, product, version, name, phys, capabilities).
        info_res = _input.ioctl_devinfo(self.fd)

        #: A :class:`DeviceInfo <evdev.device.DeviceInfo>` instance.
        self.info = DeviceInfo(*info_res[:4])

        #: The name of the event device.
        self.name = info_res[4]

        #: The physical topology of the device.
        self.phys = info_res[5]

        #: The unique address of the device.
        self.uniq = info_res[6]

        #: The evdev protocol version.
        self.version = _input.ioctl_EVIOCGVERSION(self.fd)

        #: The raw dictionary of device capabilities - see `:func:capabilities()`.
        self._rawcapabilities = _input.ioctl_capabilities(self.fd)

        #: The number of force feedback effects the device can keep in its memory.
        self.ff_effects_count = _input.ioctl_EVIOCGEFFECTS(self.fd)

    def __del__(self):
        if hasattr(self, 'fd') and self.fd is not None:
            try:
                self.close()
            except OSError:
                pass

    def _capabilities(self, absinfo=True):
        res = {}

        for etype, ecodes in self._rawcapabilities.items():
            for code in ecodes:
                l = res.setdefault(etype, [])
                if isinstance(code, tuple):
                    if absinfo:
                        a = code[1]  # (0, 0, 0, 255, 0, 0)
                        i = AbsInfo(*a)
                        l.append((code[0], i))
                    else:
                        l.append(code[0])
                else:
                    l.append(code)

        return res

    def capabilities(self, verbose=False, absinfo=True):
        '''
        Return the event types that this device supports as a mapping of
        supported event types to lists of handled event codes.

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

        If ``verbose`` is ``True``, event codes and types will be resolved
        to their names.

        ::

          { ('EV_KEY', 1): [('BTN_MOUSE', 272),
                            ('BTN_RIGHT', 273),
                            ('BTN_MIDDLE', 273)],
            ('EV_REL', 2): [('REL_X', 0),
                            ('REL_Y', 1),
                            ('REL_HWHEEL', 6),
                            ('REL_WHEEL', 8)] }

        Unknown codes or types will be resolved to ``'?'``.

        If ``absinfo`` is ``True``, the list of capabilities will also
        include absolute axis information in the form of
        :class:`AbsInfo` instances::

          { 3: [ (0, AbsInfo(min=0, max=255, fuzz=0, flat=0)),
                 (1, AbsInfo(min=0, max=255, fuzz=0, flat=0)) ]}

        Combined with ``verbose`` the above becomes::

          { ('EV_ABS', 3): [ (('ABS_X', 0), AbsInfo(min=0, max=255, fuzz=0, flat=0)),
                             (('ABS_Y', 1), AbsInfo(min=0, max=255, fuzz=0, flat=0)) ]}

        '''

        if verbose:
            return dict(util.resolve_ecodes_dict(self._capabilities(absinfo)))
        else:
            return self._capabilities(absinfo)

    def leds(self, verbose=False):
        '''
        Return currently set LED keys.

        Example
        -------
        >>> device.leds()
        [0, 1, 8, 9]

        If ``verbose`` is ``True``, event codes are resolved to their
        names. Unknown codes are resolved to ``'?'``::

        [('LED_NUML', 0), ('LED_CAPSL', 1), ('LED_MISC', 8), ('LED_MAIL', 9)]

        '''
        leds = _input.ioctl_EVIOCG_bits(self.fd, ecodes.EV_LED)
        if verbose:
            return util.resolve_ecodes(ecodes.LED, leds)

        return leds

    def set_led(self, led_num, value):
        '''
        Set the state of the selected LED.

        Example
        -------
        >>> device.set_led(ecodes.LED_NUML, 1)
        '''
        self.write(ecodes.EV_LED, led_num, value)

    def __eq__(self, other):
        '''
        Two devices are equal if their :data:`info` attributes are equal.
        '''
        return isinstance(other, self.__class__) and self.info == other.info \
            and self.path == other.path

    def __ne__(self, other):
        # Python 2 compatibility. Python 3 automatically negates the value of
        # __eq__, in case __ne__ is not defined.
        return not self == other

    def __str__(self):
        msg = 'device {}, name "{}", phys "{}"'
        return msg.format(self.path, self.name, self.phys)

    def __repr__(self):
        msg = (self.__class__.__name__, self.path)
        return '{}({!r})'.format(*msg)

    def __fspath__(self):
        return self.path

    def close(self):
        if self.fd > -1:
            try:
                os.close(self.fd)
            finally:
                self.fd = -1

    def grab(self):
        '''
        Grab input device using ``EVIOCGRAB`` - other applications will
        be unable to receive events until the device is released. Only
        one process can hold a ``EVIOCGRAB`` on a device.

        Warning
        -------
        Grabbing an already grabbed device will raise an ``IOError``.
        '''

        _input.ioctl_EVIOCGRAB(self.fd, 1)

    def ungrab(self):
        '''
        Release device if it has been already grabbed (uses `EVIOCGRAB`).

        Warning
        -------
        Releasing an already released device will raise an
        ``IOError('Invalid argument')``.
        '''

        _input.ioctl_EVIOCGRAB(self.fd, 0)

    @contextlib.contextmanager
    def grab_context(self):
        '''
        A context manager for the duration of which only the current
        process will be able to receive events from the device.
        '''
        self.grab()
        yield
        self.ungrab()

    def upload_effect(self, effect):
        '''
        Upload a force feedback effect to a force feedback device.
        '''

        data = memoryview(effect).tobytes()
        ff_id = _input.upload_effect(self.fd, data)
        return ff_id

    def erase_effect(self, ff_id):
        '''
        Erase a force effect from a force feedback device. This also
        stops the effect.
        '''

        _input.erase_effect(self.fd, ff_id)

    @property
    def repeat(self):
        '''
        Get or set the keyboard repeat rate (in characters per
        minute) and delay (in milliseconds).
        '''

        return KbdInfo(*_input.ioctl_EVIOCGREP(self.fd))

    @repeat.setter
    def repeat(self, value):
        return _input.ioctl_EVIOCSREP(self.fd, *value)

    def active_keys(self, verbose=False):
        '''
        Return currently active keys.

        Example
        -------

        >>> device.active_keys()
        [1, 42]

        If ``verbose`` is ``True``, key codes are resolved to their
        verbose names. Unknown codes are resolved to ``'?'``. For
        example::

          [('KEY_ESC', 1), ('KEY_LEFTSHIFT', 42)]

        '''
        active_keys = _input.ioctl_EVIOCG_bits(self.fd, ecodes.EV_KEY)
        if verbose:
            return util.resolve_ecodes(ecodes.KEY, active_keys)

        return active_keys

    @property
    def fn(self):
        msg = 'Please use {0}.path instead of {0}.fn'.format(self.__class__.__name__)
        warnings.warn(msg, DeprecationWarning, stacklevel=2)
        return self.path