def adapter_added(om, adapter_path, ifaces, adapter_name, state_manager): try: adapter = bluez.Adapter(adapter_path.split('/')[-1]) if adapter.name == state_manager.adapter_name: state_manager.init_adapter() except bluez.BluezError as e: state_manager.logger.error("Adapter added failed: %s", str(e))
def bt_connect(self): dev_obj = None try: adapter_obj = bluez.Adapter(self.adapter) devs = adapter_obj.devices() for d in devs: if d.name == self.device_addr.upper(): dev_obj = d break if not dev_obj: adapter_obj.scan() time.sleep(self.scan_duration) adapter_obj.scan(enable=False) devs = adapter_obj.devices() for d in devs: if d.name == self.device_addr.upper(): dev_obj = d break if dev_obj: dev_obj.connect() if dev_obj.connected: return bluez.Gatt(dev_obj, self.gatt_db_description) print("Failed:", file=sys.stderr) else: print("Failed to find device nearby", file=sys.stderr) except bluez.BluezError as e: print("Failed:", str(e), file=sys.stderr) return None
def do_remove(self, arg): "remove device" # d = bluez.Device(name=self.cli_args.device, adapter=hci) # d.remove() if self.gatt and self.gatt.dev: self.gatt.dev.remove() else: if self.device_addr: hci = bluez.Adapter(self.adapter) hci.remove_device(self.device_addr) print("Done", file=sys.stderr)
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 do_scan(self, arg): "enable/disable scanning (on/off)" pl = _parse_args_simple(arg) if len(pl) == 0 or pl[0] == "on": enable = True elif pl[0] == "off": enable = False else: print("Argument needs to be on/off") return try: hci = bluez.Adapter(self.adapter) scanning = hci.scan(enable=enable, filters=self.scan_filters) print("Scanning:", scanning) except bluez.BluezError: print("Setting scanning failed", file=sys.stderr) return None
def complete_connect(self, text, line, begidx, endidx): if len(line) != endidx: return None pl = _parse_args_simple(line) # (len(pl) == 2 and line[-1] != ' ') or if len(pl) == 2 or (len(pl) == 1 and line.endswith(" ")): try: hci = bluez.Adapter(self.adapter) devs = hci.devices() except bluez.BluezError: print("autocomplete failed", file=sys.stderr) return None return [ d.name for d in devs if d.name.lower().startswith(text.lower()) ] return None