Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen to USB keyboard with Python

The setup: a minimalistic Linux (OpenWRT on ASUS router), a USB keyboard (assume I know the device name like /dev/hiddev0)

A goal: write a python (or shell, in this case I can use it like a proxy for python) script that will listen to this device and perform some actions based on the user input

As a beginning - quite enough to echo user-entered characters to text file of given name.

PyUSB looks really confusing. I'm ok with PySerial, though I'm not sure if it suits the task - when trying to open the device it says "serial.serialutil.SerialException: Could not configure port: (22, 'Invalid argument')"

UPD: well, OK, the trivial answer was "cat /dev/input/event1"

But the output is really cryptic - any hint on interpreting it (as character int codes)?

UPD UPD: hexdump /dev/input/event1 is much better! it gives 6 9-tuples for each key press (I suppose, 3 for key down, 3 for key up) It would probably be not so difficult to decrypt it

But more civil way is still highly appreciated

http://svn.navi.cx/misc/trunk/python/evdev/evdev.py looks interesting...

like image 425
Guard Avatar asked May 15 '11 21:05

Guard


2 Answers

http://svn.navi.cx/misc/trunk/python/evdev/evdev.py is the real answer - the output is greatly detailed, and there's ready .poll() method that returns events.

the only problem I encountered - readMetadata() failed with Error 22. Then I commented its call out, and it worked like a charm

actually, I downloaded some more recent version from http://autokey.googlecode.com/svn/trunk/src/lib/evdev.py

Add: to discover the actual eventN,

cat /proc/bus/input/devices

and carefully read through it

like image 191
Guard Avatar answered Oct 30 '22 03:10

Guard


For anyone who discovers this question later (as happened to me): there is a wonderful library by Georgi Valkov for evdev:

https://github.com/gvalkov/python-evdev

http://python-evdev.readthedocs.org/en/latest/index.html

like image 3
martin Avatar answered Oct 30 '22 03:10

martin