其实最关键的就是找对路,找对路就好说。
操蛋的就是你根本不知道用哪个库,好像网上大家都不用python做ble似的。
本着赛博李时珍的精神,只好挨个试,最后发现bleak这个库能用,而且好装,不至于走了那么多弯路。
上代码:
import asyncio
from bleak import BleakScanner, BleakClient
import struct
SERVICE_UUID = "181A" # 环境监测服务
CHAR_UUID = "2A6E" # 温度特征值
async def main():
print("开始扫描设备...")
# 扫描周围的BLE设备
devices = await BleakScanner.discover()
esp32_device = None
# 遍历扫描到的设备,查找ESP32
for device in devices:
print(device)
if device.name and "ESP32-BLE" in device.name:
esp32_device = device
break
if not esp32_device:
print("未找到ESP32设备")
return
print(f"找到ESP32设备: {esp32_device.name} ({esp32_device.address})")
try:
async with BleakClient(esp32_device.address) as client:
print("已连接到ESP32")
# 定义数据接收回调函数
def notification_handler(sender, data):
value = struct.unpack("f", data)[0]
print(f"收到数据: {value}")
await client.start_notify(CHAR_UUID, notification_handler)
while True:
await asyncio.sleep(1)
except Exception as e:
print(f"发生错误: {str(e)}")
finally:
print("断开连接")
# 运行主程序
if __name__ == "__main__":
asyncio.run(main())
很简单,就是那么个意思,esp32端用我之前的就行,注意的是要改下UUID对应上就行了。