Web Bluetooth API 可实现网页与BLE设备通信,通过 requestDevice 选择设备并连接 GATT 服务器,读写特征值或监听数据变化,需在 HTTPS 环境下使用且仅支持 Chromium 浏览器。

Web Bluetooth API 让网页可以直接与附近的蓝牙低功耗(BLE)设备进行通信,无需安装原生应用。它适用于控制智能灯、传感器、健康设备等支持 BLE 的外设。下面介绍如何使用该 API 实现基本的连接与数据交互。
要使用 Web Bluetooth,第一步是让用户选择一个可用的蓝牙设备。通过 navigator.bluetooth.requestDevice() 方法触发设备选择弹窗。
你需要指定设备需要支持的服务(如心率服务 'heart_rate' 或自定义的 UUID)。例如,连接一个带自定义服务的设备:
const device = await navigator.bluetooth.requestDevice({
filters: [{ services: ['battery_service'] }], // 按服务过滤
optionalServices: ['device_information'] // 需要访问其他服务时添加
});
用户从列表中选择设备后,浏览器会尝试建立 GATT 连接:
const server = await device.gatt.connect();
连接成功后,可以通过远程 GATT 服务器获取服务和特征值。特征值是实际传输数据的单元,分为读、写、通知等类型。
例如,从电池服务中读取当前电量:
const service = await server.getPrimaryService('battery_service');
const characteristic = await service.getCharacteristic('battery_level');
const value = await characteristic.readValue();
const batteryLevel = value.getUint8(0);
console.log(`电量:${batteryLevel}%`);
若要向设备发送指令(比如打开灯光),可使用 writeValue 或 writeValueWithResponse:
const lightChar = await service.getCharacteristic('light_control');
await lightChar.writeValue(new Uint8Array([1])); // 发送开灯命令
某些设备会主动推送数据(如心率监测器)。你需要启用特征值的通知功能来实时接收更新。
设置监听如下:
const sensorChar = await service.getCharacteristic('heart_rate_measurement');
sensorChar.addEventListener('characteristicvaluechanged', (event) => {
const value = event.target.value;
console.log('心率:', value.getUint8(1));
});
await sensorChar.startNotifications();
Web Bluetooth 目前仅在基于 Chromium 的浏览器(如 Chrome、Edge)上支持,且必须运行在 HTTPS 环境下(localhost 除外)。
常见限制包括:
建议在用户操作(如点击按钮)后调用 requestDevice,避免自动弹窗被拦截。
基本上就这些。只要设备服务公开且格式明确,Web Bluetooth 能轻松实现网页端控制。关键是理解 GATT 结构和服务 UUID 的匹配方式。不复杂但容易忽略细节。
以上就是如何用Web Bluetooth API控制蓝牙设备?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号