r-util-js/packages/uni-app/src/printer/index.ts

66 lines
1.6 KiB
TypeScript
Raw Normal View History

2026-03-16 17:58:57 +08:00
import { BluetoothUtils, Device } from "@/bluetooth-utils";
import { wait } from "@r-utils/common";
type DeviceData = Required<Device>;
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<any> {
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));
}
}