961eecae
“wangming”
对打印机进行开发
|
1
2
|
import {
clearPrinter,
|
c9bc327f
杨鑫
修改前端
|
3
|
discoverBleWriteCharacteristic,
|
43d16ca6
杨鑫
打印日志
|
4
|
ensureBleUartNotifyIfNeeded,
|
961eecae
“wangming”
对打印机进行开发
|
5
6
7
|
getBluetoothConnection,
getCurrentPrinterDriverKey,
getPrinterType,
|
699ea6e8
杨鑫
完善打印逻辑
|
8
|
getStoredUposPrintOptions,
|
58d2e61c
杨鑫
最新代码
|
9
|
isNativeBaseClassicBluetoothTransport,
|
fdce24a6
杨鑫
修改bug
|
10
|
isVirtualBtBluetoothConnection,
|
961eecae
“wangming”
对打印机进行开发
|
11
12
13
14
|
sendToPrinter,
setBluetoothConnection,
setBuiltinPrinter,
} from '../printerConnection'
|
58d2e61c
杨鑫
最新代码
|
15
|
// @ts-ignore - js bridge module (app-plus only)
|
961eecae
“wangming”
对打印机进行开发
|
16
|
import classicBluetooth from '../bluetoothTool.js'
|
fdce24a6
杨鑫
修改bug
|
17
|
import { rasterizeImageData, rasterizeImageForPrinter, trimMonochromeImageBottomWhitespace, sharpenInvertedTextInMonochromeRaster, INVERTED_TEXT_IMAGE_THRESHOLD } from '../imageRaster'
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
18
19
|
import { buildEscPosImageData, buildEscPosTemplateData } from '../protocols/escPosBuilder'
import { buildTscImageData, buildTscTemplateData } from '../protocols/tscProtocol'
|
a001da6d
杨鑫
APP 预览打印
|
20
|
import type { LabelPrintJobPayload } from '../../labelPreview/buildLabelPrintPayload'
|
a6f5c1af
“wangming”
开发了安卓基座
|
21
22
23
24
|
import {
connectNativeFastPrinter as connectNativeFastPrinterPlugin,
disconnectNativeFastPrinter as disconnectNativeFastPrinterPlugin,
isNativeFastPrinterAvailable,
|
a001da6d
杨鑫
APP 预览打印
|
25
|
printNativeFastFromLabelPrintJob,
|
a6f5c1af
“wangming”
开发了安卓基座
|
26
27
|
printNativeFastTemplate as printNativeFastTemplatePlugin,
} from '../nativeFastPrinter'
|
b04bc3a5
杨鑫
打印日志 重新打印
|
28
29
|
import {
getLabelPrintRasterLayout,
|
699ea6e8
杨鑫
完善打印逻辑
|
30
|
renderLabelPreviewCanvasImageDataForPrint,
|
b04bc3a5
杨鑫
打印日志 重新打印
|
31
|
renderLabelPreviewCanvasToTempPathForPrint,
|
91821909
杨鑫
最新
|
32
|
settleAfterLabelCanvasResize,
|
b04bc3a5
杨鑫
打印日志 重新打印
|
33
|
} from '../../labelPreview/renderLabelPreviewCanvas'
|
83ccb207
杨鑫
最新
|
34
35
|
import {
ensureTemplateHeightCoversElements,
|
fdce24a6
杨鑫
修改bug
|
36
|
rasterDotsToMillimeters,
|
83ccb207
杨鑫
最新
|
37
|
} from '../templatePhysicalMm'
|
3ead62fc
杨鑫
优化
|
38
|
import { storedValueLooksLikeImagePath } from '../../resolveMediaUrl'
|
699ea6e8
杨鑫
完善打印逻辑
|
39
|
import { printRunDiag } from '../printRunDiagnostics'
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
40
|
import { adaptSystemLabelTemplate } from '../systemTemplateAdapter'
|
20554770
杨鑫
更新bug
|
41
|
import { templateRequiresCanvasStyleFidelity } from '../nativeTemplateElementSupport'
|
fdce24a6
杨鑫
修改bug
|
42
|
import { templateHasInvertedTextElements } from '../../invertColorsConfig'
|
b04bc3a5
杨鑫
打印日志 重新打印
|
43
|
import { hydrateSystemTemplateImagesForPrint } from '../hydrateTemplateImagesForPrint'
|
a6f5c1af
“wangming”
开发了安卓基座
|
44
|
import { TEST_PRINT_SYSTEM_TEMPLATE, TEST_PRINT_TEMPLATE_DATA } from '../templates/testPrintTemplate'
|
961eecae
“wangming”
对打印机进行开发
|
45
46
47
48
|
import { describePrinterCandidate, getPrinterDriverByKey, resolvePrinterDriver } from './driverRegistry'
import type {
CurrentPrinterSummary,
LabelPrintPayload,
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
49
50
51
|
LabelTemplateData,
RawImageDataSource,
PrintImageOptions,
|
961eecae
“wangming”
对打印机进行开发
|
52
53
|
PrinterCandidate,
PrinterDriver,
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
54
55
|
StructuredLabelTemplate,
SystemLabelTemplate,
|
961eecae
“wangming”
对打印机进行开发
|
56
57
|
} from '../types/printer'
|
699ea6e8
杨鑫
完善打印逻辑
|
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
type LastImagePrintDebug = {
protocol: string
rasterWidth: number
rasterHeight: number
blackPixels: number
totalPixels: number
blackRatio: number
commandBytes: number
updatedAt: number
}
let lastImagePrintDebug: LastImagePrintDebug | null = null
export function getLastImagePrintDebug (): LastImagePrintDebug | null {
return lastImagePrintDebug
}
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
75
76
77
78
79
80
|
function getPrinterTypeDisplayName (type: '' | 'bluetooth' | 'builtin'): string {
if (type === 'bluetooth') return 'Bluetooth'
if (type === 'builtin') return 'Built-in'
return ''
}
|
961eecae
“wangming”
对打印机进行开发
|
81
82
83
|
function connectClassicBluetooth (device: PrinterCandidate, driver: PrinterDriver): Promise<void> {
return new Promise((resolve, reject) => {
// #ifdef APP-PLUS
|
58d2e61c
杨鑫
最新代码
|
84
85
86
87
88
89
90
91
92
|
/**
* 一体机 / Virtual BT / d320fax:在已集成 native-fast-printer(安卓基座 AAR)时优先走佳博 SDK 连接;
* 不再强制仅用 JS 经典蓝牙,否则光栅大包易超时,且与「走基座」需求不符。
* gp-d320fx、ESC 等仍走通用 socket。
*/
const shouldUseGenericClassicOnly =
driver.key === 'gp-d320fx' ||
driver.key === 'generic-tsc' ||
driver.protocol === 'esc'
|
4ad9ae43
“wangming”
1111
|
93
94
95
96
97
98
99
100
101
|
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) {
|
58d2e61c
杨鑫
最新代码
|
102
103
104
105
106
107
108
109
110
111
112
|
/**
* connDevice 回调 ok 可能早于 socket/outputStream 就绪;
* 若立刻测试打印,会出现 state=idle、outputReady=false。
*/
const start = Date.now()
const poll = () => {
const st = typeof classicBluetooth.getDebugState === 'function'
? classicBluetooth.getDebugState()
: null
const ready = !!st?.outputReady && (!!st?.socketConnected || String(st?.connectionState || '').toLowerCase() === 'connected')
if (ready) {
|
5a192b24
杨鑫
最新同步
|
113
114
115
116
117
118
119
120
|
setBluetoothConnection({
deviceId: device.deviceId,
deviceName: device.name || 'Bluetooth Printer',
deviceType: 'classic',
transportMode: 'generic',
driverKey: driver.key,
mtu: driver.preferredBleMtu || 20,
})
|
58d2e61c
杨鑫
最新代码
|
121
122
123
124
|
resolve()
return
}
if (Date.now() - start > 2500) {
|
5a192b24
杨鑫
最新同步
|
125
|
clearPrinter()
|
58d2e61c
杨鑫
最新代码
|
126
127
128
129
130
131
|
reject(new Error('Classic Bluetooth connection is not ready'))
return
}
setTimeout(poll, 120)
}
poll()
|
4ad9ae43
“wangming”
1111
|
132
133
134
135
136
|
return
}
const message = typeof classicBluetooth.getLastError === 'function'
? classicBluetooth.getLastError()
: ''
|
5a192b24
杨鑫
最新同步
|
137
|
clearPrinter()
|
4ad9ae43
“wangming”
1111
|
138
139
140
|
reject(new Error(message || 'Classic Bluetooth connection failed.'))
})
} catch (error: any) {
|
5a192b24
杨鑫
最新同步
|
141
|
clearPrinter()
|
4ad9ae43
“wangming”
1111
|
142
143
144
145
146
|
reject(error instanceof Error ? error : new Error(String(error || 'Classic Bluetooth connection failed.')))
}
}
if (!shouldUseGenericClassicOnly && isNativeFastPrinterAvailable()) {
|
a6f5c1af
“wangming”
开发了安卓基座
|
147
|
connectNativeFastPrinterPlugin({
|
961eecae
“wangming”
对打印机进行开发
|
148
149
|
deviceId: device.deviceId,
deviceName: device.name || 'Bluetooth Printer',
|
a6f5c1af
“wangming”
开发了安卓基座
|
150
151
152
153
154
|
}).then(() => {
setBluetoothConnection({
deviceId: device.deviceId,
deviceName: device.name || 'Bluetooth Printer',
deviceType: 'classic',
|
4ad9ae43
“wangming”
1111
|
155
|
transportMode: 'native-plugin',
|
a6f5c1af
“wangming”
开发了安卓基座
|
156
157
158
159
160
|
driverKey: driver.key,
mtu: driver.preferredBleMtu || 20,
})
resolve()
}).catch((error: any) => {
|
4ad9ae43
“wangming”
1111
|
161
162
163
164
|
if (driver.key === 'd320fax') {
connectClassicSocketFallback()
return
}
|
a6f5c1af
“wangming”
开发了安卓基座
|
165
|
reject(error instanceof Error ? error : new Error(String(error || 'Classic Bluetooth connection failed.')))
|
961eecae
“wangming”
对打印机进行开发
|
166
|
})
|
a6f5c1af
“wangming”
开发了安卓基座
|
167
168
|
return
}
|
4ad9ae43
“wangming”
1111
|
169
170
171
172
|
if (driver.key === 'd320fax' || shouldUseGenericClassicOnly) {
connectClassicSocketFallback()
return
}
|
a6f5c1af
“wangming”
开发了安卓基座
|
173
|
reject(new Error('NATIVE_FAST_PRINTER_PLUGIN_NOT_FOUND. Please rebuild the custom base with native-fast-printer.'))
|
961eecae
“wangming”
对打印机进行开发
|
174
175
176
177
178
179
180
|
// #endif
// #ifndef APP-PLUS
reject(new Error('Classic Bluetooth requires the app.'))
// #endif
})
}
|
4ad9ae43
“wangming”
1111
|
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
|
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),
})
})
}
|
961eecae
“wangming”
对打印机进行开发
|
205
206
|
function connectBlePrinter (device: PrinterCandidate, driver: PrinterDriver): Promise<void> {
const finalizeExistingBleConnection = async () => {
|
c9bc327f
杨鑫
修改前端
|
207
|
const write = await discoverBleWriteCharacteristic(device.deviceId)
|
961eecae
“wangming”
对打印机进行开发
|
208
209
210
|
if (!write) {
throw new Error('No writable characteristic found. This device may not support printing.')
}
|
43d16ca6
杨鑫
打印日志
|
211
|
await ensureBleUartNotifyIfNeeded(device.deviceId, write.serviceId, write.characteristicId)
|
4ad9ae43
“wangming”
1111
|
212
|
const negotiatedMtu = await requestBleMtu(device.deviceId, driver.preferredBleMtu || 20)
|
961eecae
“wangming”
对打印机进行开发
|
213
214
215
216
217
218
|
setBluetoothConnection({
deviceId: device.deviceId,
deviceName: device.name || 'Bluetooth Printer',
serviceId: write.serviceId,
characteristicId: write.characteristicId,
deviceType: 'ble',
|
4ad9ae43
“wangming”
1111
|
219
|
mtu: negotiatedMtu,
|
961eecae
“wangming”
对打印机进行开发
|
220
|
driverKey: driver.key,
|
a001da6d
杨鑫
APP 预览打印
|
221
|
bleWriteUsesNoResponse: write.bleWriteUsesNoResponse,
|
961eecae
“wangming”
对打印机进行开发
|
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
|
})
}
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)
|
5a192b24
杨鑫
最新同步
|
250
251
252
253
254
255
256
257
258
259
260
|
try {
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') {
|
4ad9ae43
“wangming”
1111
|
261
|
await connectClassicBluetooth(device, driver)
|
5a192b24
杨鑫
最新同步
|
262
263
|
} else {
await connectBlePrinter(device, driver)
|
4ad9ae43
“wangming”
1111
|
264
265
|
}
return driver
|
5a192b24
杨鑫
最新同步
|
266
267
268
|
} catch (error) {
clearPrinter()
throw error
|
4ad9ae43
“wangming”
1111
|
269
|
}
|
961eecae
“wangming”
对打印机进行开发
|
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
|
}
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,
})
}
}
|
699ea6e8
杨鑫
完善打印逻辑
|
290
291
292
|
if (type === 'builtin') {
return getPrinterDriverByKey('generic-tsc')
}
|
961eecae
“wangming”
对打印机进行开发
|
293
294
295
296
297
298
299
300
301
|
return getPrinterDriverByKey('generic-tsc')
}
export function getCurrentPrinterSummary (): CurrentPrinterSummary {
const type = getPrinterType()
const driver = getCurrentPrinterDriver()
if (type === 'builtin') {
return {
type,
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
302
|
displayName: getPrinterTypeDisplayName(type),
|
961eecae
“wangming”
对打印机进行开发
|
303
304
305
306
307
308
309
310
311
312
313
314
|
deviceId: 'builtin',
driverKey: driver.key,
driverName: driver.displayName,
protocol: driver.protocol,
deviceType: '',
}
}
if (type === 'bluetooth') {
const connection = getBluetoothConnection()
if (connection) {
return {
type,
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
315
|
displayName: getPrinterTypeDisplayName(type),
|
961eecae
“wangming”
对打印机进行开发
|
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
|
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: '',
}
}
|
699ea6e8
杨鑫
完善打印逻辑
|
335
336
337
338
339
340
341
342
|
/**
* 内置 UPOS 的 `printNormal` 按「原始字节」打出;多数一体机机芯为 ESC/POS 通道,下发 TSPL 会被当成普通字符印在纸上(与预览 JSON 不符)。
* 内置一律不走原生 TSPL printTemplate,改走预览同源 Canvas → PNG → ESC 光栅(resolveRasterPrintDriver 映射 generic-esc)。
*/
function canUseBuiltinNativeFastTemplatePrint (): boolean {
return false
}
|
a6f5c1af
“wangming”
开发了安卓基座
|
343
|
function canUseNativeFastTemplatePrint (driver: PrinterDriver): boolean {
|
699ea6e8
杨鑫
完善打印逻辑
|
344
345
346
|
if (driver.protocol !== 'tsc' || !isNativeFastPrinterAvailable()) return false
if (isNativeBaseClassicBluetoothTransport()) return true
return canUseBuiltinNativeFastTemplatePrint()
|
a6f5c1af
“wangming”
开发了安卓基座
|
347
348
|
}
|
3ead62fc
杨鑫
优化
|
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
|
function templateHasQrDataForCommandPrint (template: SystemLabelTemplate): boolean {
const elements = template.elements || []
for (const el of elements) {
const type = String(el.type || '').toUpperCase()
if (type !== 'QRCODE') continue
const cfg = (el.config || {}) as Record<string, unknown>
const raw = String(
cfg.data ?? cfg.Data ?? cfg.value ?? cfg.Value ?? cfg.src ?? cfg.Src ?? cfg.url ?? cfg.Url ?? '',
).trim()
if (!raw) continue
if (storedValueLooksLikeImagePath(raw)) continue
return true
}
return false
}
function templateHasUnsupportedElementsForCommandPrint (template: SystemLabelTemplate): boolean {
const elements = template.elements || []
for (const el of elements) {
const type = String(el.type || '').toUpperCase()
if (type.startsWith('TEXT_')) continue
if (
type === 'WEIGHT'
|| type === 'DATE'
|| type === 'TIME'
|| type === 'DURATION'
|| type === 'NUTRITION'
|| type === 'QRCODE'
|| type === 'BARCODE'
|| type === 'IMAGE'
|| type === 'BLANK'
) {
continue
}
return true
}
return false
}
|
a001da6d
杨鑫
APP 预览打印
|
388
389
390
391
392
393
|
/** 预览/业务侧:是否可走 native-fast-printer 的 printTemplate(templateJson + dataJson) */
export function canPrintCurrentLabelViaNativeFastJob (): boolean {
return canUseNativeFastTemplatePrint(getCurrentPrinterDriver())
}
/**
|
699ea6e8
杨鑫
完善打印逻辑
|
394
|
* 整页标签光栅是否一律走 canvasGetImageData(纯 JS 二值化),而不用「PNG → Bitmap.getPixels → readJavaIntArrayValue」。
|
fdce24a6
杨鑫
修改bug
|
395
396
|
* - 内置 / Virtual BT:一体机 Bitmap int[] 桥接读数恒为 0
* - 纯蓝牙 BLE(如 GP-D320FX-ble):手机基座 strip getPixels 同样全白 → RASTER_EMPTY_IMAGE
|
699ea6e8
杨鑫
完善打印逻辑
|
397
398
|
*/
export function shouldRasterPrintViaCanvasImageData (): boolean {
|
fdce24a6
杨鑫
修改bug
|
399
400
401
402
403
|
if (getPrinterType() === 'builtin') return true
if (isVirtualBtBluetoothConnection()) return true
const conn = getBluetoothConnection()
if (conn?.deviceType === 'ble') return true
return false
|
699ea6e8
杨鑫
完善打印逻辑
|
404
405
406
|
}
/**
|
a001da6d
杨鑫
APP 预览打印
|
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
|
* 将 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.')
}
|
699ea6e8
杨鑫
完善打印逻辑
|
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
|
const printQty = Math.max(1, options.printQty ?? payload.meta?.printQuantity ?? 1)
if (canUseBuiltinNativeFastTemplatePrint()) {
const upos = getStoredUposPrintOptions()
await printNativeFastFromLabelPrintJob({
deviceId: 'builtin-upos',
deviceName: 'Built-in',
payload,
dpi: driver.imageDpi || 203,
printQty,
outputTransport: 'upos',
uposPrefer: upos.prefer,
uposSerialPath: upos.serialPath || '',
uposBaudrate: upos.baudrate,
})
if (onProgress) onProgress(100)
return driver
}
|
a001da6d
杨鑫
APP 预览打印
|
445
446
447
448
|
const nativeConnection = getNativeClassicConnection()
if (!nativeConnection) {
throw new Error('Native classic Bluetooth connection is not ready.')
}
|
a001da6d
杨鑫
APP 预览打印
|
449
450
451
452
453
454
455
456
457
458
459
|
await printNativeFastFromLabelPrintJob({
deviceId: nativeConnection.deviceId,
deviceName: nativeConnection.deviceName,
payload,
dpi: driver.imageDpi || 203,
printQty,
})
if (onProgress) onProgress(100)
return driver
}
|
a6f5c1af
“wangming”
开发了安卓基座
|
460
461
|
function getNativeClassicConnection () {
const connection = getBluetoothConnection()
|
4ad9ae43
“wangming”
1111
|
462
|
if (!connection || connection.deviceType !== 'classic' || connection.transportMode !== 'native-plugin') return null
|
a6f5c1af
“wangming”
开发了安卓基座
|
463
464
465
|
return connection
}
|
a001da6d
杨鑫
APP 预览打印
|
466
467
468
|
/**
* 连接自检用测试页;**不要**在此处调用 `postUsAppLabelPrint` / 接口 9(仅预览页业务打印落库)。
*/
|
961eecae
“wangming”
对打印机进行开发
|
469
470
|
export async function testPrintCurrentPrinter (onProgress?: (percent: number) => void): Promise<PrinterDriver> {
const driver = getCurrentPrinterDriver()
|
a6f5c1af
“wangming”
开发了安卓基座
|
471
|
const connection = getBluetoothConnection()
|
4ad9ae43
“wangming”
1111
|
472
473
474
475
476
477
|
if (
driver.protocol === 'tsc'
&& connection?.deviceType === 'classic'
&& connection?.transportMode === 'native-plugin'
&& !isNativeFastPrinterAvailable()
) {
|
a6f5c1af
“wangming”
开发了安卓基座
|
478
479
480
|
throw new Error('NATIVE_FAST_PRINTER_PLUGIN_NOT_FOUND. Please rebuild the custom base with native-fast-printer.')
}
if (canUseNativeFastTemplatePrint(driver)) {
|
699ea6e8
杨鑫
完善打印逻辑
|
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
|
if (canUseBuiltinNativeFastTemplatePrint()) {
const upos = getStoredUposPrintOptions()
await printNativeFastTemplatePlugin({
deviceId: 'builtin-upos',
deviceName: 'Built-in',
template: TEST_PRINT_SYSTEM_TEMPLATE,
data: TEST_PRINT_TEMPLATE_DATA,
dpi: driver.imageDpi || 203,
printQty: 1,
outputTransport: 'upos',
uposPrefer: upos.prefer,
uposSerialPath: upos.serialPath || '',
uposBaudrate: upos.baudrate,
})
if (onProgress) onProgress(100)
return driver
}
|
a6f5c1af
“wangming”
开发了安卓基座
|
498
499
500
501
502
503
504
505
506
507
508
509
510
511
|
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
}
}
|
58d2e61c
杨鑫
最新代码
|
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
|
// d320fax 在部分安卓设备上经 sendToPrinter Promise 链会无回调卡住;测试页走经典蓝牙直发更稳定。
if (driver.key === 'd320fax' && connection?.deviceType === 'classic') {
// #ifdef APP-PLUS
try {
const payload = driver.buildTestPrintData().map((byte) => {
const v = byte & 0xff
return v >= 128 ? v - 256 : v
})
if (onProgress) onProgress(10)
/**
* 部分设备会出现“连接状态看似为 connected,但实际输出流不可写”的假连接。
* 测试打印前强制重连一次 classic socket,确保 btOutStream 新鲜可用。
*/
await new Promise<void>((resolve, reject) => {
if (typeof classicBluetooth?.connDevice !== 'function') {
reject(new Error('D320FAX_CLASSIC_CONN_API_MISSING'))
return
}
let done = false
const timer = setTimeout(() => {
if (done) return
done = true
reject(new Error('D320FAX_CLASSIC_RECONNECT_TIMEOUT'))
}, 8000)
try {
classicBluetooth.connDevice(connection.deviceId, (ok: boolean) => {
if (done) return
done = true
clearTimeout(timer)
if (ok) resolve()
else reject(new Error(classicBluetooth.getLastError?.() || 'D320FAX_CLASSIC_RECONNECT_FAILED'))
})
} catch (e: any) {
if (done) return
done = true
clearTimeout(timer)
reject(e instanceof Error ? e : new Error(String(e || 'D320FAX_CLASSIC_RECONNECT_EXCEPTION')))
}
})
if (typeof classicBluetooth?.ensureConnection === 'function') {
classicBluetooth.ensureConnection(connection.deviceId)
}
if (onProgress) onProgress(30)
const ok = await new Promise<boolean>((resolve) => {
let done = false
const timer = setTimeout(() => {
if (done) return
done = true
resolve(false)
}, 10000)
try {
if (typeof classicBluetooth?.sendByteDataAsync === 'function') {
const started = classicBluetooth.sendByteDataAsync(payload, (sendOk: boolean) => {
if (done) return
done = true
clearTimeout(timer)
resolve(!!sendOk)
})
if (started === false) {
done = true
clearTimeout(timer)
resolve(false)
}
return
}
done = true
clearTimeout(timer)
resolve(false)
} catch {
done = true
clearTimeout(timer)
resolve(false)
}
})
if (!ok) {
const err = typeof classicBluetooth?.getLastError === 'function'
? classicBluetooth.getLastError()
: ''
const debug = typeof classicBluetooth?.getDebugState === 'function'
? classicBluetooth.getDebugState()
: null
const details = [
`device=${connection.deviceId}`,
`state=${String(debug?.connectionState || '-')}`,
`connected=${String(!!debug?.socketConnected)}`,
`outputReady=${String(!!debug?.outputReady)}`,
`sendMode=${String(debug?.lastSendMode || '-')}`,
err ? `lastError=${err}` : '',
].filter(Boolean).join('\n')
throw new Error(`D320FAX_CLASSIC_SEND_TIMEOUT_OR_FAILED\n${details}`)
}
if (onProgress) onProgress(100)
return driver
} catch (e: any) {
throw (e instanceof Error ? e : new Error(String(e || 'D320FAX_CLASSIC_SEND_EXCEPTION')))
}
// #endif
}
|
699ea6e8
杨鑫
完善打印逻辑
|
612
613
614
615
616
617
|
/** 内置 UPOS 同业务打印:勿发 TSC 自检页(会被当文本打出) */
if (getPrinterType() === 'builtin') {
await sendToPrinter(getPrinterDriverByKey('generic-esc').buildTestPrintData(), onProgress)
return driver
}
|
961eecae
“wangming”
对打印机进行开发
|
618
619
620
621
622
623
624
625
626
627
628
629
630
|
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
}
|
699ea6e8
杨鑫
完善打印逻辑
|
631
|
/**
|
fdce24a6
杨鑫
修改bug
|
632
633
|
* 界面仍可存 generic-tsc;内置 UPOS(rk3568 等)实际需 ESC/POS 位图。
* D320FAX Virtual BT 佳博 SDK 连接为 TSC 模式,禁止转 ESC,否则 write 成功但不出纸。
|
699ea6e8
杨鑫
完善打印逻辑
|
634
635
|
*/
export function resolveRasterPrintDriver (driver: PrinterDriver): PrinterDriver {
|
fdce24a6
杨鑫
修改bug
|
636
637
638
639
640
|
const useEscRaster =
getPrinterType() === 'builtin'
&& !isVirtualBtBluetoothConnection()
&& driver.protocol === 'tsc'
if (useEscRaster) {
|
699ea6e8
杨鑫
完善打印逻辑
|
641
642
643
644
645
|
return getPrinterDriverByKey('generic-esc')
}
return driver
}
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
646
647
648
649
650
651
|
export async function printImageForCurrentPrinter (
imageSource: string,
options: PrintImageOptions = {},
onProgress?: (percent: number) => void
): Promise<PrinterDriver> {
const driver = getCurrentPrinterDriver()
|
699ea6e8
杨鑫
完善打印逻辑
|
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
|
const rasterDriver = resolveRasterPrintDriver(driver)
const printerType = getPrinterType()
const startedAt = Date.now()
const withStageTimeout = async <T>(promise: Promise<T>, ms: number, stage: string): Promise<T> => {
return await new Promise<T>((resolve, reject) => {
let settled = false
const timer = setTimeout(() => {
if (settled) return
settled = true
reject(new Error(`PRINT_STAGE_TIMEOUT:${stage}:${ms}`))
}, ms)
promise.then(
(v) => {
if (settled) return
settled = true
clearTimeout(timer)
resolve(v)
},
(e) => {
if (settled) return
settled = true
clearTimeout(timer)
reject(e)
}
)
})
}
console.warn(
'[print-image] start'
+ ' printerType=' + String(printerType || '-')
+ ' driver=' + String(driver.key || '-')
+ ' rasterDriver=' + String(rasterDriver.key || '-')
+ ' source=' + String(imageSource ? 'ok' : 'empty')
)
printRunDiag('printImage_start', {
printerType,
driver: driver.key,
rasterDriver: rasterDriver.key,
rasterProtocol: rasterDriver.protocol,
})
|
58d2e61c
杨鑫
最新代码
|
692
|
if (onProgress) onProgress(2)
|
699ea6e8
杨鑫
完善打印逻辑
|
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
|
const rasterOptions: PrintImageOptions = { ...options }
if (onProgress) {
const prevRasterCb = options.onRasterizeProgress
rasterOptions.onRasterizeProgress = (sub) => {
try {
prevRasterCb?.(sub)
} catch (_) {}
onProgress(2 + Math.round((Math.min(100, Math.max(0, sub)) / 100) * 16))
}
}
const rasterStart = Date.now()
let raster = rasterDriver.protocol === 'esc'
? await rasterizeImageForPrinter(imageSource, rasterDriver, rasterOptions)
: await withStageTimeout(
rasterizeImageForPrinter(imageSource, rasterDriver, rasterOptions),
120000,
'rasterize'
)
console.warn(
'[print-image] rasterize done'
+ ' ms=' + String(Date.now() - rasterStart)
+ ' width=' + String(raster.width)
+ ' height=' + String(raster.height)
)
printRunDiag('printImage_rasterize_done', {
ms: Date.now() - rasterStart,
w: raster.width,
h: raster.height,
})
const calcBlackStats = (r: { width: number; height: number; pixels: number[] }) => {
const totalPixels = Math.max(1, r.width * r.height)
let blackPixels = 0
for (let i = 0; i < r.pixels.length; i++) {
if (r.pixels[i]) blackPixels++
}
const blackRatio = blackPixels / totalPixels
return { totalPixels, blackPixels, blackRatio }
}
let { totalPixels, blackPixels, blackRatio } = calcBlackStats(raster)
if (blackRatio <= 0) {
printRunDiag('printImage_raster_retry_black0', {
blackPixels,
totalPixels,
firstPassMs: Date.now() - rasterStart,
})
// 某些复杂模板在特定阈值/清顶行下会被二值化成“全白”。
// 为了避免继续抛错,这里做一次失败后重光栅兜底:逐步降低 threshold,并在必要时不再清顶行。
const tried: string[] = []
const baseClearTop = options.clearTopRasterRows
const thresholdCandidates = [150, 130, 110, 90]
const clearTopCandidates: Array<number | undefined> = [
baseClearTop,
0, // 兜底:避免把内容切掉(printSystemTemplateForCurrentPrinter 里默认 clearTopRasterRows=1)
].filter((v, i, arr) => v !== undefined || arr.indexOf(undefined) === i)
const rasterAttempts = async () => {
for (const clearTop of clearTopCandidates) {
for (const threshold of thresholdCandidates) {
tried.push(`clearTop=${String(clearTop)};threshold=${threshold}`)
/** 重试光栅勿再回调 onRasterizeProgress,否则会从 2% 重新映射,UI 像「15% 突然掉回 5%」 */
const nextRaster = await rasterizeImageForPrinter(
imageSource,
rasterDriver,
{
...rasterOptions,
threshold,
...(typeof clearTop === 'number' ? { clearTopRasterRows: clearTop } : {}),
onRasterizeProgress: undefined,
},
)
const stats = calcBlackStats(nextRaster)
console.warn(
'[print-image] raster retry stats'
+ ` clearTop=${String(clearTop)}`
+ ` threshold=${threshold}`
+ ` black=${stats.blackPixels}/${stats.totalPixels}`
+ ` ratio=${stats.blackRatio.toFixed(4)}`
)
if (stats.blackRatio > 0) {
raster = nextRaster
totalPixels = stats.totalPixels
blackPixels = stats.blackPixels
blackRatio = stats.blackRatio
return true
}
}
}
return false
}
const ok = await rasterAttempts()
if (!ok) {
throw new Error(
`RASTER_EMPTY_IMAGE:protocol=${String(driver.protocol || '-')};size=${raster.width}x${raster.height};pixels=${blackPixels}/${totalPixels};tried=${tried.join('|')}`
)
}
}
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
793
|
|
fdce24a6
杨鑫
修改bug
|
794
|
const rasterForPrint = finalizeRasterForPrint(raster, rasterDriver.protocol, options)
|
699ea6e8
杨鑫
完善打印逻辑
|
795
796
|
let data: number[] = []
if (rasterDriver.protocol === 'esc') {
|
83ccb207
杨鑫
最新
|
797
|
data = buildEscPosImageData(rasterForPrint, options)
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
798
|
} else {
|
699ea6e8
杨鑫
完善打印逻辑
|
799
800
801
802
803
804
805
806
807
808
809
|
data = buildTscImageData(raster, options, rasterDriver.imageDpi || 203)
}
lastImagePrintDebug = {
protocol: String(rasterDriver.protocol || '-'),
rasterWidth: raster.width,
rasterHeight: raster.height,
blackPixels,
totalPixels,
blackRatio,
commandBytes: data.length,
updatedAt: Date.now(),
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
810
|
}
|
699ea6e8
杨鑫
完善打印逻辑
|
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
|
console.warn(
'[print-image] raster-stats'
+ ' logicalDriver=' + String(driver.key || '-')
+ ' protocol=' + String(lastImagePrintDebug.protocol)
+ ' size=' + String(raster.width) + 'x' + String(raster.height)
+ ' black=' + String(blackPixels) + '/' + String(totalPixels)
+ ' ratio=' + String(blackRatio.toFixed(4))
+ ' bytes=' + String(data.length)
)
console.warn(
'[print-image] build bytes done'
+ ' protocol=' + String(rasterDriver.protocol || '-')
+ ' bytes=' + String(data.length)
+ ' elapsed=' + String(Date.now() - startedAt)
)
printRunDiag('printImage_commands_built', {
protocol: rasterDriver.protocol,
commandBytes: data.length,
elapsedMs: Date.now() - startedAt,
})
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
831
|
|
58d2e61c
杨鑫
最新代码
|
832
|
if (onProgress) onProgress(22)
|
699ea6e8
杨鑫
完善打印逻辑
|
833
834
835
836
|
const sendStart = Date.now()
let sendVisualProgress = 22
let lastExternalProgressAt = Date.now()
const reportSendProgress = (p: number) => {
|
58d2e61c
杨鑫
最新代码
|
837
838
|
if (!onProgress) return
const u = Math.min(100, Math.max(0, Math.round(p)))
|
699ea6e8
杨鑫
完善打印逻辑
|
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
|
const mapped = 22 + Math.round((u / 100) * 78)
if (mapped > sendVisualProgress) {
sendVisualProgress = mapped
onProgress(mapped)
} else {
lastExternalProgressAt = Date.now()
}
}
const sendProgressKeepAlive = onProgress
? setInterval(() => {
// 内置/部分传输链路不会持续回调进度,UI 会停在 22%;这里做轻量保活推进。
if (Date.now() - lastExternalProgressAt < 1200) return
if (sendVisualProgress >= 96) return
sendVisualProgress += sendVisualProgress < 80 ? 2 : 1
onProgress(sendVisualProgress)
}, 800)
: null
printRunDiag('printImage_send_start', { bytes: data.length })
if (rasterDriver.protocol === 'esc') {
try {
await sendToPrinter(data, (p) => {
lastExternalProgressAt = Date.now()
reportSendProgress(p)
if (p === 0 || p === 50 || p === 100) {
printRunDiag('printImage_send_progress', { p })
}
})
} finally {
if (sendProgressKeepAlive) clearInterval(sendProgressKeepAlive)
}
} else {
try {
|
3b969879
杨鑫
修改bug
|
871
|
const sendStageMs = isVirtualBtBluetoothConnection() ? 600000 : 180000
|
699ea6e8
杨鑫
完善打印逻辑
|
872
873
874
875
876
877
878
879
|
await withStageTimeout(
sendToPrinter(data, (p) => {
lastExternalProgressAt = Date.now()
reportSendProgress(p)
if (p === 0 || p === 50 || p === 100) {
printRunDiag('printImage_send_progress', { p })
}
}),
|
3b969879
杨鑫
修改bug
|
880
|
sendStageMs,
|
699ea6e8
杨鑫
完善打印逻辑
|
881
882
883
884
885
886
887
888
889
890
891
892
893
894
|
'sendToPrinter'
)
} finally {
if (sendProgressKeepAlive) clearInterval(sendProgressKeepAlive)
}
}
console.warn(
'[print-image] send done'
+ ' ms=' + String(Date.now() - sendStart)
+ ' total=' + String(Date.now() - startedAt)
)
printRunDiag('printImage_send_done', {
sendMs: Date.now() - sendStart,
totalMs: Date.now() - startedAt,
|
58d2e61c
杨鑫
最新代码
|
895
896
|
})
if (onProgress) onProgress(100)
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
897
898
899
900
901
902
903
904
905
|
return driver
}
export async function printImageDataForCurrentPrinter (
imageData: RawImageDataSource,
options: PrintImageOptions = {},
onProgress?: (percent: number) => void
): Promise<PrinterDriver> {
const driver = getCurrentPrinterDriver()
|
699ea6e8
杨鑫
完善打印逻辑
|
906
|
const rasterDriver = resolveRasterPrintDriver(driver)
|
83ccb207
杨鑫
最新
|
907
|
let raster = rasterizeImageData(imageData, options)
|
fdce24a6
杨鑫
修改bug
|
908
|
raster = finalizeRasterForPrint(raster, rasterDriver.protocol, options)
|
3b969879
杨鑫
修改bug
|
909
|
if (onProgress) onProgress(18)
|
699ea6e8
杨鑫
完善打印逻辑
|
910
|
const data = rasterDriver.protocol === 'esc'
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
911
|
? buildEscPosImageData(raster, options)
|
699ea6e8
杨鑫
完善打印逻辑
|
912
|
: buildTscImageData(raster, options, rasterDriver.imageDpi || 203)
|
3b969879
杨鑫
修改bug
|
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
|
let sendVisual = 22
let lastExternalAt = Date.now()
const reportSend = (p: number) => {
if (!onProgress) return
const mapped = 22 + Math.round((Math.min(100, Math.max(0, p)) / 100) * 78)
if (mapped > sendVisual) {
sendVisual = mapped
onProgress(sendVisual)
} else {
lastExternalAt = Date.now()
}
}
const keepAlive = onProgress
? setInterval(() => {
if (Date.now() - lastExternalAt < 1200) return
if (sendVisual >= 96) return
sendVisual += sendVisual < 80 ? 2 : 1
onProgress(sendVisual)
}, 800)
: null
try {
await sendToPrinter(data, reportSend)
} finally {
if (keepAlive) clearInterval(keepAlive)
}
if (onProgress) onProgress(100)
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
|
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
}
|
b04bc3a5
杨鑫
打印日志 重新打印
|
955
956
957
958
959
960
961
962
963
964
965
966
967
968
|
/** 与预览页「整页光栅」分支一致:用同一套 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>
}
|
91821909
杨鑫
最新
|
969
970
971
972
|
function templateForRasterPrint (template: SystemLabelTemplate): SystemLabelTemplate {
return ensureTemplateHeightCoversElements(template)
}
|
83ccb207
杨鑫
最新
|
973
974
975
976
977
978
979
980
981
982
|
/** 内置 ESC 光栅:按图像高度走纸,裁掉底部全白行(布局已按 contentHeight 时仍可去掉少量留白) */
function finalizeRasterForEscPrint (
raster: { width: number; height: number; pixels: number[] },
protocol: string,
options: PrintImageOptions,
) {
if (protocol !== 'esc' || options.useContentHeight === false) return raster
return trimMonochromeImageBottomWhitespace(raster, 8)
}
|
fdce24a6
杨鑫
修改bug
|
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
|
function finalizeRasterForPrint (
raster: { width: number; height: number; pixels: number[] },
protocol: string,
options: PrintImageOptions,
) {
let out = finalizeRasterForEscPrint(raster, protocol, options)
if (options.sharpenInvertedText) {
out = sharpenInvertedTextInMonochromeRaster(out)
}
return out
}
function buildInvertedTextPrintImageOptions (
template: SystemLabelTemplate,
base: PrintImageOptions = {},
): PrintImageOptions {
if (!templateHasInvertedTextElements(template)) return base
return {
...base,
threshold: base.threshold ?? INVERTED_TEXT_IMAGE_THRESHOLD,
bilinearImageScale: base.bilinearImageScale ?? false,
sharpenInvertedText: base.sharpenInvertedText ?? true,
density: base.density ?? 10,
printSpeed: base.printSpeed ?? 4,
}
}
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
1010
1011
1012
1013
1014
|
export async function printSystemTemplateForCurrentPrinter (
template: SystemLabelTemplate,
data: LabelTemplateData = {},
options: {
printQty?: number
|
b04bc3a5
杨鑫
打印日志 重新打印
|
1015
|
canvasRaster?: SystemTemplatePrintCanvasRasterOptions
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
1016
1017
1018
1019
|
} = {},
onProgress?: (percent: number) => void
): Promise<PrinterDriver> {
const driver = getCurrentPrinterDriver()
|
699ea6e8
杨鑫
完善打印逻辑
|
1020
|
const rasterDriver = resolveRasterPrintDriver(driver)
|
b04bc3a5
杨鑫
打印日志 重新打印
|
1021
|
const canvasRaster = options.canvasRaster
|
3ead62fc
杨鑫
优化
|
1022
1023
1024
1025
|
const bypassCanvasRasterForQr =
!!canvasRaster
&& templateHasQrDataForCommandPrint(template)
&& !templateHasUnsupportedElementsForCommandPrint(template)
|
20554770
杨鑫
更新bug
|
1026
|
&& !templateRequiresCanvasStyleFidelity(template)
|
b04bc3a5
杨鑫
打印日志 重新打印
|
1027
|
|
3ead62fc
杨鑫
优化
|
1028
|
if (canvasRaster && !bypassCanvasRasterForQr) {
|
58d2e61c
杨鑫
最新代码
|
1029
|
if (onProgress) onProgress(1)
|
91821909
杨鑫
最新
|
1030
|
const templateForDraw = templateForRasterPrint(template)
|
b04bc3a5
杨鑫
打印日志 重新打印
|
1031
|
const maxDots =
|
699ea6e8
杨鑫
完善打印逻辑
|
1032
|
rasterDriver.imageMaxWidthDots || (rasterDriver.protocol === 'esc' ? 384 : 576)
|
fdce24a6
杨鑫
修改bug
|
1033
1034
|
const printDpi = rasterDriver.imageDpi || 203
const layout = getLabelPrintRasterLayout(templateForDraw, maxDots, printDpi)
|
58d2e61c
杨鑫
最新代码
|
1035
|
if (onProgress) onProgress(4)
|
b04bc3a5
杨鑫
打印日志 重新打印
|
1036
|
if (canvasRaster.applyLayout) {
|
91821909
杨鑫
最新
|
1037
|
await Promise.resolve(canvasRaster.applyLayout(layout))
|
b04bc3a5
杨鑫
打印日志 重新打印
|
1038
|
}
|
58d2e61c
杨鑫
最新代码
|
1039
|
if (onProgress) onProgress(7)
|
91821909
杨鑫
最新
|
1040
|
await settleAfterLabelCanvasResize()
|
58d2e61c
杨鑫
最新代码
|
1041
|
if (onProgress) onProgress(9)
|
fdce24a6
杨鑫
修改bug
|
1042
1043
|
const layoutMm = rasterDotsToMillimeters(layout.outW, layout.outH, printDpi)
const printOpts = buildInvertedTextPrintImageOptions(templateForDraw, {
|
699ea6e8
杨鑫
完善打印逻辑
|
1044
|
printQty: options.printQty || 1,
|
91821909
杨鑫
最新
|
1045
|
clearTopRasterRows: 0,
|
699ea6e8
杨鑫
完善打印逻辑
|
1046
1047
|
targetWidthDots: layout.outW,
targetHeightDots: layout.outH,
|
fdce24a6
杨鑫
修改bug
|
1048
|
useContentHeight: false,
|
83ccb207
杨鑫
最新
|
1049
|
cutBetweenCopies: true,
|
fdce24a6
杨鑫
修改bug
|
1050
1051
1052
|
widthMm: layoutMm.widthMm,
heightMm: layoutMm.heightMm,
})
|
699ea6e8
杨鑫
完善打印逻辑
|
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
|
const mapRasterProgress = onProgress
? (p: number) => {
onProgress(12 + Math.round((Math.min(100, Math.max(0, p)) / 100) * 88))
}
: undefined
/** 内置一体机:统一 canvas 取像素,避免 Bitmap int[] 桥接假 0 */
if (shouldRasterPrintViaCanvasImageData()) {
try {
const imageData = await renderLabelPreviewCanvasImageDataForPrint(
canvasRaster.canvasId,
canvasRaster.componentInstance,
|
91821909
杨鑫
最新
|
1064
|
templateForDraw,
|
699ea6e8
杨鑫
完善打印逻辑
|
1065
1066
1067
1068
1069
1070
1071
1072
1073
|
layout,
)
if (onProgress) onProgress(12)
await printImageDataForCurrentPrinter(imageData, printOpts, mapRasterProgress)
return driver
} catch (e) {
console.warn('[print] builtin canvasGetImageData failed, fallback PNG→Bitmap raster', e)
}
}
|
b04bc3a5
杨鑫
打印日志 重新打印
|
1074
1075
1076
|
const tmpPath = await renderLabelPreviewCanvasToTempPathForPrint(
canvasRaster.canvasId,
canvasRaster.componentInstance,
|
91821909
杨鑫
最新
|
1077
|
templateForDraw,
|
b04bc3a5
杨鑫
打印日志 重新打印
|
1078
1079
|
layout,
)
|
58d2e61c
杨鑫
最新代码
|
1080
|
if (onProgress) onProgress(12)
|
699ea6e8
杨鑫
完善打印逻辑
|
1081
|
await printImageForCurrentPrinter(tmpPath, printOpts, mapRasterProgress)
|
b04bc3a5
杨鑫
打印日志 重新打印
|
1082
1083
1084
|
return driver
}
|
a6f5c1af
“wangming”
开发了安卓基座
|
1085
|
const connection = getBluetoothConnection()
|
58d2e61c
杨鑫
最新代码
|
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
|
/**
* d320fax + classic 历史上存在卡顿风险,这里对图片 hydration 增加总超时兜底:
* - 成功:使用本地化后的图片路径,提高 IMAGE/QRCODE 出图概率
* - 超时/失败:自动回退原模板,保证仍可继续出纸
*/
if (onProgress) onProgress(1)
const preferStableForD320faxClassic = driver.key === 'd320fax' && connection?.deviceType === 'classic'
let templateReady = template
if (preferStableForD320faxClassic) {
try {
if (onProgress) onProgress(3)
templateReady = await Promise.race<SystemLabelTemplate>([
hydrateSystemTemplateImagesForPrint(template),
new Promise<SystemLabelTemplate>((resolve) => setTimeout(() => resolve(template), 8000)),
])
} catch {
templateReady = template
}
} else {
if (onProgress) onProgress(3)
templateReady = await hydrateSystemTemplateImagesForPrint(template)
}
if (onProgress) onProgress(12)
|
4ad9ae43
“wangming”
1111
|
1110
1111
1112
1113
1114
1115
|
if (
driver.protocol === 'tsc'
&& connection?.deviceType === 'classic'
&& connection?.transportMode === 'native-plugin'
&& !isNativeFastPrinterAvailable()
) {
|
a6f5c1af
“wangming”
开发了安卓基座
|
1116
1117
1118
|
throw new Error('NATIVE_FAST_PRINTER_PLUGIN_NOT_FOUND. Please rebuild the custom base with native-fast-printer.')
}
if (canUseNativeFastTemplatePrint(driver)) {
|
699ea6e8
杨鑫
完善打印逻辑
|
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
|
if (canUseBuiltinNativeFastTemplatePrint()) {
const upos = getStoredUposPrintOptions()
await printNativeFastTemplatePlugin({
deviceId: 'builtin-upos',
deviceName: 'Built-in',
template: templateReady,
data,
dpi: driver.imageDpi || 203,
printQty: options.printQty || 1,
outputTransport: 'upos',
uposPrefer: upos.prefer,
uposSerialPath: upos.serialPath || '',
uposBaudrate: upos.baudrate,
})
if (onProgress) onProgress(100)
return driver
}
|
a6f5c1af
“wangming”
开发了安卓基座
|
1136
1137
1138
1139
1140
|
const nativeConnection = getNativeClassicConnection()
if (nativeConnection) {
await printNativeFastTemplatePlugin({
deviceId: nativeConnection.deviceId,
deviceName: nativeConnection.deviceName,
|
b04bc3a5
杨鑫
打印日志 重新打印
|
1141
|
template: templateReady,
|
a6f5c1af
“wangming”
开发了安卓基座
|
1142
1143
1144
1145
1146
1147
1148
1149
1150
|
data,
dpi: driver.imageDpi || 203,
printQty: options.printQty || 1,
})
if (onProgress) onProgress(100)
return driver
}
}
|
58d2e61c
杨鑫
最新代码
|
1151
|
if (onProgress) onProgress(14)
|
b04bc3a5
杨鑫
打印日志 重新打印
|
1152
|
const structuredTemplate = adaptSystemLabelTemplate(templateReady, data, {
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
1153
1154
|
dpi: driver.imageDpi || 203,
printQty: options.printQty || 1,
|
58d2e61c
杨鑫
最新代码
|
1155
1156
1157
1158
1159
1160
|
disableBitmapText: driver.key === 'gp-d320fx' || driver.key === 'd320fax',
/**
* d320fax 内置字库对货币符号兼容差,TEXT_PRICE 容易整段丢失。
* 仅恢复“货币文本位图”兜底(非全量位图文本),兼顾稳定性与 ¥ 展示。
*/
allowCurrencyBitmapWhenDisabled: true,
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
1161
|
})
|
58d2e61c
杨鑫
最新代码
|
1162
|
if (onProgress) onProgress(16)
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
1163
1164
1165
|
const bytes = driver.protocol === 'esc'
? buildEscPosTemplateData(structuredTemplate)
: buildTscTemplateData(structuredTemplate)
|
58d2e61c
杨鑫
最新代码
|
1166
1167
1168
1169
1170
1171
1172
|
if (onProgress) onProgress(18)
await sendToPrinter(bytes, (p) => {
if (!onProgress) return
const u = Math.min(100, Math.max(0, Math.round(p)))
onProgress(18 + Math.round((u / 100) * 82))
})
if (onProgress) onProgress(100)
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
1173
1174
1175
|
return driver
}
|
961eecae
“wangming”
对打印机进行开发
|
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
|
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
|
4ad9ae43
“wangming”
1111
|
1187
|
if (connection.transportMode === 'native-plugin' && isNativeFastPrinterAvailable()) {
|
a6f5c1af
“wangming”
开发了安卓基座
|
1188
1189
1190
1191
1192
1193
1194
1195
|
disconnectNativeFastPrinterPlugin().catch((e: any) => {
console.error('Disconnect native fast printer failed', e)
}).finally(() => {
clearPrinter()
resolve()
})
return
}
|
961eecae
“wangming”
对打印机进行开发
|
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
|
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()
})
}
|