web连接低功耗蓝牙设备(BLE)

 

前言:

最近正在开发一个项目,项目的需求如下:
在H5(基于vue框架)页面上,通过js调用webbluetooth接口,读取某个蓝牙设备传输的数据,并返回显示。

使用条件:

     开发版本:无特殊要求

  正式版本:需要HTTPS证书

在手机上面测试:推荐使用Edge浏览器或者谷歌浏览器(其他浏览器我测不行,你们可以测试哈,如还有支持的,希望能给我说一声  Thanks♪(・ω・)ノ)

代码:

1、连接蓝牙

        navigator.bluetooth.requestDevice({
          optionalServices:['蓝牙设备服务ID'],
          acceptAllDevices:true
          }).then(async (device) => {
            that.unCharDevice = device;
            let server = await device.gatt.connect();
            let service = await server.getPrimaryService('蓝牙设备服务ID')
            let characteristic = await service.getCharacteristic('设备主动上报状态ID')
            let unCharacteristic = await service.getCharacteristic('向设备写入命令ID')
            characteristic.readValue();//读取命令
            characteristic.startNotifications();//监听命令下发后的返回值
            //监听蓝牙设备命令下发后的返回值
       characteristic.addEventListener('characteristicvaluechanged',item => {
console.log(item) }) }) .catch(error => { alert('报错'+error) })

2、下发命令

        unCharacteristic.writeValue(
          new Uint8Array('下发的命令byte数组')
        )

3、断开连接

  that.unCharDevice.addEventListener('gattserverdisconnected', event => {
  const device = event.target;
  console.log(`Device ${device.name} is disconnected.`);
});
  return device.gatt.connect();

参考文案:

https://blog.csdn.net/qq_44628595/article/details/117028837

https://zhuanlan.zhihu.com/p/20657057

https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API

posted @ 2021-09-13 10:29  zhumeng_WEB  阅读(2747)  评论(1编辑  收藏  举报