为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

鸿蒙传说 2023-05-09 09:30:53
我需要所有连接的蓝牙设备到我的电脑。我找到了图书馆,但我无法连接设备简单查询示例:    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 回答

?
慕勒3428872

TA贡献1848条经验 获得超6个赞

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

作为如何在 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()


查看完整回答
反对 回复 2023-05-09
?
慕的地8271018

TA贡献1796条经验 获得超4个赞

使用前需要安装依赖

布鲁斯

代码

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


查看完整回答
反对 回复 2023-05-09
  • 2 回答
  • 0 关注
  • 270 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信