blob: 775074034d029b159f06fec1a4ed42dca738dd14 [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 Pedrol0e57aad2017-05-29 14:25:22 +020095def _async_result_handler(obj, result, user_data):
96 '''Generic callback dispatcher called from glib loop when an async method
97 call has returned. This callback is set up by method dbus_async_call.'''
98 (result_callback, error_callback, real_user_data) = user_data
99 try:
100 ret = obj.call_finish(result)
101 except Exception as e:
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200102 if isinstance(e, GLib.Error) and e.code == Gio.IOErrorEnum.CANCELLED:
103 log.dbg('DBus method cancelled')
104 return
105
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200106 if error_callback:
107 error_callback(obj, e, real_user_data)
108 else:
109 result_callback(obj, e, real_user_data)
110 return
111
112 ret = ret.unpack()
113 # to be compatible with standard Python behaviour, unbox
114 # single-element tuples and return None for empty result tuples
115 if len(ret) == 1:
116 ret = ret[0]
117 elif len(ret) == 0:
118 ret = None
119 result_callback(obj, ret, real_user_data)
120
121def dbus_async_call(instance, proxymethod, *proxymethod_args,
122 result_handler=None, error_handler=None,
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200123 user_data=None, timeout=30, cancellable=None,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200124 **proxymethod_kwargs):
125 '''pydbus doesn't support asynchronous methods. This method adds support for
126 it until pydbus implements it'''
127
128 argdiff = len(proxymethod_args) - len(proxymethod._inargs)
129 if argdiff < 0:
130 raise TypeError(proxymethod.__qualname__ + " missing {} required positional argument(s)".format(-argdiff))
131 elif argdiff > 0:
132 raise TypeError(proxymethod.__qualname__ + " takes {} positional argument(s) but {} was/were given".format(len(proxymethod._inargs), len(proxymethod_args)))
133
134 timeout = timeout * 1000
135 user_data = (result_handler, error_handler, user_data)
136
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200137 # See https://lazka.github.io/pgi-docs/Gio-2.0/classes/DBusProxy.html#Gio.DBusProxy.call
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200138 ret = instance._bus.con.call(
139 instance._bus_name, instance._path,
140 proxymethod._iface_name, proxymethod.__name__,
141 GLib.Variant(proxymethod._sinargs, proxymethod_args),
142 GLib.VariantType.new(proxymethod._soutargs),
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200143 0, timeout, cancellable,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200144 _async_result_handler, user_data)
145
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200146def dbus_call_dismiss_error(log_obj, err_str, method):
147 try:
148 method()
Pau Espin Pedrol9b670212017-11-07 17:50:20 +0100149 except GLib.Error as e:
150 if Gio.DBusError.is_remote_error(e) and Gio.DBusError.get_remote_error(e) == err_str:
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200151 log_obj.log('Dismissed Dbus method error: %r' % e)
152 return
Pau Espin Pedrol9b670212017-11-07 17:50:20 +0100153 raise e
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200154
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200155class ModemDbusInteraction(log.Origin):
156 '''Work around inconveniences specific to pydbus and ofono.
157 ofono adds and removes DBus interfaces and notifies about them.
158 Upon changes we need a fresh pydbus object to benefit from that.
159 Watching the interfaces change is optional; be sure to call
160 watch_interfaces() if you'd like to have signals subscribed.
161 Related: https://github.com/LEW21/pydbus/issues/56
162 '''
163
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200164 modem_path = None
165 watch_props_subscription = None
166 _dbus_obj = None
167 interfaces = None
168
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200169 def __init__(self, modem_path):
170 self.modem_path = modem_path
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200171 super().__init__(log.C_BUS, self.modem_path)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200172 self.interfaces = set()
173
174 # A dict listing signal handlers to connect, e.g.
175 # { I_SMS: ( ('IncomingMessage', self._on_incoming_message), ), }
176 self.required_signals = {}
177
178 # A dict collecting subscription tokens for connected signal handlers.
179 # { I_SMS: ( token1, token2, ... ), }
180 self.connected_signals = util.listdict()
181
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200182 def cleanup(self):
Pau Espin Pedrol58ff38d2017-06-23 13:10:38 +0200183 self.set_powered(False)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200184 self.unwatch_interfaces()
185 for interface_name in list(self.connected_signals.keys()):
186 self.remove_signals(interface_name)
187
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200188 def __del__(self):
189 self.cleanup()
190
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200191 def get_new_dbus_obj(self):
192 return systembus_get(self.modem_path)
193
194 def dbus_obj(self):
195 if self._dbus_obj is None:
196 self._dbus_obj = self.get_new_dbus_obj()
197 return self._dbus_obj
198
199 def interface(self, interface_name):
200 try:
201 return self.dbus_obj()[interface_name]
202 except KeyError:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200203 raise log.Error('Modem interface is not available:', interface_name)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200204
205 def signal(self, interface_name, signal):
206 return getattr(self.interface(interface_name), signal)
207
208 def watch_interfaces(self):
209 self.unwatch_interfaces()
210 # Note: we are watching the properties on a get_new_dbus_obj() that is
211 # separate from the one used to interact with interfaces. We need to
212 # refresh the pydbus object to interact with Interfaces that have newly
213 # appeared, but exchanging the DBus object to watch Interfaces being
214 # enabled and disabled is racy: we may skip some removals and
215 # additions. Hence do not exchange this DBus object. We don't even
216 # need to store the dbus object used for this, we will not touch it
217 # again. We only store the signal subscription.
218 self.watch_props_subscription = dbus_connect(self.get_new_dbus_obj().PropertyChanged,
219 self.on_property_change)
220 self.on_interfaces_change(self.properties().get('Interfaces'))
221
222 def unwatch_interfaces(self):
223 if self.watch_props_subscription is None:
224 return
225 self.watch_props_subscription.disconnect()
226 self.watch_props_subscription = None
227
228 def on_property_change(self, name, value):
229 if name == 'Interfaces':
230 self.on_interfaces_change(value)
Pau Espin Pedrol77631212017-09-05 19:04:06 +0200231 else:
232 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_MODEM, name, value))
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200233
234 def on_interfaces_change(self, interfaces_now):
235 # First some logging.
236 now = set(interfaces_now)
237 additions = now - self.interfaces
238 removals = self.interfaces - now
239 self.interfaces = now
240 if not (additions or removals):
241 # nothing changed.
242 return
243
244 if additions:
245 self.dbg('interface enabled:', ', '.join(sorted(additions)))
246
247 if removals:
248 self.dbg('interface disabled:', ', '.join(sorted(removals)))
249
250 # The dbus object is now stale and needs refreshing before we
251 # access the next interface function.
252 self._dbus_obj = None
253
254 # If an interface disappeared, disconnect the signal handlers for it.
255 # Even though we're going to use a fresh dbus object for new
256 # subscriptions, we will still keep active subscriptions alive on the
257 # old dbus object which will linger, associated with the respective
258 # signal subscription.
259 for removed in removals:
260 self.remove_signals(removed)
261
262 # Connect signals for added interfaces.
263 for interface_name in additions:
264 self.connect_signals(interface_name)
265
266 def remove_signals(self, interface_name):
267 got = self.connected_signals.pop(interface_name, [])
268
269 if not got:
270 return
271
272 self.dbg('Disconnecting', len(got), 'signals for', interface_name)
273 for subscription in got:
274 subscription.disconnect()
275
276 def connect_signals(self, interface_name):
277 # If an interface was added, it must not have existed before. For
278 # paranoia, make sure we have no handlers for those.
279 self.remove_signals(interface_name)
280
281 want = self.required_signals.get(interface_name, [])
282 if not want:
283 return
284
285 self.dbg('Connecting', len(want), 'signals for', interface_name)
286 for signal, cb in self.required_signals.get(interface_name, []):
287 subscription = dbus_connect(self.signal(interface_name, signal), cb)
288 self.connected_signals.add(interface_name, subscription)
289
290 def has_interface(self, *interface_names):
291 try:
292 for interface_name in interface_names:
293 self.dbus_obj()[interface_name]
294 result = True
295 except KeyError:
296 result = False
297 self.dbg('has_interface(%s) ==' % (', '.join(interface_names)), result)
298 return result
299
300 def properties(self, iface=I_MODEM):
301 return self.dbus_obj()[iface].GetProperties()
302
303 def property_is(self, name, val, iface=I_MODEM):
304 is_val = self.properties(iface).get(name)
305 self.dbg(name, '==', is_val)
306 return is_val is not None and is_val == val
307
308 def set_bool(self, name, bool_val, iface=I_MODEM):
309 # to make sure any pending signals are received before we send out more DBus requests
310 event_loop.poll()
311
312 val = bool(bool_val)
313 self.log('Setting', name, val)
314 self.interface(iface).SetProperty(name, Variant('b', val))
315
316 event_loop.wait(self, self.property_is, name, bool_val)
317
318 def set_powered(self, powered=True):
319 self.set_bool('Powered', powered)
320
321 def set_online(self, online=True):
322 self.set_bool('Online', online)
323
324 def is_powered(self):
325 return self.property_is('Powered', True)
326
327 def is_online(self):
328 return self.property_is('Online', True)
329
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200330
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200331
332class Modem(log.Origin):
333 'convenience for ofono Modem interaction'
334 msisdn = None
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200335 sms_received_list = None
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200336 _ki = None
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200337
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100338 CTX_PROT_IPv4 = 'ip'
339 CTX_PROT_IPv6 = 'ipv6'
340 CTX_PROT_IPv46 = 'dual'
341
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200342 def __init__(self, conf):
343 self.conf = conf
344 self.path = conf.get('path')
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200345 super().__init__(log.C_TST, self.path)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200346 self.sms_received_list = []
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200347 self.dbus = ModemDbusInteraction(self.path)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200348 self.register_attempts = 0
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200349 self.call_list = []
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200350 # one Cancellable can handle several concurrent methods.
351 self.cancellable = Gio.Cancellable.new()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200352 self.dbus.required_signals = {
353 I_SMS: ( ('IncomingMessage', self._on_incoming_message), ),
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200354 I_NETREG: ( ('PropertyChanged', self._on_netreg_property_changed), ),
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100355 I_CONNMGR: ( ('PropertyChanged', self._on_connmgr_property_changed), ),
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200356 I_CALLMGR: ( ('PropertyChanged', self._on_callmgr_property_changed),
357 ('CallAdded', self._on_callmgr_call_added),
358 ('CallRemoved', self._on_callmgr_call_removed), ),
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200359 }
360 self.dbus.watch_interfaces()
361
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200362 def cleanup(self):
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200363 self.dbg('cleanup')
364 if self.cancellable:
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200365 self.cancel_pending_dbus_methods()
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200366 self.cancellable = None
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100367 if self.is_powered():
368 self.power_off()
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200369 self.dbus.cleanup()
370 self.dbus = None
371
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200372 def properties(self, *args, **kwargs):
373 '''Return a dict of properties on this modem. For the actual arguments,
374 see ModemDbusInteraction.properties(), which this function calls. The
375 returned dict is defined by ofono. An example is:
376 {'Lockdown': False,
377 'Powered': True,
378 'Model': 'MC7304',
379 'Revision': 'SWI9X15C_05.05.66.00 r29972 CARMD-EV-FRMWR1 2015/10/08 08:36:28',
380 'Manufacturer': 'Sierra Wireless, Incorporated',
381 'Emergency': False,
382 'Interfaces': ['org.ofono.SmartMessaging',
383 'org.ofono.PushNotification',
384 'org.ofono.MessageManager',
385 'org.ofono.NetworkRegistration',
386 'org.ofono.ConnectionManager',
387 'org.ofono.SupplementaryServices',
388 'org.ofono.RadioSettings',
389 'org.ofono.AllowedAccessPoints',
390 'org.ofono.SimManager',
391 'org.ofono.LocationReporting',
392 'org.ofono.VoiceCallManager'],
393 'Serial': '356853054230919',
394 'Features': ['sms', 'net', 'gprs', 'ussd', 'rat', 'sim', 'gps'],
395 'Type': 'hardware',
396 'Online': True}
397 '''
398 return self.dbus.properties(*args, **kwargs)
399
400 def set_powered(self, powered=True):
401 return self.dbus.set_powered(powered=powered)
402
403 def set_online(self, online=True):
404 return self.dbus.set_online(online=online)
405
406 def is_powered(self):
407 return self.dbus.is_powered()
408
409 def is_online(self):
410 return self.dbus.is_online()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200411
412 def set_msisdn(self, msisdn):
413 self.msisdn = msisdn
414
415 def imsi(self):
Neels Hofmeyrb02c2112017-04-09 18:46:48 +0200416 imsi = self.conf.get('imsi')
417 if not imsi:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200418 raise log.Error('No IMSI')
Neels Hofmeyrb02c2112017-04-09 18:46:48 +0200419 return imsi
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200420
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200421 def set_ki(self, ki):
422 self._ki = ki
423
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200424 def ki(self):
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200425 if self._ki is not None:
426 return self._ki
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200427 return self.conf.get('ki')
428
Pau Espin Pedrol713ce2c2017-08-24 16:57:17 +0200429 def auth_algo(self):
430 return self.conf.get('auth_algo', None)
431
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100432 def features(self):
433 return self.conf.get('features', [])
434
435 def _required_ifaces(self):
436 req_ifaces = (I_NETREG,)
437 req_ifaces += (I_SMS,) if 'sms' in self.features() else ()
438 req_ifaces += (I_SS,) if 'ussd' in self.features() else ()
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100439 req_ifaces += (I_CONNMGR,) if 'gprs' in self.features() else ()
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100440 return req_ifaces
441
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200442 def _on_netreg_property_changed(self, name, value):
443 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_NETREG, name, value))
444
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200445 def is_connected(self, mcc_mnc=None):
446 netreg = self.dbus.interface(I_NETREG)
447 prop = netreg.GetProperties()
448 status = prop.get('Status')
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200449 self.dbg('status:', status)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200450 if not (status == NETREG_ST_REGISTERED or status == NETREG_ST_ROAMING):
451 return False
452 if mcc_mnc is None: # Any network is fine and we are registered.
453 return True
454 mcc = prop.get('MobileCountryCode')
455 mnc = prop.get('MobileNetworkCode')
456 if (mcc, mnc) == mcc_mnc:
457 return True
458 return False
459
460 def schedule_scan_register(self, mcc_mnc):
461 if self.register_attempts > NETREG_MAX_REGISTER_ATTEMPTS:
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200462 raise log.Error('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200463 self.register_attempts += 1
464 netreg = self.dbus.interface(I_NETREG)
465 self.dbg('Scanning for operators...')
466 # Scan method can take several seconds, and we don't want to block
467 # waiting for that. Make it async and try to register when the scan is
468 # finished.
469 register_func = self.scan_cb_register_automatic if mcc_mnc is None else self.scan_cb_register
470 result_handler = lambda obj, result, user_data: defer(register_func, result, user_data)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200471 error_handler = lambda obj, e, user_data: defer(self.scan_cb_error_handler, e, mcc_mnc)
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200472 dbus_async_call(netreg, netreg.Scan, timeout=30, cancellable=self.cancellable,
473 result_handler=result_handler, error_handler=error_handler,
474 user_data=mcc_mnc)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200475
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200476 def scan_cb_error_handler(self, e, mcc_mnc):
477 # It was detected that Scan() method can fail for some modems on some
478 # specific circumstances. For instance it fails with org.ofono.Error.Failed
479 # if the modem starts to register internally after we started Scan() and
480 # the registering succeeds while we are still waiting for Scan() to finsih.
481 # So far the easiest seems to check if we are now registered and
482 # otherwise schedule a scan again.
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200483 self.err('Scan() failed, retrying if needed:', e)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200484 if not self.is_connected(mcc_mnc):
485 self.schedule_scan_register(mcc_mnc)
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200486 else:
487 self.log('Already registered with network', mcc_mnc)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200488
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200489 def scan_cb_register_automatic(self, scanned_operators, mcc_mnc):
490 self.dbg('scanned operators: ', scanned_operators);
491 for op_path, op_prop in scanned_operators:
492 if op_prop.get('Status') == 'current':
493 mcc = op_prop.get('MobileCountryCode')
494 mnc = op_prop.get('MobileNetworkCode')
495 self.log('Already registered with network', (mcc, mnc))
496 return
497 self.log('Registering with the default network')
498 netreg = self.dbus.interface(I_NETREG)
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200499 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', netreg.Register)
500
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200501
502 def scan_cb_register(self, scanned_operators, mcc_mnc):
503 self.dbg('scanned operators: ', scanned_operators);
504 matching_op_path = None
505 for op_path, op_prop in scanned_operators:
506 mcc = op_prop.get('MobileCountryCode')
507 mnc = op_prop.get('MobileNetworkCode')
508 if (mcc, mnc) == mcc_mnc:
509 if op_prop.get('Status') == 'current':
510 self.log('Already registered with network', mcc_mnc)
511 # We discovered the network and we are already registered
512 # with it. Avoid calling op.Register() in this case (it
513 # won't act as a NO-OP, it actually returns an error).
514 return
515 matching_op_path = op_path
516 break
517 if matching_op_path is None:
518 self.dbg('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
519 self.schedule_scan_register(mcc_mnc)
520 return
521 dbus_op = systembus_get(matching_op_path)
522 self.log('Registering with operator', matching_op_path, mcc_mnc)
Pau Espin Pedrol9f59b822017-11-07 17:50:52 +0100523 try:
524 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', dbus_op.Register)
525 except GLib.Error as e:
526 if Gio.DBusError.is_remote_error(e) and Gio.DBusError.get_remote_error(e) == 'org.ofono.Error.NotSupported':
527 self.log('modem does not support manual registering, attempting automatic registering')
528 self.scan_cb_register_automatic(scanned_operators, mcc_mnc)
529 return
530 raise e
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200531
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200532 def cancel_pending_dbus_methods(self):
533 self.cancellable.cancel()
534 # Cancel op is applied as a signal coming from glib mainloop, so we
535 # need to run it and wait for the callbacks to handle cancellations.
536 poll_glib()
Pau Espin Pedrole685c622017-10-04 18:30:22 +0200537 # once it has been triggered, create a new one for next operation:
538 self.cancellable = Gio.Cancellable.new()
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200539
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100540 def power_off(self):
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100541 if self.dbus.has_interface(I_CONNMGR) and self.is_attached():
542 self.detach()
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100543 self.set_online(False)
544 self.set_powered(False)
545 req_ifaces = self._required_ifaces()
546 for iface in req_ifaces:
547 event_loop.wait(self, lambda: not self.dbus.has_interface(iface), timeout=10)
548
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200549 def power_cycle(self):
550 'Power the modem and put it online, power cycle it if it was already on'
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100551 req_ifaces = self._required_ifaces()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200552 if self.is_powered():
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200553 self.dbg('Power cycling')
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100554 self.power_off()
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200555 else:
556 self.dbg('Powering on')
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200557 self.set_powered()
Pau Espin Pedrolb9955762017-05-02 09:39:27 +0200558 self.set_online()
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100559 event_loop.wait(self, self.dbus.has_interface, *req_ifaces, timeout=10)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200560
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200561 def connect(self, mcc_mnc=None):
562 'Connect to MCC+MNC'
563 if (mcc_mnc is not None) and (len(mcc_mnc) != 2 or None in mcc_mnc):
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200564 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 +0200565 # if test called connect() before and async scanning has not finished, we need to get rid of it:
566 self.cancel_pending_dbus_methods()
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200567 self.power_cycle()
568 self.register_attempts = 0
569 if self.is_connected(mcc_mnc):
570 self.log('Already registered with', mcc_mnc if mcc_mnc else 'default network')
571 else:
572 self.log('Connect to', mcc_mnc if mcc_mnc else 'default network')
573 self.schedule_scan_register(mcc_mnc)
574
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100575 def is_attached(self):
576 connmgr = self.dbus.interface(I_CONNMGR)
577 prop = connmgr.GetProperties()
578 attached = prop.get('Attached')
579 self.dbg('attached:', attached)
580 return attached
581
582 def attach(self, allow_roaming=False):
583 self.dbg('attach')
584 if self.is_attached():
585 self.detach()
586 connmgr = self.dbus.interface(I_CONNMGR)
587 prop = connmgr.SetProperty('RoamingAllowed', Variant('b', allow_roaming))
588 prop = connmgr.SetProperty('Powered', Variant('b', True))
589
590 def detach(self):
591 self.dbg('detach')
592 connmgr = self.dbus.interface(I_CONNMGR)
593 prop = connmgr.SetProperty('RoamingAllowed', Variant('b', False))
594 prop = connmgr.SetProperty('Powered', Variant('b', False))
595 connmgr.DeactivateAll()
596 connmgr.ResetContexts() # Requires Powered=false
597
598 def activate_context(self, apn='internet', user='ogt', pwd='', protocol='ip'):
Pau Espin Pedrolb05e36a2017-12-15 12:39:36 +0100599 self.dbg('activate_context', apn=apn, user=user, protocol=protocol)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100600
601 connmgr = self.dbus.interface(I_CONNMGR)
602 ctx_path = connmgr.AddContext('internet')
603
604 ctx = systembus_get(ctx_path)
605 ctx.SetProperty('AccessPointName', Variant('s', apn))
606 ctx.SetProperty('Username', Variant('s', user))
607 ctx.SetProperty('Password', Variant('s', pwd))
608 ctx.SetProperty('Protocol', Variant('s', protocol))
609
610 # Activate can only be called after we are attached
611 ctx.SetProperty('Active', Variant('b', True))
612 event_loop.wait(self, lambda: ctx.GetProperties()['Active'] == True)
613 self.log('context activated', path=ctx_path, apn=apn, user=user, properties=ctx.GetProperties())
614 return ctx_path
615
616 def deactivate_context(self, ctx_id):
617 self.dbg('activate_context', path=ctx_id)
618 ctx = systembus_get(ctx_id)
619 ctx.SetProperty('Active', Variant('b', False))
620 event_loop.wait(self, lambda: ctx.GetProperties()['Active'] == False)
621
Neels Hofmeyr8c7477f2017-05-25 04:33:53 +0200622 def sms_send(self, to_msisdn_or_modem, *tokens):
623 if isinstance(to_msisdn_or_modem, Modem):
624 to_msisdn = to_msisdn_or_modem.msisdn
625 tokens = list(tokens)
626 tokens.append('to ' + to_msisdn_or_modem.name())
627 else:
628 to_msisdn = str(to_msisdn_or_modem)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200629 msg = sms.Sms(self.msisdn, to_msisdn, 'from ' + self.name(), *tokens)
630 self.log('sending sms to MSISDN', to_msisdn, sms=msg)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200631 mm = self.dbus.interface(I_SMS)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200632 mm.SendMessage(to_msisdn, str(msg))
633 return msg
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200634
635 def _on_incoming_message(self, message, info):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200636 self.log('Incoming SMS:', repr(message))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200637 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200638 self.sms_received_list.append((message, info))
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200639
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200640 def sms_was_received(self, sms_obj):
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200641 for msg, info in self.sms_received_list:
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200642 if sms_obj.matches(msg):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200643 self.log('SMS received as expected:', repr(msg))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200644 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200645 return True
646 return False
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200647
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200648 def call_id_list(self):
649 self.dbg('call_id_list: %r' % self.call_list)
650 return self.call_list
651
652 def call_dial(self, to_msisdn_or_modem):
653 if isinstance(to_msisdn_or_modem, Modem):
654 to_msisdn = to_msisdn_or_modem.msisdn
655 else:
656 to_msisdn = str(to_msisdn_or_modem)
657 self.dbg('Dialing:', to_msisdn)
658 cmgr = self.dbus.interface(I_CALLMGR)
659 call_obj_path = cmgr.Dial(to_msisdn, 'default')
660 if call_obj_path not in self.call_list:
661 self.dbg('Adding %s to call list' % call_obj_path)
662 self.call_list.append(call_obj_path)
663 else:
664 self.dbg('Dial returned already existing call')
665 return call_obj_path
666
667 def _find_call_msisdn_state(self, msisdn, state):
668 cmgr = self.dbus.interface(I_CALLMGR)
669 ret = cmgr.GetCalls()
670 for obj_path, props in ret:
671 if props['LineIdentification'] == msisdn and props['State'] == state:
672 return obj_path
673 return None
674
675 def call_wait_incoming(self, caller_msisdn_or_modem, timeout=60):
676 if isinstance(caller_msisdn_or_modem, Modem):
677 caller_msisdn = caller_msisdn_or_modem.msisdn
678 else:
679 caller_msisdn = str(caller_msisdn_or_modem)
680 self.dbg('Waiting for incoming call from:', caller_msisdn)
681 event_loop.wait(self, lambda: self._find_call_msisdn_state(caller_msisdn, 'incoming') is not None, timeout=timeout)
682 return self._find_call_msisdn_state(caller_msisdn, 'incoming')
683
684 def call_answer(self, call_id):
685 self.dbg('Answer call %s' % call_id)
686 assert self.call_state(call_id) == 'incoming'
687 call_dbus_obj = systembus_get(call_id)
688 call_dbus_obj.Answer()
689
690 def call_hangup(self, call_id):
691 self.dbg('Hang up call %s' % call_id)
692 call_dbus_obj = systembus_get(call_id)
693 call_dbus_obj.Hangup()
694
695 def call_is_active(self, call_id):
696 return self.call_state(call_id) == 'active'
697
698 def call_state(self, call_id):
699 call_dbus_obj = systembus_get(call_id)
700 props = call_dbus_obj.GetProperties()
701 state = props.get('State')
702 self.dbg('call state: %s' % state)
703 return state
704
705 def _on_callmgr_call_added(self, obj_path, properties):
706 self.dbg('%r.CallAdded() -> %s=%r' % (I_CALLMGR, obj_path, repr(properties)))
707 if obj_path not in self.call_list:
708 self.call_list.append(obj_path)
709 else:
710 self.dbg('Call already exists %r' % obj_path)
711
712 def _on_callmgr_call_removed(self, obj_path):
713 self.dbg('%r.CallRemoved() -> %s' % (I_CALLMGR, obj_path))
714 if obj_path in self.call_list:
715 self.call_list.remove(obj_path)
716 else:
717 self.dbg('Trying to remove non-existing call %r' % obj_path)
718
719 def _on_callmgr_property_changed(self, name, value):
720 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_CALLMGR, name, value))
721
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100722 def _on_connmgr_property_changed(self, name, value):
723 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_CONNMGR, name, value))
724
Pau Espin Pedrolee6e4912017-09-05 18:46:34 +0200725 def info(self, keys=('Manufacturer', 'Model', 'Revision', 'Serial')):
Neels Hofmeyrb8011692017-05-29 03:45:24 +0200726 props = self.properties()
727 return ', '.join(['%s: %r'%(k,props.get(k)) for k in keys])
728
729 def log_info(self, *args, **kwargs):
730 self.log(self.info(*args, **kwargs))
731
Pau Espin Pedrol03983aa2017-06-12 15:31:27 +0200732 def ussd_send(self, command):
733 ss = self.dbus.interface(I_SS)
734 service_type, response = ss.Initiate(command)
735 return response
736
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200737# vim: expandtab tabstop=4 shiftwidth=4