Python:如何连接蓝牙设备?(Linux)

Python:如何连接蓝牙设备?(Linux),python,linux,bluetooth,bluez,pybluez,Python,Linux,Bluetooth,Bluez,Pybluez,我需要将所有已连接的蓝牙设备连接到我的计算机。 我找到了库,但无法连接设备 简单查询示例: import bluetooth nearby_devices = bluetooth.discover_devices(lookup_names=True) print("Found {} devices.".format(len(nearby_devices))) for addr, name in nearby_devices:

我需要将所有已连接的蓝牙设备连接到我的计算机。 我找到了库,但无法连接设备

简单查询示例:

    import bluetooth

    nearby_devices = bluetooth.discover_devices(lookup_names=True)
    print("Found {} devices.".format(len(nearby_devices)))

    for addr, name in nearby_devices:
        print("  {} - {}".format(addr, name))

我找到了一个解决方案,但它使用终端

在使用之前,您需要安装依赖项

布鲁兹

代码


我找到了一个解决方案,但它使用终端

在使用之前,您需要安装依赖项

布鲁兹

代码


问题中的代码片段是扫描新设备,而不是报告连接的设备

PyBluez库非常有用,因此我倾向于避免使用它

BlueZ(Linux上的蓝牙堆栈)通过D-Bus提供了一组API,Python可以使用D-Bus绑定访问这些API。大多数情况下我更喜欢

BlueZ API记录在:

作为如何在Python3中实现此功能的示例:

导入pydbus
总线=pydbus.SystemBus()
adapter=bus.get('org.bluez','/org/bluez/hci0')
mngr=bus.get('org.bluez','/'))
def list_已连接的_设备():
mngd_objs=mngr.GetManagedObjects()
对于mngd_objs中的路径:
con_state=mngd_objs[path].get('org.bluez.Device1',{}).get('Connected',False)
如果con_状态:
addr=mngd_objs[path].get('org.bluez.Device1',{}.get('Address'))
name=mngd_objs[path].get('org.bluez.Device1',{}.get('name'))
打印(f'设备{name}[{addr}]已连接')
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
列出连接的设备()

问题中的代码片段是扫描新设备,而不是报告连接的设备

PyBluez库非常有用,因此我倾向于避免使用它

BlueZ(Linux上的蓝牙堆栈)通过D-Bus提供了一组API,Python可以使用D-Bus绑定访问这些API。大多数情况下我更喜欢

BlueZ API记录在:

作为如何在Python3中实现此功能的示例:

导入pydbus
总线=pydbus.SystemBus()
adapter=bus.get('org.bluez','/org/bluez/hci0')
mngr=bus.get('org.bluez','/'))
def list_已连接的_设备():
mngd_objs=mngr.GetManagedObjects()
对于mngd_objs中的路径:
con_state=mngd_objs[path].get('org.bluez.Device1',{}).get('Connected',False)
如果con_状态:
addr=mngd_objs[path].get('org.bluez.Device1',{}.get('Address'))
name=mngd_objs[path].get('org.bluez.Device1',{}.get('name'))
打印(f'设备{name}[{addr}]已连接')
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
列出连接的设备()
如果有人对“pydbus no module named gi”有问题,那么他们将帮助您如果有人对“pydbus no module named gi”有问题,那么他们将帮助您
def get_connected_devices():
    bounded_devices = check_output(['bt-device', '-l']).decode().split("\n")[1:-1]
    connected_devices = list()
    for device in bounded_devices:
        name = device[:device.rfind(' ')]
        #mac_address regex
        regex = '([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})|([0-9a-fA-F]{4}\\.[0-9a-fA-F]{4}\\.[0-9a-fA-F]{4})$'
        mac_address = re.search(regex, device).group(0)

        device_info = check_output(['bt-device', '-i', mac_address]).decode()
        connection_state = device_info[device_info.find('Connected: ') + len('Connected: ')]
        if connection_state == '1':
            connected_devices.append({"name": name, "address": mac_address})
    return connected_devices