1# Copyright (c) 2011 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"""A Python utility library for TPM module testing."""
6
7import logging, subprocess, time
8from autotest_lib.client.common_lib import error
9
10
11def runInSubprocess(args, rc_list=None):
12    """Run a command in subprocess and return stdout.
13
14    Args:
15      args: a list of string, command to run.
16      rc_list: a list of int, acceptable return code values.
17
18    Returns:
19      out: a string, stdout of the command executed.
20      err: a string, stderr of the command executed, or None.
21
22    Raises:
23      RuntimeError: if subprocess return code is non-zero and not in rc_list.
24    """
25    if rc_list is None:
26        rc_list = []
27
28    # Sleep for 1 second so we don't overwhelm I2C bus with too many commands
29    time.sleep(1)
30    logging.debug('runInSubprocess args = %r; rc_list = %r', args, rc_list)
31    proc = subprocess.Popen(args,
32                            stdout=subprocess.PIPE,
33                            stderr=subprocess.PIPE)
34    out, err = proc.communicate()
35    logging.error('runInSubprocess %s: out=%r, err=%r', args[0], out, err)
36    if proc.returncode and proc.returncode not in rc_list:
37        raise RuntimeError('runInSubprocess %s failed with returncode %d: %s' %
38                           (args[0], proc.returncode, out))
39    return str(out), str(err)
40
41
42def enableI2C():
43    """Enable i2c-dev so i2c-tools can be used.
44
45    Dependency: 'i2cdetect' is a command from 'i2c-tools' package, which comes
46                with Chrom* OS image and is available from inside chroot.
47
48    Raises:
49      TestFail: if i2c-dev can't be enabled.
50    """
51    args = ['i2cdetect', '-l']
52    out, _ = runInSubprocess(args)
53    if not out:
54        logging.info('i2c-dev disabled. Enabling it with modprobe')
55        out, _ = runInSubprocess(['modprobe', 'i2c-dev'])
56        if out:
57            raise error.TestFail('Error enable i2c-dev: %s' % out)
58        out, _ = runInSubprocess(args)
59    logging.info('i2c-dev ready to go:\n%s', out)
60
61
62def computeTimeElapsed(end, start):
63    """Computes time difference in microseconds.
64
65    Args:
66      end: a datetime.datetime() object, end timestamp.
67      start: a datetime.datetime() object, start timestamp.
68
69    Returns:
70      usec: an int, difference between end and start in microseconds.
71    """
72    t = end - start
73    usec = 1000000 * t.seconds + t.microseconds
74    logging.info('Elapsed time = %d usec', usec)
75    return usec
76