blob: 510670270d7e90f57c273a0eba4c169b6b031aba [file] [log] [blame]
Neels Hofmeyr3531a192017-03-28 14:30:28 +02001# osmo_gsm_tester: DBUS client to talk to ofono
2#
3# Copyright (C) 2016-2017 by sysmocom - s.f.m.c. GmbH
4#
5# Author: Neels Hofmeyr <neels@hofmeyr.de>
6#
7# This program is free software: you can redistribute it and/or modify
Harald Welte27205342017-06-03 09:51:45 +02008# it under the terms of the GNU General Public License as
Neels Hofmeyr3531a192017-03-28 14:30:28 +02009# published by the Free Software Foundation, either version 3 of the
10# License, or (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Harald Welte27205342017-06-03 09:51:45 +020015# GNU General Public License for more details.
Neels Hofmeyr3531a192017-03-28 14:30:28 +020016#
Harald Welte27205342017-06-03 09:51:45 +020017# You should have received a copy of the GNU General Public License
Neels Hofmeyr3531a192017-03-28 14:30:28 +020018# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +020020from . import log, util, sms, process
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +020021from .event_loop import MainLoop
Neels Hofmeyr3531a192017-03-28 14:30:28 +020022
23from pydbus import SystemBus, Variant
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +020024import os
Neels Hofmeyr3531a192017-03-28 14:30:28 +020025
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +020026# Required for Gio.Cancellable.
27# See https://lazka.github.io/pgi-docs/Gio-2.0/classes/Cancellable.html#Gio.Cancellable
28from gi.module import get_introspection_module
29Gio = get_introspection_module('Gio')
30
Neels Hofmeyr3531a192017-03-28 14:30:28 +020031from gi.repository import GLib
Neels Hofmeyr3531a192017-03-28 14:30:28 +020032bus = SystemBus()
33
Pau Espin Pedrol504a6642017-05-04 11:38:23 +020034I_MODEM = 'org.ofono.Modem'
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +020035I_NETREG = 'org.ofono.NetworkRegistration'
36I_SMS = 'org.ofono.MessageManager'
Pau Espin Pedrolde899612017-11-23 17:18:40 +010037I_CONNMGR = 'org.ofono.ConnectionManager'
Pau Espin Pedrold71edd12017-10-06 13:53:54 +020038I_CALLMGR = 'org.ofono.VoiceCallManager'
39I_CALL = 'org.ofono.VoiceCall'
Pau Espin Pedrol03983aa2017-06-12 15:31:27 +020040I_SS = 'org.ofono.SupplementaryServices'
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +010041I_SIMMGR = 'org.ofono.SimManager'
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +020042
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020043# See https://github.com/intgr/ofono/blob/master/doc/network-api.txt#L78
44NETREG_ST_REGISTERED = 'registered'
45NETREG_ST_ROAMING = 'roaming'
46
47NETREG_MAX_REGISTER_ATTEMPTS = 3
48
Pau Espin Pedrolbf176e42018-03-26 19:13:32 +020049class DeferredDBus:
Neels Hofmeyr035cda82017-05-05 17:52:45 +020050
51 def __init__(self, dbus_iface, handler):
52 self.handler = handler
Neels Hofmeyr47de6b02017-05-10 13:24:05 +020053 self.subscription_id = dbus_iface.connect(self.receive_signal)
Neels Hofmeyr035cda82017-05-05 17:52:45 +020054
55 def receive_signal(self, *args, **kwargs):
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +020056 MainLoop.defer(self.handler, *args, **kwargs)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020057
Neels Hofmeyr035cda82017-05-05 17:52:45 +020058def dbus_connect(dbus_iface, handler):
59 '''This function shall be used instead of directly connecting DBus signals.
60 It ensures that we don't nest a glib main loop within another, and also
61 that we receive exceptions raised within the signal handlers. This makes it
62 so that a signal handler is invoked only after the DBus polling is through
63 by enlisting signals that should be handled in the
64 DeferredHandling.defer_queue.'''
Pau Espin Pedrolbf176e42018-03-26 19:13:32 +020065 return DeferredDBus(dbus_iface, handler).subscription_id
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020066
Neels Hofmeyr93f58662017-05-03 16:32:16 +020067def systembus_get(path):
Neels Hofmeyr3531a192017-03-28 14:30:28 +020068 global bus
69 return bus.get('org.ofono', path)
70
71def list_modems():
Neels Hofmeyr93f58662017-05-03 16:32:16 +020072 root = systembus_get('/')
Neels Hofmeyr3531a192017-03-28 14:30:28 +020073 return sorted(root.GetModems())
74
Pau Espin Pedrole25cf042018-02-23 17:00:09 +010075def get_dbuspath_from_syspath(syspath):
76 modems = list_modems()
77 for dbuspath, props in modems:
78 if props.get('SystemPath', '') == syspath:
79 return dbuspath
80 raise ValueError('could not find %s in modem list: %s' % (syspath, modems))
81
82
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020083def _async_result_handler(obj, result, user_data):
84 '''Generic callback dispatcher called from glib loop when an async method
85 call has returned. This callback is set up by method dbus_async_call.'''
86 (result_callback, error_callback, real_user_data) = user_data
87 try:
88 ret = obj.call_finish(result)
89 except Exception as e:
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +020090 if isinstance(e, GLib.Error) and e.code == Gio.IOErrorEnum.CANCELLED:
91 log.dbg('DBus method cancelled')
92 return
93
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020094 if error_callback:
95 error_callback(obj, e, real_user_data)
96 else:
97 result_callback(obj, e, real_user_data)
98 return
99
100 ret = ret.unpack()
101 # to be compatible with standard Python behaviour, unbox
102 # single-element tuples and return None for empty result tuples
103 if len(ret) == 1:
104 ret = ret[0]
105 elif len(ret) == 0:
106 ret = None
107 result_callback(obj, ret, real_user_data)
108
109def dbus_async_call(instance, proxymethod, *proxymethod_args,
110 result_handler=None, error_handler=None,
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200111 user_data=None, timeout=30, cancellable=None,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200112 **proxymethod_kwargs):
113 '''pydbus doesn't support asynchronous methods. This method adds support for
114 it until pydbus implements it'''
115
116 argdiff = len(proxymethod_args) - len(proxymethod._inargs)
117 if argdiff < 0:
118 raise TypeError(proxymethod.__qualname__ + " missing {} required positional argument(s)".format(-argdiff))
119 elif argdiff > 0:
120 raise TypeError(proxymethod.__qualname__ + " takes {} positional argument(s) but {} was/were given".format(len(proxymethod._inargs), len(proxymethod_args)))
121
122 timeout = timeout * 1000
123 user_data = (result_handler, error_handler, user_data)
124
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200125 # See https://lazka.github.io/pgi-docs/Gio-2.0/classes/DBusProxy.html#Gio.DBusProxy.call
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200126 ret = instance._bus.con.call(
127 instance._bus_name, instance._path,
128 proxymethod._iface_name, proxymethod.__name__,
129 GLib.Variant(proxymethod._sinargs, proxymethod_args),
130 GLib.VariantType.new(proxymethod._soutargs),
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200131 0, timeout, cancellable,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200132 _async_result_handler, user_data)
133
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200134def dbus_call_dismiss_error(log_obj, err_str, method):
135 try:
136 method()
Pau Espin Pedrol9b670212017-11-07 17:50:20 +0100137 except GLib.Error as e:
138 if Gio.DBusError.is_remote_error(e) and Gio.DBusError.get_remote_error(e) == err_str:
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200139 log_obj.log('Dismissed Dbus method error: %r' % e)
140 return
Pau Espin Pedrol9b670212017-11-07 17:50:20 +0100141 raise e
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200142
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200143class ModemDbusInteraction(log.Origin):
144 '''Work around inconveniences specific to pydbus and ofono.
145 ofono adds and removes DBus interfaces and notifies about them.
146 Upon changes we need a fresh pydbus object to benefit from that.
147 Watching the interfaces change is optional; be sure to call
148 watch_interfaces() if you'd like to have signals subscribed.
149 Related: https://github.com/LEW21/pydbus/issues/56
150 '''
151
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200152 modem_path = None
153 watch_props_subscription = None
154 _dbus_obj = None
155 interfaces = None
156
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200157 def __init__(self, modem_path):
158 self.modem_path = modem_path
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200159 super().__init__(log.C_BUS, self.modem_path)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200160 self.interfaces = set()
161
162 # A dict listing signal handlers to connect, e.g.
163 # { I_SMS: ( ('IncomingMessage', self._on_incoming_message), ), }
164 self.required_signals = {}
165
166 # A dict collecting subscription tokens for connected signal handlers.
167 # { I_SMS: ( token1, token2, ... ), }
168 self.connected_signals = util.listdict()
169
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200170 def cleanup(self):
Pau Espin Pedrol58ff38d2017-06-23 13:10:38 +0200171 self.set_powered(False)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200172 self.unwatch_interfaces()
173 for interface_name in list(self.connected_signals.keys()):
174 self.remove_signals(interface_name)
175
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200176 def __del__(self):
177 self.cleanup()
178
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200179 def get_new_dbus_obj(self):
180 return systembus_get(self.modem_path)
181
182 def dbus_obj(self):
183 if self._dbus_obj is None:
184 self._dbus_obj = self.get_new_dbus_obj()
185 return self._dbus_obj
186
187 def interface(self, interface_name):
188 try:
189 return self.dbus_obj()[interface_name]
190 except KeyError:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200191 raise log.Error('Modem interface is not available:', interface_name)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200192
193 def signal(self, interface_name, signal):
194 return getattr(self.interface(interface_name), signal)
195
196 def watch_interfaces(self):
197 self.unwatch_interfaces()
198 # Note: we are watching the properties on a get_new_dbus_obj() that is
199 # separate from the one used to interact with interfaces. We need to
200 # refresh the pydbus object to interact with Interfaces that have newly
201 # appeared, but exchanging the DBus object to watch Interfaces being
202 # enabled and disabled is racy: we may skip some removals and
203 # additions. Hence do not exchange this DBus object. We don't even
204 # need to store the dbus object used for this, we will not touch it
205 # again. We only store the signal subscription.
206 self.watch_props_subscription = dbus_connect(self.get_new_dbus_obj().PropertyChanged,
207 self.on_property_change)
208 self.on_interfaces_change(self.properties().get('Interfaces'))
209
210 def unwatch_interfaces(self):
211 if self.watch_props_subscription is None:
212 return
213 self.watch_props_subscription.disconnect()
214 self.watch_props_subscription = None
215
216 def on_property_change(self, name, value):
217 if name == 'Interfaces':
218 self.on_interfaces_change(value)
Pau Espin Pedrol77631212017-09-05 19:04:06 +0200219 else:
220 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_MODEM, name, value))
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200221
222 def on_interfaces_change(self, interfaces_now):
223 # First some logging.
224 now = set(interfaces_now)
225 additions = now - self.interfaces
226 removals = self.interfaces - now
227 self.interfaces = now
228 if not (additions or removals):
229 # nothing changed.
230 return
231
232 if additions:
233 self.dbg('interface enabled:', ', '.join(sorted(additions)))
234
235 if removals:
236 self.dbg('interface disabled:', ', '.join(sorted(removals)))
237
238 # The dbus object is now stale and needs refreshing before we
239 # access the next interface function.
240 self._dbus_obj = None
241
242 # If an interface disappeared, disconnect the signal handlers for it.
243 # Even though we're going to use a fresh dbus object for new
244 # subscriptions, we will still keep active subscriptions alive on the
245 # old dbus object which will linger, associated with the respective
246 # signal subscription.
247 for removed in removals:
248 self.remove_signals(removed)
249
250 # Connect signals for added interfaces.
251 for interface_name in additions:
252 self.connect_signals(interface_name)
253
254 def remove_signals(self, interface_name):
255 got = self.connected_signals.pop(interface_name, [])
256
257 if not got:
258 return
259
260 self.dbg('Disconnecting', len(got), 'signals for', interface_name)
261 for subscription in got:
262 subscription.disconnect()
263
264 def connect_signals(self, interface_name):
265 # If an interface was added, it must not have existed before. For
266 # paranoia, make sure we have no handlers for those.
267 self.remove_signals(interface_name)
268
269 want = self.required_signals.get(interface_name, [])
270 if not want:
271 return
272
273 self.dbg('Connecting', len(want), 'signals for', interface_name)
274 for signal, cb in self.required_signals.get(interface_name, []):
275 subscription = dbus_connect(self.signal(interface_name, signal), cb)
276 self.connected_signals.add(interface_name, subscription)
277
278 def has_interface(self, *interface_names):
279 try:
280 for interface_name in interface_names:
281 self.dbus_obj()[interface_name]
282 result = True
283 except KeyError:
284 result = False
285 self.dbg('has_interface(%s) ==' % (', '.join(interface_names)), result)
286 return result
287
288 def properties(self, iface=I_MODEM):
289 return self.dbus_obj()[iface].GetProperties()
290
291 def property_is(self, name, val, iface=I_MODEM):
292 is_val = self.properties(iface).get(name)
293 self.dbg(name, '==', is_val)
294 return is_val is not None and is_val == val
295
296 def set_bool(self, name, bool_val, iface=I_MODEM):
297 # to make sure any pending signals are received before we send out more DBus requests
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200298 MainLoop.poll()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200299
300 val = bool(bool_val)
301 self.log('Setting', name, val)
302 self.interface(iface).SetProperty(name, Variant('b', val))
303
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200304 MainLoop.wait(self, self.property_is, name, bool_val)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200305
306 def set_powered(self, powered=True):
307 self.set_bool('Powered', powered)
308
309 def set_online(self, online=True):
310 self.set_bool('Online', online)
311
312 def is_powered(self):
313 return self.property_is('Powered', True)
314
315 def is_online(self):
316 return self.property_is('Online', True)
317
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200318
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200319
320class Modem(log.Origin):
321 'convenience for ofono Modem interaction'
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200322
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100323 CTX_PROT_IPv4 = 'ip'
324 CTX_PROT_IPv6 = 'ipv6'
325 CTX_PROT_IPv46 = 'dual'
326
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200327 def __init__(self, suite_run, conf):
328 self.suite_run = suite_run
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200329 self.conf = conf
Pau Espin Pedrole25cf042018-02-23 17:00:09 +0100330 self.syspath = conf.get('path')
331 self.dbuspath = get_dbuspath_from_syspath(self.syspath)
332 super().__init__(log.C_TST, self.dbuspath)
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200333 self.dbg('creating from syspath %s' % self.syspath)
Pau Espin Pedrol58603672018-08-09 13:45:55 +0200334 self.msisdn = None
335 self._ki = None
336 self._imsi = None
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200337 self.run_dir = util.Dir(self.suite_run.get_test_run_dir().new_dir(self.name().strip('/')))
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200338 self.sms_received_list = []
Pau Espin Pedrole25cf042018-02-23 17:00:09 +0100339 self.dbus = ModemDbusInteraction(self.dbuspath)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200340 self.register_attempts = 0
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200341 self.call_list = []
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200342 # one Cancellable can handle several concurrent methods.
343 self.cancellable = Gio.Cancellable.new()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200344 self.dbus.required_signals = {
345 I_SMS: ( ('IncomingMessage', self._on_incoming_message), ),
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200346 I_NETREG: ( ('PropertyChanged', self._on_netreg_property_changed), ),
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100347 I_CONNMGR: ( ('PropertyChanged', self._on_connmgr_property_changed), ),
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200348 I_CALLMGR: ( ('PropertyChanged', self._on_callmgr_property_changed),
349 ('CallAdded', self._on_callmgr_call_added),
350 ('CallRemoved', self._on_callmgr_call_removed), ),
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200351 }
352 self.dbus.watch_interfaces()
353
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200354 def cleanup(self):
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200355 self.dbg('cleanup')
356 if self.cancellable:
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200357 self.cancel_pending_dbus_methods()
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200358 self.cancellable = None
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100359 if self.is_powered():
360 self.power_off()
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200361 self.dbus.cleanup()
362 self.dbus = None
363
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200364 def netns(self):
365 return os.path.basename(self.syspath.rstrip('/'))
366
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200367 def properties(self, *args, **kwargs):
368 '''Return a dict of properties on this modem. For the actual arguments,
369 see ModemDbusInteraction.properties(), which this function calls. The
370 returned dict is defined by ofono. An example is:
371 {'Lockdown': False,
372 'Powered': True,
373 'Model': 'MC7304',
374 'Revision': 'SWI9X15C_05.05.66.00 r29972 CARMD-EV-FRMWR1 2015/10/08 08:36:28',
375 'Manufacturer': 'Sierra Wireless, Incorporated',
376 'Emergency': False,
377 'Interfaces': ['org.ofono.SmartMessaging',
378 'org.ofono.PushNotification',
379 'org.ofono.MessageManager',
380 'org.ofono.NetworkRegistration',
381 'org.ofono.ConnectionManager',
382 'org.ofono.SupplementaryServices',
383 'org.ofono.RadioSettings',
384 'org.ofono.AllowedAccessPoints',
385 'org.ofono.SimManager',
386 'org.ofono.LocationReporting',
387 'org.ofono.VoiceCallManager'],
388 'Serial': '356853054230919',
389 'Features': ['sms', 'net', 'gprs', 'ussd', 'rat', 'sim', 'gps'],
390 'Type': 'hardware',
391 'Online': True}
392 '''
393 return self.dbus.properties(*args, **kwargs)
394
395 def set_powered(self, powered=True):
396 return self.dbus.set_powered(powered=powered)
397
398 def set_online(self, online=True):
399 return self.dbus.set_online(online=online)
400
401 def is_powered(self):
402 return self.dbus.is_powered()
403
404 def is_online(self):
405 return self.dbus.is_online()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200406
407 def set_msisdn(self, msisdn):
408 self.msisdn = msisdn
409
410 def imsi(self):
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100411 if self._imsi is None:
412 if 'sim' in self.features():
413 if not self.is_powered():
414 self.set_powered()
415 # wait for SimManager iface to appear after we power on
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200416 MainLoop.wait(self, self.dbus.has_interface, I_SIMMGR, timeout=10)
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100417 simmgr = self.dbus.interface(I_SIMMGR)
418 # If properties are requested quickly, it may happen that Sim property is still not there.
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200419 MainLoop.wait(self, lambda: simmgr.GetProperties().get('SubscriberIdentity', None) is not None, timeout=10)
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100420 props = simmgr.GetProperties()
421 self.dbg('got SIM properties', props)
422 self._imsi = props.get('SubscriberIdentity', None)
423 else:
424 self._imsi = self.conf.get('imsi')
425 if self._imsi is None:
426 raise log.Error('No IMSI')
427 return self._imsi
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200428
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200429 def set_ki(self, ki):
430 self._ki = ki
431
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200432 def ki(self):
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200433 if self._ki is not None:
434 return self._ki
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200435 return self.conf.get('ki')
436
Pau Espin Pedrol713ce2c2017-08-24 16:57:17 +0200437 def auth_algo(self):
438 return self.conf.get('auth_algo', None)
439
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100440 def features(self):
441 return self.conf.get('features', [])
442
443 def _required_ifaces(self):
444 req_ifaces = (I_NETREG,)
445 req_ifaces += (I_SMS,) if 'sms' in self.features() else ()
446 req_ifaces += (I_SS,) if 'ussd' in self.features() else ()
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100447 req_ifaces += (I_CONNMGR,) if 'gprs' in self.features() else ()
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100448 req_ifaces += (I_SIMMGR,) if 'sim' in self.features() else ()
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100449 return req_ifaces
450
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200451 def _on_netreg_property_changed(self, name, value):
452 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_NETREG, name, value))
453
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200454 def is_connected(self, mcc_mnc=None):
455 netreg = self.dbus.interface(I_NETREG)
456 prop = netreg.GetProperties()
457 status = prop.get('Status')
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200458 self.dbg('status:', status)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200459 if not (status == NETREG_ST_REGISTERED or status == NETREG_ST_ROAMING):
460 return False
461 if mcc_mnc is None: # Any network is fine and we are registered.
462 return True
463 mcc = prop.get('MobileCountryCode')
464 mnc = prop.get('MobileNetworkCode')
465 if (mcc, mnc) == mcc_mnc:
466 return True
467 return False
468
469 def schedule_scan_register(self, mcc_mnc):
470 if self.register_attempts > NETREG_MAX_REGISTER_ATTEMPTS:
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200471 raise log.Error('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200472 self.register_attempts += 1
473 netreg = self.dbus.interface(I_NETREG)
474 self.dbg('Scanning for operators...')
475 # Scan method can take several seconds, and we don't want to block
476 # waiting for that. Make it async and try to register when the scan is
477 # finished.
478 register_func = self.scan_cb_register_automatic if mcc_mnc is None else self.scan_cb_register
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200479 result_handler = lambda obj, result, user_data: MainLoop.defer(register_func, result, user_data)
480 error_handler = lambda obj, e, user_data: MainLoop.defer(self.scan_cb_error_handler, e, mcc_mnc)
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200481 dbus_async_call(netreg, netreg.Scan, timeout=30, cancellable=self.cancellable,
482 result_handler=result_handler, error_handler=error_handler,
483 user_data=mcc_mnc)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200484
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200485 def scan_cb_error_handler(self, e, mcc_mnc):
486 # It was detected that Scan() method can fail for some modems on some
487 # specific circumstances. For instance it fails with org.ofono.Error.Failed
488 # if the modem starts to register internally after we started Scan() and
489 # the registering succeeds while we are still waiting for Scan() to finsih.
490 # So far the easiest seems to check if we are now registered and
491 # otherwise schedule a scan again.
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200492 self.err('Scan() failed, retrying if needed:', e)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200493 if not self.is_connected(mcc_mnc):
494 self.schedule_scan_register(mcc_mnc)
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200495 else:
496 self.log('Already registered with network', mcc_mnc)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200497
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200498 def scan_cb_register_automatic(self, scanned_operators, mcc_mnc):
499 self.dbg('scanned operators: ', scanned_operators);
500 for op_path, op_prop in scanned_operators:
501 if op_prop.get('Status') == 'current':
502 mcc = op_prop.get('MobileCountryCode')
503 mnc = op_prop.get('MobileNetworkCode')
504 self.log('Already registered with network', (mcc, mnc))
505 return
506 self.log('Registering with the default network')
507 netreg = self.dbus.interface(I_NETREG)
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200508 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', netreg.Register)
509
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200510
511 def scan_cb_register(self, scanned_operators, mcc_mnc):
512 self.dbg('scanned operators: ', scanned_operators);
513 matching_op_path = None
514 for op_path, op_prop in scanned_operators:
515 mcc = op_prop.get('MobileCountryCode')
516 mnc = op_prop.get('MobileNetworkCode')
517 if (mcc, mnc) == mcc_mnc:
518 if op_prop.get('Status') == 'current':
519 self.log('Already registered with network', mcc_mnc)
520 # We discovered the network and we are already registered
521 # with it. Avoid calling op.Register() in this case (it
522 # won't act as a NO-OP, it actually returns an error).
523 return
524 matching_op_path = op_path
525 break
526 if matching_op_path is None:
527 self.dbg('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
528 self.schedule_scan_register(mcc_mnc)
529 return
530 dbus_op = systembus_get(matching_op_path)
531 self.log('Registering with operator', matching_op_path, mcc_mnc)
Pau Espin Pedrol9f59b822017-11-07 17:50:52 +0100532 try:
533 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', dbus_op.Register)
534 except GLib.Error as e:
535 if Gio.DBusError.is_remote_error(e) and Gio.DBusError.get_remote_error(e) == 'org.ofono.Error.NotSupported':
536 self.log('modem does not support manual registering, attempting automatic registering')
537 self.scan_cb_register_automatic(scanned_operators, mcc_mnc)
538 return
539 raise e
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200540
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200541 def cancel_pending_dbus_methods(self):
542 self.cancellable.cancel()
543 # Cancel op is applied as a signal coming from glib mainloop, so we
544 # need to run it and wait for the callbacks to handle cancellations.
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200545 MainLoop.poll()
Pau Espin Pedrole685c622017-10-04 18:30:22 +0200546 # once it has been triggered, create a new one for next operation:
547 self.cancellable = Gio.Cancellable.new()
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200548
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100549 def power_off(self):
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100550 if self.dbus.has_interface(I_CONNMGR) and self.is_attached():
551 self.detach()
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100552 self.set_online(False)
553 self.set_powered(False)
554 req_ifaces = self._required_ifaces()
555 for iface in req_ifaces:
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200556 MainLoop.wait(self, lambda: not self.dbus.has_interface(iface), timeout=10)
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100557
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200558 def power_cycle(self):
559 'Power the modem and put it online, power cycle it if it was already on'
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100560 req_ifaces = self._required_ifaces()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200561 if self.is_powered():
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200562 self.dbg('Power cycling')
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200563 MainLoop.sleep(self, 1.0) # workaround for ofono bug OS#3064
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100564 self.power_off()
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200565 else:
566 self.dbg('Powering on')
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200567 self.set_powered()
Pau Espin Pedrolb9955762017-05-02 09:39:27 +0200568 self.set_online()
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200569 MainLoop.wait(self, self.dbus.has_interface, *req_ifaces, timeout=10)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200570
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200571 def connect(self, mcc_mnc=None):
572 'Connect to MCC+MNC'
573 if (mcc_mnc is not None) and (len(mcc_mnc) != 2 or None in mcc_mnc):
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200574 raise log.Error('mcc_mnc value is invalid. It should be None or contain both valid mcc and mnc values:', mcc_mnc=mcc_mnc)
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200575 # if test called connect() before and async scanning has not finished, we need to get rid of it:
576 self.cancel_pending_dbus_methods()
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200577 self.power_cycle()
578 self.register_attempts = 0
579 if self.is_connected(mcc_mnc):
580 self.log('Already registered with', mcc_mnc if mcc_mnc else 'default network')
581 else:
582 self.log('Connect to', mcc_mnc if mcc_mnc else 'default network')
583 self.schedule_scan_register(mcc_mnc)
584
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100585 def is_attached(self):
586 connmgr = self.dbus.interface(I_CONNMGR)
587 prop = connmgr.GetProperties()
588 attached = prop.get('Attached')
589 self.dbg('attached:', attached)
590 return attached
591
592 def attach(self, allow_roaming=False):
593 self.dbg('attach')
594 if self.is_attached():
595 self.detach()
596 connmgr = self.dbus.interface(I_CONNMGR)
597 prop = connmgr.SetProperty('RoamingAllowed', Variant('b', allow_roaming))
598 prop = connmgr.SetProperty('Powered', Variant('b', True))
599
600 def detach(self):
601 self.dbg('detach')
602 connmgr = self.dbus.interface(I_CONNMGR)
603 prop = connmgr.SetProperty('RoamingAllowed', Variant('b', False))
604 prop = connmgr.SetProperty('Powered', Variant('b', False))
605 connmgr.DeactivateAll()
606 connmgr.ResetContexts() # Requires Powered=false
607
608 def activate_context(self, apn='internet', user='ogt', pwd='', protocol='ip'):
Pau Espin Pedrolb05e36a2017-12-15 12:39:36 +0100609 self.dbg('activate_context', apn=apn, user=user, protocol=protocol)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100610
611 connmgr = self.dbus.interface(I_CONNMGR)
612 ctx_path = connmgr.AddContext('internet')
613
614 ctx = systembus_get(ctx_path)
615 ctx.SetProperty('AccessPointName', Variant('s', apn))
616 ctx.SetProperty('Username', Variant('s', user))
617 ctx.SetProperty('Password', Variant('s', pwd))
618 ctx.SetProperty('Protocol', Variant('s', protocol))
619
620 # Activate can only be called after we are attached
621 ctx.SetProperty('Active', Variant('b', True))
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200622 MainLoop.wait(self, lambda: ctx.GetProperties()['Active'] == True)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100623 self.log('context activated', path=ctx_path, apn=apn, user=user, properties=ctx.GetProperties())
624 return ctx_path
625
626 def deactivate_context(self, ctx_id):
Pau Espin Pedrol263dd3b2018-02-13 16:53:51 +0100627 self.dbg('deactivate_context', path=ctx_id)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100628 ctx = systembus_get(ctx_id)
629 ctx.SetProperty('Active', Variant('b', False))
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200630 MainLoop.wait(self, lambda: ctx.GetProperties()['Active'] == False)
Pau Espin Pedrolcdac2972018-02-16 15:14:32 +0100631 self.dbg('deactivate_context active=false, removing', path=ctx_id)
632 connmgr = self.dbus.interface(I_CONNMGR)
633 connmgr.RemoveContext(ctx_id)
Pau Espin Pedrolb05aa3c2018-02-16 15:03:50 +0100634 self.log('context deactivated', path=ctx_id)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100635
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200636 def run_netns_wait(self, name, popen_args):
637 proc = process.NetNSProcess(name, self.run_dir.new_dir(name), self.netns(), popen_args,
638 env={})
Pau Espin Pedrol79df7392018-11-12 18:15:30 +0100639 proc.launch_sync()
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200640
641 def setup_context_data_plane(self, ctx_id):
642 self.dbg('setup_context_data', path=ctx_id)
643 ctx = systembus_get(ctx_id)
644 ctx_settings = ctx.GetProperties().get('Settings', None)
645 if not ctx_settings:
646 raise log.Error('%s no Settings found! No way to get iface!' % ctx_id)
647 iface = ctx_settings.get('Interface', None)
648 if not iface:
649 raise log.Error('%s Settings contains no iface! %r' % (ctx_id, repr(ctx_settings)))
650 self.run_netns_wait('ifup', ('ip', 'link', 'set', 'dev', iface, 'up'))
651 self.run_netns_wait('dhcp', ('udhcpc', '-q', '-i', iface))
652
Neels Hofmeyr8c7477f2017-05-25 04:33:53 +0200653 def sms_send(self, to_msisdn_or_modem, *tokens):
654 if isinstance(to_msisdn_or_modem, Modem):
655 to_msisdn = to_msisdn_or_modem.msisdn
656 tokens = list(tokens)
657 tokens.append('to ' + to_msisdn_or_modem.name())
658 else:
659 to_msisdn = str(to_msisdn_or_modem)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200660 msg = sms.Sms(self.msisdn, to_msisdn, 'from ' + self.name(), *tokens)
661 self.log('sending sms to MSISDN', to_msisdn, sms=msg)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200662 mm = self.dbus.interface(I_SMS)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200663 mm.SendMessage(to_msisdn, str(msg))
664 return msg
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200665
666 def _on_incoming_message(self, message, info):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200667 self.log('Incoming SMS:', repr(message))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200668 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200669 self.sms_received_list.append((message, info))
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200670
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200671 def sms_was_received(self, sms_obj):
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200672 for msg, info in self.sms_received_list:
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200673 if sms_obj.matches(msg):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200674 self.log('SMS received as expected:', repr(msg))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200675 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200676 return True
677 return False
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200678
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200679 def call_id_list(self):
680 self.dbg('call_id_list: %r' % self.call_list)
681 return self.call_list
682
683 def call_dial(self, to_msisdn_or_modem):
684 if isinstance(to_msisdn_or_modem, Modem):
685 to_msisdn = to_msisdn_or_modem.msisdn
686 else:
687 to_msisdn = str(to_msisdn_or_modem)
688 self.dbg('Dialing:', to_msisdn)
689 cmgr = self.dbus.interface(I_CALLMGR)
690 call_obj_path = cmgr.Dial(to_msisdn, 'default')
691 if call_obj_path not in self.call_list:
692 self.dbg('Adding %s to call list' % call_obj_path)
693 self.call_list.append(call_obj_path)
694 else:
695 self.dbg('Dial returned already existing call')
696 return call_obj_path
697
698 def _find_call_msisdn_state(self, msisdn, state):
699 cmgr = self.dbus.interface(I_CALLMGR)
700 ret = cmgr.GetCalls()
701 for obj_path, props in ret:
702 if props['LineIdentification'] == msisdn and props['State'] == state:
703 return obj_path
704 return None
705
706 def call_wait_incoming(self, caller_msisdn_or_modem, timeout=60):
707 if isinstance(caller_msisdn_or_modem, Modem):
708 caller_msisdn = caller_msisdn_or_modem.msisdn
709 else:
710 caller_msisdn = str(caller_msisdn_or_modem)
711 self.dbg('Waiting for incoming call from:', caller_msisdn)
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200712 MainLoop.wait(self, lambda: self._find_call_msisdn_state(caller_msisdn, 'incoming') is not None, timeout=timeout)
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200713 return self._find_call_msisdn_state(caller_msisdn, 'incoming')
714
715 def call_answer(self, call_id):
716 self.dbg('Answer call %s' % call_id)
717 assert self.call_state(call_id) == 'incoming'
718 call_dbus_obj = systembus_get(call_id)
719 call_dbus_obj.Answer()
720
721 def call_hangup(self, call_id):
722 self.dbg('Hang up call %s' % call_id)
723 call_dbus_obj = systembus_get(call_id)
724 call_dbus_obj.Hangup()
725
726 def call_is_active(self, call_id):
727 return self.call_state(call_id) == 'active'
728
729 def call_state(self, call_id):
Pau Espin Pedrolccb1bc62018-04-22 12:58:08 +0200730 try:
731 call_dbus_obj = systembus_get(call_id)
732 props = call_dbus_obj.GetProperties()
733 state = props.get('State')
734 except Exception as e:
735 self.log('asking call state for non existent call')
736 log.log_exn()
737 state = 'disconnected'
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200738 self.dbg('call state: %s' % state)
739 return state
740
741 def _on_callmgr_call_added(self, obj_path, properties):
742 self.dbg('%r.CallAdded() -> %s=%r' % (I_CALLMGR, obj_path, repr(properties)))
743 if obj_path not in self.call_list:
744 self.call_list.append(obj_path)
745 else:
746 self.dbg('Call already exists %r' % obj_path)
747
748 def _on_callmgr_call_removed(self, obj_path):
749 self.dbg('%r.CallRemoved() -> %s' % (I_CALLMGR, obj_path))
750 if obj_path in self.call_list:
751 self.call_list.remove(obj_path)
752 else:
753 self.dbg('Trying to remove non-existing call %r' % obj_path)
754
755 def _on_callmgr_property_changed(self, name, value):
756 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_CALLMGR, name, value))
757
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100758 def _on_connmgr_property_changed(self, name, value):
759 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_CONNMGR, name, value))
760
Pau Espin Pedrolee6e4912017-09-05 18:46:34 +0200761 def info(self, keys=('Manufacturer', 'Model', 'Revision', 'Serial')):
Neels Hofmeyrb8011692017-05-29 03:45:24 +0200762 props = self.properties()
763 return ', '.join(['%s: %r'%(k,props.get(k)) for k in keys])
764
765 def log_info(self, *args, **kwargs):
766 self.log(self.info(*args, **kwargs))
767
Pau Espin Pedrol03983aa2017-06-12 15:31:27 +0200768 def ussd_send(self, command):
769 ss = self.dbus.interface(I_SS)
770 service_type, response = ss.Initiate(command)
771 return response
772
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200773# vim: expandtab tabstop=4 shiftwidth=4