blob: 21b208c83e215a5ff8f39fccd8dd923682989802 [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 Pedrol9a4631c2018-03-28 19:17:34 +020020from . import log, util, sms
21from .event_loop import MainLoop
Neels Hofmeyr3531a192017-03-28 14:30:28 +020022
23from pydbus import SystemBus, Variant
Neels Hofmeyr3531a192017-03-28 14:30:28 +020024
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +020025# Required for Gio.Cancellable.
26# See https://lazka.github.io/pgi-docs/Gio-2.0/classes/Cancellable.html#Gio.Cancellable
27from gi.module import get_introspection_module
28Gio = get_introspection_module('Gio')
29
Neels Hofmeyr3531a192017-03-28 14:30:28 +020030from gi.repository import GLib
Neels Hofmeyr3531a192017-03-28 14:30:28 +020031bus = SystemBus()
32
Pau Espin Pedrol504a6642017-05-04 11:38:23 +020033I_MODEM = 'org.ofono.Modem'
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +020034I_NETREG = 'org.ofono.NetworkRegistration'
35I_SMS = 'org.ofono.MessageManager'
Pau Espin Pedrolde899612017-11-23 17:18:40 +010036I_CONNMGR = 'org.ofono.ConnectionManager'
Pau Espin Pedrold71edd12017-10-06 13:53:54 +020037I_CALLMGR = 'org.ofono.VoiceCallManager'
38I_CALL = 'org.ofono.VoiceCall'
Pau Espin Pedrol03983aa2017-06-12 15:31:27 +020039I_SS = 'org.ofono.SupplementaryServices'
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +010040I_SIMMGR = 'org.ofono.SimManager'
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +020041
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020042# See https://github.com/intgr/ofono/blob/master/doc/network-api.txt#L78
43NETREG_ST_REGISTERED = 'registered'
44NETREG_ST_ROAMING = 'roaming'
45
46NETREG_MAX_REGISTER_ATTEMPTS = 3
47
Pau Espin Pedrolbf176e42018-03-26 19:13:32 +020048class DeferredDBus:
Neels Hofmeyr035cda82017-05-05 17:52:45 +020049
50 def __init__(self, dbus_iface, handler):
51 self.handler = handler
Neels Hofmeyr47de6b02017-05-10 13:24:05 +020052 self.subscription_id = dbus_iface.connect(self.receive_signal)
Neels Hofmeyr035cda82017-05-05 17:52:45 +020053
54 def receive_signal(self, *args, **kwargs):
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +020055 MainLoop.defer(self.handler, *args, **kwargs)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020056
Neels Hofmeyr035cda82017-05-05 17:52:45 +020057def dbus_connect(dbus_iface, handler):
58 '''This function shall be used instead of directly connecting DBus signals.
59 It ensures that we don't nest a glib main loop within another, and also
60 that we receive exceptions raised within the signal handlers. This makes it
61 so that a signal handler is invoked only after the DBus polling is through
62 by enlisting signals that should be handled in the
63 DeferredHandling.defer_queue.'''
Pau Espin Pedrolbf176e42018-03-26 19:13:32 +020064 return DeferredDBus(dbus_iface, handler).subscription_id
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020065
Neels Hofmeyr93f58662017-05-03 16:32:16 +020066def systembus_get(path):
Neels Hofmeyr3531a192017-03-28 14:30:28 +020067 global bus
68 return bus.get('org.ofono', path)
69
70def list_modems():
Neels Hofmeyr93f58662017-05-03 16:32:16 +020071 root = systembus_get('/')
Neels Hofmeyr3531a192017-03-28 14:30:28 +020072 return sorted(root.GetModems())
73
Pau Espin Pedrole25cf042018-02-23 17:00:09 +010074def get_dbuspath_from_syspath(syspath):
75 modems = list_modems()
76 for dbuspath, props in modems:
77 if props.get('SystemPath', '') == syspath:
78 return dbuspath
79 raise ValueError('could not find %s in modem list: %s' % (syspath, modems))
80
81
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020082def _async_result_handler(obj, result, user_data):
83 '''Generic callback dispatcher called from glib loop when an async method
84 call has returned. This callback is set up by method dbus_async_call.'''
85 (result_callback, error_callback, real_user_data) = user_data
86 try:
87 ret = obj.call_finish(result)
88 except Exception as e:
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +020089 if isinstance(e, GLib.Error) and e.code == Gio.IOErrorEnum.CANCELLED:
90 log.dbg('DBus method cancelled')
91 return
92
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020093 if error_callback:
94 error_callback(obj, e, real_user_data)
95 else:
96 result_callback(obj, e, real_user_data)
97 return
98
99 ret = ret.unpack()
100 # to be compatible with standard Python behaviour, unbox
101 # single-element tuples and return None for empty result tuples
102 if len(ret) == 1:
103 ret = ret[0]
104 elif len(ret) == 0:
105 ret = None
106 result_callback(obj, ret, real_user_data)
107
108def dbus_async_call(instance, proxymethod, *proxymethod_args,
109 result_handler=None, error_handler=None,
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200110 user_data=None, timeout=30, cancellable=None,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200111 **proxymethod_kwargs):
112 '''pydbus doesn't support asynchronous methods. This method adds support for
113 it until pydbus implements it'''
114
115 argdiff = len(proxymethod_args) - len(proxymethod._inargs)
116 if argdiff < 0:
117 raise TypeError(proxymethod.__qualname__ + " missing {} required positional argument(s)".format(-argdiff))
118 elif argdiff > 0:
119 raise TypeError(proxymethod.__qualname__ + " takes {} positional argument(s) but {} was/were given".format(len(proxymethod._inargs), len(proxymethod_args)))
120
121 timeout = timeout * 1000
122 user_data = (result_handler, error_handler, user_data)
123
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200124 # See https://lazka.github.io/pgi-docs/Gio-2.0/classes/DBusProxy.html#Gio.DBusProxy.call
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200125 ret = instance._bus.con.call(
126 instance._bus_name, instance._path,
127 proxymethod._iface_name, proxymethod.__name__,
128 GLib.Variant(proxymethod._sinargs, proxymethod_args),
129 GLib.VariantType.new(proxymethod._soutargs),
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200130 0, timeout, cancellable,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200131 _async_result_handler, user_data)
132
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200133def dbus_call_dismiss_error(log_obj, err_str, method):
134 try:
135 method()
Pau Espin Pedrol9b670212017-11-07 17:50:20 +0100136 except GLib.Error as e:
137 if Gio.DBusError.is_remote_error(e) and Gio.DBusError.get_remote_error(e) == err_str:
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200138 log_obj.log('Dismissed Dbus method error: %r' % e)
139 return
Pau Espin Pedrol9b670212017-11-07 17:50:20 +0100140 raise e
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200141
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200142class ModemDbusInteraction(log.Origin):
143 '''Work around inconveniences specific to pydbus and ofono.
144 ofono adds and removes DBus interfaces and notifies about them.
145 Upon changes we need a fresh pydbus object to benefit from that.
146 Watching the interfaces change is optional; be sure to call
147 watch_interfaces() if you'd like to have signals subscribed.
148 Related: https://github.com/LEW21/pydbus/issues/56
149 '''
150
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200151 modem_path = None
152 watch_props_subscription = None
153 _dbus_obj = None
154 interfaces = None
155
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200156 def __init__(self, modem_path):
157 self.modem_path = modem_path
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200158 super().__init__(log.C_BUS, self.modem_path)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200159 self.interfaces = set()
160
161 # A dict listing signal handlers to connect, e.g.
162 # { I_SMS: ( ('IncomingMessage', self._on_incoming_message), ), }
163 self.required_signals = {}
164
165 # A dict collecting subscription tokens for connected signal handlers.
166 # { I_SMS: ( token1, token2, ... ), }
167 self.connected_signals = util.listdict()
168
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200169 def cleanup(self):
Pau Espin Pedrol58ff38d2017-06-23 13:10:38 +0200170 self.set_powered(False)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200171 self.unwatch_interfaces()
172 for interface_name in list(self.connected_signals.keys()):
173 self.remove_signals(interface_name)
174
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200175 def __del__(self):
176 self.cleanup()
177
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200178 def get_new_dbus_obj(self):
179 return systembus_get(self.modem_path)
180
181 def dbus_obj(self):
182 if self._dbus_obj is None:
183 self._dbus_obj = self.get_new_dbus_obj()
184 return self._dbus_obj
185
186 def interface(self, interface_name):
187 try:
188 return self.dbus_obj()[interface_name]
189 except KeyError:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200190 raise log.Error('Modem interface is not available:', interface_name)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200191
192 def signal(self, interface_name, signal):
193 return getattr(self.interface(interface_name), signal)
194
195 def watch_interfaces(self):
196 self.unwatch_interfaces()
197 # Note: we are watching the properties on a get_new_dbus_obj() that is
198 # separate from the one used to interact with interfaces. We need to
199 # refresh the pydbus object to interact with Interfaces that have newly
200 # appeared, but exchanging the DBus object to watch Interfaces being
201 # enabled and disabled is racy: we may skip some removals and
202 # additions. Hence do not exchange this DBus object. We don't even
203 # need to store the dbus object used for this, we will not touch it
204 # again. We only store the signal subscription.
205 self.watch_props_subscription = dbus_connect(self.get_new_dbus_obj().PropertyChanged,
206 self.on_property_change)
207 self.on_interfaces_change(self.properties().get('Interfaces'))
208
209 def unwatch_interfaces(self):
210 if self.watch_props_subscription is None:
211 return
212 self.watch_props_subscription.disconnect()
213 self.watch_props_subscription = None
214
215 def on_property_change(self, name, value):
216 if name == 'Interfaces':
217 self.on_interfaces_change(value)
Pau Espin Pedrol77631212017-09-05 19:04:06 +0200218 else:
219 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_MODEM, name, value))
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200220
221 def on_interfaces_change(self, interfaces_now):
222 # First some logging.
223 now = set(interfaces_now)
224 additions = now - self.interfaces
225 removals = self.interfaces - now
226 self.interfaces = now
227 if not (additions or removals):
228 # nothing changed.
229 return
230
231 if additions:
232 self.dbg('interface enabled:', ', '.join(sorted(additions)))
233
234 if removals:
235 self.dbg('interface disabled:', ', '.join(sorted(removals)))
236
237 # The dbus object is now stale and needs refreshing before we
238 # access the next interface function.
239 self._dbus_obj = None
240
241 # If an interface disappeared, disconnect the signal handlers for it.
242 # Even though we're going to use a fresh dbus object for new
243 # subscriptions, we will still keep active subscriptions alive on the
244 # old dbus object which will linger, associated with the respective
245 # signal subscription.
246 for removed in removals:
247 self.remove_signals(removed)
248
249 # Connect signals for added interfaces.
250 for interface_name in additions:
251 self.connect_signals(interface_name)
252
253 def remove_signals(self, interface_name):
254 got = self.connected_signals.pop(interface_name, [])
255
256 if not got:
257 return
258
259 self.dbg('Disconnecting', len(got), 'signals for', interface_name)
260 for subscription in got:
261 subscription.disconnect()
262
263 def connect_signals(self, interface_name):
264 # If an interface was added, it must not have existed before. For
265 # paranoia, make sure we have no handlers for those.
266 self.remove_signals(interface_name)
267
268 want = self.required_signals.get(interface_name, [])
269 if not want:
270 return
271
272 self.dbg('Connecting', len(want), 'signals for', interface_name)
273 for signal, cb in self.required_signals.get(interface_name, []):
274 subscription = dbus_connect(self.signal(interface_name, signal), cb)
275 self.connected_signals.add(interface_name, subscription)
276
277 def has_interface(self, *interface_names):
278 try:
279 for interface_name in interface_names:
280 self.dbus_obj()[interface_name]
281 result = True
282 except KeyError:
283 result = False
284 self.dbg('has_interface(%s) ==' % (', '.join(interface_names)), result)
285 return result
286
287 def properties(self, iface=I_MODEM):
288 return self.dbus_obj()[iface].GetProperties()
289
290 def property_is(self, name, val, iface=I_MODEM):
291 is_val = self.properties(iface).get(name)
292 self.dbg(name, '==', is_val)
293 return is_val is not None and is_val == val
294
295 def set_bool(self, name, bool_val, iface=I_MODEM):
296 # to make sure any pending signals are received before we send out more DBus requests
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200297 MainLoop.poll()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200298
299 val = bool(bool_val)
300 self.log('Setting', name, val)
301 self.interface(iface).SetProperty(name, Variant('b', val))
302
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200303 MainLoop.wait(self, self.property_is, name, bool_val)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200304
305 def set_powered(self, powered=True):
306 self.set_bool('Powered', powered)
307
308 def set_online(self, online=True):
309 self.set_bool('Online', online)
310
311 def is_powered(self):
312 return self.property_is('Powered', True)
313
314 def is_online(self):
315 return self.property_is('Online', True)
316
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200317
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200318
319class Modem(log.Origin):
320 'convenience for ofono Modem interaction'
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200321
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100322 CTX_PROT_IPv4 = 'ip'
323 CTX_PROT_IPv6 = 'ipv6'
324 CTX_PROT_IPv46 = 'dual'
325
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200326 def __init__(self, conf):
327 self.conf = conf
Pau Espin Pedrole25cf042018-02-23 17:00:09 +0100328 self.syspath = conf.get('path')
329 self.dbuspath = get_dbuspath_from_syspath(self.syspath)
330 super().__init__(log.C_TST, self.dbuspath)
331 self.dbg('creating from syspath %s', self.syspath)
Pau Espin Pedrol58603672018-08-09 13:45:55 +0200332 self.msisdn = None
333 self._ki = None
334 self._imsi = None
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200335 self.sms_received_list = []
Pau Espin Pedrole25cf042018-02-23 17:00:09 +0100336 self.dbus = ModemDbusInteraction(self.dbuspath)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200337 self.register_attempts = 0
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200338 self.call_list = []
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200339 # one Cancellable can handle several concurrent methods.
340 self.cancellable = Gio.Cancellable.new()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200341 self.dbus.required_signals = {
342 I_SMS: ( ('IncomingMessage', self._on_incoming_message), ),
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200343 I_NETREG: ( ('PropertyChanged', self._on_netreg_property_changed), ),
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100344 I_CONNMGR: ( ('PropertyChanged', self._on_connmgr_property_changed), ),
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200345 I_CALLMGR: ( ('PropertyChanged', self._on_callmgr_property_changed),
346 ('CallAdded', self._on_callmgr_call_added),
347 ('CallRemoved', self._on_callmgr_call_removed), ),
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200348 }
349 self.dbus.watch_interfaces()
350
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200351 def cleanup(self):
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200352 self.dbg('cleanup')
353 if self.cancellable:
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200354 self.cancel_pending_dbus_methods()
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200355 self.cancellable = None
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100356 if self.is_powered():
357 self.power_off()
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200358 self.dbus.cleanup()
359 self.dbus = None
360
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200361 def properties(self, *args, **kwargs):
362 '''Return a dict of properties on this modem. For the actual arguments,
363 see ModemDbusInteraction.properties(), which this function calls. The
364 returned dict is defined by ofono. An example is:
365 {'Lockdown': False,
366 'Powered': True,
367 'Model': 'MC7304',
368 'Revision': 'SWI9X15C_05.05.66.00 r29972 CARMD-EV-FRMWR1 2015/10/08 08:36:28',
369 'Manufacturer': 'Sierra Wireless, Incorporated',
370 'Emergency': False,
371 'Interfaces': ['org.ofono.SmartMessaging',
372 'org.ofono.PushNotification',
373 'org.ofono.MessageManager',
374 'org.ofono.NetworkRegistration',
375 'org.ofono.ConnectionManager',
376 'org.ofono.SupplementaryServices',
377 'org.ofono.RadioSettings',
378 'org.ofono.AllowedAccessPoints',
379 'org.ofono.SimManager',
380 'org.ofono.LocationReporting',
381 'org.ofono.VoiceCallManager'],
382 'Serial': '356853054230919',
383 'Features': ['sms', 'net', 'gprs', 'ussd', 'rat', 'sim', 'gps'],
384 'Type': 'hardware',
385 'Online': True}
386 '''
387 return self.dbus.properties(*args, **kwargs)
388
389 def set_powered(self, powered=True):
390 return self.dbus.set_powered(powered=powered)
391
392 def set_online(self, online=True):
393 return self.dbus.set_online(online=online)
394
395 def is_powered(self):
396 return self.dbus.is_powered()
397
398 def is_online(self):
399 return self.dbus.is_online()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200400
401 def set_msisdn(self, msisdn):
402 self.msisdn = msisdn
403
404 def imsi(self):
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100405 if self._imsi is None:
406 if 'sim' in self.features():
407 if not self.is_powered():
408 self.set_powered()
409 # wait for SimManager iface to appear after we power on
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200410 MainLoop.wait(self, self.dbus.has_interface, I_SIMMGR, timeout=10)
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100411 simmgr = self.dbus.interface(I_SIMMGR)
412 # If properties are requested quickly, it may happen that Sim property is still not there.
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200413 MainLoop.wait(self, lambda: simmgr.GetProperties().get('SubscriberIdentity', None) is not None, timeout=10)
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100414 props = simmgr.GetProperties()
415 self.dbg('got SIM properties', props)
416 self._imsi = props.get('SubscriberIdentity', None)
417 else:
418 self._imsi = self.conf.get('imsi')
419 if self._imsi is None:
420 raise log.Error('No IMSI')
421 return self._imsi
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200422
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200423 def set_ki(self, ki):
424 self._ki = ki
425
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200426 def ki(self):
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200427 if self._ki is not None:
428 return self._ki
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200429 return self.conf.get('ki')
430
Pau Espin Pedrol713ce2c2017-08-24 16:57:17 +0200431 def auth_algo(self):
432 return self.conf.get('auth_algo', None)
433
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100434 def features(self):
435 return self.conf.get('features', [])
436
437 def _required_ifaces(self):
438 req_ifaces = (I_NETREG,)
439 req_ifaces += (I_SMS,) if 'sms' in self.features() else ()
440 req_ifaces += (I_SS,) if 'ussd' in self.features() else ()
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100441 req_ifaces += (I_CONNMGR,) if 'gprs' in self.features() else ()
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100442 req_ifaces += (I_SIMMGR,) if 'sim' in self.features() else ()
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100443 return req_ifaces
444
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200445 def _on_netreg_property_changed(self, name, value):
446 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_NETREG, name, value))
447
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200448 def is_connected(self, mcc_mnc=None):
449 netreg = self.dbus.interface(I_NETREG)
450 prop = netreg.GetProperties()
451 status = prop.get('Status')
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200452 self.dbg('status:', status)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200453 if not (status == NETREG_ST_REGISTERED or status == NETREG_ST_ROAMING):
454 return False
455 if mcc_mnc is None: # Any network is fine and we are registered.
456 return True
457 mcc = prop.get('MobileCountryCode')
458 mnc = prop.get('MobileNetworkCode')
459 if (mcc, mnc) == mcc_mnc:
460 return True
461 return False
462
463 def schedule_scan_register(self, mcc_mnc):
464 if self.register_attempts > NETREG_MAX_REGISTER_ATTEMPTS:
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200465 raise log.Error('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200466 self.register_attempts += 1
467 netreg = self.dbus.interface(I_NETREG)
468 self.dbg('Scanning for operators...')
469 # Scan method can take several seconds, and we don't want to block
470 # waiting for that. Make it async and try to register when the scan is
471 # finished.
472 register_func = self.scan_cb_register_automatic if mcc_mnc is None else self.scan_cb_register
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200473 result_handler = lambda obj, result, user_data: MainLoop.defer(register_func, result, user_data)
474 error_handler = lambda obj, e, user_data: MainLoop.defer(self.scan_cb_error_handler, e, mcc_mnc)
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200475 dbus_async_call(netreg, netreg.Scan, timeout=30, cancellable=self.cancellable,
476 result_handler=result_handler, error_handler=error_handler,
477 user_data=mcc_mnc)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200478
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200479 def scan_cb_error_handler(self, e, mcc_mnc):
480 # It was detected that Scan() method can fail for some modems on some
481 # specific circumstances. For instance it fails with org.ofono.Error.Failed
482 # if the modem starts to register internally after we started Scan() and
483 # the registering succeeds while we are still waiting for Scan() to finsih.
484 # So far the easiest seems to check if we are now registered and
485 # otherwise schedule a scan again.
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200486 self.err('Scan() failed, retrying if needed:', e)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200487 if not self.is_connected(mcc_mnc):
488 self.schedule_scan_register(mcc_mnc)
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200489 else:
490 self.log('Already registered with network', mcc_mnc)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200491
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200492 def scan_cb_register_automatic(self, scanned_operators, mcc_mnc):
493 self.dbg('scanned operators: ', scanned_operators);
494 for op_path, op_prop in scanned_operators:
495 if op_prop.get('Status') == 'current':
496 mcc = op_prop.get('MobileCountryCode')
497 mnc = op_prop.get('MobileNetworkCode')
498 self.log('Already registered with network', (mcc, mnc))
499 return
500 self.log('Registering with the default network')
501 netreg = self.dbus.interface(I_NETREG)
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200502 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', netreg.Register)
503
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200504
505 def scan_cb_register(self, scanned_operators, mcc_mnc):
506 self.dbg('scanned operators: ', scanned_operators);
507 matching_op_path = None
508 for op_path, op_prop in scanned_operators:
509 mcc = op_prop.get('MobileCountryCode')
510 mnc = op_prop.get('MobileNetworkCode')
511 if (mcc, mnc) == mcc_mnc:
512 if op_prop.get('Status') == 'current':
513 self.log('Already registered with network', mcc_mnc)
514 # We discovered the network and we are already registered
515 # with it. Avoid calling op.Register() in this case (it
516 # won't act as a NO-OP, it actually returns an error).
517 return
518 matching_op_path = op_path
519 break
520 if matching_op_path is None:
521 self.dbg('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
522 self.schedule_scan_register(mcc_mnc)
523 return
524 dbus_op = systembus_get(matching_op_path)
525 self.log('Registering with operator', matching_op_path, mcc_mnc)
Pau Espin Pedrol9f59b822017-11-07 17:50:52 +0100526 try:
527 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', dbus_op.Register)
528 except GLib.Error as e:
529 if Gio.DBusError.is_remote_error(e) and Gio.DBusError.get_remote_error(e) == 'org.ofono.Error.NotSupported':
530 self.log('modem does not support manual registering, attempting automatic registering')
531 self.scan_cb_register_automatic(scanned_operators, mcc_mnc)
532 return
533 raise e
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200534
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200535 def cancel_pending_dbus_methods(self):
536 self.cancellable.cancel()
537 # Cancel op is applied as a signal coming from glib mainloop, so we
538 # need to run it and wait for the callbacks to handle cancellations.
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200539 MainLoop.poll()
Pau Espin Pedrole685c622017-10-04 18:30:22 +0200540 # once it has been triggered, create a new one for next operation:
541 self.cancellable = Gio.Cancellable.new()
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200542
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100543 def power_off(self):
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100544 if self.dbus.has_interface(I_CONNMGR) and self.is_attached():
545 self.detach()
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100546 self.set_online(False)
547 self.set_powered(False)
548 req_ifaces = self._required_ifaces()
549 for iface in req_ifaces:
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200550 MainLoop.wait(self, lambda: not self.dbus.has_interface(iface), timeout=10)
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100551
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200552 def power_cycle(self):
553 'Power the modem and put it online, power cycle it if it was already on'
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100554 req_ifaces = self._required_ifaces()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200555 if self.is_powered():
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200556 self.dbg('Power cycling')
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200557 MainLoop.sleep(self, 1.0) # workaround for ofono bug OS#3064
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100558 self.power_off()
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200559 else:
560 self.dbg('Powering on')
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200561 self.set_powered()
Pau Espin Pedrolb9955762017-05-02 09:39:27 +0200562 self.set_online()
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200563 MainLoop.wait(self, self.dbus.has_interface, *req_ifaces, timeout=10)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200564
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200565 def connect(self, mcc_mnc=None):
566 'Connect to MCC+MNC'
567 if (mcc_mnc is not None) and (len(mcc_mnc) != 2 or None in mcc_mnc):
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200568 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 +0200569 # if test called connect() before and async scanning has not finished, we need to get rid of it:
570 self.cancel_pending_dbus_methods()
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200571 self.power_cycle()
572 self.register_attempts = 0
573 if self.is_connected(mcc_mnc):
574 self.log('Already registered with', mcc_mnc if mcc_mnc else 'default network')
575 else:
576 self.log('Connect to', mcc_mnc if mcc_mnc else 'default network')
577 self.schedule_scan_register(mcc_mnc)
578
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100579 def is_attached(self):
580 connmgr = self.dbus.interface(I_CONNMGR)
581 prop = connmgr.GetProperties()
582 attached = prop.get('Attached')
583 self.dbg('attached:', attached)
584 return attached
585
586 def attach(self, allow_roaming=False):
587 self.dbg('attach')
588 if self.is_attached():
589 self.detach()
590 connmgr = self.dbus.interface(I_CONNMGR)
591 prop = connmgr.SetProperty('RoamingAllowed', Variant('b', allow_roaming))
592 prop = connmgr.SetProperty('Powered', Variant('b', True))
593
594 def detach(self):
595 self.dbg('detach')
596 connmgr = self.dbus.interface(I_CONNMGR)
597 prop = connmgr.SetProperty('RoamingAllowed', Variant('b', False))
598 prop = connmgr.SetProperty('Powered', Variant('b', False))
599 connmgr.DeactivateAll()
600 connmgr.ResetContexts() # Requires Powered=false
601
602 def activate_context(self, apn='internet', user='ogt', pwd='', protocol='ip'):
Pau Espin Pedrolb05e36a2017-12-15 12:39:36 +0100603 self.dbg('activate_context', apn=apn, user=user, protocol=protocol)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100604
605 connmgr = self.dbus.interface(I_CONNMGR)
606 ctx_path = connmgr.AddContext('internet')
607
608 ctx = systembus_get(ctx_path)
609 ctx.SetProperty('AccessPointName', Variant('s', apn))
610 ctx.SetProperty('Username', Variant('s', user))
611 ctx.SetProperty('Password', Variant('s', pwd))
612 ctx.SetProperty('Protocol', Variant('s', protocol))
613
614 # Activate can only be called after we are attached
615 ctx.SetProperty('Active', Variant('b', True))
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200616 MainLoop.wait(self, lambda: ctx.GetProperties()['Active'] == True)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100617 self.log('context activated', path=ctx_path, apn=apn, user=user, properties=ctx.GetProperties())
618 return ctx_path
619
620 def deactivate_context(self, ctx_id):
Pau Espin Pedrol263dd3b2018-02-13 16:53:51 +0100621 self.dbg('deactivate_context', path=ctx_id)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100622 ctx = systembus_get(ctx_id)
623 ctx.SetProperty('Active', Variant('b', False))
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200624 MainLoop.wait(self, lambda: ctx.GetProperties()['Active'] == False)
Pau Espin Pedrolcdac2972018-02-16 15:14:32 +0100625 self.dbg('deactivate_context active=false, removing', path=ctx_id)
626 connmgr = self.dbus.interface(I_CONNMGR)
627 connmgr.RemoveContext(ctx_id)
Pau Espin Pedrolb05aa3c2018-02-16 15:03:50 +0100628 self.log('context deactivated', path=ctx_id)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100629
Neels Hofmeyr8c7477f2017-05-25 04:33:53 +0200630 def sms_send(self, to_msisdn_or_modem, *tokens):
631 if isinstance(to_msisdn_or_modem, Modem):
632 to_msisdn = to_msisdn_or_modem.msisdn
633 tokens = list(tokens)
634 tokens.append('to ' + to_msisdn_or_modem.name())
635 else:
636 to_msisdn = str(to_msisdn_or_modem)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200637 msg = sms.Sms(self.msisdn, to_msisdn, 'from ' + self.name(), *tokens)
638 self.log('sending sms to MSISDN', to_msisdn, sms=msg)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200639 mm = self.dbus.interface(I_SMS)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200640 mm.SendMessage(to_msisdn, str(msg))
641 return msg
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200642
643 def _on_incoming_message(self, message, info):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200644 self.log('Incoming SMS:', repr(message))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200645 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200646 self.sms_received_list.append((message, info))
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200647
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200648 def sms_was_received(self, sms_obj):
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200649 for msg, info in self.sms_received_list:
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200650 if sms_obj.matches(msg):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200651 self.log('SMS received as expected:', repr(msg))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200652 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200653 return True
654 return False
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200655
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200656 def call_id_list(self):
657 self.dbg('call_id_list: %r' % self.call_list)
658 return self.call_list
659
660 def call_dial(self, to_msisdn_or_modem):
661 if isinstance(to_msisdn_or_modem, Modem):
662 to_msisdn = to_msisdn_or_modem.msisdn
663 else:
664 to_msisdn = str(to_msisdn_or_modem)
665 self.dbg('Dialing:', to_msisdn)
666 cmgr = self.dbus.interface(I_CALLMGR)
667 call_obj_path = cmgr.Dial(to_msisdn, 'default')
668 if call_obj_path not in self.call_list:
669 self.dbg('Adding %s to call list' % call_obj_path)
670 self.call_list.append(call_obj_path)
671 else:
672 self.dbg('Dial returned already existing call')
673 return call_obj_path
674
675 def _find_call_msisdn_state(self, msisdn, state):
676 cmgr = self.dbus.interface(I_CALLMGR)
677 ret = cmgr.GetCalls()
678 for obj_path, props in ret:
679 if props['LineIdentification'] == msisdn and props['State'] == state:
680 return obj_path
681 return None
682
683 def call_wait_incoming(self, caller_msisdn_or_modem, timeout=60):
684 if isinstance(caller_msisdn_or_modem, Modem):
685 caller_msisdn = caller_msisdn_or_modem.msisdn
686 else:
687 caller_msisdn = str(caller_msisdn_or_modem)
688 self.dbg('Waiting for incoming call from:', caller_msisdn)
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200689 MainLoop.wait(self, lambda: self._find_call_msisdn_state(caller_msisdn, 'incoming') is not None, timeout=timeout)
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200690 return self._find_call_msisdn_state(caller_msisdn, 'incoming')
691
692 def call_answer(self, call_id):
693 self.dbg('Answer call %s' % call_id)
694 assert self.call_state(call_id) == 'incoming'
695 call_dbus_obj = systembus_get(call_id)
696 call_dbus_obj.Answer()
697
698 def call_hangup(self, call_id):
699 self.dbg('Hang up call %s' % call_id)
700 call_dbus_obj = systembus_get(call_id)
701 call_dbus_obj.Hangup()
702
703 def call_is_active(self, call_id):
704 return self.call_state(call_id) == 'active'
705
706 def call_state(self, call_id):
Pau Espin Pedrolccb1bc62018-04-22 12:58:08 +0200707 try:
708 call_dbus_obj = systembus_get(call_id)
709 props = call_dbus_obj.GetProperties()
710 state = props.get('State')
711 except Exception as e:
712 self.log('asking call state for non existent call')
713 log.log_exn()
714 state = 'disconnected'
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200715 self.dbg('call state: %s' % state)
716 return state
717
718 def _on_callmgr_call_added(self, obj_path, properties):
719 self.dbg('%r.CallAdded() -> %s=%r' % (I_CALLMGR, obj_path, repr(properties)))
720 if obj_path not in self.call_list:
721 self.call_list.append(obj_path)
722 else:
723 self.dbg('Call already exists %r' % obj_path)
724
725 def _on_callmgr_call_removed(self, obj_path):
726 self.dbg('%r.CallRemoved() -> %s' % (I_CALLMGR, obj_path))
727 if obj_path in self.call_list:
728 self.call_list.remove(obj_path)
729 else:
730 self.dbg('Trying to remove non-existing call %r' % obj_path)
731
732 def _on_callmgr_property_changed(self, name, value):
733 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_CALLMGR, name, value))
734
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100735 def _on_connmgr_property_changed(self, name, value):
736 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_CONNMGR, name, value))
737
Pau Espin Pedrolee6e4912017-09-05 18:46:34 +0200738 def info(self, keys=('Manufacturer', 'Model', 'Revision', 'Serial')):
Neels Hofmeyrb8011692017-05-29 03:45:24 +0200739 props = self.properties()
740 return ', '.join(['%s: %r'%(k,props.get(k)) for k in keys])
741
742 def log_info(self, *args, **kwargs):
743 self.log(self.info(*args, **kwargs))
744
Pau Espin Pedrol03983aa2017-06-12 15:31:27 +0200745 def ussd_send(self, command):
746 ss = self.dbus.interface(I_SS)
747 service_type, response = ss.Initiate(command)
748 return response
749
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200750# vim: expandtab tabstop=4 shiftwidth=4