blob: 43aa0913c70a9927b8ee8115684b0786c26b5fae [file] [log] [blame]
Neels Hofmeyr3531a192017-03-28 14:30:28 +02001# osmo_gsm_tester: DBUS client to talk to ofono
2#
3# Copyright (C) 2016-2017 by sysmocom - s.f.m.c. GmbH
4#
5# Author: Neels Hofmeyr <neels@hofmeyr.de>
6#
7# This program is free software: you can redistribute it and/or modify
Harald Welte27205342017-06-03 09:51:45 +02008# it under the terms of the GNU General Public License as
Neels Hofmeyr3531a192017-03-28 14:30:28 +02009# published by the Free Software Foundation, either version 3 of the
10# License, or (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Harald Welte27205342017-06-03 09:51:45 +020015# GNU General Public License for more details.
Neels Hofmeyr3531a192017-03-28 14:30:28 +020016#
Harald Welte27205342017-06-03 09:51:45 +020017# You should have received a copy of the GNU General Public License
Neels Hofmeyr3531a192017-03-28 14:30:28 +020018# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
Pau Espin Pedrol996651a2017-05-30 15:13:29 +020020from . import log, test, util, event_loop, sms
Neels Hofmeyr3531a192017-03-28 14:30:28 +020021
22from pydbus import SystemBus, Variant
23import time
24import pprint
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020025import sys
Neels Hofmeyr3531a192017-03-28 14:30:28 +020026
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +020027# Required for Gio.Cancellable.
28# See https://lazka.github.io/pgi-docs/Gio-2.0/classes/Cancellable.html#Gio.Cancellable
29from gi.module import get_introspection_module
30Gio = get_introspection_module('Gio')
31
Neels Hofmeyr3531a192017-03-28 14:30:28 +020032from gi.repository import GLib
33glib_main_loop = GLib.MainLoop()
34glib_main_ctx = glib_main_loop.get_context()
35bus = SystemBus()
36
Pau Espin Pedrol504a6642017-05-04 11:38:23 +020037I_MODEM = 'org.ofono.Modem'
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +020038I_NETREG = 'org.ofono.NetworkRegistration'
39I_SMS = 'org.ofono.MessageManager'
40
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020041# See https://github.com/intgr/ofono/blob/master/doc/network-api.txt#L78
42NETREG_ST_REGISTERED = 'registered'
43NETREG_ST_ROAMING = 'roaming'
44
45NETREG_MAX_REGISTER_ATTEMPTS = 3
46
Neels Hofmeyr035cda82017-05-05 17:52:45 +020047class DeferredHandling:
48 defer_queue = []
49
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):
55 DeferredHandling.defer_queue.append((self.handler, args, kwargs))
56
57 @staticmethod
58 def handle_queue():
59 while DeferredHandling.defer_queue:
60 handler, args, kwargs = DeferredHandling.defer_queue.pop(0)
61 handler(*args, **kwargs)
62
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020063def defer(handler, *args, **kwargs):
64 DeferredHandling.defer_queue.append((handler, args, kwargs))
65
Neels Hofmeyr035cda82017-05-05 17:52:45 +020066def dbus_connect(dbus_iface, handler):
67 '''This function shall be used instead of directly connecting DBus signals.
68 It ensures that we don't nest a glib main loop within another, and also
69 that we receive exceptions raised within the signal handlers. This makes it
70 so that a signal handler is invoked only after the DBus polling is through
71 by enlisting signals that should be handled in the
72 DeferredHandling.defer_queue.'''
Neels Hofmeyr47de6b02017-05-10 13:24:05 +020073 return DeferredHandling(dbus_iface, handler).subscription_id
Neels Hofmeyr035cda82017-05-05 17:52:45 +020074
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020075def poll_glib():
Neels Hofmeyr3531a192017-03-28 14:30:28 +020076 global glib_main_ctx
77 while glib_main_ctx.pending():
78 glib_main_ctx.iteration()
Neels Hofmeyr035cda82017-05-05 17:52:45 +020079 DeferredHandling.handle_queue()
Neels Hofmeyr3531a192017-03-28 14:30:28 +020080
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020081event_loop.register_poll_func(poll_glib)
82
Neels Hofmeyr93f58662017-05-03 16:32:16 +020083def systembus_get(path):
Neels Hofmeyr3531a192017-03-28 14:30:28 +020084 global bus
85 return bus.get('org.ofono', path)
86
87def list_modems():
Neels Hofmeyr93f58662017-05-03 16:32:16 +020088 root = systembus_get('/')
Neels Hofmeyr3531a192017-03-28 14:30:28 +020089 return sorted(root.GetModems())
90
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +020091def _async_result_handler(obj, result, user_data):
92 '''Generic callback dispatcher called from glib loop when an async method
93 call has returned. This callback is set up by method dbus_async_call.'''
94 (result_callback, error_callback, real_user_data) = user_data
95 try:
96 ret = obj.call_finish(result)
97 except Exception as e:
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +020098 if isinstance(e, GLib.Error) and e.code == Gio.IOErrorEnum.CANCELLED:
99 log.dbg('DBus method cancelled')
100 return
101
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200102 if error_callback:
103 error_callback(obj, e, real_user_data)
104 else:
105 result_callback(obj, e, real_user_data)
106 return
107
108 ret = ret.unpack()
109 # to be compatible with standard Python behaviour, unbox
110 # single-element tuples and return None for empty result tuples
111 if len(ret) == 1:
112 ret = ret[0]
113 elif len(ret) == 0:
114 ret = None
115 result_callback(obj, ret, real_user_data)
116
117def dbus_async_call(instance, proxymethod, *proxymethod_args,
118 result_handler=None, error_handler=None,
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200119 user_data=None, timeout=30, cancellable=None,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200120 **proxymethod_kwargs):
121 '''pydbus doesn't support asynchronous methods. This method adds support for
122 it until pydbus implements it'''
123
124 argdiff = len(proxymethod_args) - len(proxymethod._inargs)
125 if argdiff < 0:
126 raise TypeError(proxymethod.__qualname__ + " missing {} required positional argument(s)".format(-argdiff))
127 elif argdiff > 0:
128 raise TypeError(proxymethod.__qualname__ + " takes {} positional argument(s) but {} was/were given".format(len(proxymethod._inargs), len(proxymethod_args)))
129
130 timeout = timeout * 1000
131 user_data = (result_handler, error_handler, user_data)
132
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200133 # See https://lazka.github.io/pgi-docs/Gio-2.0/classes/DBusProxy.html#Gio.DBusProxy.call
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200134 ret = instance._bus.con.call(
135 instance._bus_name, instance._path,
136 proxymethod._iface_name, proxymethod.__name__,
137 GLib.Variant(proxymethod._sinargs, proxymethod_args),
138 GLib.VariantType.new(proxymethod._soutargs),
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200139 0, timeout, cancellable,
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200140 _async_result_handler, user_data)
141
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200142def dbus_call_dismiss_error(log_obj, err_str, method):
143 try:
144 method()
145 except Exception as e:
146 if isinstance(e, GLib.Error) and err_str in e.domain:
147 log_obj.log('Dismissed Dbus method error: %r' % e)
148 return
149 raise log.Error('dbus_call_dismiss_error raised error %r' % e)
150
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200151class ModemDbusInteraction(log.Origin):
152 '''Work around inconveniences specific to pydbus and ofono.
153 ofono adds and removes DBus interfaces and notifies about them.
154 Upon changes we need a fresh pydbus object to benefit from that.
155 Watching the interfaces change is optional; be sure to call
156 watch_interfaces() if you'd like to have signals subscribed.
157 Related: https://github.com/LEW21/pydbus/issues/56
158 '''
159
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200160 modem_path = None
161 watch_props_subscription = None
162 _dbus_obj = None
163 interfaces = None
164
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200165 def __init__(self, modem_path):
166 self.modem_path = modem_path
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200167 super().__init__(log.C_BUS, self.modem_path)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200168 self.interfaces = set()
169
170 # A dict listing signal handlers to connect, e.g.
171 # { I_SMS: ( ('IncomingMessage', self._on_incoming_message), ), }
172 self.required_signals = {}
173
174 # A dict collecting subscription tokens for connected signal handlers.
175 # { I_SMS: ( token1, token2, ... ), }
176 self.connected_signals = util.listdict()
177
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200178 def cleanup(self):
Pau Espin Pedrol58ff38d2017-06-23 13:10:38 +0200179 self.set_powered(False)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200180 self.unwatch_interfaces()
181 for interface_name in list(self.connected_signals.keys()):
182 self.remove_signals(interface_name)
183
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200184 def __del__(self):
185 self.cleanup()
186
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200187 def get_new_dbus_obj(self):
188 return systembus_get(self.modem_path)
189
190 def dbus_obj(self):
191 if self._dbus_obj is None:
192 self._dbus_obj = self.get_new_dbus_obj()
193 return self._dbus_obj
194
195 def interface(self, interface_name):
196 try:
197 return self.dbus_obj()[interface_name]
198 except KeyError:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200199 raise log.Error('Modem interface is not available:', interface_name)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200200
201 def signal(self, interface_name, signal):
202 return getattr(self.interface(interface_name), signal)
203
204 def watch_interfaces(self):
205 self.unwatch_interfaces()
206 # Note: we are watching the properties on a get_new_dbus_obj() that is
207 # separate from the one used to interact with interfaces. We need to
208 # refresh the pydbus object to interact with Interfaces that have newly
209 # appeared, but exchanging the DBus object to watch Interfaces being
210 # enabled and disabled is racy: we may skip some removals and
211 # additions. Hence do not exchange this DBus object. We don't even
212 # need to store the dbus object used for this, we will not touch it
213 # again. We only store the signal subscription.
214 self.watch_props_subscription = dbus_connect(self.get_new_dbus_obj().PropertyChanged,
215 self.on_property_change)
216 self.on_interfaces_change(self.properties().get('Interfaces'))
217
218 def unwatch_interfaces(self):
219 if self.watch_props_subscription is None:
220 return
221 self.watch_props_subscription.disconnect()
222 self.watch_props_subscription = None
223
224 def on_property_change(self, name, value):
225 if name == 'Interfaces':
226 self.on_interfaces_change(value)
227
228 def on_interfaces_change(self, interfaces_now):
229 # First some logging.
230 now = set(interfaces_now)
231 additions = now - self.interfaces
232 removals = self.interfaces - now
233 self.interfaces = now
234 if not (additions or removals):
235 # nothing changed.
236 return
237
238 if additions:
239 self.dbg('interface enabled:', ', '.join(sorted(additions)))
240
241 if removals:
242 self.dbg('interface disabled:', ', '.join(sorted(removals)))
243
244 # The dbus object is now stale and needs refreshing before we
245 # access the next interface function.
246 self._dbus_obj = None
247
248 # If an interface disappeared, disconnect the signal handlers for it.
249 # Even though we're going to use a fresh dbus object for new
250 # subscriptions, we will still keep active subscriptions alive on the
251 # old dbus object which will linger, associated with the respective
252 # signal subscription.
253 for removed in removals:
254 self.remove_signals(removed)
255
256 # Connect signals for added interfaces.
257 for interface_name in additions:
258 self.connect_signals(interface_name)
259
260 def remove_signals(self, interface_name):
261 got = self.connected_signals.pop(interface_name, [])
262
263 if not got:
264 return
265
266 self.dbg('Disconnecting', len(got), 'signals for', interface_name)
267 for subscription in got:
268 subscription.disconnect()
269
270 def connect_signals(self, interface_name):
271 # If an interface was added, it must not have existed before. For
272 # paranoia, make sure we have no handlers for those.
273 self.remove_signals(interface_name)
274
275 want = self.required_signals.get(interface_name, [])
276 if not want:
277 return
278
279 self.dbg('Connecting', len(want), 'signals for', interface_name)
280 for signal, cb in self.required_signals.get(interface_name, []):
281 subscription = dbus_connect(self.signal(interface_name, signal), cb)
282 self.connected_signals.add(interface_name, subscription)
283
284 def has_interface(self, *interface_names):
285 try:
286 for interface_name in interface_names:
287 self.dbus_obj()[interface_name]
288 result = True
289 except KeyError:
290 result = False
291 self.dbg('has_interface(%s) ==' % (', '.join(interface_names)), result)
292 return result
293
294 def properties(self, iface=I_MODEM):
295 return self.dbus_obj()[iface].GetProperties()
296
297 def property_is(self, name, val, iface=I_MODEM):
298 is_val = self.properties(iface).get(name)
299 self.dbg(name, '==', is_val)
300 return is_val is not None and is_val == val
301
302 def set_bool(self, name, bool_val, iface=I_MODEM):
303 # to make sure any pending signals are received before we send out more DBus requests
304 event_loop.poll()
305
306 val = bool(bool_val)
307 self.log('Setting', name, val)
308 self.interface(iface).SetProperty(name, Variant('b', val))
309
310 event_loop.wait(self, self.property_is, name, bool_val)
311
312 def set_powered(self, powered=True):
313 self.set_bool('Powered', powered)
314
315 def set_online(self, online=True):
316 self.set_bool('Online', online)
317
318 def is_powered(self):
319 return self.property_is('Powered', True)
320
321 def is_online(self):
322 return self.property_is('Online', True)
323
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200324
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200325
326class Modem(log.Origin):
327 'convenience for ofono Modem interaction'
328 msisdn = None
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200329 sms_received_list = None
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200330 _ki = None
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200331
332 def __init__(self, conf):
333 self.conf = conf
334 self.path = conf.get('path')
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200335 super().__init__(log.C_TST, self.path)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200336 self.sms_received_list = []
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200337 self.dbus = ModemDbusInteraction(self.path)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200338 self.register_attempts = 0
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), ),
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200344 }
345 self.dbus.watch_interfaces()
346
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200347 def cleanup(self):
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200348 self.dbg('cleanup')
349 if self.cancellable:
350 self.cancellable.cancel()
351 # Cancel op is applied as a signal coming from glib mainloop, so we
352 # need to run it and wait for the callbacks to handle cancellations.
353 poll_glib()
354 self.cancellable = None
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200355 self.dbus.cleanup()
356 self.dbus = None
357
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200358 def properties(self, *args, **kwargs):
359 '''Return a dict of properties on this modem. For the actual arguments,
360 see ModemDbusInteraction.properties(), which this function calls. The
361 returned dict is defined by ofono. An example is:
362 {'Lockdown': False,
363 'Powered': True,
364 'Model': 'MC7304',
365 'Revision': 'SWI9X15C_05.05.66.00 r29972 CARMD-EV-FRMWR1 2015/10/08 08:36:28',
366 'Manufacturer': 'Sierra Wireless, Incorporated',
367 'Emergency': False,
368 'Interfaces': ['org.ofono.SmartMessaging',
369 'org.ofono.PushNotification',
370 'org.ofono.MessageManager',
371 'org.ofono.NetworkRegistration',
372 'org.ofono.ConnectionManager',
373 'org.ofono.SupplementaryServices',
374 'org.ofono.RadioSettings',
375 'org.ofono.AllowedAccessPoints',
376 'org.ofono.SimManager',
377 'org.ofono.LocationReporting',
378 'org.ofono.VoiceCallManager'],
379 'Serial': '356853054230919',
380 'Features': ['sms', 'net', 'gprs', 'ussd', 'rat', 'sim', 'gps'],
381 'Type': 'hardware',
382 'Online': True}
383 '''
384 return self.dbus.properties(*args, **kwargs)
385
386 def set_powered(self, powered=True):
387 return self.dbus.set_powered(powered=powered)
388
389 def set_online(self, online=True):
390 return self.dbus.set_online(online=online)
391
392 def is_powered(self):
393 return self.dbus.is_powered()
394
395 def is_online(self):
396 return self.dbus.is_online()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200397
398 def set_msisdn(self, msisdn):
399 self.msisdn = msisdn
400
401 def imsi(self):
Neels Hofmeyrb02c2112017-04-09 18:46:48 +0200402 imsi = self.conf.get('imsi')
403 if not imsi:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200404 raise log.Error('No IMSI')
Neels Hofmeyrb02c2112017-04-09 18:46:48 +0200405 return imsi
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200406
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200407 def set_ki(self, ki):
408 self._ki = ki
409
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200410 def ki(self):
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200411 if self._ki is not None:
412 return self._ki
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200413 return self.conf.get('ki')
414
Pau Espin Pedrol713ce2c2017-08-24 16:57:17 +0200415 def auth_algo(self):
416 return self.conf.get('auth_algo', None)
417
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200418 def _on_netreg_property_changed(self, name, value):
419 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_NETREG, name, value))
420
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200421 def is_connected(self, mcc_mnc=None):
422 netreg = self.dbus.interface(I_NETREG)
423 prop = netreg.GetProperties()
424 status = prop.get('Status')
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200425 self.dbg('status:', status)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200426 if not (status == NETREG_ST_REGISTERED or status == NETREG_ST_ROAMING):
427 return False
428 if mcc_mnc is None: # Any network is fine and we are registered.
429 return True
430 mcc = prop.get('MobileCountryCode')
431 mnc = prop.get('MobileNetworkCode')
432 if (mcc, mnc) == mcc_mnc:
433 return True
434 return False
435
436 def schedule_scan_register(self, mcc_mnc):
437 if self.register_attempts > NETREG_MAX_REGISTER_ATTEMPTS:
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200438 raise log.Error('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200439 self.register_attempts += 1
440 netreg = self.dbus.interface(I_NETREG)
441 self.dbg('Scanning for operators...')
442 # Scan method can take several seconds, and we don't want to block
443 # waiting for that. Make it async and try to register when the scan is
444 # finished.
445 register_func = self.scan_cb_register_automatic if mcc_mnc is None else self.scan_cb_register
446 result_handler = lambda obj, result, user_data: defer(register_func, result, user_data)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200447 error_handler = lambda obj, e, user_data: defer(self.scan_cb_error_handler, e, mcc_mnc)
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200448 dbus_async_call(netreg, netreg.Scan, timeout=30, cancellable=self.cancellable,
449 result_handler=result_handler, error_handler=error_handler,
450 user_data=mcc_mnc)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200451
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200452 def scan_cb_error_handler(self, e, mcc_mnc):
453 # It was detected that Scan() method can fail for some modems on some
454 # specific circumstances. For instance it fails with org.ofono.Error.Failed
455 # if the modem starts to register internally after we started Scan() and
456 # the registering succeeds while we are still waiting for Scan() to finsih.
457 # So far the easiest seems to check if we are now registered and
458 # otherwise schedule a scan again.
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200459 self.err('Scan() failed, retrying if needed:', e)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200460 if not self.is_connected(mcc_mnc):
461 self.schedule_scan_register(mcc_mnc)
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200462 else:
463 self.log('Already registered with network', mcc_mnc)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200464
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200465 def scan_cb_register_automatic(self, scanned_operators, mcc_mnc):
466 self.dbg('scanned operators: ', scanned_operators);
467 for op_path, op_prop in scanned_operators:
468 if op_prop.get('Status') == 'current':
469 mcc = op_prop.get('MobileCountryCode')
470 mnc = op_prop.get('MobileNetworkCode')
471 self.log('Already registered with network', (mcc, mnc))
472 return
473 self.log('Registering with the default network')
474 netreg = self.dbus.interface(I_NETREG)
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200475 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', netreg.Register)
476
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200477
478 def scan_cb_register(self, scanned_operators, mcc_mnc):
479 self.dbg('scanned operators: ', scanned_operators);
480 matching_op_path = None
481 for op_path, op_prop in scanned_operators:
482 mcc = op_prop.get('MobileCountryCode')
483 mnc = op_prop.get('MobileNetworkCode')
484 if (mcc, mnc) == mcc_mnc:
485 if op_prop.get('Status') == 'current':
486 self.log('Already registered with network', mcc_mnc)
487 # We discovered the network and we are already registered
488 # with it. Avoid calling op.Register() in this case (it
489 # won't act as a NO-OP, it actually returns an error).
490 return
491 matching_op_path = op_path
492 break
493 if matching_op_path is None:
494 self.dbg('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
495 self.schedule_scan_register(mcc_mnc)
496 return
497 dbus_op = systembus_get(matching_op_path)
498 self.log('Registering with operator', matching_op_path, mcc_mnc)
Pau Espin Pedrol7423d2e2017-08-25 12:58:25 +0200499 dbus_call_dismiss_error(self, 'org.ofono.Error.InProgress', dbus_op.Register)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200500
501 def power_cycle(self):
502 'Power the modem and put it online, power cycle it if it was already on'
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200503 if self.is_powered():
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200504 self.dbg('Power cycling')
Pau Espin Pedrol107f2752017-05-04 11:37:16 +0200505 self.set_online(False)
506 self.set_powered(False)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200507 event_loop.wait(self, lambda: not self.dbus.has_interface(I_NETREG, I_SMS), timeout=10)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200508 else:
509 self.dbg('Powering on')
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200510 self.set_powered()
Pau Espin Pedrolb9955762017-05-02 09:39:27 +0200511 self.set_online()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200512 event_loop.wait(self, self.dbus.has_interface, I_NETREG, I_SMS, timeout=10)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200513
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200514 def connect(self, mcc_mnc=None):
515 'Connect to MCC+MNC'
516 if (mcc_mnc is not None) and (len(mcc_mnc) != 2 or None in mcc_mnc):
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200517 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 Pedrol0e57aad2017-05-29 14:25:22 +0200518 self.power_cycle()
519 self.register_attempts = 0
520 if self.is_connected(mcc_mnc):
521 self.log('Already registered with', mcc_mnc if mcc_mnc else 'default network')
522 else:
523 self.log('Connect to', mcc_mnc if mcc_mnc else 'default network')
524 self.schedule_scan_register(mcc_mnc)
525
Neels Hofmeyr8c7477f2017-05-25 04:33:53 +0200526 def sms_send(self, to_msisdn_or_modem, *tokens):
527 if isinstance(to_msisdn_or_modem, Modem):
528 to_msisdn = to_msisdn_or_modem.msisdn
529 tokens = list(tokens)
530 tokens.append('to ' + to_msisdn_or_modem.name())
531 else:
532 to_msisdn = str(to_msisdn_or_modem)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200533 msg = sms.Sms(self.msisdn, to_msisdn, 'from ' + self.name(), *tokens)
534 self.log('sending sms to MSISDN', to_msisdn, sms=msg)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200535 mm = self.dbus.interface(I_SMS)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200536 mm.SendMessage(to_msisdn, str(msg))
537 return msg
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200538
539 def _on_incoming_message(self, message, info):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200540 self.log('Incoming SMS:', repr(message))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200541 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200542 self.sms_received_list.append((message, info))
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200543
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200544 def sms_was_received(self, sms_obj):
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200545 for msg, info in self.sms_received_list:
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200546 if sms_obj.matches(msg):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200547 self.log('SMS received as expected:', repr(msg))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200548 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200549 return True
550 return False
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200551
Neels Hofmeyrb8011692017-05-29 03:45:24 +0200552 def info(self, keys=('Manufacturer', 'Model', 'Revision')):
553 props = self.properties()
554 return ', '.join(['%s: %r'%(k,props.get(k)) for k in keys])
555
556 def log_info(self, *args, **kwargs):
557 self.log(self.info(*args, **kwargs))
558
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200559# vim: expandtab tabstop=4 shiftwidth=4