您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Linux上以Python列出附近/可发现的蓝牙设备,包括已配对的蓝牙设备

在Linux上以Python列出附近/可发现的蓝牙设备,包括已配对的蓝牙设备

自从采用蓝牙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/

python 2022/1/1 18:22:19 有503人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