1# Copyright (c) 2012 The Chromium OS Authors. All rights reserved. 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4 5"""Keyboard device module to capture keyboard events.""" 6 7import fcntl 8import os 9import sys 10 11sys.path.append('../../bin/input') 12import input_device 13 14from linux_input import EV_KEY 15 16 17class KeyboardDevice: 18 """A class about keyboard device properties.""" 19 20 def __init__(self, device_node=None): 21 if device_node: 22 self.device_node = device_node 23 else: 24 self.device_node = input_device.get_device_node( 25 input_device.KEYBOARD_TYPES) 26 self.system_device = self._non_blocking_open(self.device_node) 27 self._input_event = input_device.InputEvent() 28 29 def __del__(self): 30 self.system_device.close() 31 32 def exists(self): 33 """Indicate whether this device exists or not.""" 34 return bool(self.device_node) 35 36 def _non_blocking_open(self, filename): 37 """Open the system file in the non-blocking mode.""" 38 fd = open(filename) 39 fcntl.fcntl(fd, fcntl.F_SETFL, os.O_NONBLOCK) 40 return fd 41 42 def _non_blocking_read(self, fd): 43 """Non-blocking read on fd.""" 44 try: 45 self._input_event.read(fd) 46 return self._input_event 47 except Exception: 48 return None 49 50 def get_key_press_event(self, fd): 51 """Read the keyboard device node to get the key press events.""" 52 event = True 53 # Read the device node continuously until either a key press event 54 # is got or there is no more events to read. 55 while event: 56 event = self._non_blocking_read(fd) 57 if event and event.type == EV_KEY and event.value == 1: 58 return event.code 59 return None 60