How to get diff time from kernel input keyboard events(from key pressed to release)?
Question: 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 ?


Answer: As a starting point, based on [a solution by
Treviño](http://stackoverflow.com/a/16682549/2363712), 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](https://www.kernel.org/doc/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`](http://www.gnu.org/software/libc/manual/html_node/Elapsed-
Time.html#index-struct-timeval) 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.

