let deviceId = "asdasdas",//蓝牙设备id 如何获取见上一篇文章
serviceId = "adasdsa";//蓝牙服务id
Page({
onLoad: function (options) {
var _this = this;
_this.getBLEDeviceCharacteristics();//获取蓝牙特征值
},
getBLEDeviceCharacteristics: function () {//获取特征值
var _this = this;
wx.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: serviceId,
success: function (res) {
let charc4 = res.characteristics[4];//读取第五个特征值
let cd100 = charc4.uuid;
let read = charc4.properties.read;//该特征值是否支持 read 操作
let write = charc4.properties.write;//该特征值是否支持 write 操作
let notify = charc4.properties.notify;//该特征值是否支持 notify 操作
if (!read||!write||!notify) { return; }
setTimeout(function () {
_this.writeCmd(cd100);//开始写命令到特征值
wx.onBLECharacteristicValueChange(function (res) {//获取蓝牙特征值变化
var cmd = ab2hex(res.value);//获取到特征值
if (cmd == "13123") {
wx.closeBLEConnection({//断开连接
deviceId,
success(res) { }
})
wx.closeBluetoothAdapter({//关闭蓝牙模块
success(res) { }
})
}
})
}, 200);
}, fail: function (res) {
console.log(res);
}
})
},
writeCmd: function (cd100) {
var _this = this;
let cmd = "13123";//写入蓝牙的指令 需转为buffer
wx.writeBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: cd100,
value: _this.string2buffer(cmd),
success(res) {
setTimeout(function () {
wx.readBLECharacteristicValue({//写入成功后读取该特征值
deviceId: deviceId,
serviceId: serviceId,
characteristicId: cd100,
success() { },
fail() { }
})
wx.notifyBLECharacteristicValueChange({//监听特征值变化
state: true,
deviceId: deviceId,
serviceId: serviceId,
characteristicId: cd100,
success(res) { }
})
}, 200)
}, fail(err) {
_this.writeCmd(cd100);
}
})
},
ab2hex: function (buffer) {//buffer 转字符串
let hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return (bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
},
string2buffer: function (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)
}
}
return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
return parseInt(h, 16)
})).buffer;
}
})
微信小程序蓝牙开发4、写入蓝牙特征值
最新推荐文章于 2022-05-22 09:15:54 发布