blob: f50a291c55e197157adc8bcf1d5b32979caa8fac [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'
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +010044I_SIMMGR = 'org.ofono.SimManager'
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +020045
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020046# See https://github.com/intgr/ofono/blob/master/doc/network-api.txt#L78
47NETREG_ST_REGISTERED = 'registered'
48NETREG_ST_ROAMING = 'roaming'
49
50NETREG_MAX_REGISTER_ATTEMPTS = 3
51
Neels Hofmeyr035cda82017-05-05 17:52:45 +020052class DeferredHandling:
53 defer_queue = []
54
55 def __init__(self, dbus_iface, handler):
56 self.handler = handler
Neels Hofmeyr47de6b02017-05-10 13:24:05 +020057 self.subscription_id = dbus_iface.connect(self.receive_signal)
Neels Hofmeyr035cda82017-05-05 17:52:45 +020058
59 def receive_signal(self, *args, **kwargs):
60 DeferredHandling.defer_queue.append((self.handler, args, kwargs))
61
62 @staticmethod
63 def handle_queue():
64 while DeferredHandling.defer_queue:
65 handler, args, kwargs = DeferredHandling.defer_queue.pop(0)
66 handler(*args, **kwargs)
67
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020068def defer(handler, *args, **kwargs):
69 DeferredHandling.defer_queue.append((handler, args, kwargs))
70
Neels Hofmeyr035cda82017-05-05 17:52:45 +020071def dbus_connect(dbus_iface, handler):
72 '''This function shall be used instead of directly connecting DBus signals.
73 It ensures that we don't nest a glib main loop within another, and also
74 that we receive exceptions raised within the signal handlers. This makes it
75 so that a signal handler is invoked only after the DBus polling is through
76 by enlisting signals that should be handled in the
77 DeferredHandling.defer_queue.'''
Neels Hofmeyr47de6b02017-05-10 13:24:05 +020078 return DeferredHandling(dbus_iface, handler).subscription_id
Neels Hofmeyr035cda82017-05-05 17:52:45 +020079
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020080def poll_glib():
Neels Hofmeyr3531a192017-03-28 14:30:28 +020081 global glib_main_ctx
82 while glib_main_ctx.pending():
83 glib_main_ctx.iteration()
Neels Hofmeyr035cda82017-05-05 17:52:45 +020084 DeferredHandling.handle_queue()
Neels Hofmeyr3531a192017-03-28 14:30:28 +020085
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020086event_loop.register_poll_func(poll_glib)
87
Neels Hofmeyr93f58662017-05-03 16:32:16 +020088def systembus_get(path):
Neels Hofmeyr3531a192017-03-28 14:30:28 +020089 global bus
90 return bus.get('org.ofono', path)
91
92def list_modems():
Neels Hofmeyr93f58662017-05-03 16:32:16 +020093 root = systembus_get('/')
Neels Hofmeyr3531a192017-03-28 14:30:28 +020094 return sorted(root.GetModems())
95
Pau Espin Pedrole25cf042018-02-23 17:00:09 +010096def get_dbuspath_from_syspath(syspath):
97 modems = list_modems()
98 for dbuspath, props in modems:
99 if props.get('SystemPath', '') == syspath:
100 return dbuspath
101 raise ValueError('could not find %s in modem list: %s' % (syspath, modems))
102
103
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200104def _async_result_handler(obj, result, user_data):
105 '''Generic callback dispatcher called from glib loop when an async method
106 call has returned. This callback is set up by method dbus_async_call.'''
107 (result_callback, error_callback, real_user_data) = user_data
108 try:
109 ret = obj.call_finish(result)
110 except Exception as e:
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200111 if isinstance(e, GLib.Error) and e.code == Gio.IOErrorEnum.CANCELLED:
112 log.dbg('DBus method cancelled')
113 return
114
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200115 if error_callback:
116 error_callback(obj, e, real_user_data)
117 else:
118 result_callback(obj, e, real_user_data)
119 return
120
121 ret = ret.unpack()
122 # to be compatible with standard Python behaviour, unbox
123 # single-element tuples and return None for empty result tuples
124 if len(ret) == 1:
125 ret = ret[0]
126 elif len(ret) == 0:
127 ret = None
128 result_callback(obj, ret, real_user_data)
129
130def dbus_async_call(instance, proxymethod, *proxymethod_args,
131 result_handler=None, error_handler=None,
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200132 user_data=None, timeout=30, cancellable=None,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200133 **proxymethod_kwargs):
134 '''pydbus doesn't support asynchronous methods. This method adds support for
135 it until pydbus implements it'''
136
137 argdiff = len(proxymethod_args) - len(proxymethod._inargs)
138 if argdiff < 0:
139 raise TypeError(proxymethod.__qualname__ + " missing {} required positional argument(s)".format(-argdiff))
140 elif argdiff > 0:
141 raise TypeError(proxymethod.__qualname__ + " takes {} positional argument(s) but {} was/were given".format(len(proxymethod._inargs), len(proxymethod_args)))
142
143 timeout = timeout * 1000
144 user_data = (result_handler, error_handler, user_data)
145
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200146 # See https://lazka.github.io/pgi-docs/Gio-2.0/classes/DBusProxy.html#Gio.DBusProxy.call
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200147 ret = instance._bus.con.call(
148 instance._bus_name, instance._path,
149 proxymethod._iface_name, proxymethod.__name__,
150 GLib.Variant(proxymethod._sinargs, proxymethod_args),
151 GLib.VariantType.new(proxymethod._soutargs),
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200152 0, timeout, cancellable,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200153 _async_result_handler, user_data)
154
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200155def dbus_call_dismiss_error(log_obj, err_str, method):
156 try:
157 method()
Pau Espin Pedrol9b670212017-11-07 17:50:20 +0100158 except GLib.Error as e:
159 if Gio.DBusError.is_remote_error(e) and Gio.DBusError.get_remote_error(e) == err_str:
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200160 log_obj.log('Dismissed Dbus method error: %r' % e)
161 return
Pau Espin Pedrol9b670212017-11-07 17:50:20 +0100162 raise e
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200163
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200164class ModemDbusInteraction(log.Origin):
165 '''Work around inconveniences specific to pydbus and ofono.
166 ofono adds and removes DBus interfaces and notifies about them.
167 Upon changes we need a fresh pydbus object to benefit from that.
168 Watching the interfaces change is optional; be sure to call
169 watch_interfaces() if you'd like to have signals subscribed.
170 Related: https://github.com/LEW21/pydbus/issues/56
171 '''
172
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200173 modem_path = None
174 watch_props_subscription = None
175 _dbus_obj = None
176 interfaces = None
177
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200178 def __init__(self, modem_path):
179 self.modem_path = modem_path
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200180 super().__init__(log.C_BUS, self.modem_path)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200181 self.interfaces = set()
182
183 # A dict listing signal handlers to connect, e.g.
184 # { I_SMS: ( ('IncomingMessage', self._on_incoming_message), ), }
185 self.required_signals = {}
186
187 # A dict collecting subscription tokens for connected signal handlers.
188 # { I_SMS: ( token1, token2, ... ), }
189 self.connected_signals = util.listdict()
190
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200191 def cleanup(self):
Pau Espin Pedrol58ff38d2017-06-23 13:10:38 +0200192 self.set_powered(False)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200193 self.unwatch_interfaces()
194 for interface_name in list(self.connected_signals.keys()):
195 self.remove_signals(interface_name)
196
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200197 def __del__(self):
198 self.cleanup()
199
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200200 def get_new_dbus_obj(self):
201 return systembus_get(self.modem_path)
202
203 def dbus_obj(self):
204 if self._dbus_obj is None:
205 self._dbus_obj = self.get_new_dbus_obj()
206 return self._dbus_obj
207
208 def interface(self, interface_name):
209 try:
210 return self.dbus_obj()[interface_name]
211 except KeyError:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200212 raise log.Error('Modem interface is not available:', interface_name)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200213
214 def signal(self, interface_name, signal):
215 return getattr(self.interface(interface_name), signal)
216
217 def watch_interfaces(self):
218 self.unwatch_interfaces()
219 # Note: we are watching the properties on a get_new_dbus_obj() that is
220 # separate from the one used to interact with interfaces. We need to
221 # refresh the pydbus object to interact with Interfaces that have newly
222 # appeared, but exchanging the DBus object to watch Interfaces being
223 # enabled and disabled is racy: we may skip some removals and
224 # additions. Hence do not exchange this DBus object. We don't even
225 # need to store the dbus object used for this, we will not touch it
226 # again. We only store the signal subscription.
227 self.watch_props_subscription = dbus_connect(self.get_new_dbus_obj().PropertyChanged,
228 self.on_property_change)
229 self.on_interfaces_change(self.properties().get('Interfaces'))
230
231 def unwatch_interfaces(self):
232 if self.watch_props_subscription is None:
233 return
234 self.watch_props_subscription.disconnect()
235 self.watch_props_subscription = None
236
237 def on_property_change(self, name, value):
238 if name == 'Interfaces':
239 self.on_interfaces_change(value)
Pau Espin Pedrol77631212017-09-05 19:04:06 +0200240 else:
241 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_MODEM, name, value))
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200242
243 def on_interfaces_change(self, interfaces_now):
244 # First some logging.
245 now = set(interfaces_now)
246 additions = now - self.interfaces
247 removals = self.interfaces - now
248 self.interfaces = now
249 if not (additions or removals):
250 # nothing changed.
251 return
252
253 if additions:
254 self.dbg('interface enabled:', ', '.join(sorted(additions)))
255
256 if removals:
257 self.dbg('interface disabled:', ', '.join(sorted(removals)))
258
259 # The dbus object is now stale and needs refreshing before we
260 # access the next interface function.
261 self._dbus_obj = None
262
263 # If an interface disappeared, disconnect the signal handlers for it.
264 # Even though we're going to use a fresh dbus object for new
265 # subscriptions, we will still keep active subscriptions alive on the
266 # old dbus object which will linger, associated with the respective
267 # signal subscription.
268 for removed in removals:
269 self.remove_signals(removed)
270
271 # Connect signals for added interfaces.
272 for interface_name in additions:
273 self.connect_signals(interface_name)
274
275 def remove_signals(self, interface_name):
276 got = self.connected_signals.pop(interface_name, [])
277
278 if not got:
279 return
280
281 self.dbg('Disconnecting', len(got), 'signals for', interface_name)
282 for subscription in got:
283 subscription.disconnect()
284
285 def connect_signals(self, interface_name):
286 # If an interface was added, it must not have existed before. For
287 # paranoia, make sure we have no handlers for those.
288 self.remove_signals(interface_name)
289
290 want = self.required_signals.get(interface_name, [])
291 if not want:
292 return
293
294 self.dbg('Connecting', len(want), 'signals for', interface_name)
295 for signal, cb in self.required_signals.get(interface_name, []):
296 subscription = dbus_connect(self.signal(interface_name, signal), cb)
297 self.connected_signals.add(interface_name, subscription)
298
299 def has_interface(self, *interface_names):
300 try:
301 for interface_name in interface_names:
302 self.dbus_obj()[interface_name]
303 result = True
304 except KeyError:
305 result = False
306 self.dbg('has_interface(%s) ==' % (', '.join(interface_names)), result)
307 return result
308
309 def properties(self, iface=I_MODEM):
310 return self.dbus_obj()[iface].GetProperties()
311
312 def property_is(self, name, val, iface=I_MODEM):
313 is_val = self.properties(iface).get(name)
314 self.dbg(name, '==', is_val)
315 return is_val is not None and is_val == val
316
317 def set_bool(self, name, bool_val, iface=I_MODEM):
318 # to make sure any pending signals are received before we send out more DBus requests
319 event_loop.poll()
320
321 val = bool(bool_val)
322 self.log('Setting', name, val)
323 self.interface(iface).SetProperty(name, Variant('b', val))
324
325 event_loop.wait(self, self.property_is, name, bool_val)
326
327 def set_powered(self, powered=True):
328 self.set_bool('Powered', powered)
329
330 def set_online(self, online=True):
331 self.set_bool('Online', online)
332
333 def is_powered(self):
334 return self.property_is('Powered', True)
335
336 def is_online(self):
337 return self.property_is('Online', True)
338
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200339
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200340
341class Modem(log.Origin):
342 'convenience for ofono Modem interaction'
343 msisdn = None
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200344 sms_received_list = None
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200345 _ki = None
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100346 _imsi = None
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200347
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100348 CTX_PROT_IPv4 = 'ip'
349 CTX_PROT_IPv6 = 'ipv6'
350 CTX_PROT_IPv46 = 'dual'
351
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200352 def __init__(self, conf):
353 self.conf = conf
Pau Espin Pedrole25cf042018-02-23 17:00:09 +0100354 self.syspath = conf.get('path')
355 self.dbuspath = get_dbuspath_from_syspath(self.syspath)
356 super().__init__(log.C_TST, self.dbuspath)
357 self.dbg('creating from syspath %s', self.syspath)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200358 self.sms_received_list = []
Pau Espin Pedrole25cf042018-02-23 17:00:09 +0100359 self.dbus = ModemDbusInteraction(self.dbuspath)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200360 self.register_attempts = 0
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200361 self.call_list = []
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200362 # one Cancellable can handle several concurrent methods.
363 self.cancellable = Gio.Cancellable.new()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200364 self.dbus.required_signals = {
365 I_SMS: ( ('IncomingMessage', self._on_incoming_message), ),
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200366 I_NETREG: ( ('PropertyChanged', self._on_netreg_property_changed), ),
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100367 I_CONNMGR: ( ('PropertyChanged', self._on_connmgr_property_changed), ),
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200368 I_CALLMGR: ( ('PropertyChanged', self._on_callmgr_property_changed),
369 ('CallAdded', self._on_callmgr_call_added),
370 ('CallRemoved', self._on_callmgr_call_removed), ),
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200371 }
372 self.dbus.watch_interfaces()
373
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200374 def cleanup(self):
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200375 self.dbg('cleanup')
376 if self.cancellable:
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200377 self.cancel_pending_dbus_methods()
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200378 self.cancellable = None
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100379 if self.is_powered():
380 self.power_off()
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200381 self.dbus.cleanup()
382 self.dbus = None
383
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200384 def properties(self, *args, **kwargs):
385 '''Return a dict of properties on this modem. For the actual arguments,
386 see ModemDbusInteraction.properties(), which this function calls. The
387 returned dict is defined by ofono. An example is:
388 {'Lockdown': False,
389 'Powered': True,
390 'Model': 'MC7304',
391 'Revision': 'SWI9X15C_05.05.66.00 r29972 CARMD-EV-FRMWR1 2015/10/08 08:36:28',
392 'Manufacturer': 'Sierra Wireless, Incorporated',
393 'Emergency': False,
394 'Interfaces': ['org.ofono.SmartMessaging',
395 'org.ofono.PushNotification',
396 'org.ofono.MessageManager',
397 'org.ofono.NetworkRegistration',
398 'org.ofono.ConnectionManager',
399 'org.ofono.SupplementaryServices',
400 'org.ofono.RadioSettings',
401 'org.ofono.AllowedAccessPoints',
402 'org.ofono.SimManager',
403 'org.ofono.LocationReporting',
404 'org.ofono.VoiceCallManager'],
405 'Serial': '356853054230919',
406 'Features': ['sms', 'net', 'gprs', 'ussd', 'rat', 'sim', 'gps'],
407 'Type': 'hardware',
408 'Online': True}
409 '''
410 return self.dbus.properties(*args, **kwargs)
411
412 def set_powered(self, powered=True):
413 return self.dbus.set_powered(powered=powered)
414
415 def set_online(self, online=True):
416 return self.dbus.set_online(online=online)
417
418 def is_powered(self):
419 return self.dbus.is_powered()
420
421 def is_online(self):
422 return self.dbus.is_online()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200423
424 def set_msisdn(self, msisdn):
425 self.msisdn = msisdn
426
427 def imsi(self):
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100428 if self._imsi is None:
429 if 'sim' in self.features():
430 if not self.is_powered():
431 self.set_powered()
432 # wait for SimManager iface to appear after we power on
433 event_loop.wait(self, self.dbus.has_interface, I_SIMMGR, timeout=10)
434 simmgr = self.dbus.interface(I_SIMMGR)
435 # If properties are requested quickly, it may happen that Sim property is still not there.
436 event_loop.wait(self, lambda: simmgr.GetProperties().get('SubscriberIdentity', None) is not None, timeout=10)
437 props = simmgr.GetProperties()
438 self.dbg('got SIM properties', props)
439 self._imsi = props.get('SubscriberIdentity', None)
440 else:
441 self._imsi = self.conf.get('imsi')
442 if self._imsi is None:
443 raise log.Error('No IMSI')
444 return self._imsi
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200445
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200446 def set_ki(self, ki):
447 self._ki = ki
448
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200449 def ki(self):
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200450 if self._ki is not None:
451 return self._ki
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200452 return self.conf.get('ki')
453
Pau Espin Pedrol713ce2c2017-08-24 16:57:17 +0200454 def auth_algo(self):
455 return self.conf.get('auth_algo', None)
456
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100457 def features(self):
458 return self.conf.get('features', [])
459
460 def _required_ifaces(self):
461 req_ifaces = (I_NETREG,)
462 req_ifaces += (I_SMS,) if 'sms' in self.features() else ()
463 req_ifaces += (I_SS,) if 'ussd' in self.features() else ()
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100464 req_ifaces += (I_CONNMGR,) if 'gprs' in self.features() else ()
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100465 req_ifaces += (I_SIMMGR,) if 'sim' in self.features() else ()
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100466 return req_ifaces
467
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200468 def _on_netreg_property_changed(self, name, value):
469 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_NETREG, name, value))
470
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200471 def is_connected(self, mcc_mnc=None):
472 netreg = self.dbus.interface(I_NETREG)
473 prop = netreg.GetProperties()
474 status = prop.get('Status')
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200475 self.dbg('status:', status)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200476 if not (status == NETREG_ST_REGISTERED or status == NETREG_ST_ROAMING):
477 return False
478 if mcc_mnc is None: # Any network is fine and we are registered.
479 return True
480 mcc = prop.get('MobileCountryCode')
481 mnc = prop.get('MobileNetworkCode')
482 if (mcc, mnc) == mcc_mnc:
483 return True
484 return False
485
486 def schedule_scan_register(self, mcc_mnc):
487 if self.register_attempts > NETREG_MAX_REGISTER_ATTEMPTS:
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200488 raise log.Error('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200489 self.register_attempts += 1
490 netreg = self.dbus.interface(I_NETREG)
491 self.dbg('Scanning for operators...')
492 # Scan method can take several seconds, and we don't want to block
493 # waiting for that. Make it async and try to register when the scan is
494 # finished.
495 register_func = self.scan_cb_register_automatic if mcc_mnc is None else self.scan_cb_register
496 result_handler = lambda obj, result, user_data: defer(register_func, result, user_data)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200497 error_handler = lambda obj, e, user_data: defer(self.scan_cb_error_handler, e, mcc_mnc)
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200498 dbus_async_call(netreg, netreg.Scan, timeout=30, cancellable=self.cancellable,
499 result_handler=result_handler, error_handler=error_handler,
500 user_data=mcc_mnc)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200501
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200502 def scan_cb_error_handler(self, e, mcc_mnc):
503 # It was detected that Scan() method can fail for some modems on some
504 # specific circumstances. For instance it fails with org.ofono.Error.Failed
505 # if the modem starts to register internally after we started Scan() and
506 # the registering succeeds while we are still waiting for Scan() to finsih.
507 # So far the easiest seems to check if we are now registered and
508 # otherwise schedule a scan again.
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200509 self.err('Scan() failed, retrying if needed:', e)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200510 if not self.is_connected(mcc_mnc):
511 self.schedule_scan_register(mcc_mnc)
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200512 else:
513 self.log('Already registered with network', mcc_mnc)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200514
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200515 def scan_cb_register_automatic(self, scanned_operators, mcc_mnc):
516 self.dbg('scanned operators: ', scanned_operators);
517 for op_path, op_prop in scanned_operators:
518 if op_prop.get('Status') == 'current':
519 mcc = op_prop.get('MobileCountryCode')
520 mnc = op_prop.get('MobileNetworkCode')
521 self.log('Already registered with network', (mcc, mnc))
522 return
523 self.log('Registering with the default network')
524 netreg = self.dbus.interface(I_NETREG)
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200525 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', netreg.Register)
526
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200527
528 def scan_cb_register(self, scanned_operators, mcc_mnc):
529 self.dbg('scanned operators: ', scanned_operators);
530 matching_op_path = None
531 for op_path, op_prop in scanned_operators:
532 mcc = op_prop.get('MobileCountryCode')
533 mnc = op_prop.get('MobileNetworkCode')
534 if (mcc, mnc) == mcc_mnc:
535 if op_prop.get('Status') == 'current':
536 self.log('Already registered with network', mcc_mnc)
537 # We discovered the network and we are already registered
538 # with it. Avoid calling op.Register() in this case (it
539 # won't act as a NO-OP, it actually returns an error).
540 return
541 matching_op_path = op_path
542 break
543 if matching_op_path is None:
544 self.dbg('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
545 self.schedule_scan_register(mcc_mnc)
546 return
547 dbus_op = systembus_get(matching_op_path)
548 self.log('Registering with operator', matching_op_path, mcc_mnc)
Pau Espin Pedrol9f59b822017-11-07 17:50:52 +0100549 try:
550 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', dbus_op.Register)
551 except GLib.Error as e:
552 if Gio.DBusError.is_remote_error(e) and Gio.DBusError.get_remote_error(e) == 'org.ofono.Error.NotSupported':
553 self.log('modem does not support manual registering, attempting automatic registering')
554 self.scan_cb_register_automatic(scanned_operators, mcc_mnc)
555 return
556 raise e
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200557
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200558 def cancel_pending_dbus_methods(self):
559 self.cancellable.cancel()
560 # Cancel op is applied as a signal coming from glib mainloop, so we
561 # need to run it and wait for the callbacks to handle cancellations.
562 poll_glib()
Pau Espin Pedrole685c622017-10-04 18:30:22 +0200563 # once it has been triggered, create a new one for next operation:
564 self.cancellable = Gio.Cancellable.new()
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200565
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100566 def power_off(self):
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100567 if self.dbus.has_interface(I_CONNMGR) and self.is_attached():
568 self.detach()
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100569 self.set_online(False)
570 self.set_powered(False)
571 req_ifaces = self._required_ifaces()
572 for iface in req_ifaces:
573 event_loop.wait(self, lambda: not self.dbus.has_interface(iface), timeout=10)
574
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200575 def power_cycle(self):
576 'Power the modem and put it online, power cycle it if it was already on'
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100577 req_ifaces = self._required_ifaces()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200578 if self.is_powered():
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200579 self.dbg('Power cycling')
Pau Espin Pedrolf8d12192018-03-14 19:19:28 +0100580 event_loop.sleep(self, 1.0) # workaround for ofono bug OS#3064
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100581 self.power_off()
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200582 else:
583 self.dbg('Powering on')
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200584 self.set_powered()
Pau Espin Pedrolb9955762017-05-02 09:39:27 +0200585 self.set_online()
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100586 event_loop.wait(self, self.dbus.has_interface, *req_ifaces, timeout=10)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200587
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200588 def connect(self, mcc_mnc=None):
589 'Connect to MCC+MNC'
590 if (mcc_mnc is not None) and (len(mcc_mnc) != 2 or None in mcc_mnc):
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200591 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 +0200592 # if test called connect() before and async scanning has not finished, we need to get rid of it:
593 self.cancel_pending_dbus_methods()
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200594 self.power_cycle()
595 self.register_attempts = 0
596 if self.is_connected(mcc_mnc):
597 self.log('Already registered with', mcc_mnc if mcc_mnc else 'default network')
598 else:
599 self.log('Connect to', mcc_mnc if mcc_mnc else 'default network')
600 self.schedule_scan_register(mcc_mnc)
601
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100602 def is_attached(self):
603 connmgr = self.dbus.interface(I_CONNMGR)
604 prop = connmgr.GetProperties()
605 attached = prop.get('Attached')
606 self.dbg('attached:', attached)
607 return attached
608
609 def attach(self, allow_roaming=False):
610 self.dbg('attach')
611 if self.is_attached():
612 self.detach()
613 connmgr = self.dbus.interface(I_CONNMGR)
614 prop = connmgr.SetProperty('RoamingAllowed', Variant('b', allow_roaming))
615 prop = connmgr.SetProperty('Powered', Variant('b', True))
616
617 def detach(self):
618 self.dbg('detach')
619 connmgr = self.dbus.interface(I_CONNMGR)
620 prop = connmgr.SetProperty('RoamingAllowed', Variant('b', False))
621 prop = connmgr.SetProperty('Powered', Variant('b', False))
622 connmgr.DeactivateAll()
623 connmgr.ResetContexts() # Requires Powered=false
624
625 def activate_context(self, apn='internet', user='ogt', pwd='', protocol='ip'):
Pau Espin Pedrolb05e36a2017-12-15 12:39:36 +0100626 self.dbg('activate_context', apn=apn, user=user, protocol=protocol)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100627
628 connmgr = self.dbus.interface(I_CONNMGR)
629 ctx_path = connmgr.AddContext('internet')
630
631 ctx = systembus_get(ctx_path)
632 ctx.SetProperty('AccessPointName', Variant('s', apn))
633 ctx.SetProperty('Username', Variant('s', user))
634 ctx.SetProperty('Password', Variant('s', pwd))
635 ctx.SetProperty('Protocol', Variant('s', protocol))
636
637 # Activate can only be called after we are attached
638 ctx.SetProperty('Active', Variant('b', True))
639 event_loop.wait(self, lambda: ctx.GetProperties()['Active'] == True)
640 self.log('context activated', path=ctx_path, apn=apn, user=user, properties=ctx.GetProperties())
641 return ctx_path
642
643 def deactivate_context(self, ctx_id):
Pau Espin Pedrol263dd3b2018-02-13 16:53:51 +0100644 self.dbg('deactivate_context', path=ctx_id)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100645 ctx = systembus_get(ctx_id)
646 ctx.SetProperty('Active', Variant('b', False))
647 event_loop.wait(self, lambda: ctx.GetProperties()['Active'] == False)
Pau Espin Pedrolcdac2972018-02-16 15:14:32 +0100648 self.dbg('deactivate_context active=false, removing', path=ctx_id)
649 connmgr = self.dbus.interface(I_CONNMGR)
650 connmgr.RemoveContext(ctx_id)
Pau Espin Pedrolb05aa3c2018-02-16 15:03:50 +0100651 self.log('context deactivated', path=ctx_id)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100652
Neels Hofmeyr8c7477f2017-05-25 04:33:53 +0200653 def sms_send(self, to_msisdn_or_modem, *tokens):
654 if isinstance(to_msisdn_or_modem, Modem):
655 to_msisdn = to_msisdn_or_modem.msisdn
656 tokens = list(tokens)
657 tokens.append('to ' + to_msisdn_or_modem.name())
658 else:
659 to_msisdn = str(to_msisdn_or_modem)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200660 msg = sms.Sms(self.msisdn, to_msisdn, 'from ' + self.name(), *tokens)
661 self.log('sending sms to MSISDN', to_msisdn, sms=msg)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200662 mm = self.dbus.interface(I_SMS)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200663 mm.SendMessage(to_msisdn, str(msg))
664 return msg
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200665
666 def _on_incoming_message(self, message, info):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200667 self.log('Incoming SMS:', repr(message))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200668 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200669 self.sms_received_list.append((message, info))
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200670
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200671 def sms_was_received(self, sms_obj):
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200672 for msg, info in self.sms_received_list:
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200673 if sms_obj.matches(msg):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200674 self.log('SMS received as expected:', repr(msg))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200675 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200676 return True
677 return False
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200678
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200679 def call_id_list(self):
680 self.dbg('call_id_list: %r' % self.call_list)
681 return self.call_list
682
683 def call_dial(self, to_msisdn_or_modem):
684 if isinstance(to_msisdn_or_modem, Modem):
685 to_msisdn = to_msisdn_or_modem.msisdn
686 else:
687 to_msisdn = str(to_msisdn_or_modem)
688 self.dbg('Dialing:', to_msisdn)
689 cmgr = self.dbus.interface(I_CALLMGR)
690 call_obj_path = cmgr.Dial(to_msisdn, 'default')
691 if call_obj_path not in self.call_list:
692 self.dbg('Adding %s to call list' % call_obj_path)
693 self.call_list.append(call_obj_path)
694 else:
695 self.dbg('Dial returned already existing call')
696 return call_obj_path
697
698 def _find_call_msisdn_state(self, msisdn, state):
699 cmgr = self.dbus.interface(I_CALLMGR)
700 ret = cmgr.GetCalls()
701 for obj_path, props in ret:
702 if props['LineIdentification'] == msisdn and props['State'] == state:
703 return obj_path
704 return None
705
706 def call_wait_incoming(self, caller_msisdn_or_modem, timeout=60):
707 if isinstance(caller_msisdn_or_modem, Modem):
708 caller_msisdn = caller_msisdn_or_modem.msisdn
709 else:
710 caller_msisdn = str(caller_msisdn_or_modem)
711 self.dbg('Waiting for incoming call from:', caller_msisdn)
712 event_loop.wait(self, lambda: self._find_call_msisdn_state(caller_msisdn, 'incoming') is not None, timeout=timeout)
713 return self._find_call_msisdn_state(caller_msisdn, 'incoming')
714
715 def call_answer(self, call_id):
716 self.dbg('Answer call %s' % call_id)
717 assert self.call_state(call_id) == 'incoming'
718 call_dbus_obj = systembus_get(call_id)
719 call_dbus_obj.Answer()
720
721 def call_hangup(self, call_id):
722 self.dbg('Hang up call %s' % call_id)
723 call_dbus_obj = systembus_get(call_id)
724 call_dbus_obj.Hangup()
725
726 def call_is_active(self, call_id):
727 return self.call_state(call_id) == 'active'
728
729 def call_state(self, call_id):
730 call_dbus_obj = systembus_get(call_id)
731 props = call_dbus_obj.GetProperties()
732 state = props.get('State')
733 self.dbg('call state: %s' % state)
734 return state
735
736 def _on_callmgr_call_added(self, obj_path, properties):
737 self.dbg('%r.CallAdded() -> %s=%r' % (I_CALLMGR, obj_path, repr(properties)))
738 if obj_path not in self.call_list:
739 self.call_list.append(obj_path)
740 else:
741 self.dbg('Call already exists %r' % obj_path)
742
743 def _on_callmgr_call_removed(self, obj_path):
744 self.dbg('%r.CallRemoved() -> %s' % (I_CALLMGR, obj_path))
745 if obj_path in self.call_list:
746 self.call_list.remove(obj_path)
747 else:
748 self.dbg('Trying to remove non-existing call %r' % obj_path)
749
750 def _on_callmgr_property_changed(self, name, value):
751 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_CALLMGR, name, value))
752
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100753 def _on_connmgr_property_changed(self, name, value):
754 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_CONNMGR, name, value))
755
Pau Espin Pedrolee6e4912017-09-05 18:46:34 +0200756 def info(self, keys=('Manufacturer', 'Model', 'Revision', 'Serial')):
Neels Hofmeyrb8011692017-05-29 03:45:24 +0200757 props = self.properties()
758 return ', '.join(['%s: %r'%(k,props.get(k)) for k in keys])
759
760 def log_info(self, *args, **kwargs):
761 self.log(self.info(*args, **kwargs))
762
Pau Espin Pedrol03983aa2017-06-12 15:31:27 +0200763 def ussd_send(self, command):
764 ss = self.dbus.interface(I_SS)
765 service_type, response = ss.Initiate(command)
766 return response
767
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200768# vim: expandtab tabstop=4 shiftwidth=4