blob: e8f57cc1b357e55c7bee221caf78a4cbdffb074f [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 Pedrol996651a2017-05-30 15:13:29 +020020from . import log, test, 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 Pedrold71edd12017-10-06 13:53:54 +020040I_CALLMGR = 'org.ofono.VoiceCallManager'
41I_CALL = 'org.ofono.VoiceCall'
Pau Espin Pedrol03983aa2017-06-12 15:31:27 +020042I_SS = 'org.ofono.SupplementaryServices'
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
Neels Hofmeyr035cda82017-05-05 17:52:45 +020050class DeferredHandling:
51 defer_queue = []
52
53 def __init__(self, dbus_iface, handler):
54 self.handler = handler
Neels Hofmeyr47de6b02017-05-10 13:24:05 +020055 self.subscription_id = dbus_iface.connect(self.receive_signal)
Neels Hofmeyr035cda82017-05-05 17:52:45 +020056
57 def receive_signal(self, *args, **kwargs):
58 DeferredHandling.defer_queue.append((self.handler, args, kwargs))
59
60 @staticmethod
61 def handle_queue():
62 while DeferredHandling.defer_queue:
63 handler, args, kwargs = DeferredHandling.defer_queue.pop(0)
64 handler(*args, **kwargs)
65
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020066def defer(handler, *args, **kwargs):
67 DeferredHandling.defer_queue.append((handler, args, kwargs))
68
Neels Hofmeyr035cda82017-05-05 17:52:45 +020069def dbus_connect(dbus_iface, handler):
70 '''This function shall be used instead of directly connecting DBus signals.
71 It ensures that we don't nest a glib main loop within another, and also
72 that we receive exceptions raised within the signal handlers. This makes it
73 so that a signal handler is invoked only after the DBus polling is through
74 by enlisting signals that should be handled in the
75 DeferredHandling.defer_queue.'''
Neels Hofmeyr47de6b02017-05-10 13:24:05 +020076 return DeferredHandling(dbus_iface, handler).subscription_id
Neels Hofmeyr035cda82017-05-05 17:52:45 +020077
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020078def poll_glib():
Neels Hofmeyr3531a192017-03-28 14:30:28 +020079 global glib_main_ctx
80 while glib_main_ctx.pending():
81 glib_main_ctx.iteration()
Neels Hofmeyr035cda82017-05-05 17:52:45 +020082 DeferredHandling.handle_queue()
Neels Hofmeyr3531a192017-03-28 14:30:28 +020083
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020084event_loop.register_poll_func(poll_glib)
85
Neels Hofmeyr93f58662017-05-03 16:32:16 +020086def systembus_get(path):
Neels Hofmeyr3531a192017-03-28 14:30:28 +020087 global bus
88 return bus.get('org.ofono', path)
89
90def list_modems():
Neels Hofmeyr93f58662017-05-03 16:32:16 +020091 root = systembus_get('/')
Neels Hofmeyr3531a192017-03-28 14:30:28 +020092 return sorted(root.GetModems())
93
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020094def _async_result_handler(obj, result, user_data):
95 '''Generic callback dispatcher called from glib loop when an async method
96 call has returned. This callback is set up by method dbus_async_call.'''
97 (result_callback, error_callback, real_user_data) = user_data
98 try:
99 ret = obj.call_finish(result)
100 except Exception as e:
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200101 if isinstance(e, GLib.Error) and e.code == Gio.IOErrorEnum.CANCELLED:
102 log.dbg('DBus method cancelled')
103 return
104
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200105 if error_callback:
106 error_callback(obj, e, real_user_data)
107 else:
108 result_callback(obj, e, real_user_data)
109 return
110
111 ret = ret.unpack()
112 # to be compatible with standard Python behaviour, unbox
113 # single-element tuples and return None for empty result tuples
114 if len(ret) == 1:
115 ret = ret[0]
116 elif len(ret) == 0:
117 ret = None
118 result_callback(obj, ret, real_user_data)
119
120def dbus_async_call(instance, proxymethod, *proxymethod_args,
121 result_handler=None, error_handler=None,
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200122 user_data=None, timeout=30, cancellable=None,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200123 **proxymethod_kwargs):
124 '''pydbus doesn't support asynchronous methods. This method adds support for
125 it until pydbus implements it'''
126
127 argdiff = len(proxymethod_args) - len(proxymethod._inargs)
128 if argdiff < 0:
129 raise TypeError(proxymethod.__qualname__ + " missing {} required positional argument(s)".format(-argdiff))
130 elif argdiff > 0:
131 raise TypeError(proxymethod.__qualname__ + " takes {} positional argument(s) but {} was/were given".format(len(proxymethod._inargs), len(proxymethod_args)))
132
133 timeout = timeout * 1000
134 user_data = (result_handler, error_handler, user_data)
135
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200136 # See https://lazka.github.io/pgi-docs/Gio-2.0/classes/DBusProxy.html#Gio.DBusProxy.call
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200137 ret = instance._bus.con.call(
138 instance._bus_name, instance._path,
139 proxymethod._iface_name, proxymethod.__name__,
140 GLib.Variant(proxymethod._sinargs, proxymethod_args),
141 GLib.VariantType.new(proxymethod._soutargs),
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200142 0, timeout, cancellable,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200143 _async_result_handler, user_data)
144
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200145def dbus_call_dismiss_error(log_obj, err_str, method):
146 try:
147 method()
148 except Exception as e:
149 if isinstance(e, GLib.Error) and err_str in e.domain:
150 log_obj.log('Dismissed Dbus method error: %r' % e)
151 return
152 raise log.Error('dbus_call_dismiss_error raised error %r' % e)
153
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200154class ModemDbusInteraction(log.Origin):
155 '''Work around inconveniences specific to pydbus and ofono.
156 ofono adds and removes DBus interfaces and notifies about them.
157 Upon changes we need a fresh pydbus object to benefit from that.
158 Watching the interfaces change is optional; be sure to call
159 watch_interfaces() if you'd like to have signals subscribed.
160 Related: https://github.com/LEW21/pydbus/issues/56
161 '''
162
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200163 modem_path = None
164 watch_props_subscription = None
165 _dbus_obj = None
166 interfaces = None
167
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200168 def __init__(self, modem_path):
169 self.modem_path = modem_path
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200170 super().__init__(log.C_BUS, self.modem_path)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200171 self.interfaces = set()
172
173 # A dict listing signal handlers to connect, e.g.
174 # { I_SMS: ( ('IncomingMessage', self._on_incoming_message), ), }
175 self.required_signals = {}
176
177 # A dict collecting subscription tokens for connected signal handlers.
178 # { I_SMS: ( token1, token2, ... ), }
179 self.connected_signals = util.listdict()
180
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200181 def cleanup(self):
Pau Espin Pedrol58ff38d2017-06-23 13:10:38 +0200182 self.set_powered(False)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200183 self.unwatch_interfaces()
184 for interface_name in list(self.connected_signals.keys()):
185 self.remove_signals(interface_name)
186
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200187 def __del__(self):
188 self.cleanup()
189
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200190 def get_new_dbus_obj(self):
191 return systembus_get(self.modem_path)
192
193 def dbus_obj(self):
194 if self._dbus_obj is None:
195 self._dbus_obj = self.get_new_dbus_obj()
196 return self._dbus_obj
197
198 def interface(self, interface_name):
199 try:
200 return self.dbus_obj()[interface_name]
201 except KeyError:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200202 raise log.Error('Modem interface is not available:', interface_name)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200203
204 def signal(self, interface_name, signal):
205 return getattr(self.interface(interface_name), signal)
206
207 def watch_interfaces(self):
208 self.unwatch_interfaces()
209 # Note: we are watching the properties on a get_new_dbus_obj() that is
210 # separate from the one used to interact with interfaces. We need to
211 # refresh the pydbus object to interact with Interfaces that have newly
212 # appeared, but exchanging the DBus object to watch Interfaces being
213 # enabled and disabled is racy: we may skip some removals and
214 # additions. Hence do not exchange this DBus object. We don't even
215 # need to store the dbus object used for this, we will not touch it
216 # again. We only store the signal subscription.
217 self.watch_props_subscription = dbus_connect(self.get_new_dbus_obj().PropertyChanged,
218 self.on_property_change)
219 self.on_interfaces_change(self.properties().get('Interfaces'))
220
221 def unwatch_interfaces(self):
222 if self.watch_props_subscription is None:
223 return
224 self.watch_props_subscription.disconnect()
225 self.watch_props_subscription = None
226
227 def on_property_change(self, name, value):
228 if name == 'Interfaces':
229 self.on_interfaces_change(value)
Pau Espin Pedrol77631212017-09-05 19:04:06 +0200230 else:
231 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_MODEM, name, value))
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200232
233 def on_interfaces_change(self, interfaces_now):
234 # First some logging.
235 now = set(interfaces_now)
236 additions = now - self.interfaces
237 removals = self.interfaces - now
238 self.interfaces = now
239 if not (additions or removals):
240 # nothing changed.
241 return
242
243 if additions:
244 self.dbg('interface enabled:', ', '.join(sorted(additions)))
245
246 if removals:
247 self.dbg('interface disabled:', ', '.join(sorted(removals)))
248
249 # The dbus object is now stale and needs refreshing before we
250 # access the next interface function.
251 self._dbus_obj = None
252
253 # If an interface disappeared, disconnect the signal handlers for it.
254 # Even though we're going to use a fresh dbus object for new
255 # subscriptions, we will still keep active subscriptions alive on the
256 # old dbus object which will linger, associated with the respective
257 # signal subscription.
258 for removed in removals:
259 self.remove_signals(removed)
260
261 # Connect signals for added interfaces.
262 for interface_name in additions:
263 self.connect_signals(interface_name)
264
265 def remove_signals(self, interface_name):
266 got = self.connected_signals.pop(interface_name, [])
267
268 if not got:
269 return
270
271 self.dbg('Disconnecting', len(got), 'signals for', interface_name)
272 for subscription in got:
273 subscription.disconnect()
274
275 def connect_signals(self, interface_name):
276 # If an interface was added, it must not have existed before. For
277 # paranoia, make sure we have no handlers for those.
278 self.remove_signals(interface_name)
279
280 want = self.required_signals.get(interface_name, [])
281 if not want:
282 return
283
284 self.dbg('Connecting', len(want), 'signals for', interface_name)
285 for signal, cb in self.required_signals.get(interface_name, []):
286 subscription = dbus_connect(self.signal(interface_name, signal), cb)
287 self.connected_signals.add(interface_name, subscription)
288
289 def has_interface(self, *interface_names):
290 try:
291 for interface_name in interface_names:
292 self.dbus_obj()[interface_name]
293 result = True
294 except KeyError:
295 result = False
296 self.dbg('has_interface(%s) ==' % (', '.join(interface_names)), result)
297 return result
298
299 def properties(self, iface=I_MODEM):
300 return self.dbus_obj()[iface].GetProperties()
301
302 def property_is(self, name, val, iface=I_MODEM):
303 is_val = self.properties(iface).get(name)
304 self.dbg(name, '==', is_val)
305 return is_val is not None and is_val == val
306
307 def set_bool(self, name, bool_val, iface=I_MODEM):
308 # to make sure any pending signals are received before we send out more DBus requests
309 event_loop.poll()
310
311 val = bool(bool_val)
312 self.log('Setting', name, val)
313 self.interface(iface).SetProperty(name, Variant('b', val))
314
315 event_loop.wait(self, self.property_is, name, bool_val)
316
317 def set_powered(self, powered=True):
318 self.set_bool('Powered', powered)
319
320 def set_online(self, online=True):
321 self.set_bool('Online', online)
322
323 def is_powered(self):
324 return self.property_is('Powered', True)
325
326 def is_online(self):
327 return self.property_is('Online', True)
328
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200329
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200330
331class Modem(log.Origin):
332 'convenience for ofono Modem interaction'
333 msisdn = None
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200334 sms_received_list = None
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200335 _ki = None
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200336
337 def __init__(self, conf):
338 self.conf = conf
339 self.path = conf.get('path')
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200340 super().__init__(log.C_TST, self.path)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200341 self.sms_received_list = []
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200342 self.dbus = ModemDbusInteraction(self.path)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200343 self.register_attempts = 0
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200344 self.call_list = []
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200345 # one Cancellable can handle several concurrent methods.
346 self.cancellable = Gio.Cancellable.new()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200347 self.dbus.required_signals = {
348 I_SMS: ( ('IncomingMessage', self._on_incoming_message), ),
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200349 I_NETREG: ( ('PropertyChanged', self._on_netreg_property_changed), ),
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200350 I_CALLMGR: ( ('PropertyChanged', self._on_callmgr_property_changed),
351 ('CallAdded', self._on_callmgr_call_added),
352 ('CallRemoved', self._on_callmgr_call_removed), ),
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200353 }
354 self.dbus.watch_interfaces()
355
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200356 def cleanup(self):
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200357 self.dbg('cleanup')
358 if self.cancellable:
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200359 self.cancel_pending_dbus_methods()
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200360 self.cancellable = None
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):
Neels Hofmeyrb02c2112017-04-09 18:46:48 +0200408 imsi = self.conf.get('imsi')
409 if not imsi:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200410 raise log.Error('No IMSI')
Neels Hofmeyrb02c2112017-04-09 18:46:48 +0200411 return imsi
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200412
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200413 def set_ki(self, ki):
414 self._ki = ki
415
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200416 def ki(self):
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200417 if self._ki is not None:
418 return self._ki
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200419 return self.conf.get('ki')
420
Pau Espin Pedrol713ce2c2017-08-24 16:57:17 +0200421 def auth_algo(self):
422 return self.conf.get('auth_algo', None)
423
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200424 def _on_netreg_property_changed(self, name, value):
425 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_NETREG, name, value))
426
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200427 def is_connected(self, mcc_mnc=None):
428 netreg = self.dbus.interface(I_NETREG)
429 prop = netreg.GetProperties()
430 status = prop.get('Status')
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200431 self.dbg('status:', status)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200432 if not (status == NETREG_ST_REGISTERED or status == NETREG_ST_ROAMING):
433 return False
434 if mcc_mnc is None: # Any network is fine and we are registered.
435 return True
436 mcc = prop.get('MobileCountryCode')
437 mnc = prop.get('MobileNetworkCode')
438 if (mcc, mnc) == mcc_mnc:
439 return True
440 return False
441
442 def schedule_scan_register(self, mcc_mnc):
443 if self.register_attempts > NETREG_MAX_REGISTER_ATTEMPTS:
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200444 raise log.Error('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200445 self.register_attempts += 1
446 netreg = self.dbus.interface(I_NETREG)
447 self.dbg('Scanning for operators...')
448 # Scan method can take several seconds, and we don't want to block
449 # waiting for that. Make it async and try to register when the scan is
450 # finished.
451 register_func = self.scan_cb_register_automatic if mcc_mnc is None else self.scan_cb_register
452 result_handler = lambda obj, result, user_data: defer(register_func, result, user_data)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200453 error_handler = lambda obj, e, user_data: defer(self.scan_cb_error_handler, e, mcc_mnc)
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200454 dbus_async_call(netreg, netreg.Scan, timeout=30, cancellable=self.cancellable,
455 result_handler=result_handler, error_handler=error_handler,
456 user_data=mcc_mnc)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200457
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200458 def scan_cb_error_handler(self, e, mcc_mnc):
459 # It was detected that Scan() method can fail for some modems on some
460 # specific circumstances. For instance it fails with org.ofono.Error.Failed
461 # if the modem starts to register internally after we started Scan() and
462 # the registering succeeds while we are still waiting for Scan() to finsih.
463 # So far the easiest seems to check if we are now registered and
464 # otherwise schedule a scan again.
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200465 self.err('Scan() failed, retrying if needed:', e)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200466 if not self.is_connected(mcc_mnc):
467 self.schedule_scan_register(mcc_mnc)
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200468 else:
469 self.log('Already registered with network', mcc_mnc)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200470
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200471 def scan_cb_register_automatic(self, scanned_operators, mcc_mnc):
472 self.dbg('scanned operators: ', scanned_operators);
473 for op_path, op_prop in scanned_operators:
474 if op_prop.get('Status') == 'current':
475 mcc = op_prop.get('MobileCountryCode')
476 mnc = op_prop.get('MobileNetworkCode')
477 self.log('Already registered with network', (mcc, mnc))
478 return
479 self.log('Registering with the default network')
480 netreg = self.dbus.interface(I_NETREG)
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200481 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', netreg.Register)
482
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200483
484 def scan_cb_register(self, scanned_operators, mcc_mnc):
485 self.dbg('scanned operators: ', scanned_operators);
486 matching_op_path = None
487 for op_path, op_prop in scanned_operators:
488 mcc = op_prop.get('MobileCountryCode')
489 mnc = op_prop.get('MobileNetworkCode')
490 if (mcc, mnc) == mcc_mnc:
491 if op_prop.get('Status') == 'current':
492 self.log('Already registered with network', mcc_mnc)
493 # We discovered the network and we are already registered
494 # with it. Avoid calling op.Register() in this case (it
495 # won't act as a NO-OP, it actually returns an error).
496 return
497 matching_op_path = op_path
498 break
499 if matching_op_path is None:
500 self.dbg('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
501 self.schedule_scan_register(mcc_mnc)
502 return
503 dbus_op = systembus_get(matching_op_path)
504 self.log('Registering with operator', matching_op_path, mcc_mnc)
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200505 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', dbus_op.Register)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200506
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200507 def cancel_pending_dbus_methods(self):
508 self.cancellable.cancel()
509 # Cancel op is applied as a signal coming from glib mainloop, so we
510 # need to run it and wait for the callbacks to handle cancellations.
511 poll_glib()
Pau Espin Pedrole685c622017-10-04 18:30:22 +0200512 # once it has been triggered, create a new one for next operation:
513 self.cancellable = Gio.Cancellable.new()
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200514
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200515 def power_cycle(self):
516 'Power the modem and put it online, power cycle it if it was already on'
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200517 if self.is_powered():
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200518 self.dbg('Power cycling')
Pau Espin Pedrol107f2752017-05-04 11:37:16 +0200519 self.set_online(False)
520 self.set_powered(False)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200521 event_loop.wait(self, lambda: not self.dbus.has_interface(I_NETREG, I_SMS), timeout=10)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200522 else:
523 self.dbg('Powering on')
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200524 self.set_powered()
Pau Espin Pedrolb9955762017-05-02 09:39:27 +0200525 self.set_online()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200526 event_loop.wait(self, self.dbus.has_interface, I_NETREG, I_SMS, timeout=10)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200527
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200528 def connect(self, mcc_mnc=None):
529 'Connect to MCC+MNC'
530 if (mcc_mnc is not None) and (len(mcc_mnc) != 2 or None in mcc_mnc):
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200531 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 +0200532 # if test called connect() before and async scanning has not finished, we need to get rid of it:
533 self.cancel_pending_dbus_methods()
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200534 self.power_cycle()
535 self.register_attempts = 0
536 if self.is_connected(mcc_mnc):
537 self.log('Already registered with', mcc_mnc if mcc_mnc else 'default network')
538 else:
539 self.log('Connect to', mcc_mnc if mcc_mnc else 'default network')
540 self.schedule_scan_register(mcc_mnc)
541
Neels Hofmeyr8c7477f2017-05-25 04:33:53 +0200542 def sms_send(self, to_msisdn_or_modem, *tokens):
543 if isinstance(to_msisdn_or_modem, Modem):
544 to_msisdn = to_msisdn_or_modem.msisdn
545 tokens = list(tokens)
546 tokens.append('to ' + to_msisdn_or_modem.name())
547 else:
548 to_msisdn = str(to_msisdn_or_modem)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200549 msg = sms.Sms(self.msisdn, to_msisdn, 'from ' + self.name(), *tokens)
550 self.log('sending sms to MSISDN', to_msisdn, sms=msg)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200551 mm = self.dbus.interface(I_SMS)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200552 mm.SendMessage(to_msisdn, str(msg))
553 return msg
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200554
555 def _on_incoming_message(self, message, info):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200556 self.log('Incoming SMS:', repr(message))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200557 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200558 self.sms_received_list.append((message, info))
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200559
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200560 def sms_was_received(self, sms_obj):
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200561 for msg, info in self.sms_received_list:
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200562 if sms_obj.matches(msg):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200563 self.log('SMS received as expected:', repr(msg))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200564 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200565 return True
566 return False
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200567
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200568 def call_id_list(self):
569 self.dbg('call_id_list: %r' % self.call_list)
570 return self.call_list
571
572 def call_dial(self, to_msisdn_or_modem):
573 if isinstance(to_msisdn_or_modem, Modem):
574 to_msisdn = to_msisdn_or_modem.msisdn
575 else:
576 to_msisdn = str(to_msisdn_or_modem)
577 self.dbg('Dialing:', to_msisdn)
578 cmgr = self.dbus.interface(I_CALLMGR)
579 call_obj_path = cmgr.Dial(to_msisdn, 'default')
580 if call_obj_path not in self.call_list:
581 self.dbg('Adding %s to call list' % call_obj_path)
582 self.call_list.append(call_obj_path)
583 else:
584 self.dbg('Dial returned already existing call')
585 return call_obj_path
586
587 def _find_call_msisdn_state(self, msisdn, state):
588 cmgr = self.dbus.interface(I_CALLMGR)
589 ret = cmgr.GetCalls()
590 for obj_path, props in ret:
591 if props['LineIdentification'] == msisdn and props['State'] == state:
592 return obj_path
593 return None
594
595 def call_wait_incoming(self, caller_msisdn_or_modem, timeout=60):
596 if isinstance(caller_msisdn_or_modem, Modem):
597 caller_msisdn = caller_msisdn_or_modem.msisdn
598 else:
599 caller_msisdn = str(caller_msisdn_or_modem)
600 self.dbg('Waiting for incoming call from:', caller_msisdn)
601 event_loop.wait(self, lambda: self._find_call_msisdn_state(caller_msisdn, 'incoming') is not None, timeout=timeout)
602 return self._find_call_msisdn_state(caller_msisdn, 'incoming')
603
604 def call_answer(self, call_id):
605 self.dbg('Answer call %s' % call_id)
606 assert self.call_state(call_id) == 'incoming'
607 call_dbus_obj = systembus_get(call_id)
608 call_dbus_obj.Answer()
609
610 def call_hangup(self, call_id):
611 self.dbg('Hang up call %s' % call_id)
612 call_dbus_obj = systembus_get(call_id)
613 call_dbus_obj.Hangup()
614
615 def call_is_active(self, call_id):
616 return self.call_state(call_id) == 'active'
617
618 def call_state(self, call_id):
619 call_dbus_obj = systembus_get(call_id)
620 props = call_dbus_obj.GetProperties()
621 state = props.get('State')
622 self.dbg('call state: %s' % state)
623 return state
624
625 def _on_callmgr_call_added(self, obj_path, properties):
626 self.dbg('%r.CallAdded() -> %s=%r' % (I_CALLMGR, obj_path, repr(properties)))
627 if obj_path not in self.call_list:
628 self.call_list.append(obj_path)
629 else:
630 self.dbg('Call already exists %r' % obj_path)
631
632 def _on_callmgr_call_removed(self, obj_path):
633 self.dbg('%r.CallRemoved() -> %s' % (I_CALLMGR, obj_path))
634 if obj_path in self.call_list:
635 self.call_list.remove(obj_path)
636 else:
637 self.dbg('Trying to remove non-existing call %r' % obj_path)
638
639 def _on_callmgr_property_changed(self, name, value):
640 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_CALLMGR, name, value))
641
Pau Espin Pedrolee6e4912017-09-05 18:46:34 +0200642 def info(self, keys=('Manufacturer', 'Model', 'Revision', 'Serial')):
Neels Hofmeyrb8011692017-05-29 03:45:24 +0200643 props = self.properties()
644 return ', '.join(['%s: %r'%(k,props.get(k)) for k in keys])
645
646 def log_info(self, *args, **kwargs):
647 self.log(self.info(*args, **kwargs))
648
Pau Espin Pedrol03983aa2017-06-12 15:31:27 +0200649 def ussd_send(self, command):
650 ss = self.dbus.interface(I_SS)
651 service_type, response = ss.Initiate(command)
652 return response
653
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200654# vim: expandtab tabstop=4 shiftwidth=4