当前位置:
首页 > Python基础教程 >
-
Python实时获取心率广播心率
前提
心率设备需支持心率广播功能
心率广播功能需处于开启状态
心率广播功能最多只能同时连接一台设备,如有其它设备正在连接需要先断开
使用方法
安装蓝牙低功耗库break
pip install bleak
开启心率广播功能后设备界面会显示当前设备名称,将设备名称替换到变量device_name
运行程序,将自动扫描设备并连接到心率广播功能,异步获取心率数据
代码
import asyncio
from bleak import BleakClient, BleakScanner
from bleak.backends.characteristic import BleakGATTCharacteristic
# 设备名称
device_name: str = "HUAWEI WATCH HR-341"
# 心率
value = 0
# 最大连接超时时间
timeout = 10
# 通知处理器函数,当收到通知时调用
def notification_handler(characteristic: BleakGATTCharacteristic, data: bytearray):
global value
value = int(data.hex().split('06')[1], 16)
print(value)
# 异步函数:扫描设备并根据本地名称获取地址
async def scan_for_device(device_name: str):
devices = await BleakScanner.discover()
for device in devices:
if device.name == device_name:
return device
return None
# 异步函数:查找描述为“Heart Rate Measurement”的特征UUID
async def find_heart_rate_measurement_uuid(client: BleakClient):
for service in client.services:
for characteristic in service.characteristics:
if "Heart Rate Measurement" in characteristic.description:
return characteristic.uuid
return None
# 异步主函数
async def main():
print("Starting scan...")
# 根据设备名称扫描设备,也可以直接填入设备的物理地址
device = await scan_for_device(device_name)
if device is None:
print(f"Device with name {device_name} not found.")
return
print(f"Found device: {device.name} ({device.address})")
# 创建一个事件对象,用于处理断开连接的情况
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, timeout=timeout) as client:
print("Connected")
# 查找“Heart Rate Measurement”特征UUID(心率广播)
hr_measurement_uuid = await find_heart_rate_measurement_uuid(client)
if hr_measurement_uuid:
# 开始通知,并设置通知处理器
await client.start_notify(hr_measurement_uuid, notification_handler)
# 等待断开连接事件
await disconnected_event.wait()
else:
print("Heart Rate Measurement characteristic not found.")
# 运行异步主函数
asyncio.run(main())
来源:https://www.cnblogs.com/qiao39gs/p/18295241/real-time-heart-rate-broadcast-with-python-bleak-ble-library
栏目列表
最新更新
VSTO 撤回代码修改的值
Web Service和Web API理解和使用场景
C# xml文档反序列化记事
再谈 Playwright:打造一体化自动化测试工
Python学习之布尔运算
Python 实现 macOS 系统代理的设置
Python 如何判断应用是否处于已打包状态
Python 跨平台路径格式不一致问题
golang 的OOP 面向对象编程
Fins TCP协议理解及C#实现思路
数据库审计与智能监控:从日志分析到异
SQL Server 中的数据类型隐式转换问题
SQL Server中T-SQL 数据类型转换详解
sqlserver 数据类型转换小实验
SQL Server数据类型转换方法
SQL Server 2017无法连接到服务器的问题解决
SQLServer地址搜索性能优化
Sql Server查询性能优化之不可小觑的书签查
SQL Server数据库的高性能优化经验总结
SQL SERVER性能优化综述(很好的总结,不要错
uniapp/H5 获取手机桌面壁纸 (静态壁纸)
[前端] DNS解析与优化
为什么在js中需要添加addEventListener()?
JS模块化系统
js通过Object.defineProperty() 定义和控制对象
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比