evdev module-----device.py

OS: Chrome

installed Directory: /usr/local/lib64/python2.7/site-packages/evdev/

files:_ecodes.so, _input.so, _uinput.so;

        device.py, events.py, uinput.py, util.py ecodes.py, __init__.py

it also has a offical website :https://python-evdev.readthedocs.io/en/latest/install.html

below is device.py

  1 # encoding: utf-8
  2 
  3 import os
  4 from select import select
  5 from collections import namedtuple
  6 
  7 from evdev import _input, ecodes, util
  8 from evdev.events import InputEvent
  9 
 10 
 11 _AbsInfo = namedtuple('AbsInfo', ['value', 'min', 'max', 'fuzz', 'flat', 'resolution'])
 12 _KbdInfo = namedtuple('KbdInfo', ['repeat', 'delay'])
 13 _DeviceInfo = namedtuple('DeviceInfo', ['bustype', 'product', 'vendor', 'version'])
 14 
 15 
 16 class AbsInfo(_AbsInfo):
 17     '''
 18     A ``namedtuple`` for storing absolut axis information -
 19     corresponds to the ``input_absinfo`` c struct:
 20 
 21      - value
 22         Latest reported value for the axis.
 23 
 24      - min
 25         Specifies minimum value for the axis.
 26 
 27      - max
 28         Specifies maximum value for the axis.
 29 
 30      - fuzz
 31         Specifies fuzz value that is used to filter noise from the
 32         event stream.
 33 
 34      - flat
 35         Values that are within this value will be discarded by joydev
 36         interface and reported as 0 instead.
 37 
 38      - resolution
 39         Specifies resolution for the values reported for the axis.
 40         Resolution for main axes (``ABS_X, ABS_Y, ABS_Z``) is reported
 41         in units per millimeter (units/mm), resolution for rotational
 42         axes (``ABS_RX, ABS_RY, ABS_RZ``) is reported in units per
 43         radian.
 44 
 45     .. note: The input core does not clamp reported values to the
 46        ``[minimum, maximum]`` limits, such task is left to userspace.
 47     '''
 48     pass
 49 
 50     def __str__(self):
 51         return 'val {0}, min {1}, max {2}, fuzz {3}, flat {4}, res {5}'.format(*self)
 52 
 53 
 54 class KbdInfo(_KbdInfo):
 55     '''
 56     Keyboard repeat rate:
 57 
 58     - repeat:
 59        Keyboard repeat rate in characters per second.
 60 
 61     - delay:
 62        Amount of time that a key must be depressed before it will start
 63        to repeat (in milliseconds).
 64     '''
 65 
 66     def __str__(self):
 67         return 'repeat {0}, delay {1}'.format(*self)
 68 
 69 
 70 class DeviceInfo(_DeviceInfo):
 71     def __str__(self):
 72         msg = 'bus: {0:04x}, product {1:04x}, vendor {2:04x}, version {3:04x}'
 73         return msg.format(*self)
 74 
 75 
 76 class InputDevice(object):
 77     '''
 78     A linux input device from which input events can be read.
 79     '''
 80 
 81     __slots__ = ('fn', 'fd', 'info', 'name', 'phys', '_rawcapabilities',
 82                  'version')
 83 
 84     def __init__(self, dev):
 85         '''
 86         :param dev: path to input device
 87         '''
 88 
 89         #: Path to input device
 90         self.fn = dev
 91 
 92         #: A non-blocking file descriptor to the device file
 93         self.fd = os.open(dev, os.O_RDONLY | os.O_NONBLOCK)
 94 
 95         # Returns (bustype, vendor, product, version, name, phys, capabilities)
 96         info_res  = _input.ioctl_devinfo(self.fd)
 97 
 98         #: A :class:`DeviceInfo <evdev.device.DeviceInfo>` instance
 99         self.info = DeviceInfo(*info_res[:4])
