blob: 2f742eae0b107349339c9d89fa398ac6b732d9c7 [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
24import time
25import pprint
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020026import sys
Neels Hofmeyr3531a192017-03-28 14:30:28 +020027
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +020028# Required for Gio.Cancellable.
29# See https://lazka.github.io/pgi-docs/Gio-2.0/classes/Cancellable.html#Gio.Cancellable
30from gi.module import get_introspection_module
31Gio = get_introspection_module('Gio')
32
Neels Hofmeyr3531a192017-03-28 14:30:28 +020033from gi.repository import GLib
Neels Hofmeyr3531a192017-03-28 14:30:28 +020034bus = SystemBus()
35
Pau Espin Pedrol504a6642017-05-04 11:38:23 +020036I_MODEM = 'org.ofono.Modem'
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +020037I_NETREG = 'org.ofono.NetworkRegistration'
38I_SMS = 'org.ofono.MessageManager'
Pau Espin Pedrolde899612017-11-23 17:18:40 +010039I_CONNMGR = 'org.ofono.ConnectionManager'
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'
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +010043I_SIMMGR = 'org.ofono.SimManager'
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +020044
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020045# See https://github.com/intgr/ofono/blob/master/doc/network-api.txt#L78
46NETREG_ST_REGISTERED = 'registered'
47NETREG_ST_ROAMING = 'roaming'
48
49NETREG_MAX_REGISTER_ATTEMPTS = 3
50
Pau Espin Pedrolbf176e42018-03-26 19:13:32 +020051class DeferredDBus:
Neels Hofmeyr035cda82017-05-05 17:52:45 +020052
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):
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +020058 MainLoop.defer(self.handler, *args, **kwargs)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020059
Neels Hofmeyr035cda82017-05-05 17:52:45 +020060def dbus_connect(dbus_iface, handler):
61 '''This function shall be used instead of directly connecting DBus signals.
62 It ensures that we don't nest a glib main loop within another, and also
63 that we receive exceptions raised within the signal handlers. This makes it
64 so that a signal handler is invoked only after the DBus polling is through
65 by enlisting signals that should be handled in the
66 DeferredHandling.defer_queue.'''
Pau Espin Pedrolbf176e42018-03-26 19:13:32 +020067 return DeferredDBus(dbus_iface, handler).subscription_id
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020068
Neels Hofmeyr93f58662017-05-03 16:32:16 +020069def systembus_get(path):
Neels Hofmeyr3531a192017-03-28 14:30:28 +020070 global bus
71 return bus.get('org.ofono', path)
72
73def list_modems():
Neels Hofmeyr93f58662017-05-03 16:32:16 +020074 root = systembus_get('/')
Neels Hofmeyr3531a192017-03-28 14:30:28 +020075 return sorted(root.GetModems())
76
Pau Espin Pedrole25cf042018-02-23 17:00:09 +010077def get_dbuspath_from_syspath(syspath):
78 modems = list_modems()
79 for dbuspath, props in modems:
80 if props.get('SystemPath', '') == syspath:
81 return dbuspath
82 raise ValueError('could not find %s in modem list: %s' % (syspath, modems))
83
84
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020085def _async_result_handler(obj, result, user_data):
86 '''Generic callback dispatcher called from glib loop when an async method
87 call has returned. This callback is set up by method dbus_async_call.'''
88 (result_callback, error_callback, real_user_data) = user_data
89 try:
90 ret = obj.call_finish(result)
91 except Exception as e:
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +020092 if isinstance(e, GLib.Error) and e.code == Gio.IOErrorEnum.CANCELLED:
93 log.dbg('DBus method cancelled')
94 return
95
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020096 if error_callback:
97 error_callback(obj, e, real_user_data)
98 else:
99 result_callback(obj, e, real_user_data)
100 return
101
102 ret = ret.unpack()
103 # to be compatible with standard Python behaviour, unbox
104 # single-element tuples and return None for empty result tuples
105 if len(ret) == 1:
106 ret = ret[0]
107 elif len(ret) == 0:
108 ret = None
109 result_callback(obj, ret, real_user_data)
110
111def dbus_async_call(instance, proxymethod, *proxymethod_args,
112 result_handler=None, error_handler=None,
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200113 user_data=None, timeout=30, cancellable=None,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200114 **proxymethod_kwargs):
115 '''pydbus doesn't support asynchronous methods. This method adds support for
116 it until pydbus implements it'''
117
118 argdiff = len(proxymethod_args) - len(proxymethod._inargs)
119 if argdiff < 0:
120 raise TypeError(proxymethod.__qualname__ + " missing {} required positional argument(s)".format(-argdiff))
121 elif argdiff > 0:
122 raise TypeError(proxymethod.__qualname__ + " takes {} positional argument(s) but {} was/were given".format(len(proxymethod._inargs), len(proxymethod_args)))
123
124 timeout = timeout * 1000
125 user_data = (result_handler, error_handler, user_data)
126
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200127 # See https://lazka.github.io/pgi-docs/Gio-2.0/classes/DBusProxy.html#Gio.DBusProxy.call
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200128 ret = instance._bus.con.call(
129 instance._bus_name, instance._path,
130 proxymethod._iface_name, proxymethod.__name__,
131 GLib.Variant(proxymethod._sinargs, proxymethod_args),
132 GLib.VariantType.new(proxymethod._soutargs),
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200133 0, timeout, cancellable,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200134 _async_result_handler, user_data)
135
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200136def dbus_call_dismiss_error(log_obj, err_str, method):
137 try:
138 method()
Pau Espin Pedrol9b670212017-11-07 17:50:20 +0100139 except GLib.Error as e:
140 if Gio.DBusError.is_remote_error(e) and Gio.DBusError.get_remote_error(e) == err_str:
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200141 log_obj.log('Dismissed Dbus method error: %r' % e)
142 return
Pau Espin Pedrol9b670212017-11-07 17:50:20 +0100143 raise e
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200144
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200145class ModemDbusInteraction(log.Origin):
146 '''Work around inconveniences specific to pydbus and ofono.
147 ofono adds and removes DBus interfaces and notifies about them.
148 Upon changes we need a fresh pydbus object to benefit from that.
149 Watching the interfaces change is optional; be sure to call
150 watch_interfaces() if you'd like to have signals subscribed.
151 Related: https://github.com/LEW21/pydbus/issues/56
152 '''
153
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200154 modem_path = None
155 watch_props_subscription = None
156 _dbus_obj = None
157 interfaces = None
158
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200159 def __init__(self, modem_path):
160 self.modem_path = modem_path
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200161 super().__init__(log.C_BUS, self.modem_path)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200162 self.interfaces = set()
163
164 # A dict listing signal handlers to connect, e.g.
165 # { I_SMS: ( ('IncomingMessage', self._on_incoming_message), ), }
166 self.required_signals = {}
167
168 # A dict collecting subscription tokens for connected signal handlers.
169 # { I_SMS: ( token1, token2, ... ), }
170 self.connected_signals = util.listdict()
171
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200172 def cleanup(self):
Pau Espin Pedrol58ff38d2017-06-23 13:10:38 +0200173 self.set_powered(False)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200174 self.unwatch_interfaces()
175 for interface_name in list(self.connected_signals.keys()):
176 self.remove_signals(interface_name)
177
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200178 def __del__(self):
179 self.cleanup()
180
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200181 def get_new_dbus_obj(self):
182 return systembus_get(self.modem_path)
183
184 def dbus_obj(self):
185 if self._dbus_obj is None:
186 self._dbus_obj = self.get_new_dbus_obj()
187 return self._dbus_obj
188
189 def interface(self, interface_name):
190 try:
191 return self.dbus_obj()[interface_name]
192 except KeyError:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200193 raise log.Error('Modem interface is not available:', interface_name)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200194
195 def signal(self, interface_name, signal):
196 return getattr(self.interface(interface_name), signal)
197
198 def watch_interfaces(self):
199 self.unwatch_interfaces()
200 # Note: we are watching the properties on a get_new_dbus_obj() that is
201 # separate from the one used to interact with interfaces. We need to
202 # refresh the pydbus object to interact with Interfaces that have newly
203 # appeared, but exchanging the DBus object to watch Interfaces being
204 # enabled and disabled is racy: we may skip some removals and
205 # additions. Hence do not exchange this DBus object. We don't even
206 # need to store the dbus object used for this, we will not touch it
207 # again. We only store the signal subscription.
208 self.watch_props_subscription = dbus_connect(self.get_new_dbus_obj().PropertyChanged,
209 self.on_property_change)
210 self.on_interfaces_change(self.properties().get('Interfaces'))
211
212 def unwatch_interfaces(self):
213 if self.watch_props_subscription is None:
214 return
215 self.watch_props_subscription.disconnect()
216 self.watch_props_subscription = None
217
218 def on_property_change(self, name, value):
219 if name == 'Interfaces':
220 self.on_interfaces_change(value)
Pau Espin Pedrol77631212017-09-05 19:04:06 +0200221 else:
222 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_MODEM, name, value))
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200223
224 def on_interfaces_change(self, interfaces_now):
225 # First some logging.
226 now = set(interfaces_now)
227 additions = now - self.interfaces
228 removals = self.interfaces - now
229 self.interfaces = now
230 if not (additions or removals):
231 # nothing changed.
232 return
233
234 if additions:
235 self.dbg('interface enabled:', ', '.join(sorted(additions)))
236
237 if removals:
238 self.dbg('interface disabled:', ', '.join(sorted(removals)))
239
240 # The dbus object is now stale and needs refreshing before we
241 # access the next interface function.
242 self._dbus_obj = None
243
244 # If an interface disappeared, disconnect the signal handlers for it.
245 # Even though we're going to use a fresh dbus object for new
246 # subscriptions, we will still keep active subscriptions alive on the
247 # old dbus object which will linger, associated with the respective
248 # signal subscription.
249 for removed in removals:
250 self.remove_signals(removed)
251
252 # Connect signals for added interfaces.
253 for interface_name in additions:
254 self.connect_signals(interface_name)
255
256 def remove_signals(self, interface_name):
257 got = self.connected_signals.pop(interface_name, [])
258
259 if not got:
260 return
261
262 self.dbg('Disconnecting', len(got), 'signals for', interface_name)
263 for subscription in got:
264 subscription.disconnect()
265
266 def connect_signals(self, interface_name):
267 # If an interface was added, it must not have existed before. For
268 # paranoia, make sure we have no handlers for those.
269 self.remove_signals(interface_name)
270
271 want = self.required_signals.get(interface_name, [])
272 if not want:
273 return
274
275 self.dbg('Connecting', len(want), 'signals for', interface_name)
276 for signal, cb in self.required_signals.get(interface_name, []):
277 subscription = dbus_connect(self.signal(interface_name, signal), cb)
278 self.connected_signals.add(interface_name, subscription)
279
280 def has_interface(self, *interface_names):
281 try:
282 for interface_name in interface_names:
283 self.dbus_obj()[interface_name]
284 result = True
285 except KeyError:
286 result = False
287 self.dbg('has_interface(%s) ==' % (', '.join(interface_names)), result)
288 return result
289
290 def properties(self, iface=I_MODEM):
291 return self.dbus_obj()[iface].GetProperties()
292
293 def property_is(self, name, val, iface=I_MODEM):
294 is_val = self.properties(iface).get(name)
295 self.dbg(name, '==', is_val)
296 return is_val is not None and is_val == val
297
298 def set_bool(self, name, bool_val, iface=I_MODEM):
299 # to make sure any pending signals are received before we send out more DBus requests
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200300 MainLoop.poll()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200301
302 val = bool(bool_val)
303 self.log('Setting', name, val)
304 self.interface(iface).SetProperty(name, Variant('b', val))
305
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200306 MainLoop.wait(self, self.property_is, name, bool_val)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200307
308 def set_powered(self, powered=True):
309 self.set_bool('Powered', powered)
310
311 def set_online(self, online=True):
312 self.set_bool('Online', online)
313
314 def is_powered(self):
315 return self.property_is('Powered', True)
316
317 def is_online(self):
318 return self.property_is('Online', True)
319
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200320
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200321
322class Modem(log.Origin):
323 'convenience for ofono Modem interaction'
324 msisdn = None
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200325 sms_received_list = None
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200326 _ki = None
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100327 _imsi = None
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200328
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100329 CTX_PROT_IPv4 = 'ip'
330 CTX_PROT_IPv6 = 'ipv6'
331 CTX_PROT_IPv46 = 'dual'
332
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200333 def __init__(self, conf):
334 self.conf = conf
Pau Espin Pedrole25cf042018-02-23 17:00:09 +0100335 self.syspath = conf.get('path')
336 self.dbuspath = get_dbuspath_from_syspath(self.syspath)
337 super().__init__(log.C_TST, self.dbuspath)
338 self.dbg('creating from syspath %s', self.syspath)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200339 self.sms_received_list = []
Pau Espin Pedrole25cf042018-02-23 17:00:09 +0100340 self.dbus = ModemDbusInteraction(self.dbuspath)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200341 self.register_attempts = 0
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200342 self.call_list = []
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200343 # one Cancellable can handle several concurrent methods.
344 self.cancellable = Gio.Cancellable.new()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200345 self.dbus.required_signals = {
346 I_SMS: ( ('IncomingMessage', self._on_incoming_message), ),
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200347 I_NETREG: ( ('PropertyChanged', self._on_netreg_property_changed), ),
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100348 I_CONNMGR: ( ('PropertyChanged', self._on_connmgr_property_changed), ),
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200349 I_CALLMGR: ( ('PropertyChanged', self._on_callmgr_property_changed),
350 ('CallAdded', self._on_callmgr_call_added),
351 ('CallRemoved', self._on_callmgr_call_removed), ),
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200352 }
353 self.dbus.watch_interfaces()
354
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200355 def cleanup(self):
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200356 self.dbg('cleanup')
357 if self.cancellable:
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200358 self.cancel_pending_dbus_methods()
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200359 self.cancellable = None
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100360 if self.is_powered():
361 self.power_off()
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200362 self.dbus.cleanup()
363 self.dbus = None
364
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200365 def properties(self, *args, **kwargs):
366 '''Return a dict of properties on this modem. For the actual arguments,
367 see ModemDbusInteraction.properties(), which this function calls. The
368 returned dict is defined by ofono. An example is:
369 {'Lockdown': False,
370 'Powered': True,
371 'Model': 'MC7304',
372 'Revision': 'SWI9X15C_05.05.66.00 r29972 CARMD-EV-FRMWR1 2015/10/08 08:36:28',
373 'Manufacturer': 'Sierra Wireless, Incorporated',
374 'Emergency': False,
375 'Interfaces': ['org.ofono.SmartMessaging',
376 'org.ofono.PushNotification',
377 'org.ofono.MessageManager',
378 'org.ofono.NetworkRegistration',
379 'org.ofono.ConnectionManager',
380 'org.ofono.SupplementaryServices',
381 'org.ofono.RadioSettings',
382 'org.ofono.AllowedAccessPoints',
383 'org.ofono.SimManager',
384 'org.ofono.LocationReporting',
385 'org.ofono.VoiceCallManager'],
386 'Serial': '356853054230919',
387 'Features': ['sms', 'net', 'gprs', 'ussd', 'rat', 'sim', 'gps'],
388 'Type': 'hardware',
389 'Online': True}
390 '''
391 return self.dbus.properties(*args, **kwargs)
392
393 def set_powered(self, powered=True):
394 return self.dbus.set_powered(powered=powered)
395
396 def set_online(self, online=True):
397 return self.dbus.set_online(online=online)
398
399 def is_powered(self):
400 return self.dbus.is_powered()
401
402 def is_online(self):
403 return self.dbus.is_online()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200404
405 def set_msisdn(self, msisdn):
406 self.msisdn = msisdn
407
408 def imsi(self):
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100409 if self._imsi is None:
410 if 'sim' in self.features():
411 if not self.is_powered():
412 self.set_powered()
413 # wait for SimManager iface to appear after we power on
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200414 MainLoop.wait(self, self.dbus.has_interface, I_SIMMGR, timeout=10)
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100415 simmgr = self.dbus.interface(I_SIMMGR)
416 # If properties are requested quickly, it may happen that Sim property is still not there.
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200417 MainLoop.wait(self, lambda: simmgr.GetProperties().get('SubscriberIdentity', None) is not None, timeout=10)
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100418 props = simmgr.GetProperties()
419 self.dbg('got SIM properties', props)
420 self._imsi = props.get('SubscriberIdentity', None)
421 else:
422 self._imsi = self.conf.get('imsi')
423 if self._imsi is None:
424 raise log.Error('No IMSI')
425 return self._imsi
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200426
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200427 def set_ki(self, ki):
428 self._ki = ki
429
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200430 def ki(self):
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200431 if self._ki is not None:
432 return self._ki
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200433 return self.conf.get('ki')
434
Pau Espin Pedrol713ce2c2017-08-24 16:57:17 +0200435 def auth_algo(self):
436 return self.conf.get('auth_algo', None)
437
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100438 def features(self):
439 return self.conf.get('features', [])
440
441 def _required_ifaces(self):
442 req_ifaces = (I_NETREG,)
443 req_ifaces += (I_SMS,) if 'sms' in self.features() else ()
444 req_ifaces += (I_SS,) if 'ussd' in self.features() else ()
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100445 req_ifaces += (I_CONNMGR,) if 'gprs' in self.features() else ()
Pau Espin Pedrolbfd0b232018-03-13 18:32:57 +0100446 req_ifaces += (I_SIMMGR,) if 'sim' in self.features() else ()
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100447 return req_ifaces
448
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200449 def _on_netreg_property_changed(self, name, value):
450 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_NETREG, name, value))
451
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200452 def is_connected(self, mcc_mnc=None):
453 netreg = self.dbus.interface(I_NETREG)
454 prop = netreg.GetProperties()
455 status = prop.get('Status')
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200456 self.dbg('status:', status)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200457 if not (status == NETREG_ST_REGISTERED or status == NETREG_ST_ROAMING):
458 return False
459 if mcc_mnc is None: # Any network is fine and we are registered.
460 return True
461 mcc = prop.get('MobileCountryCode')
462 mnc = prop.get('MobileNetworkCode')
463 if (mcc, mnc) == mcc_mnc:
464 return True
465 return False
466
467 def schedule_scan_register(self, mcc_mnc):
468 if self.register_attempts > NETREG_MAX_REGISTER_ATTEMPTS:
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200469 raise log.Error('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200470 self.register_attempts += 1
471 netreg = self.dbus.interface(I_NETREG)
472 self.dbg('Scanning for operators...')
473 # Scan method can take several seconds, and we don't want to block
474 # waiting for that. Make it async and try to register when the scan is
475 # finished.
476 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 +0200477 result_handler = lambda obj, result, user_data: MainLoop.defer(register_func, result, user_data)
478 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 +0200479 dbus_async_call(netreg, netreg.Scan, timeout=30, cancellable=self.cancellable,
480 result_handler=result_handler, error_handler=error_handler,
481 user_data=mcc_mnc)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200482
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200483 def scan_cb_error_handler(self, e, mcc_mnc):
484 # It was detected that Scan() method can fail for some modems on some
485 # specific circumstances. For instance it fails with org.ofono.Error.Failed
486 # if the modem starts to register internally after we started Scan() and
487 # the registering succeeds while we are still waiting for Scan() to finsih.
488 # So far the easiest seems to check if we are now registered and
489 # otherwise schedule a scan again.
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200490 self.err('Scan() failed, retrying if needed:', e)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200491 if not self.is_connected(mcc_mnc):
492 self.schedule_scan_register(mcc_mnc)
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200493 else:
494 self.log('Already registered with network', mcc_mnc)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200495
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200496 def scan_cb_register_automatic(self, scanned_operators, mcc_mnc):
497 self.dbg('scanned operators: ', scanned_operators);
498 for op_path, op_prop in scanned_operators:
499 if op_prop.get('Status') == 'current':
500 mcc = op_prop.get('MobileCountryCode')
501 mnc = op_prop.get('MobileNetworkCode')
502 self.log('Already registered with network', (mcc, mnc))
503 return
504 self.log('Registering with the default network')
505 netreg = self.dbus.interface(I_NETREG)
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200506 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', netreg.Register)
507
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200508
509 def scan_cb_register(self, scanned_operators, mcc_mnc):
510 self.dbg('scanned operators: ', scanned_operators);
511 matching_op_path = None
512 for op_path, op_prop in scanned_operators:
513 mcc = op_prop.get('MobileCountryCode')
514 mnc = op_prop.get('MobileNetworkCode')
515 if (mcc, mnc) == mcc_mnc:
516 if op_prop.get('Status') == 'current':
517 self.log('Already registered with network', mcc_mnc)
518 # We discovered the network and we are already registered
519 # with it. Avoid calling op.Register() in this case (it
520 # won't act as a NO-OP, it actually returns an error).
521 return
522 matching_op_path = op_path
523 break
524 if matching_op_path is None:
525 self.dbg('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
526 self.schedule_scan_register(mcc_mnc)
527 return
528 dbus_op = systembus_get(matching_op_path)
529 self.log('Registering with operator', matching_op_path, mcc_mnc)
Pau Espin Pedrol9f59b822017-11-07 17:50:52 +0100530 try:
531 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', dbus_op.Register)
532 except GLib.Error as e:
533 if Gio.DBusError.is_remote_error(e) and Gio.DBusError.get_remote_error(e) == 'org.ofono.Error.NotSupported':
534 self.log('modem does not support manual registering, attempting automatic registering')
535 self.scan_cb_register_automatic(scanned_operators, mcc_mnc)
536 return
537 raise e
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200538
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200539 def cancel_pending_dbus_methods(self):
540 self.cancellable.cancel()
541 # Cancel op is applied as a signal coming from glib mainloop, so we
542 # need to run it and wait for the callbacks to handle cancellations.
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200543 MainLoop.poll()
Pau Espin Pedrole685c622017-10-04 18:30:22 +0200544 # once it has been triggered, create a new one for next operation:
545 self.cancellable = Gio.Cancellable.new()
Pau Espin Pedrol6680ef22017-09-11 01:24:05 +0200546
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100547 def power_off(self):
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100548 if self.dbus.has_interface(I_CONNMGR) and self.is_attached():
549 self.detach()
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100550 self.set_online(False)
551 self.set_powered(False)
552 req_ifaces = self._required_ifaces()
553 for iface in req_ifaces:
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200554 MainLoop.wait(self, lambda: not self.dbus.has_interface(iface), timeout=10)
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100555
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200556 def power_cycle(self):
557 'Power the modem and put it online, power cycle it if it was already on'
Pau Espin Pedrole0f49862017-11-23 11:37:34 +0100558 req_ifaces = self._required_ifaces()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200559 if self.is_powered():
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200560 self.dbg('Power cycling')
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200561 MainLoop.sleep(self, 1.0) # workaround for ofono bug OS#3064
Pau Espin Pedrol7aef3862017-11-23 12:15:55 +0100562 self.power_off()
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200563 else:
564 self.dbg('Powering on')
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200565 self.set_powered()
Pau Espin Pedrolb9955762017-05-02 09:39:27 +0200566 self.set_online()
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200567 MainLoop.wait(self, self.dbus.has_interface, *req_ifaces, timeout=10)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200568
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200569 def connect(self, mcc_mnc=None):
570 'Connect to MCC+MNC'
571 if (mcc_mnc is not None) and (len(mcc_mnc) != 2 or None in mcc_mnc):
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200572 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 +0200573 # if test called connect() before and async scanning has not finished, we need to get rid of it:
574 self.cancel_pending_dbus_methods()
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200575 self.power_cycle()
576 self.register_attempts = 0
577 if self.is_connected(mcc_mnc):
578 self.log('Already registered with', mcc_mnc if mcc_mnc else 'default network')
579 else:
580 self.log('Connect to', mcc_mnc if mcc_mnc else 'default network')
581 self.schedule_scan_register(mcc_mnc)
582
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100583 def is_attached(self):
584 connmgr = self.dbus.interface(I_CONNMGR)
585 prop = connmgr.GetProperties()
586 attached = prop.get('Attached')
587 self.dbg('attached:', attached)
588 return attached
589
590 def attach(self, allow_roaming=False):
591 self.dbg('attach')
592 if self.is_attached():
593 self.detach()
594 connmgr = self.dbus.interface(I_CONNMGR)
595 prop = connmgr.SetProperty('RoamingAllowed', Variant('b', allow_roaming))
596 prop = connmgr.SetProperty('Powered', Variant('b', True))
597
598 def detach(self):
599 self.dbg('detach')
600 connmgr = self.dbus.interface(I_CONNMGR)
601 prop = connmgr.SetProperty('RoamingAllowed', Variant('b', False))
602 prop = connmgr.SetProperty('Powered', Variant('b', False))
603 connmgr.DeactivateAll()
604 connmgr.ResetContexts() # Requires Powered=false
605
606 def activate_context(self, apn='internet', user='ogt', pwd='', protocol='ip'):
Pau Espin Pedrolb05e36a2017-12-15 12:39:36 +0100607 self.dbg('activate_context', apn=apn, user=user, protocol=protocol)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100608
609 connmgr = self.dbus.interface(I_CONNMGR)
610 ctx_path = connmgr.AddContext('internet')
611
612 ctx = systembus_get(ctx_path)
613 ctx.SetProperty('AccessPointName', Variant('s', apn))
614 ctx.SetProperty('Username', Variant('s', user))
615 ctx.SetProperty('Password', Variant('s', pwd))
616 ctx.SetProperty('Protocol', Variant('s', protocol))
617
618 # Activate can only be called after we are attached
619 ctx.SetProperty('Active', Variant('b', True))
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200620 MainLoop.wait(self, lambda: ctx.GetProperties()['Active'] == True)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100621 self.log('context activated', path=ctx_path, apn=apn, user=user, properties=ctx.GetProperties())
622 return ctx_path
623
624 def deactivate_context(self, ctx_id):
Pau Espin Pedrol263dd3b2018-02-13 16:53:51 +0100625 self.dbg('deactivate_context', path=ctx_id)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100626 ctx = systembus_get(ctx_id)
627 ctx.SetProperty('Active', Variant('b', False))
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200628 MainLoop.wait(self, lambda: ctx.GetProperties()['Active'] == False)
Pau Espin Pedrolcdac2972018-02-16 15:14:32 +0100629 self.dbg('deactivate_context active=false, removing', path=ctx_id)
630 connmgr = self.dbus.interface(I_CONNMGR)
631 connmgr.RemoveContext(ctx_id)
Pau Espin Pedrolb05aa3c2018-02-16 15:03:50 +0100632 self.log('context deactivated', path=ctx_id)
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100633
Neels Hofmeyr8c7477f2017-05-25 04:33:53 +0200634 def sms_send(self, to_msisdn_or_modem, *tokens):
635 if isinstance(to_msisdn_or_modem, Modem):
636 to_msisdn = to_msisdn_or_modem.msisdn
637 tokens = list(tokens)
638 tokens.append('to ' + to_msisdn_or_modem.name())
639 else:
640 to_msisdn = str(to_msisdn_or_modem)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200641 msg = sms.Sms(self.msisdn, to_msisdn, 'from ' + self.name(), *tokens)
642 self.log('sending sms to MSISDN', to_msisdn, sms=msg)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200643 mm = self.dbus.interface(I_SMS)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200644 mm.SendMessage(to_msisdn, str(msg))
645 return msg
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200646
647 def _on_incoming_message(self, message, info):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200648 self.log('Incoming SMS:', repr(message))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200649 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200650 self.sms_received_list.append((message, info))
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200651
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200652 def sms_was_received(self, sms_obj):
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200653 for msg, info in self.sms_received_list:
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200654 if sms_obj.matches(msg):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200655 self.log('SMS received as expected:', repr(msg))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200656 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200657 return True
658 return False
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200659
Pau Espin Pedrold71edd12017-10-06 13:53:54 +0200660 def call_id_list(self):
661 self.dbg('call_id_list: %r' % self.call_list)
662 return self.call_list
663
664 def call_dial(self, to_msisdn_or_modem):
665 if isinstance(to_msisdn_or_modem, Modem):
666 to_msisdn = to_msisdn_or_modem.msisdn
667 else:
668 to_msisdn = str(to_msisdn_or_modem)
669 self.dbg('Dialing:', to_msisdn)
670 cmgr = self.dbus.interface(I_CALLMGR)
671 call_obj_path = cmgr.Dial(to_msisdn, 'default')
672 if call_obj_path not in self.call_list:
673 self.dbg('Adding %s to call list' % call_obj_path)
674 self.call_list.append(call_obj_path)
675 else:
676 self.dbg('Dial returned already existing call')
677 return call_obj_path
678
679 def _find_call_msisdn_state(self, msisdn, state):
680 cmgr = self.dbus.interface(I_CALLMGR)
681 ret = cmgr.GetCalls()
682 for obj_path, props in ret:
683 if props['LineIdentification'] == msisdn and props['State'] == state:
684 return obj_path
685 return None
686
687 def call_wait_incoming(self, caller_msisdn_or_modem, timeout=60):
688 if isinstance(caller_msisdn_or_modem, Modem):
689 caller_msisdn = caller_msisdn_or_modem.msisdn
690 else:
691 caller_msisdn = str(caller_msisdn_or_modem)
692 self.dbg('Waiting for incoming call from:', caller_msisdn)
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200693 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 +0200694 return self._find_call_msisdn_state(caller_msisdn, 'incoming')
695
696 def call_answer(self, call_id):
697 self.dbg('Answer call %s' % call_id)
698 assert self.call_state(call_id) == 'incoming'
699 call_dbus_obj = systembus_get(call_id)
700 call_dbus_obj.Answer()
701
702 def call_hangup(self, call_id):
703 self.dbg('Hang up call %s' % call_id)
704 call_dbus_obj = systembus_get(call_id)
705 call_dbus_obj.Hangup()
706
707 def call_is_active(self, call_id):
708 return self.call_state(call_id) == 'active'
709
710 def call_state(self, call_id):
711 call_dbus_obj = systembus_get(call_id)
712 props = call_dbus_obj.GetProperties()
713 state = props.get('State')
714 self.dbg('call state: %s' % state)
715 return state
716
717 def _on_callmgr_call_added(self, obj_path, properties):
718 self.dbg('%r.CallAdded() -> %s=%r' % (I_CALLMGR, obj_path, repr(properties)))
719 if obj_path not in self.call_list:
720 self.call_list.append(obj_path)
721 else:
722 self.dbg('Call already exists %r' % obj_path)
723
724 def _on_callmgr_call_removed(self, obj_path):
725 self.dbg('%r.CallRemoved() -> %s' % (I_CALLMGR, obj_path))
726 if obj_path in self.call_list:
727 self.call_list.remove(obj_path)
728 else:
729 self.dbg('Trying to remove non-existing call %r' % obj_path)
730
731 def _on_callmgr_property_changed(self, name, value):
732 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_CALLMGR, name, value))
733
Pau Espin Pedrolde899612017-11-23 17:18:40 +0100734 def _on_connmgr_property_changed(self, name, value):
735 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_CONNMGR, name, value))
736
Pau Espin Pedrolee6e4912017-09-05 18:46:34 +0200737 def info(self, keys=('Manufacturer', 'Model', 'Revision', 'Serial')):
Neels Hofmeyrb8011692017-05-29 03:45:24 +0200738 props = self.properties()
739 return ', '.join(['%s: %r'%(k,props.get(k)) for k in keys])
740
741 def log_info(self, *args, **kwargs):
742 self.log(self.info(*args, **kwargs))
743
Pau Espin Pedrol03983aa2017-06-12 15:31:27 +0200744 def ussd_send(self, command):
745 ss = self.dbus.interface(I_SS)
746 service_type, response = ss.Initiate(command)
747 return response
748
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200749# vim: expandtab tabstop=4 shiftwidth=4