blob: e7ce68a6816c90a867a08d0b52365bcb3b7517cf [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
Holger Hans Peter Freyther48c83a82019-02-27 08:27:46 +000022from .ms import MS
Neels Hofmeyr3531a192017-03-28 14:30:28 +020023
24from pydbus import SystemBus, Variant
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +020025import os
Neels Hofmeyr3531a192017-03-28 14:30:28 +020026
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +020027# Required for Gio.Cancellable.
28# See https://lazka.github.io/pgi-docs/Gio-2.0/classes/Cancellable.html#Gio.Cancellable
29from gi.module import get_introspection_module
30Gio = get_introspection_module('Gio')
31
Neels Hofmeyr3531a192017-03-28 14:30:28 +020032from gi.repository import GLib
Holger Hans Peter Freytherae0dae82019-02-20 08:57:46 +000033bus = None
Neels Hofmeyr3531a192017-03-28 14:30:28 +020034
Pau Espin Pedrol504a6642017-05-04 11:38:23 +020035I_MODEM = 'org.ofono.Modem'
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +020036I_NETREG = 'org.ofono.NetworkRegistration'
37I_SMS = 'org.ofono.MessageManager'
Pau Espin Pedrolde899612017-11-23 17:18:40 +010038I_CONNMGR = 'org.ofono.ConnectionManager'
Pau Espin Pedrold71edd12017-10-06 13:53:54 +020039I_CALLMGR = 'org.ofono.VoiceCallManager'
40I_CALL = 'org.ofono.VoiceCall'
Pau Espin Pedrol03983aa2017-06-12 15:31:27 +020041I_SS = 'org.ofono.SupplementaryServices'
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +010042I_SIMMGR = 'org.ofono.SimManager'
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +020043
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020044# See https://github.com/intgr/ofono/blob/master/doc/network-api.txt#L78
45NETREG_ST_REGISTERED = 'registered'
46NETREG_ST_ROAMING = 'roaming'
47
48NETREG_MAX_REGISTER_ATTEMPTS = 3
49
Pau Espin Pedrolbf176e42018-03-26 19:13:32 +020050class DeferredDBus:
Neels Hofmeyr035cda82017-05-05 17:52:45 +020051
52 def __init__(self, dbus_iface, handler):
53 self.handler = handler
Neels Hofmeyr47de6b02017-05-10 13:24:05 +020054 self.subscription_id = dbus_iface.connect(self.receive_signal)
Neels Hofmeyr035cda82017-05-05 17:52:45 +020055
56 def receive_signal(self, *args, **kwargs):
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +020057 MainLoop.defer(self.handler, *args, **kwargs)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020058
Neels Hofmeyr035cda82017-05-05 17:52:45 +020059def dbus_connect(dbus_iface, handler):
60 '''This function shall be used instead of directly connecting DBus signals.
61 It ensures that we don't nest a glib main loop within another, and also
62 that we receive exceptions raised within the signal handlers. This makes it
63 so that a signal handler is invoked only after the DBus polling is through
64 by enlisting signals that should be handled in the
65 DeferredHandling.defer_queue.'''
Pau Espin Pedrolbf176e42018-03-26 19:13:32 +020066 return DeferredDBus(dbus_iface, handler).subscription_id
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020067
Neels Hofmeyr93f58662017-05-03 16:32:16 +020068def systembus_get(path):
Neels Hofmeyr3531a192017-03-28 14:30:28 +020069 global bus
Holger Hans Peter Freytherae0dae82019-02-20 08:57:46 +000070 if not bus:
71 bus = SystemBus()
Neels Hofmeyr3531a192017-03-28 14:30:28 +020072 return bus.get('org.ofono', path)
73
74def list_modems():
Neels Hofmeyr93f58662017-05-03 16:32:16 +020075 root = systembus_get('/')
Neels Hofmeyr3531a192017-03-28 14:30:28 +020076 return sorted(root.GetModems())
77
Pau Espin Pedrole25cf042018-02-23 17:00:09 +010078def get_dbuspath_from_syspath(syspath):
79 modems = list_modems()
80 for dbuspath, props in modems:
81 if props.get('SystemPath', '') == syspath:
82 return dbuspath
83 raise ValueError('could not find %s in modem list: %s' % (syspath, modems))
84
85
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020086def _async_result_handler(obj, result, user_data):
87 '''Generic callback dispatcher called from glib loop when an async method
88 call has returned. This callback is set up by method dbus_async_call.'''
89 (result_callback, error_callback, real_user_data) = user_data
90 try:
91 ret = obj.call_finish(result)
92 except Exception as e:
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +020093 if isinstance(e, GLib.Error) and e.code == Gio.IOErrorEnum.CANCELLED:
94 log.dbg('DBus method cancelled')
95 return
96
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020097 if error_callback:
98 error_callback(obj, e, real_user_data)
99 else:
100 result_callback(obj, e, real_user_data)
101 return
102
103 ret = ret.unpack()
104 # to be compatible with standard Python behaviour, unbox
105 # single-element tuples and return None for empty result tuples
106 if len(ret) == 1:
107 ret = ret[0]
108 elif len(ret) == 0:
109 ret = None
110 result_callback(obj, ret, real_user_data)
111
112def dbus_async_call(instance, proxymethod, *proxymethod_args,
113 result_handler=None, error_handler=None,
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200114 user_data=None, timeout=30, cancellable=None,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200115 **proxymethod_kwargs):
116 '''pydbus doesn't support asynchronous methods. This method adds support for
117 it until pydbus implements it'''
118
119 argdiff = len(proxymethod_args) - len(proxymethod._inargs)
120 if argdiff < 0:
121 raise TypeError(proxymethod.__qualname__ + " missing {} required positional argument(s)".format(-argdiff))
122 elif argdiff > 0:
123 raise TypeError(proxymethod.__qualname__ + " takes {} positional argument(s) but {} was/were given".format(len(proxymethod._inargs), len(proxymethod_args)))
124
125 timeout = timeout * 1000
126 user_data = (result_handler, error_handler, user_data)
127
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200128 # See https://lazka.github.io/pgi-docs/Gio-2.0/classes/DBusProxy.html#Gio.DBusProxy.call
Holger Hans Peter Freyther34dce0e2019-02-27 04:34:00 +0000129 instance._bus.con.call(
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200130 instance._bus_name, instance._path,
131 proxymethod._iface_name, proxymethod.__name__,
132 GLib.Variant(proxymethod._sinargs, proxymethod_args),
133 GLib.VariantType.new(proxymethod._soutargs),
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200134 0, timeout, cancellable,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200135 _async_result_handler, user_data)
136
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200137def dbus_call_dismiss_error(log_obj, err_str, method):
138 try:
139 method()
Pau Espin Pedrol9b670212017-11-07 17:50:20 +0100140 except GLib.Error as e:
141 if Gio.DBusError.is_remote_error(e) and Gio.DBusError.get_remote_error(e) == err_str:
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200142 log_obj.log('Dismissed Dbus method error: %r' % e)
143 return
Pau Espin Pedrol9b670212017-11-07 17:50:20 +0100144 raise e
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200145
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200146class ModemDbusInteraction(log.Origin):
147 '''Work around inconveniences specific to pydbus and ofono.
148 ofono adds and removes DBus interfaces and notifies about them.
149 Upon changes we need a fresh pydbus object to benefit from that.
150 Watching the interfaces change is optional; be sure to call
151 watch_interfaces() if you'd like to have signals subscribed.
152 Related: https://github.com/LEW21/pydbus/issues/56
153 '''
154
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200155 modem_path = None
156 watch_props_subscription = None
157 _dbus_obj = None
158 interfaces = None
159
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200160 def __init__(self, modem_path):
161 self.modem_path = modem_path
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200162 super().__init__(log.C_BUS, self.modem_path)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200163 self.interfaces = set()
164
165 # A dict listing signal handlers to connect, e.g.
166 # { I_SMS: ( ('IncomingMessage', self._on_incoming_message), ), }
167 self.required_signals = {}
168
169 # A dict collecting subscription tokens for connected signal handlers.
170 # { I_SMS: ( token1, token2, ... ), }
171 self.connected_signals = util.listdict()
172
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200173 def cleanup(self):
Pau Espin Pedrol58ff38d2017-06-23 13:10:38 +0200174 self.set_powered(False)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200175 self.unwatch_interfaces()
176 for interface_name in list(self.connected_signals.keys()):
177 self.remove_signals(interface_name)
178
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200179 def __del__(self):
180 self.cleanup()
181
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200182 def get_new_dbus_obj(self):
183 return systembus_get(self.modem_path)
184
185 def dbus_obj(self):
186 if self._dbus_obj is None:
187 self._dbus_obj = self.get_new_dbus_obj()
188 return self._dbus_obj
189
190 def interface(self, interface_name):
191 try:
192 return self.dbus_obj()[interface_name]
193 except KeyError:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200194 raise log.Error('Modem interface is not available:', interface_name)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200195
196 def signal(self, interface_name, signal):
197 return getattr(self.interface(interface_name), signal)
198
199 def watch_interfaces(self):
200 self.unwatch_interfaces()
201 # Note: we are watching the properties on a get_new_dbus_obj() that is
202 # separate from the one used to interact with interfaces. We need to
203 # refresh the pydbus object to interact with Interfaces that have newly
204 # appeared, but exchanging the DBus object to watch Interfaces being
205 # enabled and disabled is racy: we may skip some removals and
206 # additions. Hence do not exchange this DBus object. We don't even
207 # need to store the dbus object used for this, we will not touch it
208 # again. We only store the signal subscription.
209 self.watch_props_subscription = dbus_connect(self.get_new_dbus_obj().PropertyChanged,
210 self.on_property_change)
211 self.on_interfaces_change(self.properties().get('Interfaces'))
212
213 def unwatch_interfaces(self):
214 if self.watch_props_subscription is None:
215 return
216 self.watch_props_subscription.disconnect()
217 self.watch_props_subscription = None
218
219 def on_property_change(self, name, value):
220 if name == 'Interfaces':
221 self.on_interfaces_change(value)
Pau Espin Pedrol77631212017-09-05 19:04:06 +0200222 else:
223 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_MODEM, name, value))
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200224
225 def on_interfaces_change(self, interfaces_now):
226 # First some logging.
227 now = set(interfaces_now)
228 additions = now - self.interfaces
229 removals = self.interfaces - now
230 self.interfaces = now
231 if not (additions or removals):
232 # nothing changed.
233 return
234
235 if additions:
236 self.dbg('interface enabled:', ', '.join(sorted(additions)))
237
238 if removals:
239 self.dbg('interface disabled:', ', '.join(sorted(removals)))
240
241 # The dbus object is now stale and needs refreshing before we
242 # access the next interface function.
243 self._dbus_obj = None
244
245 # If an interface disappeared, disconnect the signal handlers for it.
246 # Even though we're going to use a fresh dbus object for new
247 # subscriptions, we will still keep active subscriptions alive on the
248 # old dbus object which will linger, associated with the respective
249 # signal subscription.
250 for removed in removals:
251 self.remove_signals(removed)
252
253 # Connect signals for added interfaces.
254 for interface_name in additions:
255 self.connect_signals(interface_name)
256
257 def remove_signals(self, interface_name):
258 got = self.connected_signals.pop(interface_name, [])
259
260 if not got:
261 return
262
263 self.dbg('Disconnecting', len(got), 'signals for', interface_name)
264 for subscription in got:
265 subscription.disconnect()
266
267 def connect_signals(self, interface_name):
268 # If an interface was added, it must not have existed before. For
269 # paranoia, make sure we have no handlers for those.
270 self.remove_signals(interface_name)
271
272 want = self.required_signals.get(interface_name, [])
273 if not want:
274 return
275
276 self.dbg('Connecting', len(want), 'signals for', interface_name)
277 for signal, cb in self.required_signals.get(interface_name, []):
278 subscription = dbus_connect(self.signal(interface_name, signal), cb)
279 self.connected_signals.add(interface_name, subscription)
280
281 def has_interface(self, *interface_names):
282 try:
283 for interface_name in interface_names:
284 self.dbus_obj()[interface_name]
285 result = True
286 except KeyError:
287 result = False
288 self.dbg('has_interface(%s) ==' % (', '.join(interface_names)), result)
289 return result
290
291 def properties(self, iface=I_MODEM):
292 return self.dbus_obj()[iface].GetProperties()
293
294 def property_is(self, name, val, iface=I_MODEM):
295 is_val = self.properties(iface).get(name)
296 self.dbg(name, '==', is_val)
297 return is_val is not None and is_val == val
298
299 def set_bool(self, name, bool_val, iface=I_MODEM):
300 # to make sure any pending signals are received before we send out more DBus requests
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200301 MainLoop.poll()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200302
303 val = bool(bool_val)
304 self.log('Setting', name, val)
305 self.interface(iface).SetProperty(name, Variant('b', val))
306
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200307 MainLoop.wait(self, self.property_is, name, bool_val)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200308
309 def set_powered(self, powered=True):
310 self.set_bool('Powered', powered)
311
312 def set_online(self, online=True):
313 self.set_bool('Online', online)
314
315 def is_powered(self):
316 return self.property_is('Powered', True)
317
318 def is_online(self):
319 return self.property_is('Online', True)
320
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200321
Holger Hans Peter Freyther48c83a82019-02-27 08:27:46 +0000322class Modem(MS):
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200323 'convenience for ofono Modem interaction'
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200324
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100325 CTX_PROT_IPv4 = 'ip'
326 CTX_PROT_IPv6 = 'ipv6'
327 CTX_PROT_IPv46 = 'dual'
328
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200329 def __init__(self, suite_run, conf):
Pau Espin Pedrole25cf042018-02-23 17:00:09 +0100330 self.syspath = conf.get('path')
331 self.dbuspath = get_dbuspath_from_syspath(self.syspath)
Holger Hans Peter Freyther48c83a82019-02-27 08:27:46 +0000332 super().__init__(self.dbuspath, conf)
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._ki = None
335 self._imsi = None
Holger Hans Peter Freyther48c83a82019-02-27 08:27:46 +0000336 self.run_dir = util.Dir(suite_run.get_test_run_dir().new_dir(self.name().strip('/')))
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200337 self.sms_received_list = []
Pau Espin Pedrole25cf042018-02-23 17:00:09 +0100338 self.dbus = ModemDbusInteraction(self.dbuspath)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200339 self.register_attempts = 0
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200340 self.call_list = []
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200341 # one Cancellable can handle several concurrent methods.
342 self.cancellable = Gio.Cancellable.new()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200343 self.dbus.required_signals = {
344 I_SMS: ( ('IncomingMessage', self._on_incoming_message), ),
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200345 I_NETREG: ( ('PropertyChanged', self._on_netreg_property_changed), ),
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100346 I_CONNMGR: ( ('PropertyChanged', self._on_connmgr_property_changed), ),
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200347 I_CALLMGR: ( ('PropertyChanged', self._on_callmgr_property_changed),
348 ('CallAdded', self._on_callmgr_call_added),
349 ('CallRemoved', self._on_callmgr_call_removed), ),
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200350 }
351 self.dbus.watch_interfaces()
352
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200353 def cleanup(self):
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200354 self.dbg('cleanup')
355 if self.cancellable:
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200356 self.cancel_pending_dbus_methods()
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200357 self.cancellable = None
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100358 if self.is_powered():
359 self.power_off()
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200360 self.dbus.cleanup()
361 self.dbus = None
362
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200363 def netns(self):
364 return os.path.basename(self.syspath.rstrip('/'))
365
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200366 def properties(self, *args, **kwargs):
367 '''Return a dict of properties on this modem. For the actual arguments,
368 see ModemDbusInteraction.properties(), which this function calls. The
369 returned dict is defined by ofono. An example is:
370 {'Lockdown': False,
371 'Powered': True,
372 'Model': 'MC7304',
373 'Revision': 'SWI9X15C_05.05.66.00 r29972 CARMD-EV-FRMWR1 2015/10/08 08:36:28',
374 'Manufacturer': 'Sierra Wireless, Incorporated',
375 'Emergency': False,
376 'Interfaces': ['org.ofono.SmartMessaging',
377 'org.ofono.PushNotification',
378 'org.ofono.MessageManager',
379 'org.ofono.NetworkRegistration',
380 'org.ofono.ConnectionManager',
381 'org.ofono.SupplementaryServices',
382 'org.ofono.RadioSettings',
383 'org.ofono.AllowedAccessPoints',
384 'org.ofono.SimManager',
385 'org.ofono.LocationReporting',
386 'org.ofono.VoiceCallManager'],
387 'Serial': '356853054230919',
388 'Features': ['sms', 'net', 'gprs', 'ussd', 'rat', 'sim', 'gps'],
389 'Type': 'hardware',
390 'Online': True}
391 '''
392 return self.dbus.properties(*args, **kwargs)
393
394 def set_powered(self, powered=True):
395 return self.dbus.set_powered(powered=powered)
396
397 def set_online(self, online=True):
398 return self.dbus.set_online(online=online)
399
400 def is_powered(self):
401 return self.dbus.is_powered()
402
403 def is_online(self):
404 return self.dbus.is_online()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200405
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200406 def imsi(self):
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100407 if self._imsi is None:
408 if 'sim' in self.features():
409 if not self.is_powered():
410 self.set_powered()
411 # wait for SimManager iface to appear after we power on
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200412 MainLoop.wait(self, self.dbus.has_interface, I_SIMMGR, timeout=10)
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100413 simmgr = self.dbus.interface(I_SIMMGR)
414 # If properties are requested quickly, it may happen that Sim property is still not there.
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200415 MainLoop.wait(self, lambda: simmgr.GetProperties().get('SubscriberIdentity', None) is not None, timeout=10)
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100416 props = simmgr.GetProperties()
417 self.dbg('got SIM properties', props)
418 self._imsi = props.get('SubscriberIdentity', None)
419 else:
Holger Hans Peter Freyther48c83a82019-02-27 08:27:46 +0000420 self._imsi = super().imsi()
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100421 if self._imsi is None:
422 raise log.Error('No IMSI')
423 return self._imsi
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200424
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200425 def set_ki(self, ki):
426 self._ki = ki
427
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200428 def ki(self):
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200429 if self._ki is not None:
430 return self._ki
Holger Hans Peter Freyther48c83a82019-02-27 08:27:46 +0000431 return super().ki()
Pau Espin Pedrol713ce2c2017-08-24 16:57:17 +0200432
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100433 def features(self):
Holger Hans Peter Freyther48c83a82019-02-27 08:27:46 +0000434 return self._conf.get('features', [])
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100435
436 def _required_ifaces(self):
437 req_ifaces = (I_NETREG,)
438 req_ifaces += (I_SMS,) if 'sms' in self.features() else ()
439 req_ifaces += (I_SS,) if 'ussd' in self.features() else ()
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100440 req_ifaces += (I_CONNMGR,) if 'gprs' in self.features() else ()
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100441 req_ifaces += (I_SIMMGR,) if 'sim' in self.features() else ()
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100442 return req_ifaces
443
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200444 def _on_netreg_property_changed(self, name, value):
445 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_NETREG, name, value))
446
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200447 def is_connected(self, mcc_mnc=None):
448 netreg = self.dbus.interface(I_NETREG)
449 prop = netreg.GetProperties()
450 status = prop.get('Status')
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200451 self.dbg('status:', status)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200452 if not (status == NETREG_ST_REGISTERED or status == NETREG_ST_ROAMING):
453 return False
454 if mcc_mnc is None: # Any network is fine and we are registered.
455 return True
456 mcc = prop.get('MobileCountryCode')
457 mnc = prop.get('MobileNetworkCode')
458 if (mcc, mnc) == mcc_mnc:
459 return True
460 return False
461
462 def schedule_scan_register(self, mcc_mnc):
463 if self.register_attempts > NETREG_MAX_REGISTER_ATTEMPTS:
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200464 raise log.Error('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200465 self.register_attempts += 1
466 netreg = self.dbus.interface(I_NETREG)
467 self.dbg('Scanning for operators...')
468 # Scan method can take several seconds, and we don't want to block
469 # waiting for that. Make it async and try to register when the scan is
470 # finished.
471 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 +0200472 result_handler = lambda obj, result, user_data: MainLoop.defer(register_func, result, user_data)
473 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 +0200474 dbus_async_call(netreg, netreg.Scan, timeout=30, cancellable=self.cancellable,
475 result_handler=result_handler, error_handler=error_handler,
476 user_data=mcc_mnc)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200477
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200478 def scan_cb_error_handler(self, e, mcc_mnc):
479 # It was detected that Scan() method can fail for some modems on some
480 # specific circumstances. For instance it fails with org.ofono.Error.Failed
481 # if the modem starts to register internally after we started Scan() and
482 # the registering succeeds while we are still waiting for Scan() to finsih.
483 # So far the easiest seems to check if we are now registered and
484 # otherwise schedule a scan again.
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200485 self.err('Scan() failed, retrying if needed:', e)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200486 if not self.is_connected(mcc_mnc):
487 self.schedule_scan_register(mcc_mnc)
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200488 else:
489 self.log('Already registered with network', mcc_mnc)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200490
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200491 def scan_cb_register_automatic(self, scanned_operators, mcc_mnc):
492 self.dbg('scanned operators: ', scanned_operators);
493 for op_path, op_prop in scanned_operators:
494 if op_prop.get('Status') == 'current':
495 mcc = op_prop.get('MobileCountryCode')
496 mnc = op_prop.get('MobileNetworkCode')
497 self.log('Already registered with network', (mcc, mnc))
498 return
499 self.log('Registering with the default network')
500 netreg = self.dbus.interface(I_NETREG)
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200501 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', netreg.Register)
502
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200503
504 def scan_cb_register(self, scanned_operators, mcc_mnc):
505 self.dbg('scanned operators: ', scanned_operators);
506 matching_op_path = None
507 for op_path, op_prop in scanned_operators:
508 mcc = op_prop.get('MobileCountryCode')
509 mnc = op_prop.get('MobileNetworkCode')
510 if (mcc, mnc) == mcc_mnc:
511 if op_prop.get('Status') == 'current':
512 self.log('Already registered with network', mcc_mnc)
513 # We discovered the network and we are already registered
514 # with it. Avoid calling op.Register() in this case (it
515 # won't act as a NO-OP, it actually returns an error).
516 return
517 matching_op_path = op_path
518 break
519 if matching_op_path is None:
520 self.dbg('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
521 self.schedule_scan_register(mcc_mnc)
522 return
523 dbus_op = systembus_get(matching_op_path)
524 self.log('Registering with operator', matching_op_path, mcc_mnc)
Pau Espin Pedrol9f59b822017-11-07 17:50:52 +0100525 try:
526 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', dbus_op.Register)
527 except GLib.Error as e:
528 if Gio.DBusError.is_remote_error(e) and Gio.DBusError.get_remote_error(e) == 'org.ofono.Error.NotSupported':
529 self.log('modem does not support manual registering, attempting automatic registering')
530 self.scan_cb_register_automatic(scanned_operators, mcc_mnc)
531 return
532 raise e
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200533
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200534 def cancel_pending_dbus_methods(self):
535 self.cancellable.cancel()
536 # Cancel op is applied as a signal coming from glib mainloop, so we
537 # need to run it and wait for the callbacks to handle cancellations.
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200538 MainLoop.poll()
Pau Espin Pedrole685c622017-10-04 18:30:22 +0200539 # once it has been triggered, create a new one for next operation:
540 self.cancellable = Gio.Cancellable.new()
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200541
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100542 def power_off(self):
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100543 if self.dbus.has_interface(I_CONNMGR) and self.is_attached():
544 self.detach()
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100545 self.set_online(False)
546 self.set_powered(False)
547 req_ifaces = self._required_ifaces()
548 for iface in req_ifaces:
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200549 MainLoop.wait(self, lambda: not self.dbus.has_interface(iface), timeout=10)
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100550
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200551 def power_cycle(self):
552 'Power the modem and put it online, power cycle it if it was already on'
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100553 req_ifaces = self._required_ifaces()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200554 if self.is_powered():
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200555 self.dbg('Power cycling')
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200556 MainLoop.sleep(self, 1.0) # workaround for ofono bug OS#3064
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100557 self.power_off()
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200558 else:
559 self.dbg('Powering on')
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200560 self.set_powered()
Pau Espin Pedrolb9955762017-05-02 09:39:27 +0200561 self.set_online()
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200562 MainLoop.wait(self, self.dbus.has_interface, *req_ifaces, timeout=10)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200563
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200564 def connect(self, mcc_mnc=None):
565 'Connect to MCC+MNC'
566 if (mcc_mnc is not None) and (len(mcc_mnc) != 2 or None in mcc_mnc):
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200567 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 +0200568 # if test called connect() before and async scanning has not finished, we need to get rid of it:
569 self.cancel_pending_dbus_methods()
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200570 self.power_cycle()
571 self.register_attempts = 0
572 if self.is_connected(mcc_mnc):
573 self.log('Already registered with', mcc_mnc if mcc_mnc else 'default network')
574 else:
575 self.log('Connect to', mcc_mnc if mcc_mnc else 'default network')
576 self.schedule_scan_register(mcc_mnc)
577
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100578 def is_attached(self):
579 connmgr = self.dbus.interface(I_CONNMGR)
580 prop = connmgr.GetProperties()
581 attached = prop.get('Attached')
582 self.dbg('attached:', attached)
583 return attached
584
585 def attach(self, allow_roaming=False):
586 self.dbg('attach')
587 if self.is_attached():
588 self.detach()
589 connmgr = self.dbus.interface(I_CONNMGR)
Holger Hans Peter Freyther34dce0e2019-02-27 04:34:00 +0000590 connmgr.SetProperty('RoamingAllowed', Variant('b', allow_roaming))
591 connmgr.SetProperty('Powered', Variant('b', True))
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100592
593 def detach(self):
594 self.dbg('detach')
595 connmgr = self.dbus.interface(I_CONNMGR)
Holger Hans Peter Freyther34dce0e2019-02-27 04:34:00 +0000596 connmgr.SetProperty('RoamingAllowed', Variant('b', False))
597 connmgr.SetProperty('Powered', Variant('b', False))
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100598 connmgr.DeactivateAll()
599 connmgr.ResetContexts() # Requires Powered=false
600
601 def activate_context(self, apn='internet', user='ogt', pwd='', protocol='ip'):
Pau Espin Pedrolb05e36a2017-12-15 12:39:36 +0100602 self.dbg('activate_context', apn=apn, user=user, protocol=protocol)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100603
604 connmgr = self.dbus.interface(I_CONNMGR)
605 ctx_path = connmgr.AddContext('internet')
606
607 ctx = systembus_get(ctx_path)
608 ctx.SetProperty('AccessPointName', Variant('s', apn))
609 ctx.SetProperty('Username', Variant('s', user))
610 ctx.SetProperty('Password', Variant('s', pwd))
611 ctx.SetProperty('Protocol', Variant('s', protocol))
612
613 # Activate can only be called after we are attached
614 ctx.SetProperty('Active', Variant('b', True))
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200615 MainLoop.wait(self, lambda: ctx.GetProperties()['Active'] == True)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100616 self.log('context activated', path=ctx_path, apn=apn, user=user, properties=ctx.GetProperties())
617 return ctx_path
618
619 def deactivate_context(self, ctx_id):
Pau Espin Pedrol263dd3b2018-02-13 16:53:51 +0100620 self.dbg('deactivate_context', path=ctx_id)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100621 ctx = systembus_get(ctx_id)
622 ctx.SetProperty('Active', Variant('b', False))
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200623 MainLoop.wait(self, lambda: ctx.GetProperties()['Active'] == False)
Pau Espin Pedrolcdac2972018-02-16 15:14:32 +0100624 self.dbg('deactivate_context active=false, removing', path=ctx_id)
625 connmgr = self.dbus.interface(I_CONNMGR)
626 connmgr.RemoveContext(ctx_id)
Pau Espin Pedrolb05aa3c2018-02-16 15:03:50 +0100627 self.log('context deactivated', path=ctx_id)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100628
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200629 def run_netns_wait(self, name, popen_args):
630 proc = process.NetNSProcess(name, self.run_dir.new_dir(name), self.netns(), popen_args,
631 env={})
Pau Espin Pedrol79df7392018-11-12 18:15:30 +0100632 proc.launch_sync()
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200633
634 def setup_context_data_plane(self, ctx_id):
635 self.dbg('setup_context_data', path=ctx_id)
636 ctx = systembus_get(ctx_id)
637 ctx_settings = ctx.GetProperties().get('Settings', None)
638 if not ctx_settings:
639 raise log.Error('%s no Settings found! No way to get iface!' % ctx_id)
640 iface = ctx_settings.get('Interface', None)
641 if not iface:
642 raise log.Error('%s Settings contains no iface! %r' % (ctx_id, repr(ctx_settings)))
643 self.run_netns_wait('ifup', ('ip', 'link', 'set', 'dev', iface, 'up'))
644 self.run_netns_wait('dhcp', ('udhcpc', '-q', '-i', iface))
645
Neels Hofmeyr8c7477f2017-05-25 04:33:53 +0200646 def sms_send(self, to_msisdn_or_modem, *tokens):
647 if isinstance(to_msisdn_or_modem, Modem):
648 to_msisdn = to_msisdn_or_modem.msisdn
649 tokens = list(tokens)
650 tokens.append('to ' + to_msisdn_or_modem.name())
651 else:
652 to_msisdn = str(to_msisdn_or_modem)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200653 msg = sms.Sms(self.msisdn, to_msisdn, 'from ' + self.name(), *tokens)
654 self.log('sending sms to MSISDN', to_msisdn, sms=msg)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200655 mm = self.dbus.interface(I_SMS)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200656 mm.SendMessage(to_msisdn, str(msg))
657 return msg
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200658
659 def _on_incoming_message(self, message, info):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200660 self.log('Incoming SMS:', repr(message))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200661 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200662 self.sms_received_list.append((message, info))
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200663
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200664 def sms_was_received(self, sms_obj):
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200665 for msg, info in self.sms_received_list:
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200666 if sms_obj.matches(msg):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200667 self.log('SMS received as expected:', repr(msg))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200668 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200669 return True
670 return False
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200671
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200672 def call_id_list(self):
673 self.dbg('call_id_list: %r' % self.call_list)
674 return self.call_list
675
676 def call_dial(self, to_msisdn_or_modem):
677 if isinstance(to_msisdn_or_modem, Modem):
678 to_msisdn = to_msisdn_or_modem.msisdn
679 else:
680 to_msisdn = str(to_msisdn_or_modem)
681 self.dbg('Dialing:', to_msisdn)
682 cmgr = self.dbus.interface(I_CALLMGR)
683 call_obj_path = cmgr.Dial(to_msisdn, 'default')
684 if call_obj_path not in self.call_list:
685 self.dbg('Adding %s to call list' % call_obj_path)
686 self.call_list.append(call_obj_path)
687 else:
688 self.dbg('Dial returned already existing call')
689 return call_obj_path
690
691 def _find_call_msisdn_state(self, msisdn, state):
692 cmgr = self.dbus.interface(I_CALLMGR)
693 ret = cmgr.GetCalls()
694 for obj_path, props in ret:
695 if props['LineIdentification'] == msisdn and props['State'] == state:
696 return obj_path
697 return None
698
699 def call_wait_incoming(self, caller_msisdn_or_modem, timeout=60):
700 if isinstance(caller_msisdn_or_modem, Modem):
701 caller_msisdn = caller_msisdn_or_modem.msisdn
702 else:
703 caller_msisdn = str(caller_msisdn_or_modem)
704 self.dbg('Waiting for incoming call from:', caller_msisdn)
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200705 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 +0200706 return self._find_call_msisdn_state(caller_msisdn, 'incoming')
707
708 def call_answer(self, call_id):
709 self.dbg('Answer call %s' % call_id)
710 assert self.call_state(call_id) == 'incoming'
711 call_dbus_obj = systembus_get(call_id)
712 call_dbus_obj.Answer()
Pau Espin Pedrol4d7f7702019-02-13 19:30:38 +0100713 self.dbg('Answered call %s' % call_id)
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200714
715 def call_hangup(self, call_id):
716 self.dbg('Hang up call %s' % call_id)
717 call_dbus_obj = systembus_get(call_id)
718 call_dbus_obj.Hangup()
719
720 def call_is_active(self, call_id):
721 return self.call_state(call_id) == 'active'
722
723 def call_state(self, call_id):
Pau Espin Pedrolccb1bc62018-04-22 12:58:08 +0200724 try:
725 call_dbus_obj = systembus_get(call_id)
726 props = call_dbus_obj.GetProperties()
727 state = props.get('State')
Holger Hans Peter Freyther34dce0e2019-02-27 04:34:00 +0000728 except Exception:
Pau Espin Pedrolccb1bc62018-04-22 12:58:08 +0200729 self.log('asking call state for non existent call')
730 log.log_exn()
731 state = 'disconnected'
Pau Espin Pedrol32e9d8c2019-02-13 17:40:31 +0100732 self.dbg('call state: %s' % state, call_id=call_id)
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200733 return state
734
735 def _on_callmgr_call_added(self, obj_path, properties):
736 self.dbg('%r.CallAdded() -> %s=%r' % (I_CALLMGR, obj_path, repr(properties)))
737 if obj_path not in self.call_list:
738 self.call_list.append(obj_path)
739 else:
740 self.dbg('Call already exists %r' % obj_path)
741
742 def _on_callmgr_call_removed(self, obj_path):
743 self.dbg('%r.CallRemoved() -> %s' % (I_CALLMGR, obj_path))
744 if obj_path in self.call_list:
745 self.call_list.remove(obj_path)
746 else:
747 self.dbg('Trying to remove non-existing call %r' % obj_path)
748
749 def _on_callmgr_property_changed(self, name, value):
750 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_CALLMGR, name, value))
751
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100752 def _on_connmgr_property_changed(self, name, value):
753 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_CONNMGR, name, value))
754
Pau Espin Pedrolee6e4912017-09-05 18:46:34 +0200755 def info(self, keys=('Manufacturer', 'Model', 'Revision', 'Serial')):
Neels Hofmeyrb8011692017-05-29 03:45:24 +0200756 props = self.properties()
757 return ', '.join(['%s: %r'%(k,props.get(k)) for k in keys])
758
759 def log_info(self, *args, **kwargs):
760 self.log(self.info(*args, **kwargs))
761
Pau Espin Pedrol03983aa2017-06-12 15:31:27 +0200762 def ussd_send(self, command):
763 ss = self.dbus.interface(I_SS)
764 service_type, response = ss.Initiate(command)
765 return response
766
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200767# vim: expandtab tabstop=4 shiftwidth=4