0

I'm trying to write a Python code to capture events from /dev/input/event* on linux. With the events I want to filter event type, event value, event code and time(tv_sec and tv_usec).

PROBLEM: With EventType=EV_KEY and Event_Code = 0,1,2 (where 0=key_release,1=key_pressed,2=key_repeat), I want to get DiffTime from key_pressed(code 0) and key_released(code 1) (time_pressed - time_released) even if key is repeated (event code 2).

Any Idea ?

  • 1
    possible duplicate of [format of /dev/input/event\*?](http://stackoverflow.com/questions/5060710/format-of-dev-input-event) – Sylvain Leroux Apr 04 '15 at 20:59
  • @SylvainLeroux: it looks like a more specific question than the one you've linked. – jfs Apr 05 '15 at 11:56
  • @J.F.Sebastian I agree about the question by itself. But I thought that some answers had the necessary pieces of informations to fix the OP issue. Anyway, you're probably right: so, I've synthesized all of this my best, and posted that as an answer here. – Sylvain Leroux Apr 05 '15 at 12:46

1 Answers1

2

As a starting point, based on a solution by Treviño, here is a quick and (mostly) dirty way to capture keyboard events and report the timings:

import struct

FORMAT = 'llHHI'
EVENT_SIZE = struct.calcsize(FORMAT)
EV_KEY = 0x01

KEY_DOWN = 1
KEY_AUTO = 2
KEY_UP = 0

devname = "/dev/input/event0"

def dt(sec_a, usec_a, sec_b, usec_b):
    return (sec_a+usec_a/1000000.) - (sec_b+usec_b/1000000)


with open(devname, "rb") as infile:
    kdtime = {}

    while True:
        event = infile.read(EVENT_SIZE)
        (tv_sec, tv_usec, typ, code, value) = struct.unpack(FORMAT, event)
        if typ == EV_KEY:
            if value == KEY_DOWN:
                kdtime[code] = (tv_sec, tv_usec)
            if value == KEY_UP and code in kdtime:
                print(code, dt(tv_sec, tv_usec, *kdtime[code]))
                del kdtime[code] # Not strictly required

From Documentation/input/input.txt events are reported by the kernel as:

struct input_event {
    struct timeval time;
    unsigned short type;
    unsigned short code;
    unsigned int value;
};

Struct timeval is is its turn defined in bits/time.h as:

struct timeval
  {
    __time_t tv_sec;            /* Seconds.  */
    __suseconds_t tv_usec;      /* Microseconds.  */
  };

So the corresponding Python struct format for an event is llHHI. Once you have that, you mostly have to loop to read events with type EV_KEY, then remember key down time, and calculate the key pressed time when you get back the key up code.

Please note that you cannot assume that a key up event match the previous key down event (think about pressing several keys at once). So I keep track of the key code and the corresponding key pressed time in a dictionary. Obviously, you will have to adapt that to your needs. But as I said, this is only a starting point.

Community
  • 1
  • 1
Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125