evdev module-----device.py

本文详细介绍了Linux系统中evdev库的功能与使用方法,包括如何读取和解析各种类型的输入事件,如按键、相对轴、绝对轴等。此外还介绍了如何获取设备能力信息及设置键盘重复率。

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

No VM guests are running outdated hypervisor (qemu) binaries on this host. [1] 14461 Error: unable to open display :1 root@srv771551:~# The XKEYBOARD keymap compiler (xkbcomp) reports: > Warning: Could not resolve keysym XF86CameraAccessEnable > Warning: Could not resolve keysym XF86CameraAccessDisable > Warning: Could not resolve keysym XF86CameraAccessToggle > Warning: Could not resolve keysym XF86NextElement > Warning: Could not resolve keysym XF86PreviousElement > Warning: Could not resolve keysym XF86AutopilotEngageToggle > Warning: Could not resolve keysym XF86MarkWaypoint > Warning: Could not resolve keysym XF86Sos > Warning: Could not resolve keysym XF86NavChart > Warning: Could not resolve keysym XF86FishingChart > Warning: Could not resolve keysym XF86SingleRangeRadar > Warning: Could not resolve keysym XF86DualRangeRadar > Warning: Could not resolve keysym XF86RadarOverlay > Warning: Could not resolve keysym XF86TraditionalSonar > Warning: Could not resolve keysym XF86ClearvuSonar > Warning: Could not resolve keysym XF86SidevuSonar > Warning: Could not resolve keysym XF86NavInfo Errors from xkbcomp are not fatal to the X server # 查看详细的DRM初始 查看详细的DRM初始化日志 sudo dmesg | grep -iE 'drm|i915|amdgpu|nouveau' # 强制重新加载图形模块(以Intel为例) sudo rmmod i915 sudo modprobe i915 debug=1 [ 8.488129] ACPI: bus type drm_connector registered [ 11.694958] systemd[1]: Starting modprobe@drm.service - Load Kernel Module drm... rmmod: ERROR: Module i915 is not currently loaded modprobe: FATAL: Module i915 not found in directory /lib/modules/6.8.0-60-generic root@srv771551:~# # 检查物理显示接口状态 sudo apt install edid-decode -y sudo cat /sys/class/drm/card0-DP-1/edid | edid-decode # 检测显示端口热插拔状态 grep -H . /sys/class/drm/*/status Reading package lists... Done Building dependency tree... Done Reading state information... Done The following NEW packages will be installed: edid-decode 0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded. Need to get 134 kB of archives. After this operation, 350 kB of additional disk space will be used. Get:1 http://in.archive.ubuntu.com/ubuntu noble/universe amd64 edid-decode amd64 0.1~git20220315.cb74358c2896-1.1 [134 kB] Fetched 134 kB in 1s (126 kB/s) Selecting previously unselected package edid-decode. (Reading database ... 104591 files and directories currently installed.) Preparing to unpack .../edid-decode_0.1~git20220315.cb74358c2896-1.1_amd64.deb ... Unpacking edid-decode (0.1~git20220315.cb74358c2896-1.1) ... Setting up edid-decode (0.1~git20220315.cb74358c2896-1.1) ... Processing triggers for man-db (2.12.0-4build2) ... Scanning processes... Scanning linux images... Running kernel seems to be up-to-date. No services need to be restarted. No containers need to be restarted. No user sessions are running outdated binaries. No VM guests are running outdated hypervisor (qemu) binaries on this host. cat: /sys/class/drm/card0-DP-1/edid: No such file or directory EDID of 'stdin' was empty. grep: /sys/class/drm/*/status: No such file or directory root@srv771551:~# # 使用LLVMpipe软件渲染 sudo apt install mesa-utils -y LIBGL_ALWAYS_SOFTWARE=1 glxinfo | grep "OpenGL renderer" # 验证CPU渲染能力 MESA_GL_VERSION_OVERRIDE=4.5 glxgears Reading package lists... Done Building dependency tree... Done Reading state information... Done mesa-utils is already the newest version (9.0.0-2). 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. OpenGL renderer string: llvmpipe (LLVM 19.1.1, 256 bits) The XKEYBOARD keymap compiler (xkbcomp) reports: > Warning: Could not resolve keysym XF86CameraAccessEnable > Warning: Could not resolve keysym XF86CameraAccessDisable > Warning: Could not resolve keysym XF86CameraAccessToggle > Warning: Could not resolve keysym XF86NextElement > Warning: Could not resolve keysym XF86PreviousElement > Warning: Could not resolve keysym XF86AutopilotEngageToggle > Warning: Could not resolve keysym XF86MarkWaypoint > Warning: Could not resolve keysym XF86Sos > Warning: Could not resolve keysym XF86NavChart > Warning: Could not resolve keysym XF86FishingChart > Warning: Could not resolve keysym XF86SingleRangeRadar > Warning: Could not resolve keysym XF86DualRangeRadar > Warning: Could not resolve keysym XF86RadarOverlay > Warning: Could not resolve keysym XF86TraditionalSonar > Warning: Could not resolve keysym XF86ClearvuSonar > Warning: Could not resolve keysym XF86SidevuSonar > Warning: Could not resolve keysym XF86NavInfo Errors from xkbcomp are not fatal to the X server 6622 frames in 5.0 seconds = 1324.350 FPS 5306 frames in 5.0 seconds = 1061.041 FPS 6476 frames in 5.0 seconds = 1295.068 FPS 7356 frames in 5.0 seconds = 1471.104 FPS 7530 frames in 5.0 seconds = 1505.943 FPS 7202 frames in 5.0 seconds = 1440.160 FPS 6918 frames in 5.0 seconds = 1383.580 FPS 6448 frames in 5.0 seconds = 1289.433 FPS 6896 frames in 5.0 seconds = 1379.091 FPS 7166 frames in 5.0 seconds = 1433.100 FPS 6667 frames in 5.0 seconds = 1333.343 FPS 6502 frames in 5.0 seconds = 1300.314 FPS 6236 frames in 5.0 seconds = 1246.892 FPS 4949 frames in 5.0 seconds = 989.683 FPS 6312 frames in 5.0 seconds = 1262.288 FPS 7286 frames in 5.0 seconds = 1456.947 FPS # 检查内核模块存储路径 sudo find /lib/modules/$(uname -r) -name '*i915*' # 查看模块依赖关系 modinfo i915 | grep -E 'depends|vermagic' # 强制重建模块依赖 sudo depmod -a # 检查黑名单配置 grep -ri 'blacklist i915' /etc/modprobe.d/6583 frames in 5.0 seconds = 1316.576 FPS 6704 frames in 5.0 seconds = 1340.529 FPS 6171 frames in 5.0 seconds = 1234.088 FPS 7279 frames in 5.0 seconds = 1455.553 FPS # 创建自定义键位符号文件 echo 'xkb_symbols "extras" { key <I240> { [ XF86CameraAccessEnable ] }; key <I241> { [ XF86CameraAccessDisable ] }; key <I242> { [ XF86CameraAccessToggle ] }; };' | sudo tee /usr/share/X11/xkb/symbols/custom # 更新XKB配置 sudo sed -i '/xkb_symbols/a include "custom(extras)"' /usr/share/X11/xkb/symbols/inet 7404 frames in 5.0 seconds = 1480.630 FPS 7454 frames in 5.0 seconds = 1490.683 FPS # 生成基础EDID二进制 echo -n -e '\x00\xFF\xFF\xFF\xFF\xFF\xFF\x00\x04\x72\x00\x00\x01\x00\x00\x00\x01\x1B\x01\x03\x80\x00\x00\x78\x0A\xEE\x91\xA3\x54\x4C\x99\x26\x0F\x50\x54\x00\x00\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x02\x3A\x80\x18\x71\x38\x2D\x40\x58\x2C\x45\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFE\x00\x41\x55\x4F\x0A\x20\x20\x20\x20\x20\x20\x00\x00\x00\xFE\x00\x42\x31\x35\x36\x48\x41\x4E\x30\x31\x2E\x30\x00\xBC' | sudo tee /sys/kernel/debug/dri/0/edid_override >/dev/null # 验证EDID注入 sudo cat /sys/kernel/debug/dri/0/edid_override | edid-decode 7467 frames in 5.0 seconds = 1493.334 FPS 7557 frames in 5.0 seconds = 1511.268 FPS # 创建最小化Xorg配置 echo 'Section "ServerFlags" Option "AutoAddGPU" "off" Option "IgnoreABI" "true" EndSection Section "Device" Identifier "DummyCard" Driver "dummy" VideoRam 32768 EndSection Section "Screen" Identifier "DummyScreen" Device "DummyCard" Monitor "DummyMonitor" DefaultDepth 24 SubSection "Display" Depth 24 Modes "1024x768" EndSubSection EndSection Section "Monitor" Identifier "DummyMonitor" HorizSync 28.0-80.0 VertRefresh 48.0-75.0 EndSection' | sudo tee /etc/X11/xorg.conf.d/99-fallback.conf 7125 frames in 5.0 seconds = 1424.958 FPS 5526 frames in 5.0 seconds = 1104.287 FPS #!/bin/bash # render_benchmark.sh export MESA_LOADER_DRIVER_OVERRIDE=llvmpipe export LIBGL_ALWAYS_SOFTWARE=1 echo "===== CPU Rendering Benchmark =====" for i in {1..4}; do taskset -c $i glxgears >/dev/null & pid=$! sleep 5 kill $pid echo "Core $i: $(grep -E 'frames in 5.0' /tmp/bench.log | tail -n1)" done echo -e "\n===== Memory Bandwidth Test =====" sudo apt install mbw -y mbw -n 5 256 | grep AVG 6637 frames in 5.0 seconds = 1327.285 FPS 7355 frames in 5.0 seconds = 1470.954 FPS # 创建systemd调试服务 echo '[Unit] Description=DRM Debugging Service [Service] Type=oneshot ExecStart=/usr/sbin/rmmod i915 ExecStart=/usr/sbin/modprobe i915 debug=1 ExecStart=/usr/bin/tee /sys/kernel/debug/dri/0/i915_engine_info < /dev/null [Install] WantedBy=multi-user.target' | sudo tee /etc/systemd/system/drm-debug.service sudo systemctl daemon-reload sudo systemctl enable drm-debug 7212 frames in 5.0 seconds = 1442.261 FPS 6695 frames in 5.0 seconds = 1338.973 FPS 6488 frames in 5.0 seconds = 1297.479 FPS
最新发布
05-29
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值