前端蓝牙通讯web Bluetooth使用

384 阅读2分钟

注:如果只需要读取设备传过来的数据就可以只找可读的uuid,要发送指令的话要找设备中可读可写可执行的uuid

    async bluetooth(){
      let that = this;
      let device = await navigator.bluetooth.requestDevice({
        filters: [
            //过滤出来的连接设备
        ],
        optionalServices: [this.dioServiceUuid],
        // acceptAllDevices: true//设置acceptAllDevices代表查询所有蓝牙设备 也是必须配置optionalServices
      });
      device.addEventListener('gattserverdisconnected', onDisconnected);//监听设备断开连接
      let server = await device.gatt.connect()
        .catch(error => {
          console.log('Argh! ' + error);
          alert('Argh! ' + error);
          return;
        });
      //获取当前时间并打印
      var _this = this;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
      _this.gettime = yy + '/' + mm + '/' + dd + ' ' + hh + ':' + mf + ':' + ss;
      alert(_this.gettime + '蓝牙设备已连接! ');
      console.log(_this.gettime + '蓝牙设备已连接! ');
      let service = await server.getPrimaryService(this.dioServiceUuid);
      console.log(service)
      let characteristic = await service.getCharacteristic(this.dioCharacteristicUuid);
      console.log(characteristic)
      characteristic.readValue();//读取命令
      characteristic.startNotifications();//监听命令下发后的返回值0
      let nowStatus = true
      //监听蓝牙设备命令下发后的返回值
      characteristic.addEventListener('characteristicvaluechanged',item => {
         //收到之后会得到一个ArrayBuffer对象,根据设备开发文档解析ArrayBuffer对象然后截取出通过蓝牙所传递的数据
      })
      function onDisconnected(event) {
        let that = this;
        that.stats = false;
        const device = event.target;
        //获取当前时间并打印
        var _this = this;
        let yy = new Date().getFullYear();
        let mm = new Date().getMonth() + 1;
        let dd = new Date().getDate();
        let hh = new Date().getHours();
        let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
        let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
        _this.gettime = yy + '/' + mm + '/' + dd + ' ' + hh + ':' + mf + ':' + ss;
        console.log(this.stats);
        console.log(_this.gettime + `设备: ${device.name} 已经断开连接`);
      }
      // 把向设备发送的指令转换为ArrayBuffer对象发送
      function string2buffer(str) {
        // 首先将字符串转为16进制
        let val = ""
        for (let i = 0; i < str.length; i++) {
          if (val === '') {
            val = str.charCodeAt(i).toString(16)
          } else {
            val += ',' + str.charCodeAt(i).toString(16)
          }
        }
        // 将16进制转化为ArrayBuffer
        return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
          return parseInt(h, 16)
        })).buffer
      }
      function ab2hex(buffer) {
        const hexArr = Array.prototype.map.call(
          new Uint8Array(buffer),
          function (bit) {
            return ('00' + bit.toString(16)).slice(-2);
          }
        )
        return hexArr.join('');
      }
    },