1import subprocess
2import re
3import threading
4
5ATRACE_PATH="/android/catapult/systrace/systrace/systrace.py"
6
7class AdbError(RuntimeError):
8    def __init__(self, arg):
9        self.args = arg
10
11def am(serial, cmd, args):
12    if not isinstance(args, list):
13        args = [args]
14    full_args = ["am"] + [cmd] + args
15    __call_adb(serial, full_args, False)
16
17def pm(serial, cmd, args):
18    if not isinstance(args, list):
19        args = [args]
20    full_args = ["pm"] + [cmd] + args
21    __call_adb(serial, full_args, False)
22
23def dumpsys(serial, topic):
24    return __call_adb(serial, ["dumpsys"] + [topic], True)
25
26def trace(serial,
27        tags = ["gfx", "sched", "view", "freq", "am", "wm", "power", "load", "memreclaim"],
28        time = "10"):
29    args = [ATRACE_PATH, "-e", serial, "-t" + time, "-b32768"] + tags
30    subprocess.call(args)
31
32def wake(serial):
33    output = dumpsys(serial, "power")
34    wakefulness = re.search('mWakefulness=([a-zA-Z]+)', output)
35    if wakefulness.group(1) != "Awake":
36        __call_adb(serial, ["input", "keyevent", "KEYCODE_POWER"], False)
37
38def root(serial):
39    subprocess.call(["adb", "-s", serial, "root"])
40
41def pull(serial, path, dest):
42    subprocess.call(["adb", "-s", serial, "wait-for-device", "pull"] + [path] + [dest])
43
44def shell(serial, cmd):
45    __call_adb(serial, cmd, False)
46
47def track_logcat(serial, awaited_string, callback):
48    threading.Thread(target=__track_logcat, name=serial + "-waiter", args=(serial, awaited_string, callback)).start()
49
50def __call_adb(serial, args, block):
51    full_args = ["adb", "-s", serial, "wait-for-device", "shell"] + args
52    print full_args
53    output = None
54    try:
55        if block:
56            output = subprocess.check_output(full_args)
57        else:
58            subprocess.call(full_args)
59    except subprocess.CalledProcessError:
60        raise AdbError("Error calling " + " ".join(args))
61
62    return output
63