windows+python+bleak+BLE低功耗蓝牙通讯连接 基于bleak模块实现蓝牙4.0设备的连接及通讯,实现了windows系统下的BLE设备的python环境开发。

前言

1.为什么选bleak
  参考这篇知乎:https://zhuanlan.zhihu.com/p/577687336
  windows端使用python连接常规的BLE设备(蓝牙4.0),仅考虑bleak模块(排除pybluez、pybluez2、pygatt)。

2.本文主要参考
  本文主要参考bleak的官方文档:https://github.com/hbldh/bleak

3.本文所用设备
  应事先学习蓝牙连接的常规知识,并用例如LightBlue软件调试对应的蓝牙设备(获取MAC地址、特征值Characteristic UUID)。
  本文选用CC2541模块,通过串口连接到电脑如所示。

正文

1.获取设备MAC地址

  本文设备的MAC地址为:88:25:83:F3:86:C1
  本文设备的特征值为:0000ffe1-0000-1000-8000-00805f9b34fb
  (PS:这个特征值挺通用的,多数设备能直接用)

方法1:使用LightBlue连接可查看

方法2:使用如下程序,打印所有设备

import asyncio
from bleak import BleakScanner
async def main():
 devices = await BleakScanner.discover()
 for d in devices: #d为类,其属性有:d.name为设备名称,d.address为设备地址
 print(d)
asyncio.run(main())

运行结果:

2.连接设备,并监听消息

  发送端:电脑端通过串口调试助手(UartAssist)发送消息
  接收端:电脑蓝牙连接设备,并监听打印(python程序)
  bleak的官方例程为:https://github.com/hbldh/bleak/blob/develop/examples/enable_notifications.py
完整程序如下

# -*- coding: utf-8 -*-
import asyncio
from bleak import BleakClient, BleakScanner
from bleak.backends.characteristic import BleakGATTCharacteristic
#设备的Characteristic UUID
par_notification_characteristic="0000ffe1-0000-1000-8000-00805f9b34fb"
#设备的MAC地址
par_device_addr="88:25:83:F3:86:C1"
#监听回调函数,此处为打印消息
def notification_handler(characteristic: BleakGATTCharacteristic, data: bytearray):
 print("rev data:",data)
async def main():
 print("starting scan...")
 #基于MAC地址查找设备
 device = await BleakScanner.find_device_by_address(
 par_device_addr, cb=dict(use_bdaddr=False) #use_bdaddr判断是否是MOC系统
 )
 if device is None:
 print("could not find device with address '%s'", par_device_addr)
 return
 print("connecting to device...")
 async with BleakClient(device) as client:
 print("Connected")
 await client.start_notify(par_notification_characteristic, notification_handler) 
 await asyncio.sleep(10.0) #程序监听的时间,此处为10秒
 await client.stop_notify(par_notification_characteristic)
asyncio.run(main())

发送:在运行过程中(即打印出“Connected”之后),由串口调试助手发送消息"hello world"

运行结果:

3.连接设备,断开连接事件回调

  在前文中,我们设定了10秒的休眠时间,可以监听消息10秒后自动断开监听。
  而实际使用中,存在设备断开连接的情况。此时我们使用连接断开事件的回调函数disconnected_callback
  bleak的官方例程为:https://github.com/hbldh/bleak/blob/develop/examples/disconnect_callback.py
完整代码如下:

# -*- coding: utf-8 -*-
import asyncio
from bleak import BleakClient, BleakScanner
from bleak.backends.characteristic import BleakGATTCharacteristic
#设备的Characteristic UUID
par_notification_characteristic="0000ffe1-0000-1000-8000-00805f9b34fb"
#设备的MAC地址
par_device_addr="88:25:83:F3:86:C1"
#监听回调函数,此处为打印消息
def notification_handler(characteristic: BleakGATTCharacteristic, data: bytearray):
 print("rev data:",data)
