blob: c5ae1ffcf520d70c6e1c3138ae7874e863d5c016 [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
8# it under the terms of the GNU Affero General Public License as
9# 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
15# GNU Affero General Public License for more details.
16#
17# You should have received a copy of the GNU Affero General Public License
18# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020020from . import log, test, util, event_loop
Neels Hofmeyr3531a192017-03-28 14:30:28 +020021
22from pydbus import SystemBus, Variant
23import time
24import pprint
25
26from gi.repository import GLib
27glib_main_loop = GLib.MainLoop()
28glib_main_ctx = glib_main_loop.get_context()
29bus = SystemBus()
30
Pau Espin Pedrol504a6642017-05-04 11:38:23 +020031I_MODEM = 'org.ofono.Modem'
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +020032I_NETREG = 'org.ofono.NetworkRegistration'
33I_SMS = 'org.ofono.MessageManager'
34
Neels Hofmeyr035cda82017-05-05 17:52:45 +020035class DeferredHandling:
36 defer_queue = []
37
38 def __init__(self, dbus_iface, handler):
39 self.handler = handler
Neels Hofmeyr47de6b02017-05-10 13:24:05 +020040 self.subscription_id = dbus_iface.connect(self.receive_signal)
Neels Hofmeyr035cda82017-05-05 17:52:45 +020041
42 def receive_signal(self, *args, **kwargs):
43 DeferredHandling.defer_queue.append((self.handler, args, kwargs))
44
45 @staticmethod
46 def handle_queue():
47 while DeferredHandling.defer_queue:
48 handler, args, kwargs = DeferredHandling.defer_queue.pop(0)
49 handler(*args, **kwargs)
50
51def dbus_connect(dbus_iface, handler):
52 '''This function shall be used instead of directly connecting DBus signals.
53 It ensures that we don't nest a glib main loop within another, and also
54 that we receive exceptions raised within the signal handlers. This makes it
55 so that a signal handler is invoked only after the DBus polling is through
56 by enlisting signals that should be handled in the
57 DeferredHandling.defer_queue.'''
Neels Hofmeyr47de6b02017-05-10 13:24:05 +020058 return DeferredHandling(dbus_iface, handler).subscription_id
Neels Hofmeyr035cda82017-05-05 17:52:45 +020059
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020060def poll_glib():
Neels Hofmeyr3531a192017-03-28 14:30:28 +020061 global glib_main_ctx
62 while glib_main_ctx.pending():
63 glib_main_ctx.iteration()
Neels Hofmeyr035cda82017-05-05 17:52:45 +020064 DeferredHandling.handle_queue()
Neels Hofmeyr3531a192017-03-28 14:30:28 +020065
Pau Espin Pedrol927344b2017-05-22 16:38:49 +020066event_loop.register_poll_func(poll_glib)
67
Neels Hofmeyr93f58662017-05-03 16:32:16 +020068def systembus_get(path):
Neels Hofmeyr3531a192017-03-28 14:30:28 +020069 global bus
70 return bus.get('org.ofono', path)
71
72def list_modems():
Neels Hofmeyr93f58662017-05-03 16:32:16 +020073 root = systembus_get('/')
Neels Hofmeyr3531a192017-03-28 14:30:28 +020074 return sorted(root.GetModems())
75
Neels Hofmeyr896f08f2017-05-24 20:17:26 +020076class ModemDbusInteraction(log.Origin):
77 '''Work around inconveniences specific to pydbus and ofono.
78 ofono adds and removes DBus interfaces and notifies about them.
79 Upon changes we need a fresh pydbus object to benefit from that.
80 Watching the interfaces change is optional; be sure to call
81 watch_interfaces() if you'd like to have signals subscribed.
82 Related: https://github.com/LEW21/pydbus/issues/56
83 '''
84
85 def __init__(self, modem_path):
86 self.modem_path = modem_path
87 self.set_name(self.modem_path)
88 self.set_log_category(log.C_BUS)
89 self.watch_props_subscription = None
90 self._dbus_obj = None
91 self.interfaces = set()
92
93 # A dict listing signal handlers to connect, e.g.
94 # { I_SMS: ( ('IncomingMessage', self._on_incoming_message), ), }
95 self.required_signals = {}
96
97 # A dict collecting subscription tokens for connected signal handlers.
98 # { I_SMS: ( token1, token2, ... ), }
99 self.connected_signals = util.listdict()
100
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200101 def cleanup(self):
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200102 self.unwatch_interfaces()
103 for interface_name in list(self.connected_signals.keys()):
104 self.remove_signals(interface_name)
105
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200106 def __del__(self):
107 self.cleanup()
108
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200109 def get_new_dbus_obj(self):
110 return systembus_get(self.modem_path)
111
112 def dbus_obj(self):
113 if self._dbus_obj is None:
114 self._dbus_obj = self.get_new_dbus_obj()
115 return self._dbus_obj
116
117 def interface(self, interface_name):
118 try:
119 return self.dbus_obj()[interface_name]
120 except KeyError:
121 self.raise_exn('Modem interface is not available:', interface_name)
122
123 def signal(self, interface_name, signal):
124 return getattr(self.interface(interface_name), signal)
125
126 def watch_interfaces(self):
127 self.unwatch_interfaces()
128 # Note: we are watching the properties on a get_new_dbus_obj() that is
129 # separate from the one used to interact with interfaces. We need to
130 # refresh the pydbus object to interact with Interfaces that have newly
131 # appeared, but exchanging the DBus object to watch Interfaces being
132 # enabled and disabled is racy: we may skip some removals and
133 # additions. Hence do not exchange this DBus object. We don't even
134 # need to store the dbus object used for this, we will not touch it
135 # again. We only store the signal subscription.
136 self.watch_props_subscription = dbus_connect(self.get_new_dbus_obj().PropertyChanged,
137 self.on_property_change)
138 self.on_interfaces_change(self.properties().get('Interfaces'))
139
140 def unwatch_interfaces(self):
141 if self.watch_props_subscription is None:
142 return
143 self.watch_props_subscription.disconnect()
144 self.watch_props_subscription = None
145
146 def on_property_change(self, name, value):
147 if name == 'Interfaces':
148 self.on_interfaces_change(value)
149
150 def on_interfaces_change(self, interfaces_now):
151 # First some logging.
152 now = set(interfaces_now)
153 additions = now - self.interfaces
154 removals = self.interfaces - now
155 self.interfaces = now
156 if not (additions or removals):
157 # nothing changed.
158 return
159
160 if additions:
161 self.dbg('interface enabled:', ', '.join(sorted(additions)))
162
163 if removals:
164 self.dbg('interface disabled:', ', '.join(sorted(removals)))
165
166 # The dbus object is now stale and needs refreshing before we
167 # access the next interface function.
168 self._dbus_obj = None
169
170 # If an interface disappeared, disconnect the signal handlers for it.
171 # Even though we're going to use a fresh dbus object for new
172 # subscriptions, we will still keep active subscriptions alive on the
173 # old dbus object which will linger, associated with the respective
174 # signal subscription.
175 for removed in removals:
176 self.remove_signals(removed)
177
178 # Connect signals for added interfaces.
179 for interface_name in additions:
180 self.connect_signals(interface_name)
181
182 def remove_signals(self, interface_name):
183 got = self.connected_signals.pop(interface_name, [])
184
185 if not got:
186 return
187
188 self.dbg('Disconnecting', len(got), 'signals for', interface_name)
189 for subscription in got:
190 subscription.disconnect()
191
192 def connect_signals(self, interface_name):
193 # If an interface was added, it must not have existed before. For
194 # paranoia, make sure we have no handlers for those.
195 self.remove_signals(interface_name)
196
197 want = self.required_signals.get(interface_name, [])
198 if not want:
199 return
200
201 self.dbg('Connecting', len(want), 'signals for', interface_name)
202 for signal, cb in self.required_signals.get(interface_name, []):
203 subscription = dbus_connect(self.signal(interface_name, signal), cb)
204 self.connected_signals.add(interface_name, subscription)
205
206 def has_interface(self, *interface_names):
207 try:
208 for interface_name in interface_names:
209 self.dbus_obj()[interface_name]
210 result = True
211 except KeyError:
212 result = False
213 self.dbg('has_interface(%s) ==' % (', '.join(interface_names)), result)
214 return result
215
216 def properties(self, iface=I_MODEM):
217 return self.dbus_obj()[iface].GetProperties()
218
219 def property_is(self, name, val, iface=I_MODEM):
220 is_val = self.properties(iface).get(name)
221 self.dbg(name, '==', is_val)
222 return is_val is not None and is_val == val
223
224 def set_bool(self, name, bool_val, iface=I_MODEM):
225 # to make sure any pending signals are received before we send out more DBus requests
226 event_loop.poll()
227
228 val = bool(bool_val)
229 self.log('Setting', name, val)
230 self.interface(iface).SetProperty(name, Variant('b', val))
231
232 event_loop.wait(self, self.property_is, name, bool_val)
233
234 def set_powered(self, powered=True):
235 self.set_bool('Powered', powered)
236
237 def set_online(self, online=True):
238 self.set_bool('Online', online)
239
240 def is_powered(self):
241 return self.property_is('Powered', True)
242
243 def is_online(self):
244 return self.property_is('Online', True)
245
246 def require_features(self, *required):
247 '''Make sure the given feature strings are present in
248 properties()['Features'], raise an exception otherwise.'''
249 features = set(self.properties().get('Features'))
250 r = set(required)
251 if not (r < features):
252 self.raise_exn('This modem lacks features:', r - features)
253
254
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200255
256class Modem(log.Origin):
257 'convenience for ofono Modem interaction'
258 msisdn = None
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200259 sms_received_list = None
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200260
261 def __init__(self, conf):
262 self.conf = conf
263 self.path = conf.get('path')
264 self.set_name(self.path)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200265 self.set_log_category(log.C_TST)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200266 self.sms_received_list = []
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200267 self.dbus = ModemDbusInteraction(self.path)
268 self.dbus.require_features('sms', 'net')
269 self.dbus.required_signals = {
270 I_SMS: ( ('IncomingMessage', self._on_incoming_message), ),
271 }
272 self.dbus.watch_interfaces()
273
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200274 def cleanup(self):
275 self.dbus.cleanup()
276 self.dbus = None
277
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200278 def properties(self, *args, **kwargs):
279 '''Return a dict of properties on this modem. For the actual arguments,
280 see ModemDbusInteraction.properties(), which this function calls. The
281 returned dict is defined by ofono. An example is:
282 {'Lockdown': False,
283 'Powered': True,
284 'Model': 'MC7304',
285 'Revision': 'SWI9X15C_05.05.66.00 r29972 CARMD-EV-FRMWR1 2015/10/08 08:36:28',
286 'Manufacturer': 'Sierra Wireless, Incorporated',
287 'Emergency': False,
288 'Interfaces': ['org.ofono.SmartMessaging',
289 'org.ofono.PushNotification',
290 'org.ofono.MessageManager',
291 'org.ofono.NetworkRegistration',
292 'org.ofono.ConnectionManager',
293 'org.ofono.SupplementaryServices',
294 'org.ofono.RadioSettings',
295 'org.ofono.AllowedAccessPoints',
296 'org.ofono.SimManager',
297 'org.ofono.LocationReporting',
298 'org.ofono.VoiceCallManager'],
299 'Serial': '356853054230919',
300 'Features': ['sms', 'net', 'gprs', 'ussd', 'rat', 'sim', 'gps'],
301 'Type': 'hardware',
302 'Online': True}
303 '''
304 return self.dbus.properties(*args, **kwargs)
305
306 def set_powered(self, powered=True):
307 return self.dbus.set_powered(powered=powered)
308
309 def set_online(self, online=True):
310 return self.dbus.set_online(online=online)
311
312 def is_powered(self):
313 return self.dbus.is_powered()
314
315 def is_online(self):
316 return self.dbus.is_online()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200317
318 def set_msisdn(self, msisdn):
319 self.msisdn = msisdn
320
321 def imsi(self):
Neels Hofmeyrb02c2112017-04-09 18:46:48 +0200322 imsi = self.conf.get('imsi')
323 if not imsi:
324 with self:
325 raise RuntimeError('No IMSI')
326 return imsi
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200327
328 def ki(self):
329 return self.conf.get('ki')
330
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200331 def connect(self, nitb):
332 'set the modem up to connect to MCC+MNC from NITB config'
333 self.log('connect to', nitb)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200334 if self.is_powered():
335 self.dbg('is powered')
Pau Espin Pedrol107f2752017-05-04 11:37:16 +0200336 self.set_online(False)
337 self.set_powered(False)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200338 event_loop.wait(self, lambda: not self.dbus.has_interface(I_NETREG, I_SMS), timeout=10)
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200339 self.set_powered()
Pau Espin Pedrolb9955762017-05-02 09:39:27 +0200340 self.set_online()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200341 event_loop.wait(self, self.dbus.has_interface, I_NETREG, I_SMS, timeout=10)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200342
Neels Hofmeyr8d8b03e2017-05-06 18:19:46 +0200343 def sms_send(self, to_msisdn, *tokens):
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200344 if hasattr(to_msisdn, 'msisdn'):
345 to_msisdn = to_msisdn.msisdn
Neels Hofmeyr8d8b03e2017-05-06 18:19:46 +0200346 sms = Sms(self.msisdn, to_msisdn, 'from ' + self.name(), *tokens)
Neels Hofmeyr1ea59ea2017-05-02 14:41:54 +0200347 self.log('sending sms to MSISDN', to_msisdn, sms=sms)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200348 mm = self.dbus.interface(I_SMS)
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200349 mm.SendMessage(to_msisdn, str(sms))
350 return sms
351
352 def _on_incoming_message(self, message, info):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200353 self.log('Incoming SMS:', repr(message))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200354 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200355 self.sms_received_list.append((message, info))
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200356
Neels Hofmeyr863cb562017-05-02 16:27:59 +0200357 def sms_was_received(self, sms):
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200358 for msg, info in self.sms_received_list:
359 if sms.matches(msg):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200360 self.log('SMS received as expected:', repr(msg))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200361 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200362 return True
363 return False
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200364
365class Sms:
366 _last_sms_idx = 0
367 msg = None
368
Neels Hofmeyr8d8b03e2017-05-06 18:19:46 +0200369 def __init__(self, from_msisdn=None, to_msisdn=None, *tokens):
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200370 Sms._last_sms_idx += 1
371 msgs = ['message nr. %d' % Sms._last_sms_idx]
Neels Hofmeyr8d8b03e2017-05-06 18:19:46 +0200372 msgs.extend(tokens)
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200373 if from_msisdn:
Neels Hofmeyr8d8b03e2017-05-06 18:19:46 +0200374 msgs.append('from %s' % from_msisdn)
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200375 if to_msisdn:
Neels Hofmeyr8d8b03e2017-05-06 18:19:46 +0200376 msgs.append('to %s' % to_msisdn)
377 self.msg = ', '.join(msgs)
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200378
379 def __str__(self):
380 return self.msg
381
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200382 def __repr__(self):
383 return repr(self.msg)
384
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200385 def __eq__(self, other):
386 if isinstance(other, Sms):
387 return self.msg == other.msg
388 return inself.msg == other
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200389
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200390 def matches(self, msg):
391 return self.msg == msg
392
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200393# vim: expandtab tabstop=4 shiftwidth=4