1# Lint as: python2, python3 2# Copyright (c) 2012 The Chromium OS Authors. All rights reserved. 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5 6import dbus 7 8import common 9from autotest_lib.client.common_lib import error 10from autotest_lib.client.cros.cellular import modem 11from autotest_lib.client.cros.cellular import modem1 12 13 14MMPROVIDERS = ['org.chromium', 'org.freedesktop'] 15SERVICE_UNKNOWN = 'org.freedesktop.DBus.Error.ServiceUnknown' 16 17 18def GetManager(): 19 """Returns a ModemManager object. 20 21 Attempts to connect to various modemmanagers, including 22 ModemManager classic interfaces, ModemManager using the 23 ModemManager1 interfaces and cromo and return the first 24 ModemManager that is found. 25 26 Returns: 27 a ModemManager object. 28 """ 29 for provider in MMPROVIDERS: 30 try: 31 return modem.ModemManager(provider) 32 except dbus.exceptions.DBusException as e: 33 if e._dbus_error_name != SERVICE_UNKNOWN: 34 raise 35 36 try: 37 return modem1.ModemManager() 38 except dbus.exceptions.DBusException as e: 39 if e._dbus_error_name != SERVICE_UNKNOWN: 40 raise 41 42 return None 43 44 45def EnumerateDevices(manager=None): 46 """Enumerates all modems in the system. 47 48 Args: 49 manager: the specific manager to use, if None use the first valid 50 manager 51 52 Returns: 53 a list of (ModemManager object, modem dbus path) 54 """ 55 if not manager: 56 manager = GetManager() 57 if not manager: 58 raise error.TestError('Cannot connect to the modem manager, is ' 59 'ModemManager/cromo/PseudoModemManager running?') 60 61 result = [] 62 for path in manager.EnumerateDevices(): 63 result.append((manager, path)) 64 65 return result 66 67 68def PickOneModem(modem_pattern, manager=None): 69 """Pick a modem. 70 71 If a machine has a single modem, managed by one of the MMPROVIDERS, 72 return the dbus path and a ModemManager object for that modem. 73 74 Args: 75 modem_pattern: pattern that should match the modem path 76 manager: the specific manager to use, if None check all known managers 77 78 Returns: 79 (ModemManager, Modem DBUS Path) tuple 80 81 Raises: 82 TestError: if there are no matching modems, or there are more 83 than one 84 """ 85 devices = EnumerateDevices(manager) 86 87 matches = [(m, path) for m, path in devices if modem_pattern in path] 88 if not matches: 89 raise error.TestError('No modems had substring: ' + modem_pattern) 90 if len(matches) > 1: 91 raise error.TestError('Expected only one modem, got: ' + 92 ', '.join([modem.path for modem in matches])) 93 return matches[0] 94