登录
首页 >  文章 >  前端

Web蓝牙控制设备教程详解

时间:2025-12-26 22:23:33 421浏览 收藏

有志者,事竟成!如果你在学习文章,那么本文《Web蓝牙API控制设备教程详解》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

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

如何用Web Bluetooth API控制蓝牙设备?

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();

读取和写入特征值(Characteristics)

连接成功后,可以通过远程 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 除外)。

常见限制包括:

  • 只能访问 BLE 设备,不支持经典蓝牙
  • 部分操作系统权限需手动开启
  • 长时间无操作可能导致连接断开

建议在用户操作(如点击按钮)后调用 requestDevice,避免自动弹窗被拦截。

基本上就这些。只要设备服务公开且格式明确,Web Bluetooth 能轻松实现网页端控制。关键是理解 GATT 结构和服务 UUID 的匹配方式。不复杂但容易忽略细节。

今天关于《Web蓝牙控制设备教程详解》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>