# 作用:扫描周围BLE设备
# 应用:发现Arduino设备
import asyncio
from bleak import BleakScanner
async def scan_ble_devices():
print("Scanning for BLE devices...")
devices = await BleakScanner.discover(timeout=5.0)
if not devices:
print("No BLE devices found.")
else:
print("Found devices:")
for d in devices:
print(f"{d.address} - {d.name}")
# 运行扫描
asyncio.run(scan_ble_devices())
2. bleak_name_conn.py - 按名称连接
python复制代码
# 作用:通过设备名称连接并读取特征
# 应用:连接特定Arduino设备
import asyncio
from bleak import BleakScanner, BleakClient
# 目标设备名称片段
TARGET_NAME_FRAGMENT = "ArduinoSensor" # 改为你的设备名
# 特征UUID(必须与Arduino一致)
CHARACTERISTIC_UUID = "19B10001-E8F2-537E-4F6C-D104768A1214"
async def scan_and_connect():
print("Scanning for BLE devices...")
devices = await BleakScanner.discover(timeout=5.0)
# 查找目标设备
target_device = None
for d in devices:
if d.name and TARGET_NAME_FRAGMENT in d.name:
target_device = d
break
if not target_device:
print(f"No device found with name containing '{TARGET_NAME_FRAGMENT}'.")
return
print(f"Found target: {target_device.name} ({target_device.address})")
# 连接并读取数据
async with BleakClient(target_device.address) as client:
if client.is_connected:
print("Connected successfully.")
try:
# 读取特征值
value = await client.read_gatt_char(CHARACTERISTIC_UUID)
print(f"Raw value: {value}")
# 尝试解码为字符串
try:
decoded_value = value.decode('utf-8')
print("Decoded value:", decoded_value)
except:
print("Value is not UTF-8 string")
except Exception as e:
print("Failed to read characteristic:", e)
else:
print("Failed to connect.")
asyncio.run(scan_and_connect())
3. bleak_rec_notify.py - 接收通知
python复制代码
# 作用:订阅特征通知并实时接收数据
# 应用:实时接收传感器数据
import asyncio
from bleak import BleakScanner, BleakClient
# 目标设备名称片段
TARGET_NAME_FRAGMENT = "ArduinoSensor"
# 特征UUID
CHARACTERISTIC_UUID = "19B10001-E8F2-537E-4F6C-D104768A1214"
# 通知处理函数
def handle_notification(sender, data):
print(f"[Notification] From {sender}: {data}")
try:
# 解码JSON数据(需要)
decoded_data = data.decode('utf-8')
print("Decoded:", decoded_data)
# 在这里添加MQTT发布逻辑
# mqtt_client.publish("sensors/dht", decoded_data)
except Exception as e:
print("Decoding error:", e)
async def scan_connect_and_subscribe():
print("Scanning for devices...")
devices = await BleakScanner.discover(timeout=5.0)
# 查找设备
target_device = None
for d in devices:
if d.name and TARGET_NAME_FRAGMENT in d.name:
target_device = d
break
if not target_device:
print(f"No device found with name containing '{TARGET_NAME_FRAGMENT}'.")
return
print(f"Found device: {target_device.name} ({target_device.address})")
# 连接并订阅通知
async with BleakClient(target_device.address) as client:
if client.is_connected:
print("Connected successfully.")
try:
# 启动通知订阅
await client.start_notify(CHARACTERISTIC_UUID, handle_notification)
print("Subscribed to notifications. Press Ctrl+C to stop.")
# 保持连接,持续接收数据
while True:
await asyncio.sleep(1)
except Exception as e:
print("Failed to subscribe:", e)
else:
print("Failed to connect.")
try:
asyncio.run(scan_connect_and_subscribe())
except KeyboardInterrupt:
print("Program stopped by user.")