
web bluetooth api允许网页与近距离的低功耗蓝牙(ble)设备进行通信。其基本流程通常包括:请求设备、连接gatt服务器、获取服务、获取特征,然后进行读写操作。以下是一个典型的发送数据到ble设备的javascript代码结构:
const sendStringToDevice = async (message) => {
try {
// 1. 请求蓝牙设备
const device = await navigator.bluetooth.requestDevice({
filters: [{ name: 'monocle' }], // 根据设备名称过滤
optionalServices: ['generic_access'] // 或使用具体的服务UUID,例如 0x2A00 代表 Generic Access
});
// 2. 连接到设备的GATT服务器
const server = await device.gatt.connect();
console.log("设备已连接,GATT服务器可用。");
// 3. 获取指定服务
// 假设我们知道服务UUID,例如 'generic_access' 或其16位UUID 0x1800
const service = await server.getPrimaryService('generic_access'); // 替换为你的服务UUID
console.log("服务已获取。");
// 4. 获取指定特征
// 假设我们知道特征UUID,例如 'device_name' 或其16位UUID 0x2A00
const characteristic = await service.getCharacteristic('device_name'); // 替换为你的特征UUID
console.log("特征已获取。");
// 5. 转换字符串为UInt8Array
const encoder = new TextEncoder('utf-8');
const data = encoder.encode(message);
// 6. 发送数据到特征
await characteristic.writeValue(data);
console.log(`字符串 "${message}" 已成功发送到 monocle 设备。`);
} catch (error) {
console.error('发送字符串到蓝牙设备时出错:', error);
}
};在上述代码中,characteristic.writeValue(data) 是用于向BLE设备发送数据的核心操作。然而,有时开发者会发现此操作既不成功也不报错,而是陷入“ limbo ”状态,即代码执行停滞,后续的 console.log 也不会运行。
导致writeValue操作挂起的常见但隐蔽的原因是,目标GATT特征的通知(Notifications)机制可能没有被正确启用。尽管writeValue本身是写入操作,通常与接收通知无关,但在某些特定的BLE设备实现或GATT协议栈中,设备可能期望在进行写入操作前,客户端(浏览器)先启用该特征的通知功能,以确保通信通道的完整性和设备状态的正确初始化。这可以被视为设备或其GATT服务器的一种隐式握手或状态要求。
要解决此问题,在调用writeValue之前,应尝试调用await characteristic.startNotifications()。
const sendStringToDevice = async (message) => {
try {
const device = await navigator.bluetooth.requestDevice({
filters: [{ name: 'monocle' }],
optionalServices: ['generic_access'] // 确保包含所有相关服务
});
const server = await device.gatt.connect();
console.log("设备已连接,GATT服务器可用。");
const service = await server.getPrimaryService('generic_access'); // 替换为你的服务UUID
console.log("服务已获取。");
const characteristic = await service.getCharacteristic('device_name'); // 替换为你的特征UUID
console.log("特征已获取。");
// 核心解决方案:在写入前启用通知
// 即使你不需要接收通知,某些设备可能要求此步骤来正确初始化特征或防止写入操作挂起
await characteristic.startNotifications();
console.log("特征通知已启用。");
// 可选:添加监听器以处理通知,如果设备会发送响应
characteristic.addEventListener('characteristicvaluechanged', (event) => {
const value = event.target.value;
const decoder = new TextDecoder('utf-8');
console.log('收到通知:', decoder.decode(value));
});
const encoder = new TextEncoder('utf-8');
const data = encoder.encode(message);
await characteristic.writeValue(data);
console.log(`字符串 "${message}" 已成功发送到 monocle 设备。`);
// 如果不再需要通知,可以在操作完成后停止
// await characteristic.stopNotifications();
} catch (error) {
console.error('发送字符串到蓝牙设备时出错:', error);
}
};characteristic.startNotifications() 的主要作用是订阅GATT特征的值变化通知。一旦启用,当设备的该特征值发生改变时,设备会主动向客户端发送通知,客户端可以通过监听characteristicvaluechanged事件来接收这些更新。
然而,在某些情况下,即使客户端的目的是单向写入数据,启用通知也可能成为必要步骤,原因可能包括:
Web Bluetooth API为网页与BLE设备交互提供了强大能力,但在实际开发中,理解GATT协议的细节至关重要。当遇到writeValue操作无响应时,除了检查服务/特征UUID和设备连接状态外,考虑启用GATT特征的通知机制(await characteristic.startNotifications())往往能解决问题。这不仅能避免操作挂起,还能确保设备与浏览器之间建立起稳定可靠的通信链路。通过深入理解BLE协议和善用调试工具,开发者可以更高效地构建健壮的Web Bluetooth应用。
以上就是Web Bluetooth API数据传输指南:解决消息发送阻塞问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号