Uniapp如何解决蓝牙写入数据超过20字节

560 阅读2分钟

Uniapp如何解决蓝牙写入数据超过20字节

官网说明:

  1. 并行调用多次会存在写失败的可能性。
  2. APP不会对写入数据包大小做限制,但系统与蓝牙设备会限制蓝牙4.0单次传输的数据大小,超过最大字节数后会发生写入错误,建议每次写入不超过20字节。
  3. 若单次写入数据过长,iOS 上存在系统不会有任何回调的情况(包括错误回调)。

使用分片写入方法:

方案 1: 使用y-bluetooth(uni-bluetooth)工具:

npm install uni-bluetooth

github: uni-bluetooth

npm: uni-bluetooth

uni插件市场: y-bluetooth

使用文档: 文档

// 向设备写入16进制的字符串 '010041240100640000000000006a46010041240100640000000000006a46'

const value = '010041240100640000000000006a46010041240100640000000000006a46'
const ble = UniBluetooth.BLE({
    deviceId: 设备ID,
})
// 第三个参数为true时会自动分片写入蓝牙数据
ble.writeValue(value, 'hex', true) // 'hex'表示value的值是16进制的,另外还有'string' 和 'buffer' 两种类型

如果使用分片写入,又需要同时写入多个指令:

// 向设备写入16进制的字符串 '010041240100640000000000006a46010041240100640000000000006a46'

const value = '010041240100640000000000006a46'
const ble = UniBluetooth.BLE({
    deviceId: 设备ID,
})
// 使用eventListWriteValue会自动将多个方法依次写入
// 事件1
ble.eventListWriteValue({
    value,
    endDelay: 2000, // 2000ms后执行下一个eventListWriteValue
    loop: true
})
// 下面的方法会在事件1执行完毕后两秒执行
ble.eventListWriteValue({
    value,
})

方案 2: 递归写入:

function writeValue(value, startIndex = 0) {
	const packetSize = 20; // 每个小包的大小为20字节
	// const len = value.byteLength //如果value是ArrayBuffer
	const len = value.length // 如果value是String
	const endIndex = startIndex + packetSize
	uni.writeBLECharacteristicValue({
		...其他参数,
		value: value.slice(startIndex, endIndex),
		success() {
			if (len > endIndex) {
				// 递归调用
				writeValue(value, endIndex)
			}
		}
	})
}