1# Copyright 2015 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
5import glob
6import logging
7import pprint
8from threading import Timer
9
10from autotest_lib.client.bin.input.input_device import *
11
12class firmwareCheckKeys(object):
13    version = 1
14    actual_output = []
15    device = None
16    ev = None
17
18    def __init__(self):
19        for evdev in glob.glob("/dev/input/event*"):
20            device = InputDevice(evdev)
21            if device.is_keyboard():
22                print 'keyboard device %s' % evdev
23                self.device = device
24
25    def _keyboard_input(self):
26        """Read key presses."""
27        index = 0
28        while True:
29            self.ev.read(self.device.f)
30            if self.ev.code != KEY_RESERVED:
31                print "EventCode is %d value is %d" % (self.ev.code, self.ev.value)
32                if self.ev.type == 0 or self.ev.type == 1:
33                    self.actual_output.append(self.ev.code)
34                    index = index + 1
35
36    def check_keys(self, expected_sequence):
37        """Wait for key press for 10 seconds.
38
39        @return number of input keys captured, -1 for error.
40        """
41        if not self.device:
42            logging.error("Could not find a keyboard device")
43            return -1
44
45        self.ev = InputEvent()
46        Timer(0, self._keyboard_input).start()
47
48        time.sleep(10)
49
50        # Keypresses will have a tendency to repeat as there is delay between
51        # the down and up events.  We're not interested in precisely how many
52        # repeats of the key there is, just what is the sequence of keys,
53        # so, we will make the list unique.
54        uniq_actual_output = sorted(list(set(self.actual_output)))
55        if uniq_actual_output != expected_sequence:
56            print 'Keys mismatched %s' % pprint.pformat(uniq_actual_output)
57            return -1
58        print 'Key match expected: %s' % pprint.pformat(uniq_actual_output)
59        return len(uniq_actual_output)
60
61