如何从bluepy的handleNotification提取变量并简化蓝牙接收代码?
解决bluepy读取Arduino蓝牙数据的两个问题
问题1:从handleNotification提取变量供主循环使用
要让主循环能拿到handleNotification里的num和tum,可以给自定义的Delegate类添加实例属性,把解析后的值存起来:
- 在
MyDelegate的__init__方法里初始化self.num和self.tum - 在
handleNotification里更新这两个属性的值 - 主循环中通过Delegate实例直接访问这些属性
问题2:简化代码
去掉冗余注释和不必要的变量,合并蓝牙连接、特征获取和通知设置的步骤,保留核心功能即可。
修改后的完整代码
from bluepy import btle class MyDelegate(btle.DefaultDelegate): def __init__(self): super().__init__() # 初始化存储变量的属性 self.num = None self.tum = None def handleNotification(self, cHandle, data): # 解析数据并更新实例属性 self.num = list(data)[0] self.tum = int.from_bytes(data, byteorder='big') # 可选:打印解析结果 print(f"解析结果:num={self.num}, tum={self.tum}") # 初始化蓝牙连接 peripheral = btle.Peripheral("3a:dc:f3:6f:b1:dc") # 创建Delegate实例并绑定 delegate = MyDelegate() peripheral.setDelegate(delegate) # 获取目标特征并开启通知 svc = peripheral.getServiceByUUID("81c30e5c-1101-4f7d-a886-de3e90749161") char = svc.getCharacteristics("81c30e5c-2101-4f7d-a886-de3e90749161")[0] peripheral.writeCharacteristic(char.valHandle + 1, b"\x01\00") # 主循环 while True: if peripheral.waitForNotifications(1.0): # 这里可以直接使用delegate.num和delegate.tum进行计算 if delegate.num is not None and delegate.tum is not None: # 示例公式:计算num和tum的和 result = delegate.num + delegate.tum print(f"公式计算结果:{result}") continue print("等待数据中...")
改动说明
- 变量共享:通过Delegate实例的属性
self.num和self.tum,实现了handleNotification和主循环之间的数据共享,主循环可以直接调用这些属性进行公式计算。 - 代码简化:
- 使用
super().__init__()替代旧的父类初始化方式,更简洁 - 去掉了冗余注释和未使用的代码(比如注释掉的print语句)
- 变量命名更清晰(比如
p改为peripheral,ch改为char) - 合并了通知设置的步骤,直接使用字节常量
b"\x01\00",无需额外变量存储
- 使用
内容的提问来源于stack exchange,提问作者user16239103
相关产品推荐
相关产品推荐

