Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / build / android / devil / utils / lsusb.py
blob9c98fa6fd5c5c0a8a990a61a3cfdba0779fc339d
1 # Copyright 2015 The Chromium 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.
5 import logging
6 import re
8 from pylib import cmd_helper
10 _INDENTATION_RE = re.compile(r'^( *)')
11 _LSUSB_BUS_DEVICE_RE = re.compile(r'^Bus (\d{3}) Device (\d{3}):')
12 _LSUSB_ENTRY_RE = re.compile(r'^ *([^ ]+) +([^ ]+) *([^ ].*)?$')
13 _LSUSB_GROUP_RE = re.compile(r'^ *([^ ]+.*):$')
15 _USBDEVFS_RESET = ord('U') << 8 | 20
18 def lsusb():
19 """Call lsusb and return the parsed output."""
20 lsusb_raw_output = cmd_helper.GetCmdOutput(['lsusb', '-v'])
21 device = None
22 devices = []
23 depth_stack = []
24 for line in lsusb_raw_output.splitlines():
25 if not line:
26 if device:
27 devices.append(device)
28 device = None
29 continue
31 if not device:
32 m = _LSUSB_BUS_DEVICE_RE.match(line)
33 if m:
34 device = {
35 'bus': m.group(1),
36 'device': m.group(2)
38 depth_stack = [device]
39 continue
41 indent_match = _INDENTATION_RE.match(line)
42 if not indent_match:
43 continue
45 depth = 1 + len(indent_match.group(1)) / 2
46 if depth > len(depth_stack):
47 logging.error('lsusb parsing error: unexpected indentation: "%s"', line)
48 continue
50 while depth < len(depth_stack):
51 depth_stack.pop()
53 cur = depth_stack[-1]
55 m = _LSUSB_GROUP_RE.match(line)
56 if m:
57 new_group = {}
58 cur[m.group(1)] = new_group
59 depth_stack.append(new_group)
60 continue
62 m = _LSUSB_ENTRY_RE.match(line)
63 if m:
64 new_entry = {
65 '_value': m.group(2),
66 '_desc': m.group(3),
68 cur[m.group(1)] = new_entry
69 depth_stack.append(new_entry)
70 continue
72 logging.error('lsusb parsing error: unrecognized line: "%s"', line)
74 if device:
75 devices.append(device)
77 return devices
80 def get_lsusb_serial(device):
81 return device.get('Device Descriptor', {}).get('iSerial', {}).get('_desc')
84 def get_android_devices():
85 return [serial for serial in (get_lsusb_serial(d) for d in lsusb())
86 if serial]