Web Bluetooth API允许网页通过HTTPS在用户手势触发下请求并连接低功耗蓝牙设备,需经用户授权选择设备,利用filters筛选服务或名称,通过GATT协议获取服务与特征,实现数据读写和订阅,同时采用临时设备ID保护隐私,确保安全通信。

浏览器中的JavaScript蓝牙API,也就是我们常说的Web Bluetooth API,它本质上就是一套让网页能够与附近支持低功耗蓝牙(BLE)的设备进行通信的接口。简单来说,它赋予了Web应用直接“对话”物理世界设备的能力,比如智能手环、传感器、甚至一些工业设备。但要用好它,得先理解它不是万能的,它有其特定的应用场景和严格的安全限制。
解决方案: 要真正让一个网页“动起来”去连接蓝牙设备,核心流程其实是围绕着几个关键的Promise链式调用展开的。我个人觉得,理解这个异步流程是掌握Web Bluetooth API的基石。
你需要确保你的网页运行在HTTPS环境下,并且用户的操作(比如点击按钮)触发了蓝牙请求。这是最基本的安全要求,没有之一。
请求设备 (Requesting a Device): 这是与用户交互的第一步。通过
navigator.bluetooth.requestDevice()
async function connectBluetoothDevice() {
try {
const device = await navigator.bluetooth.requestDevice({
filters: [{ services: ['heart_rate'] }], // 过滤心率服务设备
// 或者通过名称过滤:
// filters: [{ namePrefix: 'MySensor' }],
optionalServices: ['battery_service'] // 可选服务,用户连接后可以访问
});
console.log('用户选择了设备:', device.name);
// 接下来连接设备
const server = await device.gatt.connect();
console.log('已连接到GATT服务器');
// 获取服务和特征
const service = await server.getPrimaryService('heart_rate');
console.log('已获取心率服务');
const characteristic = await service.getCharacteristic('heart_rate_measurement');
console.log('已获取心率测量特征');
// 读取或订阅数据
await characteristic.startNotifications();
characteristic.addEventListener('characteristicvaluechanged', handleHeartRateMeasurement);
console.log('已开始接收心率通知');
} catch (error) {
console.error('蓝牙连接或操作出错:', error);
// 这里需要更详细的错误处理,比如用户取消、设备断开等
}
}
function handleHeartRateMeasurement(event) {
const value = event.target.value; // DataView
// 这里需要解析DataView中的数据,通常是Uint8Array
// 假设心率值在第二个字节,具体取决于设备规范
const heartRate = value.getUint8(1);
console.log('当前心率:', heartRate);
}filters
services
name
namePrefix
optionalServices
filters
optionalServices
optionalServices
连接到GATT服务器 (Connecting to GATT Server): 一旦用户选择了设备,你就会得到一个
BluetoothDevice
device.gatt.connect()
BluetoothRemoteGATTServer
获取服务和特征 (Getting Services and Characteristics): BLE设备的数据是以服务(Services)和特征(Characteristics)的形式组织的。一个服务可以包含多个特征,每个特征代表一个具体的数据点或控制点。
server.getPrimaryService(serviceUUID)
service.getCharacteristic(characteristicUUID)
'heart_rate'
0x2A37
读写和订阅数据 (Reading, Writing, and Subscribing): 拿到特征后,你就可以进行操作了:
characteristic.readValue()
DataView
characteristic.writeValue(value)
value
ArrayBuffer
DataView
characteristic.startNotifications()
characteristic.stopNotifications()
characteristic.addEventListener('characteristicvaluechanged', handler)整个过程都是基于Promise的异步操作,所以错误处理(
try...catch
说实话,Web Bluetooth API在设计之初,安全和隐私就是被放在非常高的优先级来考虑的。这不像一些本地应用,可以随意扫描和连接设备。在浏览器环境里,限制多是好事,毕竟没人希望随便打开一个网页,自己的蓝牙设备就被悄悄控制了。
最核心的几点:
navigator.bluetooth.requestDevice()
requestDevice()
以上就是浏览器JS蓝牙API如何使用?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号