- Dev input event linux
- The hacker Diary
- Veni, Vidi, Vici.
- Exploring /dev/input
- The /dev directory
- eventX
- Let’s read the data stream !
- Interpreting the input stream
- Reading the mouse
- Reading the keyboard
- Other eventX ?
- Как обрабатывать ввод с символьного устройства / геймпада непосредственно в системах Linux?
- вопросы:
- как устройство представляет собой:
- исследования:
- 2 ответов
Dev input event linux
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Should you need to contact me, the author, you can do so either by e-mail — mail your message to , or by paper mail: Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic For your convenience, the GNU General Public License version 2 is included in the package: See the file COPYING. 1. Introduction
This is a collection of drivers that is designed to support all input devices under Linux. While it is currently used only on for USB input devices, future use (say 2.5/2.6) is expected to expand to replace most of the existing input system, which is why it lives in drivers/input/ instead of drivers/usb/. The centre of the input drivers is the input module, which must be loaded before any other of the input modules — it serves as a way of communication between two groups of modules: 1.1 Device drivers
These modules talk to the hardware (for example via USB), and provide events (keystrokes, mouse movements) to the input module. 1.2 Event handlers
These modules get events from input and pass them where needed via various interfaces — keystrokes to the kernel, mouse movements via a simulated PS/2 interface to GPM and X and so on. 2. Simple Usage
For the most usual configuration, with one USB mouse and one USB keyboard, you’ll have to load the following modules (or have them built in to the kernel): input mousedev keybdev usbcore uhci_hcd or ohci_hcd or ehci_hcd usbhid After this, the USB keyboard will work straight away, and the USB mouse will be available as a character device on major 13, minor 63: crw-r—r— 1 root root 13, 63 Mar 28 22:45 mice This device has to be created. The commands to create it by hand are: cd /dev mkdir input mknod input/mice c 13 63 After that you have to point GPM (the textmode mouse cut&paste tool) and XFree to this device to use it — GPM should be called like: gpm -t ps2 -m /dev/input/mice And in X: Section «Pointer» Protocol «ImPS/2» Device «/dev/input/mice» ZAxisMapping 4 5 EndSection When you do all of the above, you can use your USB mouse and keyboard. 3. Detailed Description
3.1 Device drivers
Device drivers are the modules that generate events. The events are however not useful without being handled, so you also will need to use some of the modules from section 3.2. 3.1.1 usbhid
usbhid is the largest and most complex driver of the whole suite. It handles all HID devices, and because there is a very wide variety of them, and because the USB HID specification isn’t simple, it needs to be this big. Currently, it handles USB mice, joysticks, gamepads, steering wheels keyboards, trackballs and digitizers. However, USB uses HID also for monitor controls, speaker controls, UPSs, LCDs and many other purposes. The monitor and speaker controls should be easy to add to the hid/input interface, but for the UPSs and LCDs it doesn’t make much sense. For this, the hiddev interface was designed. See Documentation/hid/hiddev.txt for more information about it. The usage of the usbhid module is very simple, it takes no parameters, detects everything automatically and when a HID device is inserted, it detects it appropriately. However, because the devices vary wildly, you might happen to have a device that doesn’t work well. In that case #define DEBUG at the beginning of hid-core.c and send me the syslog traces. 3.1.2 usbmouse
For embedded systems, for mice with broken HID descriptors and just any other use when the big usbhid wouldn’t be a good choice, there is the usbmouse driver. It handles USB mice only. It uses a simpler HIDBP protocol. This also means the mice must support this simpler protocol. Not all do. If you don’t have any strong reason to use this module, use usbhid instead. 3.1.3 usbkbd
Much like usbmouse, this module talks to keyboards with a simplified HIDBP protocol. It’s smaller, but doesn’t support any extra special keys. Use usbhid instead if there isn’t any special reason to use this. 3.1.4 wacom
This is a driver for Wacom Graphire and Intuos tablets. Not for Wacom PenPartner, that one is handled by the HID driver. Although the Intuos and Graphire tablets claim that they are HID tablets as well, they are not and thus need this specific driver. 3.1.5 iforce
A driver for I-Force joysticks and wheels, both over USB and RS232. It includes ForceFeedback support now, even though Immersion Corp. considers the protocol a trade secret and won’t disclose a word about it. 3.2 Event handlers
Event handlers distribute the events from the devices to userland and kernel, as needed. 3.2.1 keybdev
keybdev is currently a rather ugly hack that translates the input events into architecture-specific keyboard raw mode (Xlated AT Set2 on x86), and passes them into the handle_scancode function of the keyboard.c module. This works well enough on all architectures that keybdev can generate rawmode on, other architectures can be added to it. The right way would be to pass the events to keyboard.c directly, best if keyboard.c would itself be an event handler. This is done in the input patch, available on the webpage mentioned below. 3.2.2 mousedev
mousedev is also a hack to make programs that use mouse input work. It takes events from either mice or digitizers/tablets and makes a PS/2-style (a la /dev/psaux) mouse device available to the userland. Ideally, the programs could use a more reasonable interface, for example evdev Mousedev devices in /dev/input (as shown above) are: crw-r—r— 1 root root 13, 32 Mar 28 22:45 mouse0 crw-r—r— 1 root root 13, 33 Mar 29 00:41 mouse1 crw-r—r— 1 root root 13, 34 Mar 29 00:41 mouse2 crw-r—r— 1 root root 13, 35 Apr 1 10:50 mouse3 . . crw-r—r— 1 root root 13, 62 Apr 1 10:50 mouse30 crw-r—r— 1 root root 13, 63 Apr 1 10:50 mice Each ‘mouse’ device is assigned to a single mouse or digitizer, except the last one — ‘mice’. This single character device is shared by all mice and digitizers, and even if none are connected, the device is present. This is useful for hotplugging USB mice, so that programs can open the device even when no mice are present. CONFIG_INPUT_MOUSEDEV_SCREEN_[XY] in the kernel configuration are the size of your screen (in pixels) in XFree86. This is needed if you want to use your digitizer in X, because its movement is sent to X via a virtual PS/2 mouse and thus needs to be scaled accordingly. These values won’t be used if you use a mouse only. Mousedev will generate either PS/2, ImPS/2 (Microsoft IntelliMouse) or ExplorerPS/2 (IntelliMouse Explorer) protocols, depending on what the program reading the data wishes. You can set GPM and X to any of these. You’ll need ImPS/2 if you want to make use of a wheel on a USB mouse and ExplorerPS/2 if you want to use extra (up to 5) buttons. 3.2.3 joydev
Joydev implements v0.x and v1.x Linux joystick api, much like drivers/char/joystick/joystick.c used to in earlier versions. See joystick-api.txt in the Documentation subdirectory for details. As soon as any joystick is connected, it can be accessed in /dev/input on: crw-r—r— 1 root root 13, 0 Apr 1 10:50 js0 crw-r—r— 1 root root 13, 1 Apr 1 10:50 js1 crw-r—r— 1 root root 13, 2 Apr 1 10:50 js2 crw-r—r— 1 root root 13, 3 Apr 1 10:50 js3 . And so on up to js31. 3.2.4 evdev
evdev is the generic input event interface. It passes the events generated in the kernel straight to the program, with timestamps. The API is still evolving, but should be usable now. It’s described in section 5. This should be the way for GPM and X to get keyboard and mouse events. It allows for multihead in X without any specific multihead kernel support. The event codes are the same on all architectures and are hardware independent. The devices are in /dev/input: crw-r—r— 1 root root 13, 64 Apr 1 10:49 event0 crw-r—r— 1 root root 13, 65 Apr 1 10:50 event1 crw-r—r— 1 root root 13, 66 Apr 1 10:50 event2 crw-r—r— 1 root root 13, 67 Apr 1 10:50 event3 . And so on up to event31. 4. Verifying if it works
Источник
The hacker Diary
Veni, Vidi, Vici.
Exploring /dev/input
Linux is one of those operating systems in which once you know your way around, you are unstoppable. In this post, we will explore what you can possibly do with access to /dev/input directory. Now you typically need to have superuser privileges to access this directory but there is a way around it. ( check this stackexchange )
The /dev directory
This is the directory in Linux that contains all the device files for all the devices that are on your system.
/dev/input – The input is a subdirectory that holds the device files for various input devices such as mouse, keyboard, joystick and so on.
This is a screenshot of my input directory and as you can see there is the mice/mouse0/mouse1 which are files corresponding to the touchpad/wired mouse/wireless mouse respectively. And then you have these ‘eventX’ files. Yours might look similar but depending on the nature of your device you might have more or less options available.
eventX
With so many event files, how can one possibly know which one corresponds to which ? This script is what you need:
This script would display relevant information about all the input devices connected to your system. Here’s a sample output for the Lid switch :
Now what we want is the event handler number for the lid switch which we can see from the information as event0. And through this one can map all the events with their corresponding devices.
Alternative method:
An alternate approach to doing this is to loo k at /dev/input/by-id or /dev/input/by-path , they have symbolic links to /dev/input/event . But the only downside to this is that it does not display all the possible devices. We will discuss how to read from both in this post.
Let’s read the data stream !
Say you want to read the mouse file, you only need to open the file using ‘cat’ and start moving the mouse.
You would observe that as you are moving the mouse a stream of data is being dumped onto your screen. This data although seems crazy contains the information for the movement of the mouse.
Interpreting the input stream
The format for the input stream is given in the Linux documentation as follows:
struct timeval – 16
unsigned short – 2 ( x 2 )
unsigned int – 4
Total size = 24 bytes
What this means is the first 16 bytes of data contain the system time, which in our case is not essential. The rest 8 bytes of data contain the actual relevant values. This is the output format of all eventX files.
Reading the mouse
Reading the mouse is probably the simplest to start with because one does not need to go through the trouble of accessing any eventX files. The mouse file in the /dev/input directory outputs a stream of 3/4 bytes ( Button value, x , y ).
You would get a 4 byte stream if the mouse is configured with the scroll wheel. Unfortunately in my case, even though I use a mouse with a scroll wheel, it was configured as a PS2 mouse. ( If you are in a similar situation – read this)
Map of the (x, y) data with the corresponding directions
My touchpad and wireless mouse do not have any special buttons and therefore when the button values are mapped with the corresponding clicks, I got the following :
When I was going through this stackexchange, the code seemed to suggest different values for the each of these buttons.
Python Code for reading mouse:
Video Demo:
Reading the keyboard
Much like the mouse, one can opt for an easier way by just reading from the /dev/input/by-id or /dev/input/by-path, but for the love of it let’s try to play around with eventX files. Let’s go about this step by step.
- Find the event handler number for the keyboard ( Mine was event5 )
- Reading the byte data and converting it to the format specified in the Linux Documentation using the struct module in python
- Extracting the relevant information from the converted data.
Python code for reading keyboard:
Video Demo:
Other eventX ?
What should you do if you would like to read from another eventX file ? Well, from my experience I can share with you this. : The first 16 bytes in the file are always almost the time stamp and you can read only that data by:
The rest depends on the type of output which you can find out by using the evtest program.
Источник
Как обрабатывать ввод с символьного устройства / геймпада непосредственно в системах Linux?
Я разрабатываю программу на C, которая использует USB SNES контроллер для входного сигнала на распределении основанном RPM. Есть ли библиотека, о которой кто-нибудь знает, что делает это проще взаимодействовать, или какой-то инструмент (joydev?), что позволяет правильно считывать входные данные с устройства? Мне не нужен весь игровой движок; он предназначен только для ввода с устройства персонажа.
если есть библиотека, которая уже делает это для меня, это было бы отлично (я могу просто посмотреть, что делает библиотека самостоятельно), и это может быть закрыто только ссылкой; в противном случае, если я должен сделать это сам, у меня есть несколько конкретных вопросов:
вопросы:
- есть ли уже существующая библиотека C, которая обрабатывает все мои взаимодействия USB-устройств с геймпадом для меня? Я с удовольствием изучу новую библиотеку. (Мой google-fu подвел меня здесь, я прошу прощения, если это слишком очевидно)
- каков подходящий способ, чтобы убедиться, что вы открываете правильный символ устройство каждый раз, когда событие* имя изменяется между сеансами/инициализацией?
- каков соответствующий метод обработки ввода с этих устройств из моего приложения? Просто определите, что каждое нажатие кнопки равнозначно значению и выполните действия на основе этого ввода, когда мы опрашиваем символьное устройство?
вкратце pseduo-C, что-то вроде этого?
как устройство представляет собой:
Я могу ясно видеть устройство регистрируется правильно, насколько я вижу:
и если я читаю с устройства, я вижу, что он получает прерывание и ввод с устройства просто с помощью hexdump:
когда я нажимаю клавишу (не отпуская), она работает так, как ожидалось, хотя я пока не могу расшифровать, что возвращается из буфера без контекста:
при отпускании кнопки, вы получаете аналогичный выход:
это «вверх» кнопка нажата и отпущена выше.
исследования:
в попытке определить, как это делают другие библиотеки, я подумал о том, чтобы сделать strace pygame в python и посмотреть, какие устройства он открывает, а также как он читает ввод, но я все еще учусь, как его использовать. Я также увидел какие-то смутные упоминания о joydev, но, опять же, не научились ими пользоваться. Я делаю это в настоящее время и опубликую результаты, если узнаю что-нибудь значение.
помимо этого, кнопка просмотра нажимает через ASCII и hexdump, я отмечаю, что у них есть аналогичный вход на основе кнопки, но, похоже, есть то, что я считаю, это количество прерываний для шины USB в конце выхода выше (0xf53a до 0xf53c). Это всегда кажется увеличивающимся, и, для моих целей, вероятно, может быть отброшено.
существует также возможность, что я просто не монтирую устройство правильно, потому что мне не хватает какого-то модуля или пакета (думаю, опять же, о joydev и что он должен делать). Я не часто работал с USB вообще, поэтому этот тип обработки устройств является новым для меня.
Поиск вокруг некоторое время, я не видел ничего, что показало именно то, что я искал, но я с удовольствием принимаю перенаправления на другие вопросы/темы для чтения.
2 ответов
устройства ввода USB в Linux обычно обрабатываются драйвером HID (устройство человеческого интерфейса), которые, в свою очередь, преобразуются в устройства ввода.
вы можете прочитать их как необработанные USB-устройства, но это обычно не очень хорошая идея, потому что это очень низкоуровневый протокол.
вы можете прочитать /dev/input/* устройств, если у вас есть соответствующие разрешения. Обычно они читаются только по корню. Если вы не хотите читать необработанные байты, есть некоторые библиотеки, такие как libinput, которые делают эту работу за вас.
но если ваша игра работает в XWindows (скорее всего), то вы должны управлять устройствами XInput. Вы можете сделать это с необработанными вызовами X, но вам, вероятно, лучше использовать некоторую библиотеку, такую как SDL. На самом деле SDL-это то, что pygame использует под капотом, поэтому я бы сначала попробовать.
о том, как определить правильное устройство, каждое устройство ввода имеет имя, а некоторые даже серийный номер (вы видите те, как симлинк под /dev/input/by-id обычно этого достаточно, чтобы идентифицировать устройство, а не входной номер.
если вы хотите прочитать сырые устройства ввода, поясню насчет о вашем hexdumps. Вы читаете input* устройства, поэтому вы получаете значения типа struct input_event (см. /usr/include/linux/input.h ):
в вашем первом дампе, например:
на самом деле их два input_event s. Первый:
первые 64 байта временная метка. Затем: 0003 (EV_ABS) означает движение абсолютной оси, 0000 (ABS_X) — индекс оси и 0000007f положение этой оси. Абсолютные оси иногда используются для представления дросселей, джойстиков и тому подобного (иногда клавиатуры отправляются как джойстик вместо 4 кнопок), и вы получаете положение на первом чтении, чтобы знать, где находится элемент управления, даже если вы его не перемещаете.
первые 64 байта-это метка времени (совпадает с выше. Тогда 0000 (EV_SYN) означает событие синхронизации. С EV_SYN , остальные поля не используются. EV_SYN используется для группировки различных значений одного события, таких как горизонтальная и вертикальная оси мыши или джойстика.
ваш другой дамп похож, но для AXIS_Y .
я предполагаю, что клавиатура рассматривается как цифровой джойстик, две оси ABS_X и ABS_Y , будучи 0x7F средняя точка (диапазон от 0x00 to 0xFF ). Сообщения, которые вы получаете, — это просто средняя точка, то есть кнопка клавиатуры не нажата. Может быть, ваш hexdump вывод в буфер?
Это устройство USB Hid, поэтому оно обрабатывается драйвером hid-см. В вашем отладочном выходе » USB HID v1.10 геймпад» Существуют различные учебные пособия и примеры того, как это сделать.
в качестве отправной точки вы можете установить джойстик поверх «apt-get install joystick» и посмотреть исходный код.
Источник