Web Bluetooth API可在支持的浏览器中实现网页与BLE设备通信,需满足Chromium内核、安全上下文、蓝牙4.0+等条件,通过requestDevice选择设备并建立GATT连接,获取服务与特征值后可读写数据或监听通知,同时需处理错误与断开连接,适用于智能硬件控制等场景。

Web Bluetooth API 允许网页在用户授权的前提下,与附近的低功耗蓝牙(BLE)设备进行通信。这项功能主要支持现代浏览器如 Chrome 和 Edge,适用于开发无需原生应用即可控制 BLE 外设的网页应用,比如智能手环、传感器或物联网设备。
要使用 Web Bluetooth API,需满足以下条件:
通过 navigator.bluetooth.requestDevice() 方法可以弹出系统级设备选择框,让用户从附近设备中选择目标设备。需要指定过滤条件,例如服务 UUID。
navigator.bluetooth.requestDevice({
filters: [{ services: ['battery_service'] }], // 按服务过滤
optionalServices: ['device_information'] // 需要访问其他服务时声明
})
.then(device => {
console.log('已选择设备:', device.name);
return device.gatt.connect(); // 建立 GATT 连接
})
.then(server => {
console.log('GATT 服务器已连接');
// 接下来可读写特征值
});
常见服务名称可使用标准 UUID 字符串或 16/128 位格式,例如 '0x180F' 表示电池服务。
连接 GATT 服务器后,可通过 getPrimaryService() 和 getCharacteristic() 获取具体特征,进而进行数据交互。
server.getPrimaryService('battery_service')
.then(service => service.getCharacteristic('battery_level'))
.then(characteristic => {
// 读取电量
return characteristic.readValue();
})
.then(value => {
const batteryLevel = value.getUint8(0);
console.log(`当前电量: ${batteryLevel}%`);
});
// 开启通知以实时接收更新
characteristic.addEventListener('characteristicvaluechanged', event => {
const value = event.target.value;
console.log('电量变化:', value.getUint8(0));
});
characteristic.startNotifications();
蓝牙操作容易受信号、权限或设备状态影响,建议对每个异步步骤添加 catch 处理。
.catch(error => {
console.error('蓝牙操作失败:', error);
});
当不再使用时,应主动调用 device.gatt.disconnect() 释放资源。也可监听设备断开事件:
device.addEventListener('gattserverdisconnected', () => {
console.log('设备已断开');
});
基本上就这些。只要设备兼容、权限允许,Web Bluetooth 能实现轻量高效的 BLE 通信,适合快速原型开发和简单控制场景。
以上就是如何通过 Web Bluetooth API 与附近的低功耗蓝牙设备进行通信?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号