__init__.py 1.5 KB

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