def testGetSerialMapping(self):
   pp = find_usb_devices.GetAllPhysicalPortToSerialMaps([TEST_HUB])
   result = list(pp)
   self.assertEquals(result[0], {7:'Battor0',
                                 5:'Battor1',
                                 3:'Battor2',
                                 1:'Battor3'})
   self.assertEquals(result[1], {})
Exemplo n.º 2
0
def assign_physical_ports(devices):
    """Based on usbfs port list, try to assign each device its physical port num.

  This corresponds to the order in which they're plugged into an external hub.
  """
    port_mapping = {}
    for hub in find_usb_devices.GetAllPhysicalPortToSerialMaps(
            usb_hubs.ALL_HUBS, fast=True):
        # Reverse the mapping.
        port_mapping.update({device: port for port, device in hub.iteritems()})
    for d in devices:
        d.physical_port = port_mapping.get(d.serial)
def GenerateSerialMap(hub_types=None):
  """Generates a map of phone serial numbers to BattOr serial numbers.

  Generates a dict of:
  {<phone serial 1>: <battor serial 1>,
   <phone serial 2>: <battor serial 2>}
  indicating which phone serial numbers should be matched with
  which BattOr serial numbers. Mapping is based on the physical port numbers
  of the hubs that the BattOrs and phones are connected to.

  Args:
      hub_types: List of hub types to check for.
      Defaults to ['plugable_7port',
                   'plugable_7port_usb3_part2',
                   'plugable_7port_usb3_part3']
      (see usb_hubs.py for details)
  """
  hub_types = [usb_hubs.GetHubType(x)
               for x in hub_types or ['plugable_7port',
                                      'plugable_7port_usb3_part2',
                                      'plugable_7port_usb3_part3']]
  devtree = find_usb_devices.GetBusNumberToDeviceTreeMap()

  # List of serial numbers in the system that represent BattOrs.
  battor_serials = list(GetBattorSerialNumbers(devtree))

  # If there's only one BattOr in the system, then a serial number ma
  # is not necessary.
  if len(battor_serials) == 1:
    return {}

  # List of dictionaries, one for each hub, that maps the physical
  # port number to the serial number of that hub. For instance, in a 2
  # hub system, this could return [{1:'ab', 2:'cd'}, {1:'jkl', 2:'xyz'}]
  # where 'ab' and 'cd' are the phone serial numbers and 'jkl' and 'xyz'
  # are the BattOr serial numbers.
  port_to_serial = find_usb_devices.GetAllPhysicalPortToSerialMaps(
      hub_types, device_tree_map=devtree)

  class serials(object):
    def __init__(self):
      self.phone = None
      self.battor = None

  # Map of {physical port number: [phone serial #, BattOr serial #]. This
  # map is populated by executing the code below. For instance, in the above
  # example, after the code below is executed, port_to_devices would equal
  # {1: ['ab', 'jkl'], 2: ['cd', 'xyz']}
  port_to_devices = collections.defaultdict(serials)
  for hub in port_to_serial:
    for (port, serial) in hub.iteritems():
      if serial in battor_serials:
        if port_to_devices[port].battor is not None:
          raise battor_error.BattorError('Multiple BattOrs on same port number')
        else:
          port_to_devices[port].battor = serial
      else:
        if port_to_devices[port].phone is not None:
          raise battor_error.BattorError('Multiple phones on same port number')
        else:
          port_to_devices[port].phone = serial

  # Turn the port_to_devices map into a map of the form
  # {phone serial number: BattOr serial number}.
  result = {}
  for pair in port_to_devices.values():
    if pair.phone is None:
      raise battor_error.BattorError(
          'BattOr detected with no corresponding phone')
    if pair.battor is None:
      raise battor_error.BattorError(
          'Phone detected with no corresponding BattOr')
    result[pair.phone] = pair.battor
  return result
Exemplo n.º 4
0
def DeviceStatus(devices, blacklist):
    """Generates status information for the given devices.

  Args:
    devices: The devices to generate status for.
    blacklist: The current device blacklist.
  Returns:
    A dict of the following form:
    {
      '<serial>': {
        'serial': '<serial>',
        'adb_status': str,
        'usb_status': bool,
        'usb_port': str,
        'blacklisted': bool,
        # only if the device is connected and not blacklisted
        'type': ro.build.product,
        'build': ro.build.id,
        'build_detail': ro.build.fingerprint,
        'battery': {
          ...
        },
        'imei_slice': str,
        'wifi_ip': str,
      },
      ...
    }
  """
    adb_devices = {
        a[0].GetDeviceSerial(): a
        for a in adb_wrapper.AdbWrapper.Devices(desired_state=None,
                                                long_list=True)
    }
    usb_devices = set(lsusb.get_android_devices())
    port_mapping = {}
    for hub in find_usb_devices.GetAllPhysicalPortToSerialMaps(
            usb_hubs.ALL_HUBS, fast=True):
        # Reverse the mapping.
        port_mapping.update(
            (serial, str(port)) for port, serial in hub.iteritems())

    def blacklisting_device_status(device):
        serial = device.adb.GetDeviceSerial()
        adb_status = (adb_devices[serial][1]
                      if serial in adb_devices else 'missing')
        usb_status = bool(serial in usb_devices)

        device_status = {
            'serial': serial,
            'adb_status': adb_status,
            'usb_status': usb_status,
            'usb_port': port_mapping.get(serial, 'unknown'),
        }

        if not IsBlacklisted(serial, blacklist):
            if adb_status == 'device':
                try:
                    build_product = device.build_product
                    build_id = device.build_id
                    build_fingerprint = device.build_fingerprint
                    build_description = device.build_description
                    wifi_ip = device.GetProp('dhcp.wlan0.ipaddress')
                    battery_info = _BatteryStatus(device, blacklist)
                    try:
                        imei_slice = device.GetIMEI()
                    except device_errors.CommandFailedError:
                        logging.exception('Unable to fetch IMEI for %s.',
                                          str(device))
                        imei_slice = 'unknown'

                    if (device.product_name == 'mantaray' and
                            battery_info.get('AC powered', None) != 'true'):
                        logger.error(
                            'Mantaray device not connected to AC power.')

                    device_status.update({
                        'ro.build.product': build_product,
                        'ro.build.id': build_id,
                        'ro.build.fingerprint': build_fingerprint,
                        'ro.build.description': build_description,
                        'battery': battery_info,
                        'imei_slice': imei_slice,
                        'wifi_ip': wifi_ip,
                    })

                except (device_errors.CommandFailedError,
                        device_errors.DeviceUnreachableError):
                    logger.exception(
                        'Failure while getting device status for %s.',
                        str(device))
                    if blacklist:
                        blacklist.Extend([serial],
                                         reason='status_check_failure')

                except device_errors.CommandTimeoutError:
                    logger.exception(
                        'Timeout while getting device status for %s.',
                        str(device))
                    if blacklist:
                        blacklist.Extend([serial],
                                         reason='status_check_timeout')

            elif blacklist:
                blacklist.Extend(
                    [serial], reason=adb_status if usb_status else 'offline')

        device_status['blacklisted'] = IsBlacklisted(serial, blacklist)

        return device_status

    parallel_devices = device_utils.DeviceUtils.parallel(devices)
    statuses = parallel_devices.pMap(blacklisting_device_status).pGet(None)
    return statuses