blob: ed7e3e44b8318a53bbdc58d5912a1b9afa0041a0 [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
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)
218
219 def on_interfaces_change(self, interfaces_now):
220 # First some logging.
221 now = set(interfaces_now)
222 additions = now - self.interfaces
223 removals = self.interfaces - now
224 self.interfaces = now
225 if not (additions or removals):
226 # nothing changed.
227 return
228
229 if additions:
230 self.dbg('interface enabled:', ', '.join(sorted(additions)))
231
232 if removals:
233 self.dbg('interface disabled:', ', '.join(sorted(removals)))
234
235 # The dbus object is now stale and needs refreshing before we
236 # access the next interface function.
237 self._dbus_obj = None
238
239 # If an interface disappeared, disconnect the signal handlers for it.
240 # Even though we're going to use a fresh dbus object for new
241 # subscriptions, we will still keep active subscriptions alive on the
242 # old dbus object which will linger, associated with the respective
243 # signal subscription.
244 for removed in removals:
245 self.remove_signals(removed)
246
247 # Connect signals for added interfaces.
248 for interface_name in additions:
249 self.connect_signals(interface_name)
250
251 def remove_signals(self, interface_name):
252 got = self.connected_signals.pop(interface_name, [])
253
254 if not got:
255 return
256
257 self.dbg('Disconnecting', len(got), 'signals for', interface_name)
258 for subscription in got:
259 subscription.disconnect()
260
261 def connect_signals(self, interface_name):
262 # If an interface was added, it must not have existed before. For
263 # paranoia, make sure we have no handlers for those.
264 self.remove_signals(interface_name)
265
266 want = self.required_signals.get(interface_name, [])
267 if not want:
268 return
269
270 self.dbg('Connecting', len(want), 'signals for', interface_name)
271 for signal, cb in self.required_signals.get(interface_name, []):
272 subscription = dbus_connect(self.signal(interface_name, signal), cb)
273 self.connected_signals.add(interface_name, subscription)
274
275 def has_interface(self, *interface_names):
276 try:
277 for interface_name in interface_names:
278 self.dbus_obj()[interface_name]
279 result = True
280 except KeyError:
281 result = False
282 self.dbg('has_interface(%s) ==' % (', '.join(interface_names)), result)
283 return result
284
285 def properties(self, iface=I_MODEM):
286 return self.dbus_obj()[iface].GetProperties()
287
288 def property_is(self, name, val, iface=I_MODEM):
289 is_val = self.properties(iface).get(name)
290 self.dbg(name, '==', is_val)
291 return is_val is not None and is_val == val
292
293 def set_bool(self, name, bool_val, iface=I_MODEM):
294 # to make sure any pending signals are received before we send out more DBus requests
295 event_loop.poll()
296
297 val = bool(bool_val)
298 self.log('Setting', name, val)
299 self.interface(iface).SetProperty(name, Variant('b', val))
300
301 event_loop.wait(self, self.property_is, name, bool_val)
302
303 def set_powered(self, powered=True):
304 self.set_bool('Powered', powered)
305
306 def set_online(self, online=True):
307 self.set_bool('Online', online)
308
309 def is_powered(self):
310 return self.property_is('Powered', True)
311
312 def is_online(self):
313 return self.property_is('Online', True)
314
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200315
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200316
317class Modem(log.Origin):
318 'convenience for ofono Modem interaction'
319 msisdn = None
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200320 sms_received_list = None
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200321 _ki = None
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200322
323 def __init__(self, conf):
324 self.conf = conf
325 self.path = conf.get('path')
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200326 super().__init__(log.C_TST, self.path)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200327 self.sms_received_list = []
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200328 self.dbus = ModemDbusInteraction(self.path)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200329 self.register_attempts = 0
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200330 # one Cancellable can handle several concurrent methods.
331 self.cancellable = Gio.Cancellable.new()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200332 self.dbus.required_signals = {
333 I_SMS: ( ('IncomingMessage', self._on_incoming_message), ),
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200334 I_NETREG: ( ('PropertyChanged', self._on_netreg_property_changed), ),
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200335 }
336 self.dbus.watch_interfaces()
337
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200338 def cleanup(self):
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200339 self.dbg('cleanup')
340 if self.cancellable:
341 self.cancellable.cancel()
342 # Cancel op is applied as a signal coming from glib mainloop, so we
343 # need to run it and wait for the callbacks to handle cancellations.
344 poll_glib()
345 self.cancellable = None
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200346 self.dbus.cleanup()
347 self.dbus = None
348
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200349 def properties(self, *args, **kwargs):
350 '''Return a dict of properties on this modem. For the actual arguments,
351 see ModemDbusInteraction.properties(), which this function calls. The
352 returned dict is defined by ofono. An example is:
353 {'Lockdown': False,
354 'Powered': True,
355 'Model': 'MC7304',
356 'Revision': 'SWI9X15C_05.05.66.00 r29972 CARMD-EV-FRMWR1 2015/10/08 08:36:28',
357 'Manufacturer': 'Sierra Wireless, Incorporated',
358 'Emergency': False,
359 'Interfaces': ['org.ofono.SmartMessaging',
360 'org.ofono.PushNotification',
361 'org.ofono.MessageManager',
362 'org.ofono.NetworkRegistration',
363 'org.ofono.ConnectionManager',
364 'org.ofono.SupplementaryServices',
365 'org.ofono.RadioSettings',
366 'org.ofono.AllowedAccessPoints',
367 'org.ofono.SimManager',
368 'org.ofono.LocationReporting',
369 'org.ofono.VoiceCallManager'],
370 'Serial': '356853054230919',
371 'Features': ['sms', 'net', 'gprs', 'ussd', 'rat', 'sim', 'gps'],
372 'Type': 'hardware',
373 'Online': True}
374 '''
375 return self.dbus.properties(*args, **kwargs)
376
377 def set_powered(self, powered=True):
378 return self.dbus.set_powered(powered=powered)
379
380 def set_online(self, online=True):
381 return self.dbus.set_online(online=online)
382
383 def is_powered(self):
384 return self.dbus.is_powered()
385
386 def is_online(self):
387 return self.dbus.is_online()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200388
389 def set_msisdn(self, msisdn):
390 self.msisdn = msisdn
391
392 def imsi(self):
Neels Hofmeyrb02c2112017-04-09 18:46:48 +0200393 imsi = self.conf.get('imsi')
394 if not imsi:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200395 raise log.Error('No IMSI')
Neels Hofmeyrb02c2112017-04-09 18:46:48 +0200396 return imsi
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200397
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200398 def set_ki(self, ki):
399 self._ki = ki
400
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200401 def ki(self):
Pau Espin Pedrolcd6ad9d2017-08-22 19:10:20 +0200402 if self._ki is not None:
403 return self._ki
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200404 return self.conf.get('ki')
405
Pau Espin Pedrol713ce2c2017-08-24 16:57:17 +0200406 def auth_algo(self):
407 return self.conf.get('auth_algo', None)
408
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200409 def _on_netreg_property_changed(self, name, value):
410 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_NETREG, name, value))
411
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200412 def is_connected(self, mcc_mnc=None):
413 netreg = self.dbus.interface(I_NETREG)
414 prop = netreg.GetProperties()
415 status = prop.get('Status')
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200416 self.dbg('status:', status)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200417 if not (status == NETREG_ST_REGISTERED or status == NETREG_ST_ROAMING):
418 return False
419 if mcc_mnc is None: # Any network is fine and we are registered.
420 return True
421 mcc = prop.get('MobileCountryCode')
422 mnc = prop.get('MobileNetworkCode')
423 if (mcc, mnc) == mcc_mnc:
424 return True
425 return False
426
427 def schedule_scan_register(self, mcc_mnc):
428 if self.register_attempts > NETREG_MAX_REGISTER_ATTEMPTS:
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200429 raise log.Error('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200430 self.register_attempts += 1
431 netreg = self.dbus.interface(I_NETREG)
432 self.dbg('Scanning for operators...')
433 # Scan method can take several seconds, and we don't want to block
434 # waiting for that. Make it async and try to register when the scan is
435 # finished.
436 register_func = self.scan_cb_register_automatic if mcc_mnc is None else self.scan_cb_register
437 result_handler = lambda obj, result, user_data: defer(register_func, result, user_data)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200438 error_handler = lambda obj, e, user_data: defer(self.scan_cb_error_handler, e, mcc_mnc)
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200439 dbus_async_call(netreg, netreg.Scan, timeout=30, cancellable=self.cancellable,
440 result_handler=result_handler, error_handler=error_handler,
441 user_data=mcc_mnc)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200442
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200443 def scan_cb_error_handler(self, e, mcc_mnc):
444 # It was detected that Scan() method can fail for some modems on some
445 # specific circumstances. For instance it fails with org.ofono.Error.Failed
446 # if the modem starts to register internally after we started Scan() and
447 # the registering succeeds while we are still waiting for Scan() to finsih.
448 # So far the easiest seems to check if we are now registered and
449 # otherwise schedule a scan again.
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200450 self.err('Scan() failed, retrying if needed:', e)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200451 if not self.is_connected(mcc_mnc):
452 self.schedule_scan_register(mcc_mnc)
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200453 else:
454 self.log('Already registered with network', mcc_mnc)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200455
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200456 def scan_cb_register_automatic(self, scanned_operators, mcc_mnc):
457 self.dbg('scanned operators: ', scanned_operators);
458 for op_path, op_prop in scanned_operators:
459 if op_prop.get('Status') == 'current':
460 mcc = op_prop.get('MobileCountryCode')
461 mnc = op_prop.get('MobileNetworkCode')
462 self.log('Already registered with network', (mcc, mnc))
463 return
464 self.log('Registering with the default network')
465 netreg = self.dbus.interface(I_NETREG)
466 netreg.Register()
467
468 def scan_cb_register(self, scanned_operators, mcc_mnc):
469 self.dbg('scanned operators: ', scanned_operators);
470 matching_op_path = None
471 for op_path, op_prop in scanned_operators:
472 mcc = op_prop.get('MobileCountryCode')
473 mnc = op_prop.get('MobileNetworkCode')
474 if (mcc, mnc) == mcc_mnc:
475 if op_prop.get('Status') == 'current':
476 self.log('Already registered with network', mcc_mnc)
477 # We discovered the network and we are already registered
478 # with it. Avoid calling op.Register() in this case (it
479 # won't act as a NO-OP, it actually returns an error).
480 return
481 matching_op_path = op_path
482 break
483 if matching_op_path is None:
484 self.dbg('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
485 self.schedule_scan_register(mcc_mnc)
486 return
487 dbus_op = systembus_get(matching_op_path)
488 self.log('Registering with operator', matching_op_path, mcc_mnc)
489 dbus_op.Register()
490
491 def power_cycle(self):
492 'Power the modem and put it online, power cycle it if it was already on'
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200493 if self.is_powered():
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200494 self.dbg('Power cycling')
Pau Espin Pedrol107f2752017-05-04 11:37:16 +0200495 self.set_online(False)
496 self.set_powered(False)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200497 event_loop.wait(self, lambda: not self.dbus.has_interface(I_NETREG, I_SMS), timeout=10)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200498 else:
499 self.dbg('Powering on')
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200500 self.set_powered()
Pau Espin Pedrolb9955762017-05-02 09:39:27 +0200501 self.set_online()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200502 event_loop.wait(self, self.dbus.has_interface, I_NETREG, I_SMS, timeout=10)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200503
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200504 def connect(self, mcc_mnc=None):
505 'Connect to MCC+MNC'
506 if (mcc_mnc is not None) and (len(mcc_mnc) != 2 or None in mcc_mnc):
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200507 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 +0200508 self.power_cycle()
509 self.register_attempts = 0
510 if self.is_connected(mcc_mnc):
511 self.log('Already registered with', mcc_mnc if mcc_mnc else 'default network')
512 else:
513 self.log('Connect to', mcc_mnc if mcc_mnc else 'default network')
514 self.schedule_scan_register(mcc_mnc)
515
Neels Hofmeyr8c7477f2017-05-25 04:33:53 +0200516 def sms_send(self, to_msisdn_or_modem, *tokens):
517 if isinstance(to_msisdn_or_modem, Modem):
518 to_msisdn = to_msisdn_or_modem.msisdn
519 tokens = list(tokens)
520 tokens.append('to ' + to_msisdn_or_modem.name())
521 else:
522 to_msisdn = str(to_msisdn_or_modem)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200523 msg = sms.Sms(self.msisdn, to_msisdn, 'from ' + self.name(), *tokens)
524 self.log('sending sms to MSISDN', to_msisdn, sms=msg)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200525 mm = self.dbus.interface(I_SMS)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200526 mm.SendMessage(to_msisdn, str(msg))
527 return msg
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200528
529 def _on_incoming_message(self, message, info):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200530 self.log('Incoming SMS:', repr(message))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200531 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200532 self.sms_received_list.append((message, info))
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200533
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200534 def sms_was_received(self, sms_obj):
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200535 for msg, info in self.sms_received_list:
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200536 if sms_obj.matches(msg):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200537 self.log('SMS received as expected:', repr(msg))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200538 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200539 return True
540 return False
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200541
Neels Hofmeyrb8011692017-05-29 03:45:24 +0200542 def info(self, keys=('Manufacturer', 'Model', 'Revision')):
543 props = self.properties()
544 return ', '.join(['%s: %r'%(k,props.get(k)) for k in keys])
545
546 def log_info(self, *args, **kwargs):
547 self.log(self.info(*args, **kwargs))
548
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200549# vim: expandtab tabstop=4 shiftwidth=4