def main(): args = cli_aruments() try: hci = Adapter(args.adapter) except BluezError as e: print(str(e), file=sys.stderr) sys.exit(1) loop = MainLoop.new(None, False) if args.scan_duration: timeout_add_seconds(args.scan_duration, scan_timeout, loop) hci.onPropertiesChanged(adapter_changed, loop) hci.onDeviceAdded(device_found, args.properties, init=True, some="Foo") # hci.onDeviceRemoved(device_removed, args.properties) # hci.scan() # for d in hci.devices(): # device_found(d, d.properties, args.properties) try: loop.run() except (KeyboardInterrupt, SystemExit): pass finally: try: hci.onDeviceAdded(None) hci.onPropertiesChanged(None) hci.scan(enable=False) hci.clear() except: pass
def __init__(self, timeout_secs, loop): self.timeout = timeout_secs self.remaining = timeout_secs self.canceled = False def mainloop_quit(): loop.quit() self.expired_cb = mainloop_quit timeout_add_seconds(1, self._tick)
def init_adapter(self): self.adapter = bluez.Adapter(self.adapter_name) self.adapter.onPropertiesChanged(adapter_changed, state_manager=self) self.adapter.onDeviceAdded(device_discovered, self, init=True) # queue function for execution in GLib mainloop self.adapter.onDeviceRemoved(device_removed, self) # queue function for execution in GLib mainloop timeout_add_seconds(0, start_scanning, self) # read a value every 10 seconds timeout_add_seconds(10, read_timer_function, self)
def period_save_thread(self): if self.period_save: if self.__file_name and self.is_modified \ and not self.__pause_period: idle_add(self.save_to_file) timeout_add_seconds(self.period_save, self.period_save_thread)
def peripheral_changed(peripheral, changed_values, state_manager): ''' changed event callback for peripherals peripheral: bluez.Device changed_values: dict state_manager: StateManager ''' # ignore these (peripheral.name == BD addr) d_addr = peripheral.name if not d_addr in state_manager.peripherals: return state_manager.logger.info('Device status changed: %s: %s', d_addr, str(changed_values)) if 'Connected' in changed_values: if not changed_values['Connected']: state_manager.logger.error('Disconnected: %s %s', d_addr, str(peripheral)) try: state_manager.adapter.scan(filters=state_manager.scan_filters) except Exception as e: state_manager.logger.error('Enableling scan failed: %s', str(e)) else: state_manager.logger.info('Connected: %s %s', d_addr, str(peripheral)) if 'ServicesResolved' in changed_values: if changed_values['ServicesResolved']: try: # load gatt database uuid matching state_manager.logger.info('Building GATT object: %s', d_addr) state_manager.peripherals[d_addr] = bluez.Gatt( peripheral, state_manager.gatt_description, warn_unmatched=False) state_manager.logger.info('Done GATT object: %s', d_addr) except Exception as e: state_manager.logger.error('ServiceResolved: %s: %s', d_addr, str(e)) state_manager.peripherals[d_addr] = None # setup all callbacks if state_manager.peripherals[d_addr]: try: enable_notifications(state_manager.peripherals[d_addr], state_manager) timeout_add_seconds(0, read_all, state_manager.peripherals[d_addr], state_manager) except bluez.BluezError as e: state_manager.logger.error('ServiceResolved: %s: %s', d_addr, str(e)) else: # clear gatt database mapping and callbacks if state_manager.peripherals[d_addr]: state_manager.peripherals[d_addr].clear() state_manager.peripherals[d_addr] = None if 'RSSI' in changed_values and not peripheral.connected: #pass device_discovered(peripheral, changed_values, state_manager)
def main(): parser = ArgumentParser(description="bluetooth tester") parser.add_argument( "-i", "--adapter", metavar="hciX", default=def_adapter, help="bluetooh adapter to use (default={})".format(def_adapter), ) parser.add_argument( "-a", "--device", metavar="addr", default=None, help="device address to connect to", ) parser.add_argument( "-p", "--pair", default=False, action="store_true", help="Send pairing request to device, if not paired (Needs an agent)", ) parser.add_argument("-k", "--keep", default=False, action="store_true", help="keep connection alive") parser.add_argument( "-l", "--loop", default=False, action="store_true", help="loop requesting info (sleeps 1s)", ) parser.add_argument( "-w", "--wait", metavar="sec", default=1, type=int, help="time to wait before starting to read", ) args = parser.parse_args() print("Scanning on: {}".format(args.adapter)) try: adapter = Adapter(args.adapter) except BluezDoesNotExistError as e: print(str(e)) sys.exit(2) devs = adapter.devices() dev = None for d in devs: da = d.address() if da and da.upper() == args.device.upper(): print("Found {}: {}".format(args.device, d)) dev = d if not dev: adapter.scan() sleep(3) sr = adapter.devices() for d in sr: da = d.address() if da and da.upper() == args.device.upper(): print("Found {}: {}".format(args.device, d)) dev = d if not dev: print("Could not find device nearby: {}".format(args.device)) adapter.scan(enable=False) sys.exit(1) adapter.scan(enable=False) if dev.connected(): print("Already connected: {}".format(dev)) else: if args.pair: if not dev.paired(): print("Device is not paired") print("Connecting/pairing to: {}".format(str(dev))) dev.pair() # waait for paring-agent wait_secs = 60 while wait_secs > 0 and not dev.paired(): wait_secs -= 1 sleep(1) if not dev.paired(): print("Pairing failed") sys.exit(1) if not dev.trusted(): dev.trust(True) print("Device is now trusted") if not dev.connect(): print("Connecting failed") sys.exit(1) gatt = Gatt(dev, [device_information]) gatt.resolve() if not dev.services_resolved: print( "Waited not long enough for service resolving, did not find uuids") sys.exit(1) print("Service UUIDs resolved") dev_info = gatt.device_information # pylint: disable=no-member for dinfo in dev_info.chars: if dinfo.obj: print(dinfo.name, ":", dinfo.read(options={"timeout": 4})) if args.wait > 0: sleep(args.wait) if args.loop: loop = MainLoop.new(None, False) for dinfo_char in dev_info.chars: if dinfo_char.obj: # add callback for printing if new value is avalable dinfo_char.onPropertiesChanged(print_char) # add cyclic read every 1 sec timeout_add_seconds(1, read_char, dinfo_char) try: loop.run() except (KeyboardInterrupt, SystemExit) as e: print("Interupted:", str(e)) if not args.keep: dev.disconnect()
def period_save_thread(self): if self.period_save: if self.__file_name and self.is_modified: thread = Thread(target=self.save_to_file) thread.start() timeout_add_seconds(self.period_save, self.period_save_thread)