blob: 96b65d898fcb6410fb9e3d46bfbdc511554fd53b [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
33glib_main_loop = GLib.MainLoop()
34glib_main_ctx = glib_main_loop.get_context()
35bus = SystemBus()
36
Pau Espin Pedrol504a6642017-05-04 11:38:23 +020037I_MODEM = 'org.ofono.Modem'
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +020038I_NETREG = 'org.ofono.NetworkRegistration'
39I_SMS = 'org.ofono.MessageManager'
Pau Espin Pedrolde899612017-11-23 17:18:40 +010040I_CONNMGR = 'org.ofono.ConnectionManager'
Pau Espin Pedrold71edd12017-10-06 13:53:54 +020041I_CALLMGR = 'org.ofono.VoiceCallManager'
42I_CALL = 'org.ofono.VoiceCall'
Pau Espin Pedrol03983aa2017-06-12 15:31:27 +020043I_SS = 'org.ofono.SupplementaryServices'
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +020044
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020045# See https://github.com/intgr/ofono/blob/master/doc/network-api.txt#L78
46NETREG_ST_REGISTERED = 'registered'
47NETREG_ST_ROAMING = 'roaming'
48
49NETREG_MAX_REGISTER_ATTEMPTS = 3
50
Neels Hofmeyr035cda82017-05-05 17:52:45 +020051class DeferredHandling:
52 defer_queue = []
53
54 def __init__(self, dbus_iface, handler):
55 self.handler = handler
Neels Hofmeyr47de6b02017-05-10 13:24:05 +020056 self.subscription_id = dbus_iface.connect(self.receive_signal)
Neels Hofmeyr035cda82017-05-05 17:52:45 +020057
58 def receive_signal(self, *args, **kwargs):
59 DeferredHandling.defer_queue.append((self.handler, args, kwargs))
60
61 @staticmethod
62 def handle_queue():
63 while DeferredHandling.defer_queue:
64 handler, args, kwargs = DeferredHandling.defer_queue.pop(0)
65 handler(*args, **kwargs)
66
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020067def defer(handler, *args, **kwargs):
68 DeferredHandling.defer_queue.append((handler, args, kwargs))
69
Neels Hofmeyr035cda82017-05-05 17:52:45 +020070def dbus_connect(dbus_iface, handler):
71 '''This function shall be used instead of directly connecting DBus signals.
72 It ensures that we don't nest a glib main loop within another, and also
73 that we receive exceptions raised within the signal handlers. This makes it
74 so that a signal handler is invoked only after the DBus polling is through
75 by enlisting signals that should be handled in the
76 DeferredHandling.defer_queue.'''
Neels Hofmeyr47de6b02017-05-10 13:24:05 +020077 return DeferredHandling(dbus_iface, handler).subscription_id
Neels Hofmeyr035cda82017-05-05 17:52:45 +020078
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020079def poll_glib():
Neels Hofmeyr3531a192017-03-28 14:30:28 +020080 global glib_main_ctx
81 while glib_main_ctx.pending():
82 glib_main_ctx.iteration()
Neels Hofmeyr035cda82017-05-05 17:52:45 +020083 DeferredHandling.handle_queue()
Neels Hofmeyr3531a192017-03-28 14:30:28 +020084
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020085event_loop.register_poll_func(poll_glib)
86
Neels Hofmeyr93f58662017-05-03 16:32:16 +020087def systembus_get(path):
Neels Hofmeyr3531a192017-03-28 14:30:28 +020088 global bus
89 return bus.get('org.ofono', path)
90
91def list_modems():
Neels Hofmeyr93f58662017-05-03 16:32:16 +020092 root = systembus_get('/')
Neels Hofmeyr3531a192017-03-28 14:30:28 +020093 return sorted(root.GetModems())
94
Pau Espin Pedrole25cf042018-02-23 17:00:09 +010095def get_dbuspath_from_syspath(syspath):
96 modems = list_modems()
97 for dbuspath, props in modems:
98 if props.get('SystemPath', '') == syspath:
99 return dbuspath
100 raise ValueError('could not find %s in modem list: %s' % (syspath, modems))
101
102
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200103def _async_result_handler(obj, result, user_data):
104 '''Generic callback dispatcher called from glib loop when an async method
105 call has returned. This callback is set up by method dbus_async_call.'''
106 (result_callback, error_callback, real_user_data) = user_data
107 try:
108 ret = obj.call_finish(result)
109 except Exception as e:
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200110 if isinstance(e, GLib.Error) and e.code == Gio.IOErrorEnum.CANCELLED:
111 log.dbg('DBus method cancelled')
112 return
113
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200114 if error_callback:
115 error_callback(obj, e, real_user_data)
116 else:
117 result_callback(obj, e, real_user_data)
118 return
119
120 ret = ret.unpack()
121 # to be compatible with standard Python behaviour, unbox
122 # single-element tuples and return None for empty result tuples
123 if len(ret) == 1:
124 ret = ret[0]
125 elif len(ret) == 0:
126 ret = None
127 result_callback(obj, ret, real_user_data)
128
129def dbus_async_call(instance, proxymethod, *proxymethod_args,
130 result_handler=None, error_handler=None,
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200131 user_data=None, timeout=30, cancellable=None,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200132 **proxymethod_kwargs):
133 '''pydbus doesn't support asynchronous methods. This method adds support for
134 it until pydbus implements it'''
135
136 argdiff = len(proxymethod_args) - len(proxymethod._inargs)
137 if argdiff < 0:
138 raise TypeError(proxymethod.__qualname__ + " missing {} required positional argument(s)".format(-argdiff))
139 elif argdiff > 0:
140 raise TypeError(proxymethod.__qualname__ + " takes {} positional argument(s) but {} was/were given".format(len(proxymethod._inargs), len(proxymethod_args)))
141
142 timeout = timeout * 1000
143 user_data = (result_handler, error_handler, user_data)
144
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200145 # See https://lazka.github.io/pgi-docs/Gio-2.0/classes/DBusProxy.html#Gio.DBusProxy.call
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200146 ret = instance._bus.con.call(
147 instance._bus_name, instance._path,
148 proxymethod._iface_name, proxymethod.__name__,
149 GLib.Variant(proxymethod._sinargs, proxymethod_args),
150 GLib.VariantType.new(proxymethod._soutargs),
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200151 0, timeout, cancellable,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200152 _async_result_handler, user_data)
153
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200154def dbus_call_dismiss_error(log_obj, err_str, method):
155 try:
156 method()
Pau Espin Pedrol9b670212017-11-07 17:50:20 +0100157 except GLib.Error as e:
158 if Gio.DBusError.is_remote_error(e) and Gio.DBusError.get_remote_error(e) == err_str:
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200159 log_obj.log('Dismissed Dbus method error: %r' % e)
160 return
Pau Espin Pedrol9b670212017-11-07 17:50:20 +0100161 raise e
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200162
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200163class ModemDbusInteraction(log.Origin):
164 '''Work around inconveniences specific to pydbus and ofono.
165 ofono adds and removes DBus interfaces and notifies about them.
166 Upon changes we need a fresh pydbus object to benefit from that.
167 Watching the interfaces change is optional; be sure to call
168 watch_interfaces() if you'd like to have signals subscribed.
169 Related: https://github.com/LEW21/pydbus/issues/56
170 '''
171
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200172 modem_path = None
173 watch_props_subscription = None
174 _dbus_obj = None
175 interfaces = None
176
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200177 def __init__(self, modem_path):
178 self.modem_path = modem_path
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200179 super().__init__(log.C_BUS, self.modem_path)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200180 self.interfaces = set()
181
182 # A dict listing signal handlers to connect, e.g.
183 # { I_SMS: ( ('IncomingMessage', self._on_incoming_message), ), }
184 self.required_signals = {}
185
186 # A dict collecting subscription tokens for connected signal handlers.
187 # { I_SMS: ( token1, token2, ... ), }
188 self.connected_signals = util.listdict()
189
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200190 def cleanup(self):
Pau Espin Pedrol58ff38d2017-06-23 13:10:38 +0200191 self.set_powered(False)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200192 self.unwatch_interfaces()
193 for interface_name in list(self.connected_signals.keys()):
194 self.remove_signals(interface_name)
195
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200196 def __del__(self):
197 self.cleanup()
198
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200199 def get_new_dbus_obj(self):
200 return systembus_get(self.modem_path)
201
202 def dbus_obj(self):
203 if self._dbus_obj is None:
204 self._dbus_obj = self.get_new_dbus_obj()
205 return self._dbus_obj
206
207 def interface(self, interface_name):
208 try:
209 return self.dbus_obj()[interface_name]
210 except KeyError:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200211 raise log.Error('Modem interface is not available:', interface_name)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200212
213 def signal(self, interface_name, signal):
214 return getattr(self.interface(interface_name), signal)
215
216 def watch_interfaces(self):
217 self.unwatch_interfaces()
218 # Note: we are watching the properties on a get_new_dbus_obj() that is
219 # separate from the one used to interact with interfaces. We need to
220 # refresh the pydbus object to interact with Interfaces that have newly
221 # appeared, but exchanging the DBus object to watch Interfaces being
222 # enabled and disabled is racy: we may skip some removals and
223 # additions. Hence do not exchange this DBus object. We don't even
224 # need to store the dbus object used for this, we will not touch it
225 # again. We only store the signal subscription.
226 self.watch_props_subscription = dbus_connect(self.get_new_dbus_obj().PropertyChanged,
227 self.on_property_change)
228 self.on_interfaces_change(self.properties().get('Interfaces'))
229
230 def unwatch_interfaces(self):
231 if self.watch_props_subscription is None:
232 return
233 self.watch_props_subscription.disconnect()
234 self.watch_props_subscription = None
235
236 def on_property_change(self, name, value):
237 if name == 'Interfaces':
238 self.on_interfaces_change(value)
Pau Espin Pedrol77631212017-09-05 19:04:06 +0200239 else:
240 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_MODEM, name, value))
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200241
242 def on_interfaces_change(self, interfaces_now):
243 # First some logging.
244 now = set(interfaces_now)
245 additions = now - self.interfaces
246 removals = self.interfaces - now
247 self.interfaces = now
248 if not (additions or removals):
249 # nothing changed.
250 return
251
252 if additions:
253 self.dbg('interface enabled:', ', '.join(sorted(additions)))
254
255 if removals:
256 self.dbg('interface disabled:', ', '.join(sorted(removals)))
257
258 # The dbus object is now stale and needs refreshing before we
259 # access the next interface function.
260 self._dbus_obj = None
261
262 # If an interface disappeared, disconnect the signal handlers for it.
263 # Even though we're going to use a fresh dbus object for new
264 # subscriptions, we will still keep active subscriptions alive on the
265 # old dbus object which will linger, associated with the respective
266 # signal subscription.
267 for removed in removals:
268 self.remove_signals(removed)
269
270 # Connect signals for added interfaces.
271 for interface_name in additions:
272 self.connect_signals(interface_name)
273
274 def remove_signals(self, interface_name):
275 got = self.connected_signals.pop(interface_name, [])
276
277 if not got:
278 return
279
280 self.dbg('Disconnecting', len(got), 'signals for', interface_name)
281 for subscription in got:
282 subscription.disconnect()
283
284 def connect_signals(self, interface_name):
285 # If an interface was added, it must not have existed before. For
286 # paranoia, make sure we have no handlers for those.
287 self.remove_signals(interface_name)
288
289 want = self.required_signals.get(interface_name, [])
290 if not want:
291 return
292
293 self.dbg('Connecting', len(want), 'signals for', interface_name)
294 for signal, cb in self.required_signals.get(interface_name, []):
295 subscription = dbus_connect(self.signal(interface_name, signal), cb)
296 self.connected_signals.add(interface_name, subscription)
297
298 def has_interface(self, *interface_names):
299 try:
300 for interface_name in interface_names:
301 self.dbus_obj()[interface_name]
302 result = True
303 except KeyError:
304 result = False
305 self.dbg('has_interface(%s) ==' % (', '.join(interface_names)), result)
306 return result
307
308 def properties(self, iface=I_MODEM):
309 return self.dbus_obj()[iface].GetProperties()
310
311 def property_is(self, name, val, iface=I_MODEM):
312 is_val = self.properties(iface).get(name)
313 self.dbg(name, '==', is_val)
314 return is_val is not None and is_val == val
315
316 def set_bool(self, name, bool_val, iface=I_MODEM):
317 # to make sure any pending signals are received before we send out more DBus requests
318 event_loop.poll()
319
320 val = bool(bool_val)
321 self.log('Setting', name, val)
322 self.interface(iface).SetProperty(name, Variant('b', val))
323
324 event_loop.wait(self, self.property_is, name, bool_val)
325
326 def set_powered(self, powered=True):
327 self.set_bool('Powered', powered)
328
329 def set_online(self, online=True):
330 self.set_bool('Online', online)
331
332 def is_powered(self):
333 return self.property_is('Powered', True)
334
335 def is_online(self):
336 return self.property_is('Online', True)
337
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200338
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200339
340class Modem(log.Origin):
341 'convenience for ofono Modem interaction'
342 msisdn = None
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200343 sms_received_list = None
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200344 _ki = None
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200345
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100346 CTX_PROT_IPv4 = 'ip'
347 CTX_PROT_IPv6 = 'ipv6'
348 CTX_PROT_IPv46 = 'dual'
349
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200350 def __init__(self, conf):
351 self.conf = conf
Pau Espin Pedrole25cf042018-02-23 17:00:09 +0100352 self.syspath = conf.get('path')
353 self.dbuspath = get_dbuspath_from_syspath(self.syspath)
354 super().__init__(log.C_TST, self.dbuspath)
355 self.dbg('creating from syspath %s', self.syspath)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200356 self.sms_received_list = []
Pau Espin Pedrole25cf042018-02-23 17:00:09 +0100357 self.dbus = ModemDbusInteraction(self.dbuspath)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200358 self.register_attempts = 0
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200359 self.call_list = []
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200360 # one Cancellable can handle several concurrent methods.
361 self.cancellable = Gio.Cancellable.new()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200362 self.dbus.required_signals = {
363 I_SMS: ( ('IncomingMessage', self._on_incoming_message), ),
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200364 I_NETREG: ( ('PropertyChanged', self._on_netreg_property_changed), ),
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100365 I_CONNMGR: ( ('PropertyChanged', self._on_connmgr_property_changed), ),
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200366 I_CALLMGR: ( ('PropertyChanged', self._on_callmgr_property_changed),
367 ('CallAdded', self._on_callmgr_call_added),
368 ('CallRemoved', self._on_callmgr_call_removed), ),
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200369 }
370 self.dbus.watch_interfaces()
371
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200372 def cleanup(self):
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200373 self.dbg('cleanup')
374 if self.cancellable:
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200375 self.cancel_pending_dbus_methods()
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200376 self.cancellable = None
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100377 if self.is_powered():
378 self.power_off()
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200379 self.dbus.cleanup()
380 self.dbus = None
381
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200382 def properties(self, *args, **kwargs):
383 '''Return a dict of properties on this modem. For the actual arguments,
384 see ModemDbusInteraction.properties(), which this function calls. The
385 returned dict is defined by ofono. An example is:
386 {'Lockdown': False,
387 'Powered': True,
388 'Model': 'MC7304',
389 'Revision': 'SWI9X15C_05.05.66.00 r29972 CARMD-EV-FRMWR1 2015/10/08 08:36:28',
390 'Manufacturer': 'Sierra Wireless, Incorporated',
391 'Emergency': False,
392 'Interfaces': ['org.ofono.SmartMessaging',
393 'org.ofono.PushNotification',
394 'org.ofono.MessageManager',
395 'org.ofono.NetworkRegistration',
396 'org.ofono.ConnectionManager',
397 'org.ofono.SupplementaryServices',
398 'org.ofono.RadioSettings',
399 'org.ofono.AllowedAccessPoints',
400 'org.ofono.SimManager',
401 'org.ofono.LocationReporting',
402 'org.ofono.VoiceCallManager'],
403 'Serial': '356853054230919',
404 'Features': ['sms', 'net', 'gprs', 'ussd', 'rat', 'sim', 'gps'],
405 'Type': 'hardware',
406 'Online': True}
407 '''
408 return self.dbus.properties(*args, **kwargs)
409
410 def set_powered(self, powered=True):
411 return self.dbus.set_powered(powered=powered)
412
413 def set_online(self, online=True):
414 return self.dbus.set_online(online=online)
415
416 def is_powered(self):
417 return self.dbus.is_powered()
418
419 def is_online(self):
420 return self.dbus.is_online()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200421
422 def set_msisdn(self, msisdn):
423 self.msisdn = msisdn
424
425 def imsi(self):
Neels Hofmeyrb02c2112017-04-09 18:46:48 +0200426 imsi = self.conf.get('imsi')
427 if not imsi:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200428 raise log.Error('No IMSI')
Neels Hofmeyrb02c2112017-04-09 18:46:48 +0200429 return imsi
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200430
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200431 def set_ki(self, ki):
432 self._ki = ki
433
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200434 def ki(self):
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200435 if self._ki is not None:
436 return self._ki
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200437 return self.conf.get('ki')
438
Pau Espin Pedrol713ce2c2017-08-24 16:57:17 +0200439 def auth_algo(self):
440 return self.conf.get('auth_algo', None)
441
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100442 def features(self):
443 return self.conf.get('features', [])
444
445 def _required_ifaces(self):
446 req_ifaces = (I_NETREG,)
447 req_ifaces += (I_SMS,) if 'sms' in self.features() else ()
448 req_ifaces += (I_SS,) if 'ussd' in self.features() else ()
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100449 req_ifaces += (I_CONNMGR,) if 'gprs' in self.features() else ()
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100450 return req_ifaces
451
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200452 def _on_netreg_property_changed(self, name, value):
453 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_NETREG, name, value))
454
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200455 def is_connected(self, mcc_mnc=None):
456 netreg = self.dbus.interface(I_NETREG)
457 prop = netreg.GetProperties()
458 status = prop.get('Status')
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200459 self.dbg('status:', status)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200460 if not (status == NETREG_ST_REGISTERED or status == NETREG_ST_ROAMING):
461 return False
462 if mcc_mnc is None: # Any network is fine and we are registered.
463 return True
464 mcc = prop.get('MobileCountryCode')
465 mnc = prop.get('MobileNetworkCode')
466 if (mcc, mnc) == mcc_mnc:
467 return True
468 return False
469
470 def schedule_scan_register(self, mcc_mnc):
471 if self.register_attempts > NETREG_MAX_REGISTER_ATTEMPTS:
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200472 raise log.Error('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200473 self.register_attempts += 1
474 netreg = self.dbus.interface(I_NETREG)
475 self.dbg('Scanning for operators...')
476 # Scan method can take several seconds, and we don't want to block
477 # waiting for that. Make it async and try to register when the scan is
478 # finished.
479 register_func = self.scan_cb_register_automatic if mcc_mnc is None else self.scan_cb_register
480 result_handler = lambda obj, result, user_data: defer(register_func, result, user_data)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200481 error_handler = lambda obj, e, user_data: defer(self.scan_cb_error_handler, e, mcc_mnc)
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200482 dbus_async_call(netreg, netreg.Scan, timeout=30, cancellable=self.cancellable,
483 result_handler=result_handler, error_handler=error_handler,
484 user_data=mcc_mnc)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200485
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200486 def scan_cb_error_handler(self, e, mcc_mnc):
487 # It was detected that Scan() method can fail for some modems on some
488 # specific circumstances. For instance it fails with org.ofono.Error.Failed
489 # if the modem starts to register internally after we started Scan() and
490 # the registering succeeds while we are still waiting for Scan() to finsih.
491 # So far the easiest seems to check if we are now registered and
492 # otherwise schedule a scan again.
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200493 self.err('Scan() failed, retrying if needed:', e)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200494 if not self.is_connected(mcc_mnc):
495 self.schedule_scan_register(mcc_mnc)
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200496 else:
497 self.log('Already registered with network', mcc_mnc)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200498
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200499 def scan_cb_register_automatic(self, scanned_operators, mcc_mnc):
500 self.dbg('scanned operators: ', scanned_operators);
501 for op_path, op_prop in scanned_operators:
502 if op_prop.get('Status') == 'current':
503 mcc = op_prop.get('MobileCountryCode')
504 mnc = op_prop.get('MobileNetworkCode')
505 self.log('Already registered with network', (mcc, mnc))
506 return
507 self.log('Registering with the default network')
508 netreg = self.dbus.interface(I_NETREG)
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200509 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', netreg.Register)
510
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200511
512 def scan_cb_register(self, scanned_operators, mcc_mnc):
513 self.dbg('scanned operators: ', scanned_operators);
514 matching_op_path = None
515 for op_path, op_prop in scanned_operators:
516 mcc = op_prop.get('MobileCountryCode')
517 mnc = op_prop.get('MobileNetworkCode')
518 if (mcc, mnc) == mcc_mnc:
519 if op_prop.get('Status') == 'current':
520 self.log('Already registered with network', mcc_mnc)
521 # We discovered the network and we are already registered
522 # with it. Avoid calling op.Register() in this case (it
523 # won't act as a NO-OP, it actually returns an error).
524 return
525 matching_op_path = op_path
526 break
527 if matching_op_path is None:
528 self.dbg('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
529 self.schedule_scan_register(mcc_mnc)
530 return
531 dbus_op = systembus_get(matching_op_path)
532 self.log('Registering with operator', matching_op_path, mcc_mnc)
Pau Espin Pedrol9f59b822017-11-07 17:50:52 +0100533 try:
534 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', dbus_op.Register)
535 except GLib.Error as e:
536 if Gio.DBusError.is_remote_error(e) and Gio.DBusError.get_remote_error(e) == 'org.ofono.Error.NotSupported':
537 self.log('modem does not support manual registering, attempting automatic registering')
538 self.scan_cb_register_automatic(scanned_operators, mcc_mnc)
539 return
540 raise e
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200541
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200542 def cancel_pending_dbus_methods(self):
543 self.cancellable.cancel()
544 # Cancel op is applied as a signal coming from glib mainloop, so we
545 # need to run it and wait for the callbacks to handle cancellations.
546 poll_glib()
Pau Espin Pedrole685c622017-10-04 18:30:22 +0200547 # once it has been triggered, create a new one for next operation:
548 self.cancellable = Gio.Cancellable.new()
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200549
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100550 def power_off(self):
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100551 if self.dbus.has_interface(I_CONNMGR) and self.is_attached():
552 self.detach()
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100553 self.set_online(False)
554 self.set_powered(False)
555 req_ifaces = self._required_ifaces()
556 for iface in req_ifaces:
557 event_loop.wait(self, lambda: not self.dbus.has_interface(iface), timeout=10)
558
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200559 def power_cycle(self):
560 'Power the modem and put it online, power cycle it if it was already on'
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100561 req_ifaces = self._required_ifaces()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200562 if self.is_powered():
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200563 self.dbg('Power cycling')
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 Pedrole0f49862017-11-23 11:37:34 +0100569 event_loop.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))
622 event_loop.wait(self, lambda: ctx.GetProperties()['Active'] == True)
623 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))
630 event_loop.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
Neels Hofmeyr8c7477f2017-05-25 04:33:53 +0200636 def sms_send(self, to_msisdn_or_modem, *tokens):
637 if isinstance(to_msisdn_or_modem, Modem):
638 to_msisdn = to_msisdn_or_modem.msisdn
639 tokens = list(tokens)
640 tokens.append('to ' + to_msisdn_or_modem.name())
641 else:
642 to_msisdn = str(to_msisdn_or_modem)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200643 msg = sms.Sms(self.msisdn, to_msisdn, 'from ' + self.name(), *tokens)
644 self.log('sending sms to MSISDN', to_msisdn, sms=msg)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200645 mm = self.dbus.interface(I_SMS)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200646 mm.SendMessage(to_msisdn, str(msg))
647 return msg
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200648
649 def _on_incoming_message(self, message, info):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200650 self.log('Incoming SMS:', repr(message))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200651 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200652 self.sms_received_list.append((message, info))
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200653
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200654 def sms_was_received(self, sms_obj):
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200655 for msg, info in self.sms_received_list:
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200656 if sms_obj.matches(msg):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200657 self.log('SMS received as expected:', repr(msg))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200658 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200659 return True
660 return False
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200661
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200662 def call_id_list(self):
663 self.dbg('call_id_list: %r' % self.call_list)
664 return self.call_list
665
666 def call_dial(self, to_msisdn_or_modem):
667 if isinstance(to_msisdn_or_modem, Modem):
668 to_msisdn = to_msisdn_or_modem.msisdn
669 else:
670 to_msisdn = str(to_msisdn_or_modem)
671 self.dbg('Dialing:', to_msisdn)
672 cmgr = self.dbus.interface(I_CALLMGR)
673 call_obj_path = cmgr.Dial(to_msisdn, 'default')
674 if call_obj_path not in self.call_list:
675 self.dbg('Adding %s to call list' % call_obj_path)
676 self.call_list.append(call_obj_path)
677 else:
678 self.dbg('Dial returned already existing call')
679 return call_obj_path
680
681 def _find_call_msisdn_state(self, msisdn, state):
682 cmgr = self.dbus.interface(I_CALLMGR)
683 ret = cmgr.GetCalls()
684 for obj_path, props in ret:
685 if props['LineIdentification'] == msisdn and props['State'] == state:
686 return obj_path
687 return None
688
689 def call_wait_incoming(self, caller_msisdn_or_modem, timeout=60):
690 if isinstance(caller_msisdn_or_modem, Modem):
691 caller_msisdn = caller_msisdn_or_modem.msisdn
692 else:
693 caller_msisdn = str(caller_msisdn_or_modem)
694 self.dbg('Waiting for incoming call from:', caller_msisdn)
695 event_loop.wait(self, lambda: self._find_call_msisdn_state(caller_msisdn, 'incoming') is not None, timeout=timeout)
696 return self._find_call_msisdn_state(caller_msisdn, 'incoming')
697
698 def call_answer(self, call_id):
699 self.dbg('Answer call %s' % call_id)
700 assert self.call_state(call_id) == 'incoming'
701 call_dbus_obj = systembus_get(call_id)
702 call_dbus_obj.Answer()
703
704 def call_hangup(self, call_id):
705 self.dbg('Hang up call %s' % call_id)
706 call_dbus_obj = systembus_get(call_id)
707 call_dbus_obj.Hangup()
708
709 def call_is_active(self, call_id):
710 return self.call_state(call_id) == 'active'
711
712 def call_state(self, call_id):
713 call_dbus_obj = systembus_get(call_id)
714 props = call_dbus_obj.GetProperties()
715 state = props.get('State')
716 self.dbg('call state: %s' % state)
717 return state
718
719 def _on_callmgr_call_added(self, obj_path, properties):
720 self.dbg('%r.CallAdded() -> %s=%r' % (I_CALLMGR, obj_path, repr(properties)))
721 if obj_path not in self.call_list:
722 self.call_list.append(obj_path)
723 else:
724 self.dbg('Call already exists %r' % obj_path)
725
726 def _on_callmgr_call_removed(self, obj_path):
727 self.dbg('%r.CallRemoved() -> %s' % (I_CALLMGR, obj_path))
728 if obj_path in self.call_list:
729 self.call_list.remove(obj_path)
730 else:
731 self.dbg('Trying to remove non-existing call %r' % obj_path)
732
733 def _on_callmgr_property_changed(self, name, value):
734 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_CALLMGR, name, value))
735
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100736 def _on_connmgr_property_changed(self, name, value):
737 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_CONNMGR, name, value))
738
Pau Espin Pedrolee6e4912017-09-05 18:46:34 +0200739 def info(self, keys=('Manufacturer', 'Model', 'Revision', 'Serial')):
Neels Hofmeyrb8011692017-05-29 03:45:24 +0200740 props = self.properties()
741 return ', '.join(['%s: %r'%(k,props.get(k)) for k in keys])
742
743 def log_info(self, *args, **kwargs):
744 self.log(self.info(*args, **kwargs))
745
Pau Espin Pedrol03983aa2017-06-12 15:31:27 +0200746 def ussd_send(self, command):
747 ss = self.dbus.interface(I_SS)
748 service_type, response = ss.Initiate(command)
749 return response
750
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200751# vim: expandtab tabstop=4 shiftwidth=4