
本文详解Web Bluetooth API中因未启用通知导致消息无法发送的问题,重点说明startNotifications()的必要性、正确调用时机及完整发送流程。
本文详解web bluetooth api中因未启用通知导致消息无法发送的问题,重点说明startnotifications()的必要性、正确调用时机及完整发送流程。
在使用 Web Bluetooth API 向 BLE 设备(如运行 Python 的接收端)发送数据时,若代码执行后既无成功日志也无错误抛出,极大概率是遗漏了关键的特征值(Characteristic)通知启用步骤——即未调用 characteristic.startNotifications()。
⚠️ 注意:startNotifications() 并非仅用于“接收设备推送”,在许多 BLE 设备(尤其是基于 BlueZ、PyBluez 或 bleak 的 Python 实现)中,该方法会触发服务端对写入操作的监听准备,是建立双向通信通道的必要前提。即使你只打算单向发送(writeValue),部分固件或 Python 服务端逻辑仍依赖通知通道被激活后才响应写请求。
以下是修复后的完整、可运行示例(关键修正已加注):
const sendStringToDevice = async () => {
try {
// 1. 请求设备(确保设备已开启且广播名匹配)
const device = await navigator.bluetooth.requestDevice({
filters: [{ name: 'monocle' }], // 或使用 services: ['00002a00-0000-1000-8000-00805f9b34fb']
optionalServices: ['00002a00-0000-1000-8000-00805f9b34fb'], // 推荐使用标准 UUID 字符串格式
});
// 2. 连接 GATT 服务器
const server = await device.gatt.connect();
// 3. 获取指定服务(注意:getPrimaryServices() 返回数组,需索引或 filter)
const services = await server.getPrimaryServices('00002a00-0000-1000-8000-00805f9b34fb');
if (services.length === 0) throw new Error('Service not found');
const service = services[0];
// 4. 获取目标 characteristic(需明确 UUID;0x2A00 是 Generic Access - Device Name,通常为只读)
// ✅ 正确做法:使用实际用于接收消息的可写特征值 UUID(例如 'ff01' 或自定义 UUID)
const characteristics = await service.getCharacteristics('ff01'); // 替换为你的写入特征值 UUID
if (characteristics.length === 0) throw new Error('Characteristic not found');
const characteristic = characteristics[0];
// ? 关键修复:启用通知(即使只写不读,此步常为必需)
await characteristic.startNotifications();
// 5. 编码并写入数据
const encoder = new TextEncoder('utf-8');
const data = encoder.encode(message);
await characteristic.writeValue(data);
console.log(`String "${message}" sent successfully to monocle`);
} catch (error) {
console.error('Error sending string to Bluetooth device:', error);
}
};
? 重要注意事项:
-
UUID 格式统一:
optionalServices和getCharacteristic()中务必使用标准 128 位 UUID 字符串(如'00002a00-0000-1000-8000-00805f9b34fb'),而非短码0x2A00(后者仅在部分底层 API 中支持,Web Bluetooth 不识别)。 -
Characteristic 权限检查:确保目标 characteristic 具有
write或writeWithoutResponse属性(可通过characteristic.properties验证),否则writeValue()会静默失败。 -
Python 端配合:若使用
bleak,需在start_notify()回调中处理写入;若用PyBluez,需正确设置Properties.Write并监听onWriteRequest。 - 浏览器限制:Web Bluetooth 仅在安全上下文(HTTPS 或 localhost)下可用,且需用户主动触发(如点击按钮),不可在页面加载时自动执行。
总结:startNotifications() 是打开通信握手的关键一环。它不仅为接收做准备,更常作为 BLE 设备服务端进入“可写就绪”状态的信号。忽略此步,writeValue() 将陷入挂起,既不成功也不报错——这正是你遇到“卡在中间”的根本原因。










