Blob: example-adv-monitor
Blob id: 09888a973267205023f21627074cf47975f896dd
Size: 12.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 | #!/usr/bin/env python3 # SPDX-License-Identifier: LGPL-2.1-or-later import argparse import dbus import dbus.mainloop.glib import dbus.service import json import time from threading import Thread try: from gi.repository import GObject # python3 except ImportError: import gobject as GObject # python2 DBUS_OM_IFACE = 'org.freedesktop.DBus.ObjectManager' DBUS_PROP_IFACE = 'org.freedesktop.DBus.Properties' BLUEZ_SERVICE_NAME = 'org.bluez' ADV_MONITOR_MANAGER_IFACE = 'org.bluez.AdvertisementMonitorManager1' ADV_MONITOR_IFACE = 'org.bluez.AdvertisementMonitor1' ADV_MONITOR_APP_BASE_PATH = '/org/bluez/example/adv_monitor_app' class AdvMonitor(dbus.service.Object): # Indexes of the Monitor object parameters in a monitor data list. MONITOR_TYPE = 0 RSSI_FILTER = 1 PATTERNS = 2 # Indexes of the RSSI filter parameters in a monitor data list. RSSI_H_THRESH = 0 RSSI_H_TIMEOUT = 1 RSSI_L_THRESH = 2 RSSI_L_TIMEOUT = 3 # Indexes of the Patterns filter parameters in a monitor data list. PATTERN_START_POS = 0 PATTERN_AD_TYPE = 1 PATTERN_DATA = 2 def __init__(self, bus, app_path, monitor_id, monitor_data): self.path = app_path + '/monitor' + str(monitor_id) self.bus = bus self._set_type(monitor_data[self.MONITOR_TYPE]) self._set_rssi(monitor_data[self.RSSI_FILTER]) self._set_patterns(monitor_data[self.PATTERNS]) super(AdvMonitor, self).__init__(self.bus, self.path) def get_path(self): return dbus.ObjectPath(self.path) def get_properties(self): properties = dict() properties['Type'] = dbus.String(self.monitor_type) properties['RSSIHighThreshold'] = dbus.Int16(self.rssi_h_thresh) properties['RSSIHighTimeout'] = dbus.UInt16(self.rssi_h_timeout) properties['RSSILowThreshold'] = dbus.Int16(self.rssi_l_thresh) properties['RSSILowTimeout'] = dbus.UInt16(self.rssi_l_timeout) properties['Patterns'] = dbus.Array(self.patterns, signature='(yyay)') return {ADV_MONITOR_IFACE: properties} def _set_type(self, monitor_type): self.monitor_type = monitor_type def _set_rssi(self, rssi): self.rssi_h_thresh = rssi[self.RSSI_H_THRESH] self.rssi_h_timeout = rssi[self.RSSI_H_TIMEOUT] self.rssi_l_thresh = rssi[self.RSSI_L_THRESH] self.rssi_l_timeout = rssi[self.RSSI_L_TIMEOUT] def _set_patterns(self, patterns): self.patterns = [] for pattern in patterns: start_pos = dbus.Byte(pattern[self.PATTERN_START_POS]) ad_type = dbus.Byte(pattern[self.PATTERN_AD_TYPE]) ad_data = [] for byte in pattern[self.PATTERN_DATA]: ad_data.append(dbus.Byte(byte)) adv_pattern = dbus.Struct((start_pos, ad_type, ad_data), signature='yyay') self.patterns.append(adv_pattern) def remove_monitor(self): self.remove_from_connection() @dbus.service.method(DBUS_PROP_IFACE, in_signature='s', out_signature='a{sv}') def GetAll(self, interface): print('{}: {} GetAll'.format(self.path, interface)) if interface != ADV_MONITOR_IFACE: print('{}: GetAll: Invalid arg {}'.format(self.path, interface)) return {} return self.get_properties()[ADV_MONITOR_IFACE] @dbus.service.method(ADV_MONITOR_IFACE, in_signature='', out_signature='') def Activate(self): print('{}: Monitor Activated'.format(self.path)) @dbus.service.method(ADV_MONITOR_IFACE, in_signature='', out_signature='') def Release(self): print('{}: Monitor Released'.format(self.path)) @dbus.service.method(ADV_MONITOR_IFACE, in_signature='o', out_signature='') def DeviceFound(self, device): print('{}: {} Device Found'.format(self.path, device)) @dbus.service.method(ADV_MONITOR_IFACE, in_signature='o', out_signature='') def DeviceLost(self, device): print('{}: {} Device Lost'.format(self.path, device)) class AdvMonitorApp(dbus.service.Object): def __init__(self, bus, advmon_manager, app_id): self.bus = bus self.advmon_mgr = advmon_manager self.app_path = ADV_MONITOR_APP_BASE_PATH + str(app_id) self.monitors = dict() super(AdvMonitorApp, self).__init__(self.bus, self.app_path) def get_app_path(self): return dbus.ObjectPath(self.app_path) def add_monitor(self, monitor_data): monitor_id = 0 while monitor_id in self.monitors: monitor_id += 1 monitor = AdvMonitor(self.bus, self.app_path, monitor_id, monitor_data) # Emit the InterfacesAdded signal once the Monitor object is created. self.InterfacesAdded(monitor.get_path(), monitor.get_properties()) self.monitors[monitor_id] = monitor return monitor_id def remove_monitor(self, monitor_id): monitor = self.monitors.pop(monitor_id, None) if not monitor: return False # Emit the InterfacesRemoved signal before removing the Monitor object. self.InterfacesRemoved(monitor.get_path(), monitor.get_properties().keys()) monitor.remove_monitor() return True def register_app(self): self.register_successful = None def register_cb(): print('{}: RegisterMonitor successful'.format(self.app_path)) self.register_successful = True def register_error_cb(error): print('{}: RegisterMonitor failed: {}'.format(self.app_path, str(error))) self.register_successful = False self.advmon_mgr.RegisterMonitor(self.get_app_path(), reply_handler=register_cb, error_handler=register_error_cb) # Wait for the reply. while self.register_successful is None: pass return self.register_successful def unregister_app(self): self.unregister_successful = None def unregister_cb(): print('{}: UnregisterMonitor successful'.format(self.app_path)) self.unregister_successful = True def unregister_error_cb(error): print('{}: UnregisterMonitor failed: {}'.format(self.app_path, str(error))) self.unregister_successful = False self.advmon_mgr.UnregisterMonitor(self.get_app_path(), reply_handler=unregister_cb, error_handler=unregister_error_cb) # Wait for the reply. while self.unregister_successful is None: pass return self.unregister_successful @dbus.service.method(DBUS_OM_IFACE, out_signature='a{oa{sa{sv}}}') def GetManagedObjects(self): print('{}: GetManagedObjects'.format(self.app_path)) objects = dict() for monitor_id in self.monitors: monitor = self.monitors[monitor_id] objects[monitor.get_path()] = monitor.get_properties() return objects @dbus.service.signal(DBUS_OM_IFACE, signature='oa{sa{sv}}') def InterfacesAdded(self, object_path, interfaces_and_properties): # Invoking this method emits the InterfacesAdded signal, # nothing needs to be done here. return @dbus.service.signal(DBUS_OM_IFACE, signature='oas') def InterfacesRemoved(self, object_path, interfaces): # Invoking this method emits the InterfacesRemoved signal, # nothing needs to be done here. return def read_adapter_supported_monitor_types(adapter_props): types = json.dumps(adapter_props.Get(ADV_MONITOR_MANAGER_IFACE, 'SupportedMonitorTypes', dbus_interface=DBUS_PROP_IFACE)) return json.loads(types) def read_adapter_supported_monitor_features(adapter_props): features = json.dumps(adapter_props.Get(ADV_MONITOR_MANAGER_IFACE, 'SupportedFeatures', dbus_interface=DBUS_PROP_IFACE)) return json.loads(features) def print_supported_types_and_features(adapter_props): supported_types = read_adapter_supported_monitor_types(adapter_props) for supported_type in supported_types: print(supported_type) supported_features = read_adapter_supported_monitor_features(adapter_props) for supported_feature in supported_features: print(supported_feature) def find_advmon_mgr(bus, adapter): return dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, adapter), ADV_MONITOR_MANAGER_IFACE) def find_adapter(bus): remote_om = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, '/'), DBUS_OM_IFACE) objects = remote_om.GetManagedObjects() adapter = None adapter_props = None for o, props in objects.items(): if ADV_MONITOR_MANAGER_IFACE in props: adapter = o break if adapter: # Turn on the bluetooth adapter. adapter_props = dbus.Interface( bus.get_object(BLUEZ_SERVICE_NAME, adapter), DBUS_PROP_IFACE) adapter_props.Set('org.bluez.Adapter1', 'Powered', dbus.Boolean(1)) return adapter, adapter_props def test(bus, mainloop, advmon_mgr, app_id): # Create an App instance. app = AdvMonitorApp(bus, advmon_mgr, app_id) # Create two monitor objects before registering the app. No Activate() or # Release() should get called yet as the app is not registered. data0 = [ 'invalid_patterns', [-50, 1, -70, 1], [[0, 0x03, [0x12, 0x18]]] # Service Class UUID is 0x1812 (HOG) ] data1 = [ 'or_patterns', [127, 0, 127, 0], [[5, 0x09, [ord('_')]]] # 5th character of the Local Name is '_' ] monitor0 = app.add_monitor(data0) monitor1 = app.add_monitor(data1) # Register the app root path to expose advertisement monitors. # Release() should get called on monitor0 - incorrect monitor type. # Activate() should get called on monitor1. ret = app.register_app() if not ret: print('RegisterMonitor failed.') mainloop.quit() exit(-1) # Create two more monitor objects. # Release() should get called on monitor2 - incorrect RSSI Filter values. # Activate() should get called on monitor3. data2 = [ 'or_patterns', [-50, 1, -30, 1], [[0, 0x19, [0xC2, 0x03]]] # Appearance is 0xC203 (Mouse) ] data3 = [ 'or_patterns', [-50, 1, -70, 1], [[0, 0x03, [0x12, 0x18]], [0, 0x19, [0xC2, 0x03]]] ] monitor2 = app.add_monitor(data2) monitor3 = app.add_monitor(data3) # Run until user hits the 'Enter' key. If any peer device is advertising # during this time, DeviceFound() should get triggered for monitors # matching the advertisements. raw_input('Press "Enter" key to quit...\n') # Remove a monitor. DeviceFound() for this monitor should not get # triggered any more. app.remove_monitor(monitor1) # Unregister the app. Release() should get invoked on active monitors, # monitor3 in this case. app.unregister_app() mainloop.quit() def main(app_id): # Initialize threads in gobject/dbus-glib before creating local threads. GObject.threads_init() dbus.mainloop.glib.threads_init() # Arrange for the GLib main loop to be the default. dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() mainloop = GObject.MainLoop() # Find bluetooth adapter and power it on. adapter, adapter_props = find_adapter(bus) if not adapter or not adapter_props: print('Bluetooth adapter not found.') exit(-1) # Read supported types and find AdvertisementMonitorManager1 interface. print_supported_types_and_features(adapter_props) advmon_mgr = find_advmon_mgr(bus, adapter) if not advmon_mgr : print('AdvertisementMonitorManager1 interface not found.') exit(-1) Thread(target=test, args=(bus, mainloop, advmon_mgr, app_id)).start() mainloop.run() # blocks until mainloop.quit() is called if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--app_id', default=0, type=int, help='use this App-ID ' 'for creating dbus objects (default: 0)') args = parser.parse_args() main(args.app_id) |