由于采用蓝牙 API 的第 5 版,@Micke 解决方案中使用的大部分功能都被删除了,与总线的交互通过 ObjectManager.GetManagedObjects [1] 进行
import dbus
def proxyobj(bus, path, interface):
""" commodity to apply an interface to a proxy object """
obj = bus.get_object('org.bluez', path)
return dbus.Interface(obj, interface)
def filter_by_interface(objects, interface_name):
""" filters the objects based on their support
for the specified interface """
result = []
for path in objects.keys():
interfaces = objects[path]
for interface in interfaces.keys():
if interface == interface_name:
result.append(path)
return result
bus = dbus.SystemBus()
# we need a dbus object manager
manager = proxyobj(bus, "/", "org.freedesktop.DBus.ObjectManager")
objects = manager.GetManagedObjects()
# once we get the objects we have to pick the bluetooth devices.
# They support the org.bluez.Device1 interface
devices = filter_by_interface(objects, "org.bluez.Device1")
# now we are ready to get the informations we need
bt_devices = []
for device in devices:
obj = proxyobj(bus, device, 'org.freedesktop.DBus.Properties')
bt_devices.append({
"name": str(obj.Get("org.bluez.Device1", "Name")),
"addr": str(obj.Get("org.bluez.Device1", "Address"))
})
在bt_device
列表中有包含所需数据的字典:即
例如
[{
'name': 'BBC micro:bit [zigiz]',
'addr': 'E0:7C:62:5A:B1:8C'
}, {
'name': 'BBC micro:bit [putup]',
'addr': 'FC:CC:69:48:5B:32'
}]
参考:[1] http://www.bluez.org/bluez-5-api-introduction-and-porting-guide/