//字符串转arrbuffer
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
}
writeBLECharacteristicValue() {
let obj = {
"stime": 1582201466
};
let newbuffer = string2buffer( JSON.stringify(obj))
wx.writeBLECharacteristicValue({
deviceId: this._deviceId,
serviceId: this._serviceId,
characteristicId: this._characteristicId,
value: newbuffer ,
success(res) {
console.info('成功')
console.log('writeBLECharacteristicValue success', res.errMsg)
},
fail(res) {
console.info('失败')
console.log('writeBLECharacteristicValue fail', res.errMsg)
},
complete(res) {
console.info('完成')
console.log('writeBLECharacteristicValue complete', res.errMsg)
}
})
},
如果数据量在20-30字节之间可直接发送 如果数据量过大 需要进行分包处理 分包发送数据期间要加上时间间隔 不然某些机型可能会传输失败
试了几个方案,结果都是发送失败,提示如下:
errMsg: "writeBLECharacteristicValue:fail getBLEDeviceCharacteristics param is empty."
原码都抄了99.9%,还是错 。。。。求指导:
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
}
const app = getApp()
Page({
writeBLE: function () {
var page = this;
var deviceId = XXXXX
var serviceId = XXXX
var characteristicId = XXXXX
var instruction = page.data.instruction
console.log('instruction', instruction)
let obj = {
"stime": 1582201466
};
let newbuffer = string2buffer( JSON.stringify(obj))
wx.writeBLECharacteristicValue({
deviceId,
serviceId,
characteristicId,
value: newbuffer,
success(res) {
console.log('写入成功', res.errMsg)
},
complete(res) {
console.log('complete', res)
},
})
},
})
"stime": 1582201466
};我估计你是这个了id问题 我这个 obj是蓝牙传输更新用的值 你需要换成你实际蓝牙传输到设备时 接收用的值 我这个是更改设备时间的 对应的字段就是stime 你要和你的硬件那确认下这个值是啥
16进制转换为ArrayBuffer 代码不是很明白,可以在哪里看知识点