import { BluetoothUtils, Device } from "@/bluetooth-utils"; import { wait } from "@r-utils/common"; type DeviceData = Required; export class Printer { device: DeviceData; size = 0; constructor(device: DeviceData, { size = 80 } = {}) { this.device = device; this.size = size; } async print(data: number[]) { console.log( data.length, data.slice(0, 100), data.slice(data.length - 100, data.length) ); let res = null; const systemInfo = uni.getSystemInfoSync(); if (systemInfo.uniPlatform === "app" && systemInfo.osName === "android") { res = await BluetoothUtils.sendDataAndroid(this.device, data); } else { res = await BluetoothUtils.bindDevice(this.device, async () => { await wait(100); return await this._print(data); }); } return res; } async _print(data: number[]):Promise { const size = Math.min(data.length, this.size); if (size === 0) { return; } const buf = new ArrayBuffer(size); const dataView = new DataView(buf); for (let i = 0; i < size; i++) { dataView.setUint8(i, data[i]); } await new Promise((resolve, reject) => { uni.writeBLECharacteristicValue({ deviceId: this.device.deviceId, serviceId: this.device.writeServiceId, characteristicId: this.device.writeCharacterId, value: buf, success: (res) => { resolve(res); }, fail: (err) => { reject(err); }, }); }); await wait(30); return await this._print(data.slice(size)); } }