100 
101         #: The name of the event device
102         self.name = info_res[4]
103 
104         #: The physical topology of the device
105         self.phys = info_res[5]
106 
107         #: The evdev protocol version
108         self.version = _input.ioctl_EVIOCGVERSION(self.fd)
109 
110         #: The raw dictionary of device capabilities - see `:func:capabilities()`
111         self._rawcapabilities = info_res[6]
112 
113     def _capabilities(self, absinfo=True):
114         res = {}
115         for etype, ecodes in self._rawcapabilities.items():
116             for code in ecodes:
117                 l = res.setdefault(etype, [])
118                 if isinstance(code, tuple):
119                     if absinfo:
120                         a = code[1]  # (0, 0, 0, 255, 0, 0)
121                         i = AbsInfo(*a)
122                         l.append((code[0], i))
123                     else:
124                         l.append(code[0])
125                 else:
126                     l.append(code)
127 
128         return res
129 
130     def capabilities(self, verbose=False, absinfo=True):
131         '''
132         Returns the event types that this device supports as a a mapping of
133         supported event types to lists of handled event codes. Example::
134 
135           { 1: [272, 273, 274],
136             2: [0, 1, 6, 8] }
137 
138         If ``verbose`` is ``True``, event codes and types will be resolved
139         to their names. Example::
140 
141           { ('EV_KEY', 1) : [('BTN_MOUSE', 272), ('BTN_RIGHT', 273), ('BTN_MIDDLE', 273)],
142             ('EV_REL', 2) : [('REL_X', 0), ('REL_Y', 0), ('REL_HWHEEL', 6), ('REL_WHEEL', 8)] }
143 
144         Unknown codes or types will be resolved to ``'?'``.
145 
146         If ``absinfo`` is ``True``, the list of capabilities will also
147         include absolute axis information (``absmin``, ``absmax``,
148         ``absfuzz``, ``absflat``) in the following form::
149 
150           { 3 : [ (0, AbsInfo(min=0, max=255, fuzz=0, flat=0)),
151                   (1, AbsInfo(min=0, max=255, fuzz=0, flat=0)) ]}
152 
153         Combined with ``verbose`` the above becomes::
154 
155           { ('EV_ABS', 3) : [ (('ABS_X', 0), AbsInfo(min=0, max=255, fuzz=0, flat=0)),
156                               (('ABS_Y', 1), AbsInfo(min=0, max=255, fuzz=0, flat=0)) ]}
157 
158         '''
159 
160         if verbose:
161             return dict(util.resolve_ecodes(self._capabilities(absinfo)))
162         else:
163             return self._capabilities(absinfo)
164 
165     def leds(self, verbose=False):
166         '''
167         Returns currently set LED keys. Example::
168 
169           [0, 1, 8, 9]
170 
171         If ``verbose`` is ``True``, event codes will be resolved to
172         their names. Unknown codes will be resolved to ``'?'``. Example::
173 
174           [('LED_NUML', 0), ('LED_CAPSL', 1), ('LED_MISC', 8), ('LED_MAIL', 9)]
175 
176         '''
177         leds = _input.get_sw_led_snd(self.fd, ecodes.EV_LED)
178         if verbose:
179             return [(ecodes.LED[l] if l in ecodes.LED else '?', l) for l in leds]
180 
181         return leds
182 
183     def __eq__(self, o):
184         '''Two devices are considered equal if their :data:`info` attributes are equal.'''
185         return self.info == o.info
186 
187     def __str__(self):
188         msg = 'device {0}, name "{1}", phys "{2}"'
189         return msg.format(self.fn, self.name, self.phys)
190 
191     def __repr__(self):
192         msg = (self.__class__.__name__, self.fn)
193         return '{0}({1!r})'.format(*msg)
194 
195     def close(self):
196         os.close(self.fd)
197         self.fd = -1
198 
199     def fileno(self):
200         '''
201         Returns the file descriptor to the event device. This makes
202         passing ``InputDevice`` instances directly to
203         :func:`select.select()` and :class:`asyncore.file_dispatcher`
204         possible. '''
205 
206         return self.fd
207 
208     def read_one(self):
209         '''
210         Read and return a single input event as a
211         :class:`InputEvent <evdev.events.InputEvent>` instance.
212 
213         Return `None` if there are no pending input events.
214         '''
215 
216         # event -> (sec, usec, type, code, val)
217         event = _input.device_read(self.fd)
218 
219         if event:
220             return InputEvent(*event)
221 
222     def read_loop(self):
223         '''Enter a polling loop that yields input events.'''
224 
225         while True:
226             r,w,x = select([self.fd], [], [])
227             for event in self.read():
228                 yield event
229 
230     def read(self):
231         '''
232         Read multiple input events from device. This function returns a
233         generator object that yields :class:`InputEvent
234         <evdev.events.InputEvent>` instances.
235         '''
236 
237         # events -> [(sec, usec, type, code, val), ...]
238         events = _input.device_read_many(self.fd)
239 
240         for i in events:
241             yield InputEvent(*i)
242 
243     def grab(self):
244         '''Grab input device using `EVIOCGRAB` - other applications
245         will be unable to receive until the device is released. Only
246         one process can hold a `EVIOCGRAB` on a device.
247 
248         .. warning:: Grabbing an already grabbed device will raise an
249                      IOError('Device or resource busy') exception.'''
250 
251         _input.ioctl_EVIOCGRAB(self.fd, 1)
252 
253     def ungrab(self):
254         '''Release device if it has been already grabbed (uses
255         `EVIOCGRAB`).
256 
257         .. warning:: Releasing an already released device will raise an
258                      IOError('Invalid argument') exception.'''
259 
260         _input.ioctl_EVIOCGRAB(self.fd, 0)
261 
262     @property
263     def repeat(self):
264         '''Get or set the keyboard repeat rate (in characters per
265         minute) and delay (in milliseconds).'''
266 
267         return KbdInfo(*_input.ioctl_EVIOCGREP(self.fd))
268 
269     @repeat.setter
270     def repeat(self, value):
271         return _input.ioctl_EVIOCSREP(self.fd, *value)
原文地址:https://www.cnblogs.com/winditsway/p/5665811.html