使用 Bleak 配对蓝牙设备

问题描述 投票:0回答:1

如何使用 bleak 配对蓝牙设备 我开发了一个用于扫描附近蓝牙设备的代码,如何配对设备。 这是为扫描蓝牙设备而编写的代码

from bleak import BleakScanner
import flet as ft


async def scan_devices(device_list, page):
    device_list.controls.clear()
    device_list.controls.append(ft.Text("Scanning for Bluetooth devices..."))
    page.update()

    devices = await BleakScanner.discover()

    device_list.controls.clear()
    if devices:
        for device in devices:
            device_list.controls.append(ft.Text(f"Name: {device.name}, Address: {device.address}, RSSI: {device.rssi}"))
    else:
        device_list.controls.append(ft.Text("No devices found."))

    page.update()


def main(page: ft.Page):
    page.title = "Bluetooth Scanner"
    page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
    page.vertical_alignment = ft.MainAxisAlignment.CENTER
    page.scroll = ft.ScrollMode.AUTO

    device_list = ft.Column()

    def on_scan_click(e):
        asyncio.run(scan_devices(device_list, page))

    scan_button = ft.ElevatedButton(text="Scan for Devices", on_click=on_scan_click)
    page.controls.append(scan_button)
    page.controls.append(device_list)
    page.update()


ft.app(target=main)
python bluetooth bluetooth-lowenergy flet python-bleak
1个回答
0
投票

从列表中选择设备后,您就可以连接和配对。此示例使用列表中的第一个设备:

def main(page: ft.Page):
    page.title = "Bluetooth Scanner"
    page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
    page.vertical_alignment = ft.MainAxisAlignment.CENTER
    page.scroll = ft.ScrollMode.AUTO

    device_list = ft.Column()

    def on_scan_click(e):
        asyncio.run(scan_devices(device_list, page))

    scan_button = ft.ElevatedButton(text="Scan for Devices", on_click=on_scan_click)
    page.controls.append(scan_button)
    page.controls.append(device_list)
    page.update()

    dev = device_list[0]

    # Connect to the device
    try:
        async with BleakClient(dev.address) as client:
            if await client.is_connected():
                try:
                    # Pair with the device (distinct from just connecting)
                    await client.pair()
                    print("Paired device")
                except Exception as e:
                    print(e)
            else:
                print("Failed to connect to device")
    except Exception as e:
        print(e)

另请参阅来自黯淡的 github 页面的此示例脚本,其中在主方法中具有连接和配对功能。

© www.soinside.com 2019 - 2024. All rights reserved.