printerManager.ts
20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
import { blePairRequiresWriteNoResponse } from '../bleWriteModeRules'
import {
clearPrinter,
ensureBleUartNotifyIfNeeded,
getBluetoothConnection,
getCurrentPrinterDriverKey,
getPrinterType,
sendToPrinter,
setBluetoothConnection,
setBuiltinPrinter,
} from '../printerConnection'
import classicBluetooth from '../bluetoothTool.js'
import { rasterizeImageData, rasterizeImageForPrinter } from '../imageRaster'
import { buildEscPosImageData, buildEscPosTemplateData } from '../protocols/escPosBuilder'
import { buildTscImageData, buildTscTemplateData } from '../protocols/tscProtocol'
import type { LabelPrintJobPayload } from '../../labelPreview/buildLabelPrintPayload'
import {
connectNativeFastPrinter as connectNativeFastPrinterPlugin,
disconnectNativeFastPrinter as disconnectNativeFastPrinterPlugin,
isNativeFastPrinterAvailable,
printNativeFastFromLabelPrintJob,
printNativeFastTemplate as printNativeFastTemplatePlugin,
} from '../nativeFastPrinter'
import {
getLabelPrintRasterLayout,
renderLabelPreviewCanvasToTempPathForPrint,
} from '../../labelPreview/renderLabelPreviewCanvas'
import { adaptSystemLabelTemplate } from '../systemTemplateAdapter'
import { hydrateSystemTemplateImagesForPrint } from '../hydrateTemplateImagesForPrint'
import { TEST_PRINT_SYSTEM_TEMPLATE, TEST_PRINT_TEMPLATE_DATA } from '../templates/testPrintTemplate'
import { describePrinterCandidate, getPrinterDriverByKey, resolvePrinterDriver } from './driverRegistry'
import type {
CurrentPrinterSummary,
LabelPrintPayload,
LabelTemplateData,
RawImageDataSource,
PrintImageOptions,
PrinterCandidate,
PrinterDriver,
StructuredLabelTemplate,
SystemLabelTemplate,
} from '../types/printer'
function getPrinterTypeDisplayName (type: '' | 'bluetooth' | 'builtin'): string {
if (type === 'bluetooth') return 'Bluetooth'
if (type === 'builtin') return 'Built-in'
return ''
}
function connectClassicBluetooth (device: PrinterCandidate, driver: PrinterDriver): Promise<void> {
return new Promise((resolve, reject) => {
// #ifdef APP-PLUS
const shouldUseGenericClassicOnly = driver.key === 'gp-d320fx'
const connectClassicSocketFallback = () => {
try {
if (!classicBluetooth || typeof classicBluetooth.connDevice !== 'function') {
reject(new Error('Classic Bluetooth fallback is not available.'))
return
}
classicBluetooth.connDevice(device.deviceId, (ok: boolean) => {
if (ok) {
setBluetoothConnection({
deviceId: device.deviceId,
deviceName: device.name || 'Bluetooth Printer',
deviceType: 'classic',
transportMode: 'generic',
driverKey: driver.key,
mtu: driver.preferredBleMtu || 20,
})
resolve()
return
}
const message = typeof classicBluetooth.getLastError === 'function'
? classicBluetooth.getLastError()
: ''
reject(new Error(message || 'Classic Bluetooth connection failed.'))
})
} catch (error: any) {
reject(error instanceof Error ? error : new Error(String(error || 'Classic Bluetooth connection failed.')))
}
}
if (!shouldUseGenericClassicOnly && isNativeFastPrinterAvailable()) {
connectNativeFastPrinterPlugin({
deviceId: device.deviceId,
deviceName: device.name || 'Bluetooth Printer',
}).then(() => {
setBluetoothConnection({
deviceId: device.deviceId,
deviceName: device.name || 'Bluetooth Printer',
deviceType: 'classic',
transportMode: 'native-plugin',
driverKey: driver.key,
mtu: driver.preferredBleMtu || 20,
})
resolve()
}).catch((error: any) => {
if (driver.key === 'd320fax') {
connectClassicSocketFallback()
return
}
reject(error instanceof Error ? error : new Error(String(error || 'Classic Bluetooth connection failed.')))
})
return
}
if (driver.key === 'd320fax' || shouldUseGenericClassicOnly) {
connectClassicSocketFallback()
return
}
reject(new Error('NATIVE_FAST_PRINTER_PLUGIN_NOT_FOUND. Please rebuild the custom base with native-fast-printer.'))
// #endif
// #ifndef APP-PLUS
reject(new Error('Classic Bluetooth requires the app.'))
// #endif
})
}
/**
* 优先带响应 write(与 uni 默认写入方式一致);仅当没有 write 再用 writeNoResponse(需在下发时传 writeType)。
* 若系统 GATT 只声明 write、未声明 writeNoResponse,却强行 writeNoResponse,会报 property not support (10007)。
*/
function hasBleWriteProperty (item: any): boolean {
const w = item.properties?.write
return w === true || w === 'true'
}
function hasBleWriteNoResponseProperty (item: any): boolean {
const p = item.properties || {}
return (
p.writeNoResponse === true ||
p.writeNoResponse === 'true' ||
p.writeWithoutResponse === true ||
p.writeWithoutResponse === 'true'
)
}
/**
* 无 writeNoResponse 属性则绝不走 Command 写。
* Nordic 白名单在「同时声明 write + writeNoResponse」时优先无响应写(佳博等实测);否则有 write 时优先带响应。
*/
function pickBleWriteUsesNoResponse (serviceId: string, item: any): boolean {
const hw = hasBleWriteProperty(item)
const hn = hasBleWriteNoResponseProperty(item)
if (!hn) return false
if (!hw) return true
return blePairRequiresWriteNoResponse(serviceId, String(item.uuid || ''))
}
function findBleWriteCharacteristic (deviceId: string): Promise<{
serviceId: string
characteristicId: string
bleWriteUsesNoResponse: boolean
} | null> {
return new Promise((resolve) => {
uni.getBLEDeviceServices({
deviceId,
success: (serviceRes) => {
const services = serviceRes.services || []
const next = (index: number) => {
if (index >= services.length) {
resolve(null)
return
}
const serviceId = services[index].uuid
uni.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (charRes) => {
const chars = charRes.characteristics || []
const writable = (item: any) => hasBleWriteProperty(item) || hasBleWriteNoResponseProperty(item)
for (const item of chars) {
const cid = String(item.uuid || '')
if (blePairRequiresWriteNoResponse(serviceId, cid) && writable(item)) {
resolve({
serviceId,
characteristicId: cid,
bleWriteUsesNoResponse: pickBleWriteUsesNoResponse(serviceId, item),
})
return
}
}
const withResp = chars.find(hasBleWriteProperty)
const noResp = chars.find(hasBleWriteNoResponseProperty)
const target = withResp || noResp
if (target) {
resolve({
serviceId,
characteristicId: String(target.uuid || ''),
bleWriteUsesNoResponse: pickBleWriteUsesNoResponse(serviceId, target),
})
return
}
next(index + 1)
},
fail: () => next(index + 1),
})
}
next(0)
},
fail: () => resolve(null),
})
})
}
function requestBleMtu (deviceId: string, preferredMtu: number): Promise<number> {
return new Promise((resolve) => {
const targetMtu = Math.max(20, Math.min(512, Math.round(preferredMtu || 20)))
if (targetMtu <= 20 || typeof (uni as any).setBLEMTU !== 'function') {
resolve(20)
return
}
let settled = false
const done = (value: number) => {
if (settled) return
settled = true
clearTimeout(timer)
resolve(Math.max(20, Math.round(value || 20)))
}
const timer = setTimeout(() => done(20), 3000)
;(uni as any).setBLEMTU({
deviceId,
mtu: targetMtu,
success: (res: any) => done(Number(res?.mtu) || targetMtu),
fail: () => done(20),
})
})
}
function connectBlePrinter (device: PrinterCandidate, driver: PrinterDriver): Promise<void> {
const finalizeExistingBleConnection = async () => {
const write = await findBleWriteCharacteristic(device.deviceId)
if (!write) {
throw new Error('No writable characteristic found. This device may not support printing.')
}
await ensureBleUartNotifyIfNeeded(device.deviceId, write.serviceId, write.characteristicId)
const negotiatedMtu = await requestBleMtu(device.deviceId, driver.preferredBleMtu || 20)
setBluetoothConnection({
deviceId: device.deviceId,
deviceName: device.name || 'Bluetooth Printer',
serviceId: write.serviceId,
characteristicId: write.characteristicId,
deviceType: 'ble',
mtu: negotiatedMtu,
driverKey: driver.key,
bleWriteUsesNoResponse: write.bleWriteUsesNoResponse,
})
}
return new Promise((resolve, reject) => {
uni.createBLEConnection({
deviceId: device.deviceId,
timeout: 10000,
success: async () => {
try {
await finalizeExistingBleConnection()
resolve()
} catch (e: any) {
reject(e)
}
},
fail: (err: any) => {
if (err?.errCode === -1) {
finalizeExistingBleConnection().then(() => resolve()).catch(reject)
} else {
reject(new Error(err?.errMsg || 'BLE connection failed.'))
}
},
})
})
}
export async function connectBluetoothPrinter (device: PrinterCandidate): Promise<PrinterDriver> {
const driver = resolvePrinterDriver(device)
if (driver.key === 'gp-d320fx') {
try {
await connectBlePrinter(device, driver)
} catch (_) {
await connectClassicBluetooth(device, driver)
}
return driver
}
const resolvedType = driver.resolveConnectionType(device)
if (resolvedType === 'classic') {
await connectClassicBluetooth(device, driver)
} else {
await connectBlePrinter(device, driver)
}
return driver
}
export function useBuiltinPrinter (driverKey = 'generic-tsc') {
setBuiltinPrinter(driverKey)
}
export function getCurrentPrinterDriver (): PrinterDriver {
const type = getPrinterType()
const storedKey = getCurrentPrinterDriverKey()
if (storedKey) return getPrinterDriverByKey(storedKey)
if (type === 'bluetooth') {
const connection = getBluetoothConnection()
if (connection) {
return resolvePrinterDriver({
deviceId: connection.deviceId,
name: connection.deviceName,
type: connection.deviceType,
})
}
}
return getPrinterDriverByKey('generic-tsc')
}
export function getCurrentPrinterSummary (): CurrentPrinterSummary {
const type = getPrinterType()
const driver = getCurrentPrinterDriver()
if (type === 'builtin') {
return {
type,
displayName: getPrinterTypeDisplayName(type),
deviceId: 'builtin',
driverKey: driver.key,
driverName: driver.displayName,
protocol: driver.protocol,
deviceType: '',
}
}
if (type === 'bluetooth') {
const connection = getBluetoothConnection()
if (connection) {
return {
type,
displayName: getPrinterTypeDisplayName(type),
deviceId: connection.deviceId,
driverKey: driver.key,
driverName: driver.displayName,
protocol: driver.protocol,
deviceType: connection.deviceType,
}
}
}
return {
type: '',
displayName: '',
deviceId: '',
driverKey: driver.key,
driverName: driver.displayName,
protocol: driver.protocol,
deviceType: '',
}
}
function canUseNativeFastTemplatePrint (driver: PrinterDriver): boolean {
const connection = getBluetoothConnection()
return driver.protocol === 'tsc'
&& connection?.deviceType === 'classic'
&& connection?.transportMode === 'native-plugin'
&& isNativeFastPrinterAvailable()
}
/** 预览/业务侧:是否可走 native-fast-printer 的 printTemplate(templateJson + dataJson) */
export function canPrintCurrentLabelViaNativeFastJob (): boolean {
return canUseNativeFastTemplatePrint(getCurrentPrinterDriver())
}
/**
* 将 buildLabelPrintJobPayload / getLastLabelPrintJobPayload 同构数据送入原生 printTemplate;
* 与 JSON.stringify(payload.template) + JSON.stringify(payload.printInputJson) 一致。
*/
export async function printLabelPrintJobPayloadForCurrentPrinter (
payload: LabelPrintJobPayload,
options: { printQty?: number } = {},
onProgress?: (percent: number) => void
): Promise<PrinterDriver> {
const driver = getCurrentPrinterDriver()
const connection = getBluetoothConnection()
if (
driver.protocol === 'tsc'
&& connection?.deviceType === 'classic'
&& connection?.transportMode === 'native-plugin'
&& !isNativeFastPrinterAvailable()
) {
throw new Error('NATIVE_FAST_PRINTER_PLUGIN_NOT_FOUND. Please rebuild the custom base with native-fast-printer.')
}
if (!canUseNativeFastTemplatePrint(driver)) {
throw new Error('Native fast template print is not available for the current printer.')
}
const nativeConnection = getNativeClassicConnection()
if (!nativeConnection) {
throw new Error('Native classic Bluetooth connection is not ready.')
}
const printQty = Math.max(1, options.printQty ?? payload.meta?.printQuantity ?? 1)
await printNativeFastFromLabelPrintJob({
deviceId: nativeConnection.deviceId,
deviceName: nativeConnection.deviceName,
payload,
dpi: driver.imageDpi || 203,
printQty,
})
if (onProgress) onProgress(100)
return driver
}
function getNativeClassicConnection () {
const connection = getBluetoothConnection()
if (!connection || connection.deviceType !== 'classic' || connection.transportMode !== 'native-plugin') return null
return connection
}
/**
* 连接自检用测试页;**不要**在此处调用 `postUsAppLabelPrint` / 接口 9(仅预览页业务打印落库)。
*/
export async function testPrintCurrentPrinter (onProgress?: (percent: number) => void): Promise<PrinterDriver> {
const driver = getCurrentPrinterDriver()
const connection = getBluetoothConnection()
if (
driver.protocol === 'tsc'
&& connection?.deviceType === 'classic'
&& connection?.transportMode === 'native-plugin'
&& !isNativeFastPrinterAvailable()
) {
throw new Error('NATIVE_FAST_PRINTER_PLUGIN_NOT_FOUND. Please rebuild the custom base with native-fast-printer.')
}
if (canUseNativeFastTemplatePrint(driver)) {
const nativeConnection = getNativeClassicConnection()
if (nativeConnection) {
await printNativeFastTemplatePlugin({
deviceId: nativeConnection.deviceId,
deviceName: nativeConnection.deviceName,
template: TEST_PRINT_SYSTEM_TEMPLATE,
data: TEST_PRINT_TEMPLATE_DATA,
dpi: driver.imageDpi || 203,
printQty: 1,
})
if (onProgress) onProgress(100)
return driver
}
}
await sendToPrinter(driver.buildTestPrintData(), onProgress)
return driver
}
export async function printLabelForCurrentPrinter (
payload: LabelPrintPayload,
onProgress?: (percent: number) => void
): Promise<PrinterDriver> {
const driver = getCurrentPrinterDriver()
await sendToPrinter(driver.buildLabelData(payload), onProgress)
return driver
}
export async function printImageForCurrentPrinter (
imageSource: string,
options: PrintImageOptions = {},
onProgress?: (percent: number) => void
): Promise<PrinterDriver> {
const driver = getCurrentPrinterDriver()
const raster = await rasterizeImageForPrinter(imageSource, driver, options)
if (onProgress) onProgress(5)
let data: number[] = []
if (driver.protocol === 'esc') {
data = buildEscPosImageData(raster, options)
} else {
data = buildTscImageData(raster, options, driver.imageDpi || 203)
}
await sendToPrinter(data, onProgress)
return driver
}
export async function printImageDataForCurrentPrinter (
imageData: RawImageDataSource,
options: PrintImageOptions = {},
onProgress?: (percent: number) => void
): Promise<PrinterDriver> {
const driver = getCurrentPrinterDriver()
const raster = rasterizeImageData(imageData, options)
if (onProgress) onProgress(5)
const data = driver.protocol === 'esc'
? buildEscPosImageData(raster, options)
: buildTscImageData(raster, options, driver.imageDpi || 203)
await sendToPrinter(data, onProgress)
return driver
}
export async function printTemplateForCurrentPrinter (
template: StructuredLabelTemplate,
data: LabelTemplateData = {},
onProgress?: (percent: number) => void
): Promise<PrinterDriver> {
const driver = getCurrentPrinterDriver()
const bytes = driver.protocol === 'esc'
? buildEscPosTemplateData(template, data)
: buildTscTemplateData(template, data)
await sendToPrinter(bytes, onProgress)
return driver
}
/** 与预览页「整页光栅」分支一致:用同一套 canvas 绘制再下发位图(/picture/、中文、¥ 与屏幕一致) */
export type SystemTemplatePrintCanvasRasterOptions = {
canvasId: string
componentInstance: any
/** 绘制前把隐藏 canvas 的 width/height(像素)设为 layout.outW/outH,并 await nextTick */
applyLayout?: (layout: {
cw: number
ch: number
outW: number
outH: number
scale: number
}) => void | Promise<void>
}
export async function printSystemTemplateForCurrentPrinter (
template: SystemLabelTemplate,
data: LabelTemplateData = {},
options: {
printQty?: number
canvasRaster?: SystemTemplatePrintCanvasRasterOptions
} = {},
onProgress?: (percent: number) => void
): Promise<PrinterDriver> {
const driver = getCurrentPrinterDriver()
const canvasRaster = options.canvasRaster
if (canvasRaster) {
const maxDots =
driver.imageMaxWidthDots || (driver.protocol === 'esc' ? 384 : 576)
const layout = getLabelPrintRasterLayout(template, maxDots, driver.imageDpi || 203)
if (canvasRaster.applyLayout) {
await canvasRaster.applyLayout(layout)
}
await new Promise<void>((r) => setTimeout(r, 50))
const tmpPath = await renderLabelPreviewCanvasToTempPathForPrint(
canvasRaster.canvasId,
canvasRaster.componentInstance,
template,
layout,
)
await printImageForCurrentPrinter(
tmpPath,
{
printQty: options.printQty || 1,
clearTopRasterRows: 1,
targetWidthDots: layout.outW,
targetHeightDots: layout.outH,
},
onProgress,
)
return driver
}
const templateReady = await hydrateSystemTemplateImagesForPrint(template)
const connection = getBluetoothConnection()
if (
driver.protocol === 'tsc'
&& connection?.deviceType === 'classic'
&& connection?.transportMode === 'native-plugin'
&& !isNativeFastPrinterAvailable()
) {
throw new Error('NATIVE_FAST_PRINTER_PLUGIN_NOT_FOUND. Please rebuild the custom base with native-fast-printer.')
}
if (canUseNativeFastTemplatePrint(driver)) {
const nativeConnection = getNativeClassicConnection()
if (nativeConnection) {
await printNativeFastTemplatePlugin({
deviceId: nativeConnection.deviceId,
deviceName: nativeConnection.deviceName,
template: templateReady,
data,
dpi: driver.imageDpi || 203,
printQty: options.printQty || 1,
})
if (onProgress) onProgress(100)
return driver
}
}
const structuredTemplate = adaptSystemLabelTemplate(templateReady, data, {
dpi: driver.imageDpi || 203,
printQty: options.printQty || 1,
disableBitmapText: driver.key === 'gp-d320fx',
})
const bytes = driver.protocol === 'esc'
? buildEscPosTemplateData(structuredTemplate)
: buildTscTemplateData(structuredTemplate)
await sendToPrinter(bytes, onProgress)
return driver
}
export function describeDiscoveredPrinter (device: PrinterCandidate) {
return describePrinterCandidate(device)
}
export function disconnectCurrentPrinter (): Promise<void> {
return new Promise((resolve) => {
const type = getPrinterType()
const connection = getBluetoothConnection()
if (type === 'bluetooth' && connection?.deviceType === 'classic') {
// #ifdef APP-PLUS
if (connection.transportMode === 'native-plugin' && isNativeFastPrinterAvailable()) {
disconnectNativeFastPrinterPlugin().catch((e: any) => {
console.error('Disconnect native fast printer failed', e)
}).finally(() => {
clearPrinter()
resolve()
})
return
}
try {
const classic = classicBluetooth
if (classic && classic.disConnDevice) classic.disConnDevice()
} catch (e) {
console.error('Disconnect classic bluetooth failed', e)
}
// #endif
clearPrinter()
resolve()
return
}
clearPrinter()
if (type === 'bluetooth' && connection?.deviceId) {
uni.closeBLEConnection({
deviceId: connection.deviceId,
complete: () => resolve(),
})
return
}
resolve()
})
}