【uniapp蓝牙分包发送】uniapp蓝牙分包发送,最大20字节
uniapp使用蓝牙与设备通信时候,在向设备写入消息会出现写入失败。查了查官方文档,在调用uni.writeBLECharacteristicValue(OBJECT)方法时候是有限制的。采用分包发送,使用递归方法
·
uniapp蓝牙分包发送,最大20字节
问题记录
uniapp使用蓝牙与设备通信时候,在向设备写入消息会出现写入失败。查了查官方文档,在调用uni.writeBLECharacteristicValue(OBJECT)方法时候是有限制的,如下图
可以看到,建议最大担保发送不超过20字节
问题解决
将数据拆分,分包发送
我的方法是采用递归调用分包发送消息,代码如下
/**
* 向设备发送消息(分包发送,单包20字节,递归发送)
*/
sendMsgToKey(buffer) {
var that = this //vue中的this
const packageSize = 20 //分包大小
if (buffer.byteLength <= 20) { //如果小于20直接发送,不再继续调用
uni.writeBLECharacteristicValue({
// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId: that.deviceId,
// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
serviceId: that.sevice,
// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
characteristicId: that.writeServiceUUID, //第二步写入的特征值
// 这里的value是ArrayBuffer类型
value: buffer,
writeType: 'write',
success: function(res) {
//此时设备已接收到你写入的数据
},
fail: function(err) {
console.log(err)
},
complete: function() {}
})
} else {//如果大于20发送完成后继续递归调用
var newData = buffer.slice(20)
var writeBuffer = buffer.slice(0, 20)
uni.writeBLECharacteristicValue({
// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId: that.deviceId,
// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
serviceId: that.sevice,
// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
characteristicId: that.writeServiceUUID, //第二步写入的特征值
// 这里的value是ArrayBuffer类型
value: writeBuffer,
writeType: 'write',
success: function(res) {
//写入成功后继续递归调用发送剩下的数据
that.sendMsgToKey(newData)
},
fail: function(err) {
console.log(err)
},
complete: function() {}
})
}
},
总结
使用分包发送后问题解决
更多推荐
所有评论(0)