原生微信小程序蓝牙开发(八)

接上一篇(原生微信小程序蓝牙开发(七)

当 notify 功能启用后,我们就可以进行接收蓝牙返回的信息和发送信息给蓝牙了

我们先讲接收

第八步:接收蓝牙返回的信息(wx.onBLECharacteristicValueChange)

监听蓝牙低功耗设备的特征值变化事件。必须先调用 wx.notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。

参数

function listener

蓝牙低功耗设备的特征值变化事件的监听函数

参数
Object res
属性类型说明
deviceIdstring蓝牙设备 id
serviceIdstring蓝牙特征对应服务的 UUID
characteristicIdstring蓝牙特征的 UUID
valueArrayBuffer特征最新的值

官方文档:wx.onBLECharacteristicValueChange

下面是我的代码:

receiveMsg(event) {
    const that = this;
    wx.onBLECharacteristicValueChange(function (res) {
      wx.$http2
        .request("wechatVisitor/hexToChinese.do", {
          hexStr: that.ab2hex(res.value),
        })
        .then((res) => {
          const str = res.data.data;
          if (str) {
            let target = JSON.parse(str).plate; 
            let tmpColor = JSON.parse(str).color; 
            let result = target.split("").map((char) => ({ value: char }));
            that.setData({
              code: result,
            });

            if (target) {
              that.setData({
                carNumber: target,
                tmpColor,
                "setInfo.hexToChinese": "成功",
              });
              that.readBle();
              // if (!that.data.isBTpaymentPage) {
                // 有车牌信息后直接跳转支付页面
                that.queryPay()
              return;
            } else {
              if (!target) {
                wx.showToast({
                  title: "没有车牌信息",
                  icon: "error",
                });
                that.setData({
                  "setInfo.hexToChinese": "没有车牌信息",
                });
                return;
              }
            }
          }
        });
    });
  },

注意:

我这里将 ArrayBuffer 转16进度字符串后给后端翻译成中文再返回我的,当然也可以直接前端操作,我也将前端将十六进制字符串转换成文字的代码写在下面,大家根据自己项目情况截取

 // ArrayBuffer转16进制字符串示例
 ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ("00" + bit.toString(16)).slice(-2);
      }
    );
    return hexArr.join("");
  },


  // 将十六进制字符串转换成文字
  hexToString(hex) {
    var str = "";
    for (var i = 0; i < hex.length; i += 2) {
      var char = String.fromCharCode(parseInt(hex.substr(i, 2), 16));
      str += char;
    }
    return str;
  },

说完接收信息下面是——给蓝牙发送信息

欢迎大家补充,一起学习进步

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值