blob: 46300ec78bd9e9d948c63b524e8219145968c9a9 [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
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
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200246
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200247
248class Modem(log.Origin):
249 'convenience for ofono Modem interaction'
250 msisdn = None
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200251 sms_received_list = None
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200252
253 def __init__(self, conf):
254 self.conf = conf
255 self.path = conf.get('path')
256 self.set_name(self.path)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200257 self.set_log_category(log.C_TST)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200258 self.sms_received_list = []
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200259 self.dbus = ModemDbusInteraction(self.path)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200260 self.dbus.required_signals = {
261 I_SMS: ( ('IncomingMessage', self._on_incoming_message), ),
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200262 I_NETREG: ( ('PropertyChanged', self._on_netreg_property_changed), ),
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200263 }
264 self.dbus.watch_interfaces()
265
Neels Hofmeyr4d688c22017-05-29 04:13:58 +0200266 def cleanup(self):
267 self.dbus.cleanup()
268 self.dbus = None
269
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200270 def properties(self, *args, **kwargs):
271 '''Return a dict of properties on this modem. For the actual arguments,
272 see ModemDbusInteraction.properties(), which this function calls. The
273 returned dict is defined by ofono. An example is:
274 {'Lockdown': False,
275 'Powered': True,
276 'Model': 'MC7304',
277 'Revision': 'SWI9X15C_05.05.66.00 r29972 CARMD-EV-FRMWR1 2015/10/08 08:36:28',
278 'Manufacturer': 'Sierra Wireless, Incorporated',
279 'Emergency': False,
280 'Interfaces': ['org.ofono.SmartMessaging',
281 'org.ofono.PushNotification',
282 'org.ofono.MessageManager',
283 'org.ofono.NetworkRegistration',
284 'org.ofono.ConnectionManager',
285 'org.ofono.SupplementaryServices',
286 'org.ofono.RadioSettings',
287 'org.ofono.AllowedAccessPoints',
288 'org.ofono.SimManager',
289 'org.ofono.LocationReporting',
290 'org.ofono.VoiceCallManager'],
291 'Serial': '356853054230919',
292 'Features': ['sms', 'net', 'gprs', 'ussd', 'rat', 'sim', 'gps'],
293 'Type': 'hardware',
294 'Online': True}
295 '''
296 return self.dbus.properties(*args, **kwargs)
297
298 def set_powered(self, powered=True):
299 return self.dbus.set_powered(powered=powered)
300
301 def set_online(self, online=True):
302 return self.dbus.set_online(online=online)
303
304 def is_powered(self):
305 return self.dbus.is_powered()
306
307 def is_online(self):
308 return self.dbus.is_online()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200309
310 def set_msisdn(self, msisdn):
311 self.msisdn = msisdn
312
313 def imsi(self):
Neels Hofmeyrb02c2112017-04-09 18:46:48 +0200314 imsi = self.conf.get('imsi')
315 if not imsi:
316 with self:
317 raise RuntimeError('No IMSI')
318 return imsi
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200319
320 def ki(self):
321 return self.conf.get('ki')
322
Pau Espin Pedrol56bf31c2017-05-31 12:05:20 +0200323 def _on_netreg_property_changed(self, name, value):
324 self.dbg('%r.PropertyChanged() -> %s=%s' % (I_NETREG, name, value))
325
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200326 def connect(self, nitb):
327 'set the modem up to connect to MCC+MNC from NITB config'
328 self.log('connect to', nitb)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200329 if self.is_powered():
330 self.dbg('is powered')
Pau Espin Pedrol107f2752017-05-04 11:37:16 +0200331 self.set_online(False)
332 self.set_powered(False)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200333 event_loop.wait(self, lambda: not self.dbus.has_interface(I_NETREG, I_SMS), timeout=10)
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200334 self.set_powered()
Pau Espin Pedrolb9955762017-05-02 09:39:27 +0200335 self.set_online()
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200336 event_loop.wait(self, self.dbus.has_interface, I_NETREG, I_SMS, timeout=10)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200337
Neels Hofmeyr8c7477f2017-05-25 04:33:53 +0200338 def sms_send(self, to_msisdn_or_modem, *tokens):
339 if isinstance(to_msisdn_or_modem, Modem):
340 to_msisdn = to_msisdn_or_modem.msisdn
341 tokens = list(tokens)
342 tokens.append('to ' + to_msisdn_or_modem.name())
343 else:
344 to_msisdn = str(to_msisdn_or_modem)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200345 msg = sms.Sms(self.msisdn, to_msisdn, 'from ' + self.name(), *tokens)
346 self.log('sending sms to MSISDN', to_msisdn, sms=msg)
Neels Hofmeyr896f08f2017-05-24 20:17:26 +0200347 mm = self.dbus.interface(I_SMS)
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200348 mm.SendMessage(to_msisdn, str(msg))
349 return msg
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200350
351 def _on_incoming_message(self, message, info):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200352 self.log('Incoming SMS:', repr(message))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200353 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200354 self.sms_received_list.append((message, info))
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200355
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200356 def sms_was_received(self, sms_obj):
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200357 for msg, info in self.sms_received_list:
Pau Espin Pedrol996651a2017-05-30 15:13:29 +0200358 if sms_obj.matches(msg):
Neels Hofmeyr2e41def2017-05-06 22:42:57 +0200359 self.log('SMS received as expected:', repr(msg))
Neels Hofmeyrf49c7da2017-05-06 22:43:32 +0200360 self.dbg(info=info)
Neels Hofmeyrfec7d162017-05-02 16:29:09 +0200361 return True
362 return False
Neels Hofmeyrb3daaea2017-04-09 14:18:34 +0200363
Neels Hofmeyrb8011692017-05-29 03:45:24 +0200364 def info(self, keys=('Manufacturer', 'Model', 'Revision')):
365 props = self.properties()
366 return ', '.join(['%s: %r'%(k,props.get(k)) for k in keys])
367
368 def log_info(self, *args, **kwargs):
369 self.log(self.info(*args, **kwargs))
370
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200371# vim: expandtab tabstop=4 shiftwidth=4