美文网首页
微信小程序 IOS蓝牙总是连接失败 如何解决看着里

微信小程序 IOS蓝牙总是连接失败 如何解决看着里

作者: 郭的妻 | 来源:发表于2020-07-08 16:49 被阅读0次

    1.test.js

    // pages/parking/test/test.js
    Page({
    
      /**
       * 页面的初始数据
       */
      data: {
        deviceId: "",//蓝牙设备号
        serviceId: '',//设备的service服务
        notifyId: '',//监听的值 
        writeId: '',//用来写入的值 
        shebei: '',//转化后 设备 命令
        lockId: '3CA5090AE608',
      },
    
      /**
       * 生命周期函数--监听页面加载
       */
      onLoad: function (options) {
    
      },
    
      /** 
       * 结算离场
       * 初始化蓝牙
       */
      lanyaTap() {
        // this.orderPay();
        wx.openBluetoothAdapter({
          success: (res) => {
            console.log('初始化蓝牙成功', res)
            this.getBluetoothAdapterState(); // 检测本机蓝牙是否可用
          },
          fail(err) {
            wx.showModal({
              content: '请开启手机蓝牙后再试',
            });
          }
        });
      },
    
    
      /**
       * 检测本机蓝牙是否可用
       */
      getBluetoothAdapterState() {
        wx.getBluetoothAdapterState({
          success: (res) => {
            console.log('检查蓝牙状态成功', res);
            this.xialock();
          },
          fail(res) {
            wx.showModal({
              content: '本机蓝牙暂不可用,请重新打开手机蓝牙',
            });
          }
        });
      },
    
      /** 下锁 转化发送命令*/
      xialock() {
        var lockid = this.data.lockId;
        var equipmentid = '191117184755';
        var shebei = this.str_add(equipmentid, 2, ":");
        var shebei1 = "10" + ":" + shebei;
        var num = shebei1.split(":");
        var number = Number(num[0]) + Number(num[1]) + Number(num[2]) + Number(num[3]) + Number(num[4]) + Number(num[5]) + Number(num[6]);
        var str = number.toString();
        var status = this.strToHexCharCode(str);
        var shebeiz = "909010" + equipmentid + status + "9191";
        console.log(shebeiz);
        this.Setdata("shebei", shebeiz);
        // 蓝牙
        this.Setdata("deviceId", this.str_add(lockid, 2, ":")) //蓝牙
        this.startBluetoothDevicesDiscovery();
      },
    
    
      /* 将 字符串 转成 AA:bb:cc:dd 格式的 字符串*/
      str_add: function (str, length, pvalue) {
        var re = new RegExp("\\w{1," + length + "}", "g");
        var ma = str.match(re);
        return ma.join(pvalue);
      },
    
    
      /**
       * 开始搜索蓝牙
       */
      startBluetoothDevicesDiscovery() {
        wx.startBluetoothDevicesDiscovery({
          services: [],
          success: (res) => {
            console.log("开始搜索蓝牙", res);
            wx.showLoading({title: '正在搜索设备中...'});
            this.onBluetoothDeviceFound();
          }
        })
      },
    
      /**
       * 监听搜索蓝牙 list
       */
      onBluetoothDeviceFound() {
        wx.onBluetoothDeviceFound((res)=> {
          console.log("监听搜索蓝牙", res)
          var devices = res.devices;
          if (devices[0].advertisData != null) {
            let bf = devices[0].advertisData.slice(4, 10);
            let mac = Array.prototype.map.call(new Uint8Array(bf), x => ('00' + x.toString(16)).slice(-2)).join(':');
            if (mac.toUpperCase() == this.data.deviceId) {
              this.Setdata("deviceId", devices[0].deviceId)
              console.log("监听搜索蓝牙-----toUpperCase", mac.toUpperCase());
              console.log('监听搜索蓝牙-----deviceId:' + devices[0].deviceId);
              wx.hideLoading();
              this.connectblue();
            }
          }
        })
      },
    
      /**
       * 连接蓝牙
       */
      connectblue: function () {
        console.log("连接蓝牙---deviceId", this.data.deviceId);
        wx.createBLEConnection({
          // 这里的 deviceId 需要已经通过 createBLEConnection 与 
          deviceId:this.data.deviceId,
          success: (res) => {
            console.log('连接成功', res);
            this.ToastShow("连接成功");
            this.getservice(); //接设备的service服务
            // 关闭蓝牙
            setTimeout(function () {
              wx.stopBluetoothDevicesDiscovery({
                success: function (res) { },
              });
              wx.offBluetoothDeviceFound({
                success: function (res) { },
              });
            }, 2000);
          },
          fail: (err) => {
            console.log("蓝牙连接失败-------",err)
            this.ToastShow("蓝牙连接失败,请重新连接");
          },
          complete:function(com){
            console.log("蓝牙连接----",com)
          }
        })
      },
    
    
      /**
       * 获取连接设备的service服务
       */
      getservice: function () {
        wx.getBLEDeviceServices({
          deviceId: this.data.deviceId,
          success: (res) => {
            console.log('获取连接设备的service服务', res.services)
            this.Setdata("serviceId", res.services[0].uuid);
            this.getchara(); // 获取连接设备的所有特征值
          }
        })
      },
    
    
      /**
       * 获取连接设备的所有特征值
       */
      getchara: function () {
        wx.getBLEDeviceCharacteristics({
          deviceId: this.data.deviceId,
          serviceId: this.data.serviceId,
          success: (res) => {
            console.log('获取特征值成功', res);
            for (var i = 0; i < res.characteristics.length; i++) { //2个值
              if (res.characteristics[i].properties.notify == true) {
                this.Setdata("notifyId", res.characteristics[i].uuid) //监听的值
                this.startNotice(res.characteristics[i].uuid) //7.0
              }
              if (res.characteristics[i].properties.write == true) {
                this.Setdata("writeId", res.characteristics[i].uuid) //用来写入的值
              }
            }
          },
          fail: function (res) {
            console.log("获取特征值失败", res);
          }
        })
      },
    
      /* 启用notify */
      startNotice(uuid) {
        var that = this;
        wx.notifyBLECharacteristicValueChange({
          state: true, // 启用 notify 功能
          deviceId: this.data.deviceId,
          serviceId: this.data.serviceId,
          characteristicId: this.data.notifyId,
          success: (res) => {
            console.log("启用 notify 功能成功", res)
            // this.sendMy(this.string2buffer('909012191117184755079191'))//8.0 上
            // this.sendMy(this.string2buffer('909010191117184755059191')) //8.0 下
            this.sendMy(this.string2buffer(this.data.shebei))
            wx.onBLECharacteristicValueChange(function (res) {
              var nonceId = that.ab2hex(res.value);
              console.log("notify监听", res, nonceId)
            });
          },
          fail: function (res) {
            console.log(res)
          }
        })
      },
    
      /**
       * 将字符串转换成ArrayBufer
       */
      string2buffer(str) {
        console.log(str);
        let val = str;
        // 将16进制转化为ArrayBuffer
        return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
          return parseInt(h, 16)
        })).buffer
      },
    
      // 数字相加的字符串 转16进制
      strToHexCharCode(str) {
        console.log(str)
        if (str === "") return "";
        var count = 0;
        for (var i = 0; i < str.length; i++) {
          var str1 = (str.charCodeAt(i)).toString(16);
          count += Number(str1);
        }
        console.log(count);
        return count.toString().slice(1);
      },
    
      /**
       * 将ArrayBuffer转换成字符串
       */
      ab2hex(buffer) {
        var hexArr = Array.prototype.map.call(
          new Uint8Array(buffer),
          function (bit) {
            return ('00' + bit.toString(16)).slice(-2)
          }
        )
        return hexArr.join('');
      },
    
      /*
       * 发送指令 
       */
      sendMy(buffer) {
        console.log("开始写入:" + this.ab2hex(buffer))
        console.log(buffer)
        wx.writeBLECharacteristicValue({
          deviceId: this.data.deviceId,
          serviceId: this.data.serviceId,
          characteristicId: this.data.writeId,
          value: buffer,
          success: (res) => {
            console.log("发送指令成功", res)
            // wx.switchTab({
            //   url: '/pages/parking/index/index'
            // });
          },
          fail: function (res) {
            console.log('写入失败', res)
          },
          complete: function () {
            console.log("调用结束");
          }
        })
      },
    
    
      //关闭蓝牙模块
      closeBluetooth: function () {
        var that = this;
        wx.closeBluetoothAdapter({
          success: function (res) {
            console.log("关闭蓝牙成功", res);
          }
        })
      },
    
      /**
       * 每当输入 或 选择值的时候  进行的 赋值
       */
      Setdata: function (data, value) {
        this.setData({
          [data]: value,
        });
      },
    
      /**
      * 小黑窗  toast
      */
      ToastShow: function (msg) {
        wx.showToast({
          title: msg,
          icon: 'none',
          duration: 2000
        });
      },
    })
    

    2.test.wxml

    <view bindtap="lanyaTap">蓝牙</view>
    

    相关文章

      网友评论

          本文标题:微信小程序 IOS蓝牙总是连接失败 如何解决看着里

          本文链接:https://www.haomeiwen.com/subject/zabccktx.html