uniapp (small program) sends data in low-power Bluetooth packets

A recent project developed with uniapp used low-power Bluetooth, but the data written in it cannot exceed 20 bytes, so we need to perform subcontracting operations.

Main code:

//指令发送分包处理
	async printbuffs(buffer) {
		// 1.并行调用多次会存在写失败的可能性
		// 2.建议每次写入不超过20字节
		// 分包处理,延时调用
		let that = this;
		const offset = 400; // 偏移量
		let pos = 0; // 位置
		let bytes = buffer.byteLength; // 总字节
		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(buffer)
			})
		}
	}
	// 延时函数
	sendDelay(delay, buffer) {
		return new Promise((resolve, reject) => {
			setTimeout(() => resolve(buffer), delay);
		})
	}

Guess you like

Origin blog.csdn.net/start1018/article/details/128206034