接上一篇(原生微信小程序蓝牙开发(七))
当 notify 功能启用后,我们就可以进行接收蓝牙返回的信息和发送信息给蓝牙了
我们先讲接收
第八步:接收蓝牙返回的信息(wx.onBLECharacteristicValueChange)
监听蓝牙低功耗设备的特征值变化事件。必须先调用 wx.notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。
参数
function listener
蓝牙低功耗设备的特征值变化事件的监听函数
参数
Object res
属性 | 类型 | 说明 |
---|---|---|
deviceId | string | 蓝牙设备 id |
serviceId | string | 蓝牙特征对应服务的 UUID |
characteristicId | string | 蓝牙特征的 UUID |
value | ArrayBuffer | 特征最新的值 |
官方文档: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;
},
欢迎大家补充,一起学习进步