zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    QueryRunner查询返回值为int的数据
    c3p0连接池获取数据库连接
    javascript-文件File转换成base64格式
    php 判断是否手机端还是pc端
    MySql -- 数据结构
    tp5--路由的使用方法(深入)
    tp5--路由的使用(初级)
    tp5--开发规范
    二维数组排序 按某个字段排序
    文件记录网页访问量
  • 原文地址:https://www.cnblogs.com/WEB_zhumeng/p/15261279.html
Copyright © 2011-2022 走看看