javascript
复制代码
// 分包写入蓝牙
async sendWriteBLECharacteristicValue(
deviceId,
serviceId,
writeCharacteristicId,
readCharacteristicId,
buffer,
success, // 成功回调
failure, // 失败回调
) {
const offset = 500; // 偏移量
let pos = 0; // 位置
let bytes = buffer.byteLength; // 总字节
let that = this;
while (bytes > 0) {
let endPos = bytes > offset ? pos + offset : pos + bytes;
const tempBuffer = buffer.slice(pos, endPos);
pos += offset;
bytes -= offset;
// 延迟发送
await that.sendDelay(150, tempBuffer).then((buffer) => {
that.writeBLECharacteristicValue(
deviceId,
serviceId,
writeCharacteristicId,
buffer,
(res) => {
if (buffer.byteLength < offset) {
success(res);
}
},
(err) => {
failure(err);
}
);
});
if (readCharacteristicId) {
console.log(readCharacteristicId, "读文件");
uni.readBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: readCharacteristicId,
});
}
}
}
sendDelay(delay, buffer) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(buffer), delay);
});
}
writeBLECharacteristicValue(
deviceId,
serviceId,
characteristicId,
buffer,
success,
failure
) {
plus.bluetooth.writeBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: characteristicId,
value: buffer,
success(res) {
success(res);
},
fail(err) {
if (res.errCode == "10006") {
//当前连接已断开,清空连接数据
}
console.log("发送失败", res);
failure(err);
},
});
}
javascript
复制代码
this.$ble.sendWriteBLECharacteristicValue(
deviceId, // 蓝牙地址ID
serveiceId, // ABF0
writeCharId, // 写入蓝牙通道 此处用ABF3
readCharId,// 读取蓝牙返回数据通道 此处用ABF4
buffer, // 要写入蓝牙的数据 Uint8Array
(res) => {
console.log("打印完成: " + JSON.stringify(res));},
(err) => {
console.log("打印失败: " + JSON.stringify(err));
}
);