2015-04-04 57 views
0

我正試圖編寫一個Python代碼來捕獲Linux上的/ dev/input/event *事件。 用事件我想過濾事件類型,事件值,事件代碼和時間(tv_sec和tv_usec)。如何從內核輸入鍵盤事件(從按鍵到釋放)獲取差異時間?

問題: 隨着的EventType = EV_KEY和EVENT_CODE = 0,1,2(其中,0 = KEY_RELEASE,1 = KEY_PRESSED,2 = key_repeat),我想DiffTime從KEY_PRESSED(代碼0)和KEY_RELEASED(代碼1 )(time_pressed - time_released),即使密鑰重複(事件代碼2)。

任何想法?

+1

[格式爲/dev/input/event\*?](http://stackoverflow.com/questions/5060710/format-of-dev-input-event) – 2015-04-04 20:59:43

+0

@SylvainLeroux:它看起來像一個比你所鏈接的問題更具體的問題。 – jfs 2015-04-05 11:56:59

+0

@ J.F.Sebastian我自己同意這個問題。但我認爲一些答案有必要的信息來解決OP問題。無論如何,你可能是對的:所以,我已經綜合了所有這一切,並將其作爲答案發布在此處。 – 2015-04-05 12:46:53

回答

2

作爲一個起點,基於a solution by Treviño,這裏是一個快速和(大部分)髒捕獲鍵盤事件並報告計時方式:

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 

Documentation/input/input.txt事件是由內核報告爲:

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

timeval結構是是反過來在bits/time.h定義爲:

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

因此,事件的相應Python結構格式爲llHHI。一旦你有了這些,你必須循環讀取類型爲EV_KEY的事件,然後記住關鍵時間,並在返回鍵入代碼時計算按鍵時間。

請注意,您不能假定按鍵事件與前一按鍵事件相匹配(請考慮一次按幾個按鍵)。因此,我會跟蹤字典中的關鍵代碼和相應的按鍵時間。顯然,你將不得不適應你的需求。但正如我所說,這只是一個起點。