You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bleak的start_notify回调外使用解码得到的变量

问题

使用Bleak库通过CSC_Decoding回调解码蓝牙骑行数据,得到CumulativeWheelRevolution和LastWheelEventTime,但回调仅能接收handle和data两个参数,无法在主循环中实时获取这两个更新后的变量,尝试给回调添加额外参数无效,需解决该问题。

现有代码:

import asyncio
import sys
from bleak import BleakClient

CSCMeasurementUUID = '00002a5b-0000-1000-8000-00805f9b34fb'

def CSC_Decoding(handle, data):
  CumulativeWheelRevolution = int.from_bytes(data[1:5],"little")
  LastWheelEventTime = int.from_bytes(data[5:7],"little")

async def main():

  address = "EA:95:75:A8:80:01" # Tacx骑行台的地址
  async with BleakClient(address) as client:
    if (not client.is_connected):
      raise "client not connected"

    await client.start_notify(CSCMeasurementUUID,CSC_Decoding)
    await asyncio.sleep(10)
    await client.stop_notify(CSCMeasurementUUID)

if __name__ == "__main__":
  asyncio.run(main())

期望实现:在主循环中实时计算变量差值,示例逻辑:

# 需要获取更新后的CumulativeWheelRevolution和LastWheelEventTime
if __name__ == "__main__":
   preWheel = 0
   preTime = 0
   while True:
      deltaWheel = CumulativeWheelRevolution - preWheel # 该变量会被回调更新
      deltaTime = LastWheelEventTime - preTime # 该变量会被回调更新
      preWheel = CumulativeWheelRevolution
      preTime = LastWheelEventTime

解决方案

方法1:用可变对象共享数据

Python中不可变对象(如int)在函数内赋值不会影响外部,但字典、列表这类可变对象可以。我们可以用字典存储共享数据,通过functools.partial将其绑定到回调参数中。

修改后代码:

import asyncio
from bleak import BleakClient
from functools import partial

CSCMeasurementUUID = '00002a5b-0000-1000-8000-00805f9b34fb'

def CSC_Decoding(shared_data, handle, data):
    # 解码数据并更新共享字典
    shared_data["CumulativeWheelRevolution"] = int.from_bytes(data[1:5], "little")
    shared_data["LastWheelEventTime"] = int.from_bytes(data[5:7], "little")

async def main():
    # 初始化共享数据
    shared_data = {
        "CumulativeWheelRevolution": 0,
        "LastWheelEventTime": 0
    }
    # 绑定共享数据到回调
    callback = partial(CSC_Decoding, shared_data)
    
    address = "EA:95:75:A8:80:01"
    async with BleakClient(address) as client:
        if not client.is_connected:
            raise ConnectionError("客户端未连接")
        
        await client.start_notify(CSCMeasurementUUID, callback)
        
        # 异步主循环实时计算差值
        preWheel = 0
        preTime = 0
        try:
            while True:
                current_wheel = shared_data["CumulativeWheelRevolution"]
                current_time = shared_data["LastWheelEventTime"]
                if current_wheel != preWheel or current_time != preTime:
                    deltaWheel = current_wheel - preWheel
                    deltaTime = current_time - preTime
                    print(f"轮圈转动增量: {deltaWheel}, 时间增量: {deltaTime}")
                    preWheel = current_wheel
                    preTime = current_time
                await asyncio.sleep(0.1) # 避免占用过多CPU
        except asyncio.CancelledError:
            pass
        finally:
            await client.stop_notify(CSCMeasurementUUID)

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("程序已终止")

方法2:用类封装状态与逻辑

若业务逻辑复杂,用类管理状态和回调会更清晰:

import asyncio
from bleak import BleakClient

CSCMeasurementUUID = '00002a5b-0000-1000-8000-00805f9b34fb'

class BikeDataProcessor:
    def __init__(self):
        self.CumulativeWheelRevolution = 0
        self.LastWheelEventTime = 0
        self.preWheel = 0
        self.preTime = 0
    
    def CSC_Decoding(self, handle, data):
        self.CumulativeWheelRevolution = int.from_bytes(data[1:5], "little")
        self.LastWheelEventTime = int.from_bytes(data[5:7], "little")
    
    async def run_calculation_loop(self):
        while True:
            current_wheel = self.CumulativeWheelRevolution
            current_time = self.LastWheelEventTime
            if current_wheel != self.preWheel or current_time != self.preTime:
                deltaWheel = current_wheel - self.preWheel
                deltaTime = current_time - self.preTime
                print(f"轮圈转动增量: {deltaWheel}, 时间增量: {deltaTime}")
                self.preWheel = current_wheel
                self.preTime = current_time
            await asyncio.sleep(0.1)

async def main():
    processor = BikeDataProcessor()
    address = "EA:95:75:A8:80:01"
    async with BleakClient(address) as client:
        if not client.is_connected:
            raise ConnectionError("客户端未连接")
        
        await client.start_notify(CSCMeasurementUUID, processor.CSC_Decoding)
        # 启动计算任务
        calculation_task = asyncio.create_task(processor.run_calculation_loop())
        
        try:
            await asyncio.gather(calculation_task)
        except asyncio.CancelledError:
            calculation_task.cancel()
            await calculation_task
        finally:
            await client.stop_notify(CSCMeasurementUUID)

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("程序已终止")

关键说明

  • Bleak的start_notify只接受固定签名(handle, data)的回调,因此需用functools.partial绑定额外参数,或使用类方法(类实例会自动作为第一个参数传递)。
  • 主循环必须是异步的,同步while True会阻塞asyncio事件循环,导致回调无法执行蓝牙数据处理。
  • 添加await asyncio.sleep(0.1)是为了让出CPU时间,确保回调有机会处理数据,避免程序卡死。

内容的提问来源于stack exchange,提问作者Meysam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 06:55:33