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

时间:2020-08-10 05:27:04

标签: 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:
        print("  {} - {}".format(addr, name))

2 个答案:

答案 0 :(得分:1)

问题中的代码段正在扫描新设备,而不是在连接的设备上进行报告。

PyBluez库是not under active development,所以我倾向于避免使用它。

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

BlueZ API记录在:

https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/adapter-api.txt

https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/device-api.txt

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

import pydbus

bus = pydbus.SystemBus()

adapter = bus.get('org.bluez', '/org/bluez/hci0')
mngr = bus.get('org.bluez', '/')

def list_connected_devices():
    mngd_objs = mngr.GetManagedObjects()
    for path in mngd_objs:
        con_state = mngd_objs[path].get('org.bluez.Device1', {}).get('Connected', False)
        if con_state:
            addr = mngd_objs[path].get('org.bluez.Device1', {}).get('Address')
            name = mngd_objs[path].get('org.bluez.Device1', {}).get('Name')
            print(f'Device {name} [{addr}] is connected')

if __name__ == '__main__':
    list_connected_devices()

答案 1 :(得分:0)

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

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

Bluez

代码

multimap<int, std::tuple<std::string, std::string>> Multimap; 
Multimap.insert(make_pair(number, std::make_tuple(name, secondname));
相关问题