1# Copyright 2017 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""This module provides the serial number to USB location map on Linux."""
16import os
17
18
19class SerialMapper(object):
20  """Maps serial number to its USB physical location.
21
22  This class should run under Linux environment and use sysfs to enumerate the
23  USB devices. Use the serial file's content to create the map.
24  """
25
26  USB_DEVICES_PATH = '/sys/bus/usb/devices/'
27
28  def __init__(self):
29    self.serial_map = {}
30
31  def refresh_serial_map(self):
32    """Refresh the serial_number -> USB location map.
33    """
34    serial_to_location_map = {}
35    # check if sysfs is mounted.
36    if not os.path.exists(self.USB_DEVICES_PATH):
37      return
38
39    for device_folder_name in os.listdir(self.USB_DEVICES_PATH):
40      device_folder = os.path.join(self.USB_DEVICES_PATH, device_folder_name)
41      if os.path.isdir(device_folder):
42        # The format of folder name should be either:
43        # USB1, USB2... which are controllers (ignored).
44        # bus-port[.port.port] which are devices.
45        # bus-port[.port.port]:config.interface which are interfaces (ignored).
46        if ':' not in device_folder and '-' in device_folder:
47          serial_path = os.path.join(device_folder, 'serial')
48          if os.path.isfile(serial_path):
49            with open(serial_path) as f:
50              serial = f.readline().rstrip('\n').lower()
51              serial_to_location_map[serial] = device_folder_name
52
53    self.serial_map = serial_to_location_map
54
55  def get_location(self, serial):
56    """Get the USB location according to the serial number.
57
58    Args:
59      serial: The serial number for the device.
60    Returns:
61      The USB physical location for the device.
62    """
63    serial_lower = serial.lower()
64    if serial_lower in self.serial_map:
65      return self.serial_map[serial_lower]
66    return None
67