blob: 60f98df0cbf11e2267fba317ad28aedeae690722 [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
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200321
322 def __init__(self, conf):
323 self.conf = conf
324 self.path = conf.get('path')
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200325 super().__init__(log.C_TST, self.path)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200326 self.sms_received_list = []
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200327 self.dbus = ModemDbusInteraction(self.path)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200328 self.register_attempts = 0
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200329 # one Cancellable can handle several concurrent methods.
330 self.cancellable = Gio.Cancellable.new()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200331 self.dbus.required_signals = {
332 I_SMS: ( ('IncomingMessage', self._on_incoming_message), ),
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200333 I_NETREG: ( ('PropertyChanged', self._on_netreg_property_changed), ),
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200334 }
335 self.dbus.watch_interfaces()
336
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200337 def cleanup(self):
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200338 self.dbg('cleanup')
339 if self.cancellable:
340 self.cancellable.cancel()
341 # Cancel op is applied as a signal coming from glib mainloop, so we
342 # need to run it and wait for the callbacks to handle cancellations.
343 poll_glib()
344 self.cancellable = None
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200345 self.dbus.cleanup()
346 self.dbus = None
347
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200348 def properties(self, *args, **kwargs):
349 '''Return a dict of properties on this modem. For the actual arguments,
350 see ModemDbusInteraction.properties(), which this function calls. The
351 returned dict is defined by ofono. An example is:
352 {'Lockdown': False,
353 'Powered': True,
354 'Model': 'MC7304',
355 'Revision': 'SWI9X15C_05.05.66.00 r29972 CARMD-EV-FRMWR1 2015/10/08 08:36:28',
356 'Manufacturer': 'Sierra Wireless, Incorporated',
357 'Emergency': False,
358 'Interfaces': ['org.ofono.SmartMessaging',
359 'org.ofono.PushNotification',
360 'org.ofono.MessageManager',
361 'org.ofono.NetworkRegistration',
362 'org.ofono.ConnectionManager',
363 'org.ofono.SupplementaryServices',
364 'org.ofono.RadioSettings',
365 'org.ofono.AllowedAccessPoints',
366 'org.ofono.SimManager',
367 'org.ofono.LocationReporting',
368 'org.ofono.VoiceCallManager'],
369 'Serial': '356853054230919',
370 'Features': ['sms', 'net', 'gprs', 'ussd', 'rat', 'sim', 'gps'],
371 'Type': 'hardware',
372 'Online': True}
373 '''
374 return self.dbus.properties(*args, **kwargs)
375
376 def set_powered(self, powered=True):
377 return self.dbus.set_powered(powered=powered)
378
379 def set_online(self, online=True):
380 return self.dbus.set_online(online=online)
381
382 def is_powered(self):
383 return self.dbus.is_powered()
384
385 def is_online(self):
386 return self.dbus.is_online()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200387
388 def set_msisdn(self, msisdn):
389 self.msisdn = msisdn
390
391 def imsi(self):
Neels Hofmeyrb02c2112017-04-09 18:46:48 +0200392 imsi = self.conf.get('imsi')
393 if not imsi:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200394 raise log.Error('No IMSI')
Neels Hofmeyrb02c2112017-04-09 18:46:48 +0200395 return imsi
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200396
397 def ki(self):
398 return self.conf.get('ki')
399
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200400 def _on_netreg_property_changed(self, name, value):
401 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_NETREG, name, value))
402
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200403 def is_connected(self, mcc_mnc=None):
404 netreg = self.dbus.interface(I_NETREG)
405 prop = netreg.GetProperties()
406 status = prop.get('Status')
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200407 self.dbg('status:', status)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200408 if not (status == NETREG_ST_REGISTERED or status == NETREG_ST_ROAMING):
409 return False
410 if mcc_mnc is None: # Any network is fine and we are registered.
411 return True
412 mcc = prop.get('MobileCountryCode')
413 mnc = prop.get('MobileNetworkCode')
414 if (mcc, mnc) == mcc_mnc:
415 return True
416 return False
417
418 def schedule_scan_register(self, mcc_mnc):
419 if self.register_attempts > NETREG_MAX_REGISTER_ATTEMPTS:
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200420 raise log.Error('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200421 self.register_attempts += 1
422 netreg = self.dbus.interface(I_NETREG)
423 self.dbg('Scanning for operators...')
424 # Scan method can take several seconds, and we don't want to block
425 # waiting for that. Make it async and try to register when the scan is
426 # finished.
427 register_func = self.scan_cb_register_automatic if mcc_mnc is None else self.scan_cb_register
428 result_handler = lambda obj, result, user_data: defer(register_func, result, user_data)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200429 error_handler = lambda obj, e, user_data: defer(self.scan_cb_error_handler, e, mcc_mnc)
Pau Espin Pedrolfbecf412017-06-14 12:14:53 +0200430 dbus_async_call(netreg, netreg.Scan, timeout=30, cancellable=self.cancellable,
431 result_handler=result_handler, error_handler=error_handler,
432 user_data=mcc_mnc)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200433
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200434 def scan_cb_error_handler(self, e, mcc_mnc):
435 # It was detected that Scan() method can fail for some modems on some
436 # specific circumstances. For instance it fails with org.ofono.Error.Failed
437 # if the modem starts to register internally after we started Scan() and
438 # the registering succeeds while we are still waiting for Scan() to finsih.
439 # So far the easiest seems to check if we are now registered and
440 # otherwise schedule a scan again.
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200441 self.err('Scan() failed, retrying if needed:', e)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200442 if not self.is_connected(mcc_mnc):
443 self.schedule_scan_register(mcc_mnc)
Pau Espin Pedrol910f3a12017-06-13 16:59:19 +0200444 else:
445 self.log('Already registered with network', mcc_mnc)
Pau Espin Pedrol4d63d922017-06-13 16:23:23 +0200446
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200447 def scan_cb_register_automatic(self, scanned_operators, mcc_mnc):
448 self.dbg('scanned operators: ', scanned_operators);
449 for op_path, op_prop in scanned_operators:
450 if op_prop.get('Status') == 'current':
451 mcc = op_prop.get('MobileCountryCode')
452 mnc = op_prop.get('MobileNetworkCode')
453 self.log('Already registered with network', (mcc, mnc))
454 return
455 self.log('Registering with the default network')
456 netreg = self.dbus.interface(I_NETREG)
457 netreg.Register()
458
459 def scan_cb_register(self, scanned_operators, mcc_mnc):
460 self.dbg('scanned operators: ', scanned_operators);
461 matching_op_path = None
462 for op_path, op_prop in scanned_operators:
463 mcc = op_prop.get('MobileCountryCode')
464 mnc = op_prop.get('MobileNetworkCode')
465 if (mcc, mnc) == mcc_mnc:
466 if op_prop.get('Status') == 'current':
467 self.log('Already registered with network', mcc_mnc)
468 # We discovered the network and we are already registered
469 # with it. Avoid calling op.Register() in this case (it
470 # won't act as a NO-OP, it actually returns an error).
471 return
472 matching_op_path = op_path
473 break
474 if matching_op_path is None:
475 self.dbg('Failed to find Network Operator', mcc_mnc=mcc_mnc, attempts=self.register_attempts)
476 self.schedule_scan_register(mcc_mnc)
477 return
478 dbus_op = systembus_get(matching_op_path)
479 self.log('Registering with operator', matching_op_path, mcc_mnc)
480 dbus_op.Register()
481
482 def power_cycle(self):
483 'Power the modem and put it online, power cycle it if it was already on'
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200484 if self.is_powered():
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200485 self.dbg('Power cycling')
Pau Espin Pedrol107f2752017-05-04 11:37:16 +0200486 self.set_online(False)
487 self.set_powered(False)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200488 event_loop.wait(self, lambda: not self.dbus.has_interface(I_NETREG, I_SMS), timeout=10)
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200489 else:
490 self.dbg('Powering on')
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200491 self.set_powered()
Pau Espin Pedrolb9955762017-05-02 09:39:27 +0200492 self.set_online()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200493 event_loop.wait(self, self.dbus.has_interface, I_NETREG, I_SMS, timeout=10)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200494
Pau Espin Pedrol0e57aad2017-05-29 14:25:22 +0200495 def connect(self, mcc_mnc=None):
496 'Connect to MCC+MNC'
497 if (mcc_mnc is not None) and (len(mcc_mnc) != 2 or None in mcc_mnc):
Pau Espin Pedrolcc5b5a22017-06-13 16:55:31 +0200498 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 +0200499 self.power_cycle()
500 self.register_attempts = 0
501 if self.is_connected(mcc_mnc):
502 self.log('Already registered with', mcc_mnc if mcc_mnc else 'default network')
503 else:
504 self.log('Connect to', mcc_mnc if mcc_mnc else 'default network')
505 self.schedule_scan_register(mcc_mnc)
506
Neels Hofmeyr8c7477f2017-05-25 04:33:53 +0200507 def sms_send(self, to_msisdn_or_modem, *tokens):
508 if isinstance(to_msisdn_or_modem, Modem):
509 to_msisdn = to_msisdn_or_modem.msisdn
510 tokens = list(tokens)
511 tokens.append('to ' + to_msisdn_or_modem.name())
512 else:
513 to_msisdn = str(to_msisdn_or_modem)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200514 msg = sms.Sms(self.msisdn, to_msisdn, 'from ' + self.name(), *tokens)
515 self.log('sending sms to MSISDN', to_msisdn, sms=msg)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200516 mm = self.dbus.interface(I_SMS)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200517 mm.SendMessage(to_msisdn, str(msg))
518 return msg
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200519
520 def _on_incoming_message(self, message, info):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200521 self.log('Incoming SMS:', repr(message))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200522 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200523 self.sms_received_list.append((message, info))
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200524
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200525 def sms_was_received(self, sms_obj):
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200526 for msg, info in self.sms_received_list:
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200527 if sms_obj.matches(msg):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200528 self.log('SMS received as expected:', repr(msg))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200529 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200530 return True
531 return False
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200532
Neels Hofmeyrb8011692017-05-29 03:45:24 +0200533 def info(self, keys=('Manufacturer', 'Model', 'Revision')):
534 props = self.properties()
535 return ', '.join(['%s: %r'%(k,props.get(k)) for k in keys])
536
537 def log_info(self, *args, **kwargs):
538 self.log(self.info(*args, **kwargs))
539
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200540# vim: expandtab tabstop=4 shiftwidth=4