python基于bleak的低功耗蓝牙连接、配对、调试

5,327 阅读1分钟

1.环境准备:

  硬件环境:windows10有蓝牙模块的主机
  python:python3.7+版本
  安装bleak包:pip install bleak
  

2.

import sys
import asyncio
from bleak import BleakClient

# 设备蓝牙地址
ADDRESS = "A0:9F:10:7E:1B:5D"

# 设备蓝牙UUID
UART_RX_CHAR_UUID = "49535343-8830-43F4-A8D4-ECBE34729B77"
UART_TX_CHAR_UUID = "49535343-1E4D-4BD9-BA61-23C647249677"

# 发送开门数据
openDoor_send = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]

# 接收返回数据
openDoor_recive = [0x00, 0x00, 0x00, 0x00, 0x00, 0x0]

async def main(address):
    async with BleakClient(address) as client:
        print(f"Connected: {client.is_connected}")

        paired = await client.pair(protection_level=2)
        print(f"Paired: {paired}")
        while client.is_connected:
            while paired == True:
                print("send data")
                await client.write_gatt_char(UART_RX_CHAR_UUID,bytes(openDoor_send))
                await client.start_notify(UART_TX_CHAR_UUID, handle_rx)
                await asyncio.sleep(1.0)
            print('Paired False')
        print('Disconnected')

def print_hex(bytes):
    l = [hex(int(i)) for i in bytes]
    # print(" ".join(l))
    return(" ".join(l))

def handle_rx(_: int, data: bytearray):
    print("received:", print_hex(data))
    print("expect:", print_hex(openDoor_recive))
    hex_callback = print_hex(data)
    if hex_callback == print_hex(openDoor_recive):
        print('Data verification succeeded')
    else:
        print('Data verification failed')

async def main(address):
    async with BleakClient(address) as client:
        print(f"Connected: {client.is_connected}")

        paired = await client.pair(protection_level=2)
        print(f"Paired: {paired}")
        while client.is_connected:
            while paired == True:
                print("send data")
                await client.write_gatt_char(UART_RX_CHAR_UUID,bytes(openDoor_send))
                await client.start_notify(UART_TX_CHAR_UUID, handle_rx)
                await asyncio.sleep(1.0)
            print('Paired False')
        print('Disconnected')


if __name__ == "__main__":
    asyncio.run(main(sys.argv[1] if len(sys.argv) == 2 else ADDRESS))

3.更多示例

github.com/hbldh/bleak