async def main():
 print("starting scan...")
 #基于MAC地址查找设备
 device = await BleakScanner.find_device_by_address(
 par_device_addr, cb=dict(use_bdaddr=False) #use_bdaddr判断是否是MOC系统
 )
 if device is None:
 print("could not find device with address '%s'", par_device_addr)
 return
 #事件定义
 disconnected_event = asyncio.Event()
 #断开连接事件回调,当设备断开连接时,会触发该函数,存在一定延迟
 def disconnected_callback(client):
 print("Disconnected callback called!")
 disconnected_event.set()
 print("connecting to device...")
 async with BleakClient(device,disconnected_callback=disconnected_callback) as client:
 print("Connected")
 await client.start_notify(par_notification_characteristic, notification_handler)
 await disconnected_event.wait() #休眠直到设备断开连接,有延迟。此处为监听设备直到断开为止
 # await asyncio.sleep(10.0) #程序监听的时间,此处为10秒
 # await client.stop_notify(par_notification_characteristic)
asyncio.run(main())

运行结果:

4.连接设备,并发送消息

  调用下面这个函数即可
  client.write_gatt_char(characteristic_UUID,send_str)
  characteristic_UUID: 需要具备写属性(Write属性),可通过LightBlue查看
  send_str: 为准备发送的数据,为bytearray类型

  本文中
  characteristic_UUID为"0000ffe1-0000-1000-8000-00805f9b34fb"(具备写属性)
  send_str为(HEX)“0x68,0x69,0x20,0x77,0x6F,0x72,0x6C,0x64,0x0A,0x0D”=(ASCII)“hi world\n”

完整代码如下

# -*- coding: utf-8 -*-
import asyncio
from bleak import BleakClient, BleakScanner
from bleak.backends.characteristic import BleakGATTCharacteristic
#设备的Characteristic UUID
par_notification_characteristic="0000ffe1-0000-1000-8000-00805f9b34fb"
#设备的Characteristic UUID(具备写属性Write)
par_write_characteristic="0000ffe1-0000-1000-8000-00805f9b34fb"
#设备的MAC地址
par_device_addr="88:25:83:F3:86:C1"
#准备发送的消息,为“hi world\n”的HEX形式(包括回车符0x0A 0x0D)
send_str=bytearray([0x68,0x69,0x20,0x77,0x6F,0x72,0x6C,0x64,0x0A,0x0D])
#监听回调函数,此处为打印消息
def notification_handler(characteristic: BleakGATTCharacteristic, data: bytearray):
 print("rev data:",data)
async def main():
 print("starting scan...")
 #基于MAC地址查找设备
 device = await BleakScanner.find_device_by_address(
 par_device_addr, cb=dict(use_bdaddr=False) #use_bdaddr判断是否是MOC系统
 )
 if device is None:
 print("could not find device with address '%s'", par_device_addr)
 return
 #事件定义
 disconnected_event = asyncio.Event()
 #断开连接事件回调
 def disconnected_callback(client):
 print("Disconnected callback called!")
 disconnected_event.set()
 print("connecting to device...")
 async with BleakClient(device,disconnected_callback=disconnected_callback) as client:
 print("Connected")
 await client.start_notify(par_notification_characteristic, notification_handler)
 while True:
 await client.write_gatt_char(par_write_characteristic, send_str)
 await asyncio.sleep(1.0) #每休眠1秒发送一次
 # await disconnected_event.wait() #休眠直到设备断开连接,有延迟。此处为监听设备直到断开为止
 # await asyncio.sleep(10.0) #程序监听的时间,此处为10秒
 # await client.stop_notify(par_notification_characteristic)
asyncio.run(main())

运行结果:

闲聊

  在上位机开发、移动端开发中,BLE设备的教程都较少,入门门槛较高。
  能连接蓝牙4.0的代码,一定能连接常规蓝牙。
  能连接常规蓝牙的代码,不一定能连接蓝牙4.0。
  CSDN写博客,图片插入的尺寸和位置不清楚怎么调节,后续再研究研究吧…

  基于本文,就能实现BLE设备的接收、发送、检测断开了。多读读文档,加一些逻辑,就能应用于各种场合了

作者:rory_wind原文地址:https://blog.csdn.net/rory_wind/article/details/128821945

%s 个评论

要回复文章请先登录注册