blob: 8d419354c28be0515c10a7fe888ac8d4f37e824a [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 Pedrol24c5de82017-11-09 13:58:24 +010020from . import log, util, event_loop, sms
Neels Hofmeyr3531a192017-03-28 14:30:28 +020021
22from pydbus import SystemBus, Variant
23import time
24import pprint
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020025import sys
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
Neels Hofmeyr3531a192017-03-28 14:30:28 +020033bus = SystemBus()
34
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 Pedrolbf176e42018-03-26 19:13:32 +020057 event_loop.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
70 return bus.get('org.ofono', path)
71
72def list_modems():
Neels Hofmeyr93f58662017-05-03 16:32:16 +020073 root = systembus_get('/')
Neels Hofmeyr3531a192017-03-28 14:30:28 +020074 return sorted(root.GetModems())
75
Pau Espin Pedrole25cf042018-02-23 17:00:09 +010076def get_dbuspath_from_syspath(syspath):
77 modems = list_modems()
78 for dbuspath, props in modems:
79 if props.get('SystemPath', '') == syspath:
80 return dbuspath
81 raise ValueError('could not find %s in modem list: %s' % (syspath, modems))
82
83
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020084def _async_result_handler(obj, result, user_data):
85 '''Generic callback dispatcher called from glib loop when an async method
86 call has returned. This callback is set up by method dbus_async_call.'''
87 (result_callback, error_callback, real_user_data) = user_data
88 try:
89 ret = obj.call_finish(result)
90 except Exception as e:
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +020091 if isinstance(e, GLib.Error) and e.code == Gio.IOErrorEnum.CANCELLED:
92 log.dbg('DBus method cancelled')
93 return
94
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020095 if error_callback:
96 error_callback(obj, e, real_user_data)
97 else:
98 result_callback(obj, e, real_user_data)
99 return
100
101 ret = ret.unpack()
102 # to be compatible with standard Python behaviour, unbox
103 # single-element tuples and return None for empty result tuples
104 if len(ret) == 1:
105 ret = ret[0]
106 elif len(ret) == 0:
107 ret = None
108 result_callback(obj, ret, real_user_data)
109
110def dbus_async_call(instance, proxymethod, *proxymethod_args,
111 result_handler=None, error_handler=None,
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200112 user_data=None, timeout=30, cancellable=None,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200113 **proxymethod_kwargs):
114 '''pydbus doesn't support asynchronous methods. This method adds support for
115 it until pydbus implements it'''
116
117 argdiff = len(proxymethod_args) - len(proxymethod._inargs)
118 if argdiff < 0:
119 raise TypeError(proxymethod.__qualname__ + " missing {} required positional argument(s)".format(-argdiff))
120 elif argdiff > 0:
121 raise TypeError(proxymethod.__qualname__ + " takes {} positional argument(s) but {} was/were given".format(len(proxymethod._inargs), len(proxymethod_args)))
122
123 timeout = timeout * 1000
124 user_data = (result_handler, error_handler, user_data)
125
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200126 # See https://lazka.github.io/pgi-docs/Gio-2.0/classes/DBusProxy.html#Gio.DBusProxy.call
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200127 ret = instance._bus.con.call(
128 instance._bus_name, instance._path,
129 proxymethod._iface_name, proxymethod.__name__,
130 GLib.Variant(proxymethod._sinargs, proxymethod_args),
131 GLib.VariantType.new(proxymethod._soutargs),
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200132 0, timeout, cancellable,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200133 _async_result_handler, user_data)
134
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200135def dbus_call_dismiss_error(log_obj, err_str, method):
136 try:
137 method()
Pau Espin Pedrol9b670212017-11-07 17:50:20 +0100138 except GLib.Error as e:
139 if Gio.DBusError.is_remote_error(e) and Gio.DBusError.get_remote_error(e) == err_str:
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200140 log_obj.log('Dismissed Dbus method error: %r' % e)
141 return
Pau Espin Pedrol9b670212017-11-07 17:50:20 +0100142 raise e
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200143
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200144class ModemDbusInteraction(log.Origin):
145 '''Work around inconveniences specific to pydbus and ofono.
146 ofono adds and removes DBus interfaces and notifies about them.
147 Upon changes we need a fresh pydbus object to benefit from that.
148 Watching the interfaces change is optional; be sure to call
149 watch_interfaces() if you'd like to have signals subscribed.
150 Related: https://github.com/LEW21/pydbus/issues/56
151 '''
152
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200153 modem_path = None
154 watch_props_subscription = None
155 _dbus_obj = None
156 interfaces = None
157
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200158 def __init__(self, modem_path):
159 self.modem_path = modem_path
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200160 super().__init__(log.C_BUS, self.modem_path)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200161 self.interfaces = set()
162
163 # A dict listing signal handlers to connect, e.g.
164 # { I_SMS: ( ('IncomingMessage', self._on_incoming_message), ), }
165 self.required_signals = {}
166
167 # A dict collecting subscription tokens for connected signal handlers.
168 # { I_SMS: ( token1, token2, ... ), }
169 self.connected_signals = util.listdict()
170
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200171 def cleanup(self):
Pau Espin Pedrol58ff38d2017-06-23 13:10:38 +0200172 self.set_powered(False)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200173 self.unwatch_interfaces()
174 for interface_name in list(self.connected_signals.keys()):
175 self.remove_signals(interface_name)
176
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200177 def __del__(self):
178 self.cleanup()
179
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200180 def get_new_dbus_obj(self):
181 return systembus_get(self.modem_path)
182
183 def dbus_obj(self):
184 if self._dbus_obj is None:
185 self._dbus_obj = self.get_new_dbus_obj()
186 return self._dbus_obj
187
188 def interface(self, interface_name):
189 try:
190 return self.dbus_obj()[interface_name]
191 except KeyError:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200192 raise log.Error('Modem interface is not available:', interface_name)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200193
194 def signal(self, interface_name, signal):
195 return getattr(self.interface(interface_name), signal)
196
197 def watch_interfaces(self):
198 self.unwatch_interfaces()
199 # Note: we are watching the properties on a get_new_dbus_obj() that is
200 # separate from the one used to interact with interfaces. We need to
201 # refresh the pydbus object to interact with Interfaces that have newly
202 # appeared, but exchanging the DBus object to watch Interfaces being
203 # enabled and disabled is racy: we may skip some removals and
204 # additions. Hence do not exchange this DBus object. We don't even
205 # need to store the dbus object used for this, we will not touch it
206 # again. We only store the signal subscription.
207 self.watch_props_subscription = dbus_connect(self.get_new_dbus_obj().PropertyChanged,
208 self.on_property_change)
209 self.on_interfaces_change(self.properties().get('Interfaces'))
210
211 def unwatch_interfaces(self):
212 if self.watch_props_subscription is None:
213 return
214 self.watch_props_subscription.disconnect()
215 self.watch_props_subscription = None
216
217 def on_property_change(self, name, value):
218 if name == 'Interfaces':
219 self.on_interfaces_change(value)
Pau Espin Pedrol77631212017-09-05 19:04:06 +0200220 else:
221 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_MODEM, name, value))
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200222
223 def on_interfaces_change(self, interfaces_now):
224 # First some logging.
225 now = set(interfaces_now)
226 additions = now - self.interfaces
227 removals = self.interfaces - now
228 self.interfaces = now
229 if not (additions or removals):
230 # nothing changed.
231 return
232
233 if additions:
234 self.dbg('interface enabled:', ', '.join(sorted(additions)))
235
236 if removals:
237 self.dbg('interface disabled:', ', '.join(sorted(removals)))
238
239 # The dbus object is now stale and needs refreshing before we
240 # access the next interface function.
241 self._dbus_obj = None
242
243 # If an interface disappeared, disconnect the signal handlers for it.
244 # Even though we're going to use a fresh dbus object for new
245 # subscriptions, we will still keep active subscriptions alive on the
246 # old dbus object which will linger, associated with the respective
247 # signal subscription.
248 for removed in removals:
249 self.remove_signals(removed)
250
251 # Connect signals for added interfaces.
252 for interface_name in additions:
253 self.connect_signals(interface_name)
254
255 def remove_signals(self, interface_name):
256 got = self.connected_signals.pop(interface_name, [])
257
258 if not got:
259 return
260
261 self.dbg('Disconnecting', len(got), 'signals for', interface_name)
262 for subscription in got:
263 subscription.disconnect()
264
265 def connect_signals(self, interface_name):
266 # If an interface was added, it must not have existed before. For
267 # paranoia, make sure we have no handlers for those.
268 self.remove_signals(interface_name)
269
270 want = self.required_signals.get(interface_name, [])
271 if not want:
272 return
273
274 self.dbg('Connecting', len(want), 'signals for', interface_name)
275 for signal, cb in self.required_signals.get(interface_name, []):
276 subscription = dbus_connect(self.signal(interface_name, signal), cb)
277 self.connected_signals.add(interface_name, subscription)
278
279 def has_interface(self, *interface_names):
280 try:
281 for interface_name in interface_names:
282 self.dbus_obj()[interface_name]
283 result = True
284 except KeyError:
285 result = False
286 self.dbg('has_interface(%s) ==' % (', '.join(interface_names)), result)
287 return result
288
289 def properties(self, iface=I_MODEM):
290 return self.dbus_obj()[iface].GetProperties()
291
292 def property_is(self, name, val, iface=I_MODEM):
293 is_val = self.properties(iface).get(name)
294 self.dbg(name, '==', is_val)
295 return is_val is not None and is_val == val
296
297 def set_bool(self, name, bool_val, iface=I_MODEM):
298 # to make sure any pending signals are received before we send out more DBus requests
299 event_loop.poll()
300
301 val = bool(bool_val)
302 self.log('Setting', name, val)
303 self.interface(iface).SetProperty(name, Variant('b', val))
304
305 event_loop.wait(self, self.property_is, name, bool_val)
306
307 def set_powered(self, powered=True):
308 self.set_bool('Powered', powered)
309
310 def set_online(self, online=True):
311 self.set_bool('Online', online)
312
313 def is_powered(self):
314 return self.property_is('Powered', True)
315
316 def is_online(self):
317 return self.property_is('Online', True)
318
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200319
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200320
321class Modem(log.Origin):
322 'convenience for ofono Modem interaction'
323 msisdn = None
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200324 sms_received_list = None
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200325 _ki = None
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100326 _imsi = None
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200327
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100328 CTX_PROT_IPv4 = 'ip'
329 CTX_PROT_IPv6 = 'ipv6'
330 CTX_PROT_IPv46 = 'dual'
331
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200332 def __init__(self, conf):
333 self.conf = conf
Pau Espin Pedrole25cf042018-02-23 17:00:09 +0100334 self.syspath = conf.get('path')
335 self.dbuspath = get_dbuspath_from_syspath(self.syspath)
336 super().__init__(log.C_TST, self.dbuspath)
337 self.dbg('creating from syspath %s', self.syspath)
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
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200364 def properties(self, *args, **kwargs):
365 '''Return a dict of properties on this modem. For the actual arguments,
366 see ModemDbusInteraction.properties(), which this function calls. The
367 returned dict is defined by ofono. An example is:
368 {'Lockdown': False,
369 'Powered': True,
370 'Model': 'MC7304',
371 'Revision': 'SWI9X15C_05.05.66.00 r29972 CARMD-EV-FRMWR1 2015/10/08 08:36:28',
372 'Manufacturer': 'Sierra Wireless, Incorporated',
373 'Emergency': False,
374 'Interfaces': ['org.ofono.SmartMessaging',
375 'org.ofono.PushNotification',
376 'org.ofono.MessageManager',
377 'org.ofono.NetworkRegistration',
378 'org.ofono.ConnectionManager',
379 'org.ofono.SupplementaryServices',
380 'org.ofono.RadioSettings',
381 'org.ofono.AllowedAccessPoints',
382 'org.ofono.SimManager',
383 'org.ofono.LocationReporting',
384 'org.ofono.VoiceCallManager'],
385 'Serial': '356853054230919',
386 'Features': ['sms', 'net', 'gprs', 'ussd', 'rat', 'sim', 'gps'],
387 'Type': 'hardware',
388 'Online': True}
389 '''
390 return self.dbus.properties(*args, **kwargs)
391
392 def set_powered(self, powered=True):
393 return self.dbus.set_powered(powered=powered)
394
395 def set_online(self, online=True):
396 return self.dbus.set_online(online=online)
397
398 def is_powered(self):
399 return self.dbus.is_powered()
400
401 def is_online(self):
402 return self.dbus.is_online()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200403
404 def set_msisdn(self, msisdn):
405 self.msisdn = msisdn
406
407 def imsi(self):
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100408 if self._imsi is None:
409 if 'sim' in self.features():
410 if not self.is_powered():
411 self.set_powered()
412 # wait for SimManager iface to appear after we power on
413 event_loop.wait(self, self.dbus.has_interface, I_SIMMGR, timeout=10)
414 simmgr = self.dbus.interface(I_SIMMGR)
415 # If properties are requested quickly, it may happen that Sim property is still not there.
416 event_loop.wait(self, lambda: simmgr.GetProperties().get('SubscriberIdentity', None) is not None, timeout=10)
417 props = simmgr.GetProperties()
418 self.dbg('got SIM properties', props)
419 self._imsi = props.get('SubscriberIdentity', None)
420 else:
421 self._imsi = self.conf.get('imsi')
422 if self._imsi is None:
423 raise log.Error('No IMSI')
424 return self._imsi
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200425
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200426 def set_ki(self, ki):
427 self._ki = ki
428
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200429 def ki(self):
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200430 if self._ki is not None:
431 return self._ki
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200432 return self.conf.get('ki')
433
Pau Espin Pedrol713ce2c2017-08-24 16:57:17 +0200434 def auth_algo(self):
435 return self.conf.get('auth_algo', None)
436
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100437 def features(self):
438 return self.conf.get('features', [])
439
440 def _required_ifaces(self):
441 req_ifaces = (I_NETREG,)
442 req_ifaces += (I_SMS,) if 'sms' in self.features() else ()
443 req_ifaces += (I_SS,) if 'ussd' in self.features() else ()
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100444 req_ifaces += (I_CONNMGR,) if 'gprs' in self.features() else ()
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100445 req_ifaces += (I_SIMMGR,) if 'sim' in self.features() else ()
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100446 return req_ifaces
447
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200448 def _on_netreg_property_changed(self, name, value):
449 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_NETREG, name, value))
450
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200451 def is_connected(self, mcc_mnc=None):
452 netreg = self.dbus.interface(I_NETREG)
453 prop = netreg.GetProperties()
454 status = prop.get('Status')
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200455 self.dbg('status:', status)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200456 if not (status == NETREG_ST_REGISTERED or status == NETREG_ST_ROAMING):
457 return False
458 if mcc_mnc is None: # Any network is fine and we are registered.
459 return True
460 mcc = prop.get('MobileCountryCode')
461 mnc = prop.get('MobileNetworkCode')
462 if (mcc, mnc) == mcc_mnc:
463 return True
464 return False
465
466 def schedule_scan_register(self, mcc_mnc):
467 if self.register_attempts > NETREG_MAX_REGISTER_ATTEMPTS:
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200468 raise log.Error('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200469 self.register_attempts += 1
470 netreg = self.dbus.interface(I_NETREG)
471 self.dbg('Scanning for operators...')
472 # Scan method can take several seconds, and we don't want to block
473 # waiting for that. Make it async and try to register when the scan is
474 # finished.
475 register_func = self.scan_cb_register_automatic if mcc_mnc is None else self.scan_cb_register
Pau Espin Pedrolbf176e42018-03-26 19:13:32 +0200476 result_handler = lambda obj, result, user_data: event_loop.defer(register_func, result, user_data)
477 error_handler = lambda obj, e, user_data: event_loop.defer(self.scan_cb_error_handler, e, mcc_mnc)
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200478 dbus_async_call(netreg, netreg.Scan, timeout=30, cancellable=self.cancellable,
479 result_handler=result_handler, error_handler=error_handler,
480 user_data=mcc_mnc)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200481
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200482 def scan_cb_error_handler(self, e, mcc_mnc):
483 # It was detected that Scan() method can fail for some modems on some
484 # specific circumstances. For instance it fails with org.ofono.Error.Failed
485 # if the modem starts to register internally after we started Scan() and
486 # the registering succeeds while we are still waiting for Scan() to finsih.
487 # So far the easiest seems to check if we are now registered and
488 # otherwise schedule a scan again.
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200489 self.err('Scan() failed, retrying if needed:', e)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200490 if not self.is_connected(mcc_mnc):
491 self.schedule_scan_register(mcc_mnc)
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200492 else:
493 self.log('Already registered with network', mcc_mnc)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200494
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200495 def scan_cb_register_automatic(self, scanned_operators, mcc_mnc):
496 self.dbg('scanned operators: ', scanned_operators);
497 for op_path, op_prop in scanned_operators:
498 if op_prop.get('Status') == 'current':
499 mcc = op_prop.get('MobileCountryCode')
500 mnc = op_prop.get('MobileNetworkCode')
501 self.log('Already registered with network', (mcc, mnc))
502 return
503 self.log('Registering with the default network')
504 netreg = self.dbus.interface(I_NETREG)
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200505 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', netreg.Register)
506
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200507
508 def scan_cb_register(self, scanned_operators, mcc_mnc):
509 self.dbg('scanned operators: ', scanned_operators);
510 matching_op_path = None
511 for op_path, op_prop in scanned_operators:
512 mcc = op_prop.get('MobileCountryCode')
513 mnc = op_prop.get('MobileNetworkCode')
514 if (mcc, mnc) == mcc_mnc:
515 if op_prop.get('Status') == 'current':
516 self.log('Already registered with network', mcc_mnc)
517 # We discovered the network and we are already registered
518 # with it. Avoid calling op.Register() in this case (it
519 # won't act as a NO-OP, it actually returns an error).
520 return
521 matching_op_path = op_path
522 break
523 if matching_op_path is None:
524 self.dbg('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
525 self.schedule_scan_register(mcc_mnc)
526 return
527 dbus_op = systembus_get(matching_op_path)
528 self.log('Registering with operator', matching_op_path, mcc_mnc)
Pau Espin Pedrol9f59b822017-11-07 17:50:52 +0100529 try:
530 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', dbus_op.Register)
531 except GLib.Error as e:
532 if Gio.DBusError.is_remote_error(e) and Gio.DBusError.get_remote_error(e) == 'org.ofono.Error.NotSupported':
533 self.log('modem does not support manual registering, attempting automatic registering')
534 self.scan_cb_register_automatic(scanned_operators, mcc_mnc)
535 return
536 raise e
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200537
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200538 def cancel_pending_dbus_methods(self):
539 self.cancellable.cancel()
540 # Cancel op is applied as a signal coming from glib mainloop, so we
541 # need to run it and wait for the callbacks to handle cancellations.
Pau Espin Pedrolbf176e42018-03-26 19:13:32 +0200542 event_loop.poll()
Pau Espin Pedrole685c622017-10-04 18:30:22 +0200543 # once it has been triggered, create a new one for next operation:
544 self.cancellable = Gio.Cancellable.new()
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200545
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100546 def power_off(self):
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100547 if self.dbus.has_interface(I_CONNMGR) and self.is_attached():
548 self.detach()
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100549 self.set_online(False)
550 self.set_powered(False)
551 req_ifaces = self._required_ifaces()
552 for iface in req_ifaces:
553 event_loop.wait(self, lambda: not self.dbus.has_interface(iface), timeout=10)
554
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200555 def power_cycle(self):
556 'Power the modem and put it online, power cycle it if it was already on'
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100557 req_ifaces = self._required_ifaces()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200558 if self.is_powered():
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200559 self.dbg('Power cycling')
Pau Espin Pedrolf8d12192018-03-14 19:19:28 +0100560 event_loop.sleep(self, 1.0) # workaround for ofono bug OS#3064
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100561 self.power_off()
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200562 else:
563 self.dbg('Powering on')
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200564 self.set_powered()
Pau Espin Pedrolb9955762017-05-02 09:39:27 +0200565 self.set_online()
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100566 event_loop.wait(self, self.dbus.has_interface, *req_ifaces, timeout=10)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200567
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200568 def connect(self, mcc_mnc=None):
569 'Connect to MCC+MNC'
570 if (mcc_mnc is not None) and (len(mcc_mnc) != 2 or None in mcc_mnc):
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200571 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 +0200572 # if test called connect() before and async scanning has not finished, we need to get rid of it:
573 self.cancel_pending_dbus_methods()
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200574 self.power_cycle()
575 self.register_attempts = 0
576 if self.is_connected(mcc_mnc):
577 self.log('Already registered with', mcc_mnc if mcc_mnc else 'default network')
578 else:
579 self.log('Connect to', mcc_mnc if mcc_mnc else 'default network')
580 self.schedule_scan_register(mcc_mnc)
581
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100582 def is_attached(self):
583 connmgr = self.dbus.interface(I_CONNMGR)
584 prop = connmgr.GetProperties()
585 attached = prop.get('Attached')
586 self.dbg('attached:', attached)
587 return attached
588
589 def attach(self, allow_roaming=False):
590 self.dbg('attach')
591 if self.is_attached():
592 self.detach()
593 connmgr = self.dbus.interface(I_CONNMGR)
594 prop = connmgr.SetProperty('RoamingAllowed', Variant('b', allow_roaming))
595 prop = connmgr.SetProperty('Powered', Variant('b', True))
596
597 def detach(self):
598 self.dbg('detach')
599 connmgr = self.dbus.interface(I_CONNMGR)
600 prop = connmgr.SetProperty('RoamingAllowed', Variant('b', False))
601 prop = connmgr.SetProperty('Powered', Variant('b', False))
602 connmgr.DeactivateAll()
603 connmgr.ResetContexts() # Requires Powered=false
604
605 def activate_context(self, apn='internet', user='ogt', pwd='', protocol='ip'):
Pau Espin Pedrolb05e36a2017-12-15 12:39:36 +0100606 self.dbg('activate_context', apn=apn, user=user, protocol=protocol)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100607
608 connmgr = self.dbus.interface(I_CONNMGR)
609 ctx_path = connmgr.AddContext('internet')
610
611 ctx = systembus_get(ctx_path)
612 ctx.SetProperty('AccessPointName', Variant('s', apn))
613 ctx.SetProperty('Username', Variant('s', user))
614 ctx.SetProperty('Password', Variant('s', pwd))
615 ctx.SetProperty('Protocol', Variant('s', protocol))
616
617 # Activate can only be called after we are attached
618 ctx.SetProperty('Active', Variant('b', True))
619 event_loop.wait(self, lambda: ctx.GetProperties()['Active'] == True)
620 self.log('context activated', path=ctx_path, apn=apn, user=user, properties=ctx.GetProperties())
621 return ctx_path
622
623 def deactivate_context(self, ctx_id):
Pau Espin Pedrol263dd3b2018-02-13 16:53:51 +0100624 self.dbg('deactivate_context', path=ctx_id)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100625 ctx = systembus_get(ctx_id)
626 ctx.SetProperty('Active', Variant('b', False))
627 event_loop.wait(self, lambda: ctx.GetProperties()['Active'] == False)
Pau Espin Pedrolcdac2972018-02-16 15:14:32 +0100628 self.dbg('deactivate_context active=false, removing', path=ctx_id)
629 connmgr = self.dbus.interface(I_CONNMGR)
630 connmgr.RemoveContext(ctx_id)
Pau Espin Pedrolb05aa3c2018-02-16 15:03:50 +0100631 self.log('context deactivated', path=ctx_id)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100632
Neels Hofmeyr8c7477f2017-05-25 04:33:53 +0200633 def sms_send(self, to_msisdn_or_modem, *tokens):
634 if isinstance(to_msisdn_or_modem, Modem):
635 to_msisdn = to_msisdn_or_modem.msisdn
636 tokens = list(tokens)
637 tokens.append('to ' + to_msisdn_or_modem.name())
638 else:
639 to_msisdn = str(to_msisdn_or_modem)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200640 msg = sms.Sms(self.msisdn, to_msisdn, 'from ' + self.name(), *tokens)
641 self.log('sending sms to MSISDN', to_msisdn, sms=msg)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200642 mm = self.dbus.interface(I_SMS)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200643 mm.SendMessage(to_msisdn, str(msg))
644 return msg
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200645
646 def _on_incoming_message(self, message, info):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200647 self.log('Incoming SMS:', repr(message))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200648 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200649 self.sms_received_list.append((message, info))
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200650
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200651 def sms_was_received(self, sms_obj):
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200652 for msg, info in self.sms_received_list:
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200653 if sms_obj.matches(msg):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200654 self.log('SMS received as expected:', repr(msg))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200655 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200656 return True
657 return False
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200658
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200659 def call_id_list(self):
660 self.dbg('call_id_list: %r' % self.call_list)
661 return self.call_list
662
663 def call_dial(self, to_msisdn_or_modem):
664 if isinstance(to_msisdn_or_modem, Modem):
665 to_msisdn = to_msisdn_or_modem.msisdn
666 else:
667 to_msisdn = str(to_msisdn_or_modem)
668 self.dbg('Dialing:', to_msisdn)
669 cmgr = self.dbus.interface(I_CALLMGR)
670 call_obj_path = cmgr.Dial(to_msisdn, 'default')
671 if call_obj_path not in self.call_list:
672 self.dbg('Adding %s to call list' % call_obj_path)
673 self.call_list.append(call_obj_path)
674 else:
675 self.dbg('Dial returned already existing call')
676 return call_obj_path
677
678 def _find_call_msisdn_state(self, msisdn, state):
679 cmgr = self.dbus.interface(I_CALLMGR)
680 ret = cmgr.GetCalls()
681 for obj_path, props in ret:
682 if props['LineIdentification'] == msisdn and props['State'] == state:
683 return obj_path
684 return None
685
686 def call_wait_incoming(self, caller_msisdn_or_modem, timeout=60):
687 if isinstance(caller_msisdn_or_modem, Modem):
688 caller_msisdn = caller_msisdn_or_modem.msisdn
689 else:
690 caller_msisdn = str(caller_msisdn_or_modem)
691 self.dbg('Waiting for incoming call from:', caller_msisdn)
692 event_loop.wait(self, lambda: self._find_call_msisdn_state(caller_msisdn, 'incoming') is not None, timeout=timeout)
693 return self._find_call_msisdn_state(caller_msisdn, 'incoming')
694
695 def call_answer(self, call_id):
696 self.dbg('Answer call %s' % call_id)
697 assert self.call_state(call_id) == 'incoming'
698 call_dbus_obj = systembus_get(call_id)
699 call_dbus_obj.Answer()
700
701 def call_hangup(self, call_id):
702 self.dbg('Hang up call %s' % call_id)
703 call_dbus_obj = systembus_get(call_id)
704 call_dbus_obj.Hangup()
705
706 def call_is_active(self, call_id):
707 return self.call_state(call_id) == 'active'
708
709 def call_state(self, call_id):
710 call_dbus_obj = systembus_get(call_id)
711 props = call_dbus_obj.GetProperties()
712 state = props.get('State')
713 self.dbg('call state: %s' % state)
714 return state
715
716 def _on_callmgr_call_added(self, obj_path, properties):
717 self.dbg('%r.CallAdded() -> %s=%r' % (I_CALLMGR, obj_path, repr(properties)))
718 if obj_path not in self.call_list:
719 self.call_list.append(obj_path)
720 else:
721 self.dbg('Call already exists %r' % obj_path)
722
723 def _on_callmgr_call_removed(self, obj_path):
724 self.dbg('%r.CallRemoved() -> %s' % (I_CALLMGR, obj_path))
725 if obj_path in self.call_list:
726 self.call_list.remove(obj_path)
727 else:
728 self.dbg('Trying to remove non-existing call %r' % obj_path)
729
730 def _on_callmgr_property_changed(self, name, value):
731 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_CALLMGR, name, value))
732
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100733 def _on_connmgr_property_changed(self, name, value):
734 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_CONNMGR, name, value))
735
Pau Espin Pedrolee6e4912017-09-05 18:46:34 +0200736 def info(self, keys=('Manufacturer', 'Model', 'Revision', 'Serial')):
Neels Hofmeyrb8011692017-05-29 03:45:24 +0200737 props = self.properties()
738 return ', '.join(['%s: %r'%(k,props.get(k)) for k in keys])
739
740 def log_info(self, *args, **kwargs):
741 self.log(self.info(*args, **kwargs))
742
Pau Espin Pedrol03983aa2017-06-12 15:31:27 +0200743 def ussd_send(self, command):
744 ss = self.dbus.interface(I_SS)
745 service_type, response = ss.Initiate(command)
746 return response
747
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200748# vim: expandtab tabstop=4 shiftwidth=4