bluezutils.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # SPDX-License-Identifier: LGPL-2.1-or-later
  2. import dbus
  3. SERVICE_NAME = "org.bluez"
  4. ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter1"
  5. DEVICE_INTERFACE = SERVICE_NAME + ".Device1"
  6. def get_managed_objects():
  7. bus = dbus.SystemBus()
  8. manager = dbus.Interface(bus.get_object("org.bluez", "/"),
  9. "org.freedesktop.DBus.ObjectManager")
  10. return manager.GetManagedObjects()
  11. def find_adapter(pattern=None):
  12. return find_adapter_in_objects(get_managed_objects(), pattern)
  13. def find_adapter_in_objects(objects, pattern=None):
  14. bus = dbus.SystemBus()
  15. for path, ifaces in objects.items():
  16. adapter = ifaces.get(ADAPTER_INTERFACE)
  17. if adapter is None:
  18. continue
  19. if not pattern or pattern == adapter["Address"] or \
  20. path.endswith(pattern):
  21. obj = bus.get_object(SERVICE_NAME, path)
  22. return dbus.Interface(obj, ADAPTER_INTERFACE)
  23. raise Exception("Bluetooth adapter not found")
  24. def find_device(device_address, adapter_pattern=None):
  25. return find_device_in_objects(get_managed_objects(), device_address,
  26. adapter_pattern)
  27. def find_device_in_objects(objects, device_address, adapter_pattern=None):
  28. bus = dbus.SystemBus()
  29. path_prefix = ""
  30. if adapter_pattern:
  31. adapter = find_adapter_in_objects(objects, adapter_pattern)
  32. path_prefix = adapter.object_path
  33. for path, ifaces in objects.items():
  34. device = ifaces.get(DEVICE_INTERFACE)
  35. if device is None:
  36. continue
  37. if (device["Address"] == device_address and
  38. path.startswith(path_prefix)):
  39. obj = bus.get_object(SERVICE_NAME, path)
  40. return dbus.Interface(obj, DEVICE_INTERFACE)
  41. raise Exception("Bluetooth device not found")