699ea6e8
杨鑫
完善打印逻辑
|
1
|
import { logBuiltinTscCapability } from './builtinTscCapabilityLog'
|
a001da6d
杨鑫
APP 预览打印
|
2
|
import type { LabelPrintJobPayload } from '../labelPreview/buildLabelPrintPayload'
|
a6f5c1af
“wangming”
开发了安卓基座
|
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
|
import type { LabelTemplateData, SystemLabelTemplate } from './types/printer'
type NativePrinterResult = {
code?: number
msg?: string
errMsg?: string
connected?: boolean
deviceId?: string
deviceName?: string
success?: boolean
backend?: string
pluginVersion?: string
stage?: string
lastError?: string
buildMs?: number
writeMs?: number
commandBytes?: number
lastPrintAt?: number
nativeTextCount?: number
rasterTextCount?: number
qrCodeCount?: number
barcodeCount?: number
imagePatchCount?: number
lineCount?: number
elementCount?: number
available?: boolean
lastAction?: string
}
const nativeFastPrinterState: NativePrinterResult = {
available: false,
lastAction: 'idle',
}
function getUniApi (): any {
return uni as any
}
function parsePluginResult (payload: any): NativePrinterResult {
if (!payload) return {}
if (typeof payload === 'string') {
try {
return JSON.parse(payload)
} catch (_) {
return { msg: payload }
}
}
return payload as NativePrinterResult
}
function updateNativeState (patch: NativePrinterResult) {
Object.assign(nativeFastPrinterState, patch, {
available: isNativeFastPrinterAvailable(),
})
}
function getNativePlugin (): any | null {
// #ifdef APP-PLUS
try {
const api = getUniApi()
if (typeof api.requireNativePlugin !== 'function') return null
const plugin = api.requireNativePlugin('native-fast-printer')
return plugin || null
} catch (_) {
return null
}
// #endif
// #ifndef APP-PLUS
return null
// #endif
}
function ensureNativePlugin (): any {
const plugin = getNativePlugin()
if (!plugin) {
updateNativeState({
available: false,
lastAction: 'plugin:missing',
lastError: 'NATIVE_FAST_PRINTER_PLUGIN_NOT_FOUND',
})
throw new Error('NATIVE_FAST_PRINTER_PLUGIN_NOT_FOUND')
}
return plugin
}
export function isNativeFastPrinterAvailable (): boolean {
const plugin = getNativePlugin()
return !!plugin
&& typeof plugin.connect === 'function'
&& typeof plugin.printTemplate === 'function'
}
|
3ead62fc
杨鑫
优化
|
95
96
97
98
99
|
export function isNativeUposPrintSupported (): boolean {
const plugin = getNativePlugin()
return !!plugin && typeof (plugin as any).printUposCommandBytes === 'function'
}
|
a6f5c1af
“wangming”
开发了安卓基座
|
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
|
export function getNativeFastPrinterState (): NativePrinterResult | null {
return {
...nativeFastPrinterState,
available: isNativeFastPrinterAvailable(),
}
}
function buildTimeoutError (action: string, timeoutMs: number): Error {
const snapshot = getNativeFastPrinterState()
const detail = [
`action=${action}`,
`timeout=${Math.round(timeoutMs / 1000)}s`,
snapshot?.backend ? `backend=${snapshot.backend}` : '',
snapshot?.stage ? `stage=${snapshot.stage}` : '',
snapshot?.commandBytes ? `commandBytes=${snapshot.commandBytes}` : '',
snapshot?.lastError ? `lastError=${snapshot.lastError}` : '',
].filter(Boolean).join('\n')
return new Error(`Native printer timeout.\n${detail}`.trim())
}
function wrapCallback (
action: string,
timeoutMs: number,
executor: (resolve: (value: NativePrinterResult) => void, reject: (reason?: any) => void) => void
) {
return new Promise<NativePrinterResult>((resolve, reject) => {
let settled = false
const timer = setTimeout(() => {
if (settled) return
settled = true
updateNativeState({
lastAction: `${action}:timeout`,
})
reject(buildTimeoutError(action, timeoutMs))
}, timeoutMs)
const done = (handler: () => void) => {
if (settled) return
settled = true
clearTimeout(timer)
handler()
}
executor(
(value) => done(() => resolve(value)),
(reason) => done(() => reject(reason)),
)
})
}
export function getNativeFastPrinterDebugInfo () {
return wrapCallback('getDebugInfo', 5000, (resolve, reject) => {
try {
const nativePlugin = ensureNativePlugin()
if (typeof nativePlugin.getDebugInfo !== 'function') {
const snapshot = getNativeFastPrinterState()
resolve(snapshot || {})
return
}
nativePlugin.getDebugInfo((payload: any) => {
const res = parsePluginResult(payload)
|
fdce24a6
杨鑫
修改bug
|
161
|
const prev = getNativeFastPrinterState() || {}
|
699ea6e8
杨鑫
完善打印逻辑
|
162
|
const patch: NativePrinterResult = {
|
fdce24a6
杨鑫
修改bug
|
163
|
...prev,
|
a6f5c1af
“wangming”
开发了安卓基座
|
164
165
|
...res,
lastAction: 'getDebugInfo',
|
fdce24a6
杨鑫
修改bug
|
166
|
available: isNativeFastPrinterAvailable(),
|
699ea6e8
杨鑫
完善打印逻辑
|
167
|
}
|
fdce24a6
杨鑫
修改bug
|
168
169
170
171
172
173
174
175
176
177
|
const resStage = String(res.stage ?? '').trim()
if (resStage) patch.stage = resStage
if (res.writeMs != null && Number.isFinite(Number(res.writeMs))) {
patch.writeMs = Number(res.writeMs)
}
if (res.commandBytes != null && Number(res.commandBytes) > 0) {
patch.commandBytes = Number(res.commandBytes)
}
if (res.lastError != null && String(res.lastError).trim()) {
patch.lastError = String(res.lastError)
|
699ea6e8
杨鑫
完善打印逻辑
|
178
179
|
}
updateNativeState(patch)
|
fdce24a6
杨鑫
修改bug
|
180
|
resolve({ ...patch })
|
a6f5c1af
“wangming”
开发了安卓基座
|
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
|
})
} catch (error: any) {
reject(error instanceof Error ? error : new Error(String(error || 'NATIVE_FAST_PRINTER_DEBUG_FAILED')))
}
})
}
export function connectNativeFastPrinter (options: {
deviceId: string
deviceName?: string
}) {
return wrapCallback('connect', 12000, (resolve, reject) => {
try {
const nativePlugin = ensureNativePlugin()
if (typeof nativePlugin.connect !== 'function') {
reject(new Error('NATIVE_FAST_PRINTER_CONNECT_METHOD_NOT_FOUND'))
return
}
nativePlugin.connect({
deviceId: options.deviceId,
deviceName: options.deviceName || '',
}, (payload: any) => {
const res = parsePluginResult(payload)
updateNativeState({
...res,
lastAction: 'connect',
})
if (res.code === 1 || res.success === true) {
resolve(res)
return
}
reject(new Error(res.msg || res.errMsg || 'NATIVE_FAST_PRINTER_CONNECT_FAILED'))
})
} catch (error: any) {
reject(error instanceof Error ? error : new Error(String(error || 'NATIVE_FAST_PRINTER_CONNECT_FAILED')))
}
})
}
export function disconnectNativeFastPrinter () {
return wrapCallback('disconnect', 8000, (resolve, reject) => {
try {
const nativePlugin = ensureNativePlugin()
if (typeof nativePlugin.disconnect !== 'function') {
reject(new Error('NATIVE_FAST_PRINTER_DISCONNECT_METHOD_NOT_FOUND'))
return
}
nativePlugin.disconnect((payload: any) => {
const res = parsePluginResult(payload)
updateNativeState({
...res,
lastAction: 'disconnect',
})
if (res.code === 1 || res.success === true) {
resolve(res)
return
}
reject(new Error(res.msg || res.errMsg || 'NATIVE_FAST_PRINTER_DISCONNECT_FAILED'))
})
} catch (error: any) {
reject(error instanceof Error ? error : new Error(String(error || 'NATIVE_FAST_PRINTER_DISCONNECT_FAILED')))
}
})
}
|
a001da6d
杨鑫
APP 预览打印
|
246
247
248
249
250
251
252
253
254
255
256
257
258
|
/**
* 与 setLastLabelPrintJobPayload / getLastLabelPrintJobPayload 同构:
* templateJson、dataJson 分别 JSON.stringify(template)、JSON.stringify(printInputJson),与平台导出的 label-template JSON 对齐。
*
* 注意:Android 插件在任务入队后即回调成功,真正写机在 PRINT_EXECUTOR 后台执行;
* 若 SIZE 超限、构建异常等,JS 仍可能已 resolve,需结合 getNativeFastPrinterDebugInfo 或改原生回调时机排查。
*/
export function printNativeFastFromLabelPrintJob (options: {
deviceId: string
deviceName?: string
payload: LabelPrintJobPayload
dpi?: number
printQty?: number
|
699ea6e8
杨鑫
完善打印逻辑
|
259
260
261
262
263
|
/** 内置 TSC:不经蓝牙,走 UPOS 写出(需基座 AAR ≥ 1.2.7) */
outputTransport?: 'bluetooth' | 'upos'
uposPrefer?: 'builtin' | 'serial'
uposSerialPath?: string
uposBaudrate?: number
|
a001da6d
杨鑫
APP 预览打印
|
264
265
|
}) {
const qty = Math.max(1, options.printQty ?? options.payload.meta?.printQuantity ?? 1)
|
699ea6e8
杨鑫
完善打印逻辑
|
266
267
268
|
/** UPOS 大标签 + 一体机可能超过 120s;与 printUposCommandBytes 量级对齐 */
const uposMs = options.outputTransport === 'upos' ? 600000 : 20000
return wrapCallback('printTemplate', uposMs, (resolve, reject) => {
|
a001da6d
杨鑫
APP 预览打印
|
269
270
271
272
273
274
|
try {
const nativePlugin = ensureNativePlugin()
if (typeof nativePlugin.printTemplate !== 'function') {
reject(new Error('NATIVE_FAST_PRINTER_PRINT_METHOD_NOT_FOUND'))
return
}
|
699ea6e8
杨鑫
完善打印逻辑
|
275
|
const params: Record<string, unknown> = {
|
a001da6d
杨鑫
APP 预览打印
|
276
277
278
279
280
281
|
deviceId: options.deviceId,
deviceName: options.deviceName || '',
templateJson: JSON.stringify(options.payload.template),
dataJson: JSON.stringify(options.payload.printInputJson ?? {}),
dpi: options.dpi || 203,
printQty: qty,
|
699ea6e8
杨鑫
完善打印逻辑
|
282
283
284
285
286
287
288
289
290
291
292
293
294
295
|
}
if (options.outputTransport === 'upos') {
params.outputTransport = 'upos'
params.uposPrefer = options.uposPrefer || 'builtin'
params.uposSerialPath = options.uposSerialPath || ''
params.uposBaudrate = Math.max(1200, options.uposBaudrate ?? 9600)
logBuiltinTscCapability('printTemplate_upos_invoke', {
deviceId: options.deviceId,
printQty: qty,
uposPrefer: params.uposPrefer,
uposBaudrate: params.uposBaudrate,
})
}
nativePlugin.printTemplate(params, (raw: any) => {
|
a001da6d
杨鑫
APP 预览打印
|
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
|
const res = parsePluginResult(raw)
updateNativeState({
...res,
lastAction: 'printTemplate',
})
if (res.code === 1 || res.success === true) {
resolve(res)
return
}
reject(new Error(res.msg || res.errMsg || 'NATIVE_FAST_PRINTER_PRINT_FAILED'))
})
} catch (error: any) {
reject(error instanceof Error ? error : new Error(String(error || 'NATIVE_FAST_PRINTER_PRINT_FAILED')))
}
})
}
|
58d2e61c
杨鑫
最新代码
|
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
|
/**
* 将已生成的 TSC 等指令字节(Base64)交给原生佳博通道写出;与 connect 使用同一 GprinterBluetoothTransport。
* 需基座 AAR ≥ 1.2.0(含 printCommandBytes);旧包会走 sendToPrinter 回退到 JS 经典蓝牙。
*/
export function printNativeCommandBytes (options: {
deviceId: string
deviceName?: string
base64: string
}) {
return wrapCallback('printCommandBytes', 600000, (resolve, reject) => {
try {
const nativePlugin = ensureNativePlugin()
if (typeof nativePlugin.printCommandBytes !== 'function') {
reject(new Error('NATIVE_PRINT_COMMAND_BYTES_NOT_SUPPORTED'))
return
}
nativePlugin.printCommandBytes({
deviceId: options.deviceId,
deviceName: options.deviceName || '',
base64: options.base64,
}, (raw: any) => {
const res = parsePluginResult(raw)
updateNativeState({
...res,
lastAction: 'printCommandBytes',
})
if (res.code === 1 || res.success === true) {
resolve(res)
return
}
reject(new Error(res.msg || res.errMsg || 'NATIVE_PRINT_COMMAND_BYTES_FAILED'))
})
} catch (error: any) {
reject(error instanceof Error ? error : new Error(String(error || 'NATIVE_PRINT_COMMAND_BYTES_FAILED')))
}
})
}
export function isNativePrintCommandBytesSupported (): boolean {
const plugin = getNativePlugin()
return !!plugin && typeof plugin.printCommandBytes === 'function'
}
|
fdce24a6
杨鑫
修改bug
|
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
|
function sleepMs (ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
/**
* printCommandBytes 原生仅首帧回调 queued 即 success,真实写出在后台线程。
* 轮询 debugInfo 直到 printCommandBytes:ok / writeMs 增长 / :error。
*/
export async function waitForNativeCommandBytesWriteComplete (
timeoutMs = 300000,
onPoll?: (percentInWait: number) => void,
): Promise<{ writeMs: number; commandBytes: number; stage: string }> {
const started = Date.now()
const baselineWriteMs = Number(getNativeFastPrinterState()?.writeMs || 0)
while (Date.now() - started < timeoutMs) {
try {
await getNativeFastPrinterDebugInfo()
} catch (_) {
/* 单次 getDebugInfo 失败不中断,继续读缓存 state */
}
const info = getNativeFastPrinterState() || {}
const stage = String(info.stage || '').toLowerCase()
const writeMs = Number(info.writeMs || 0)
const commandBytes = Number(info.commandBytes || 0)
if (stage.includes('printcommandbytes:error')) {
throw new Error(String(info.lastError || 'NATIVE_PRINT_COMMAND_BYTES_ERROR'))
}
if (stage.includes('printcommandbytes:ok')) {
return { writeMs, commandBytes, stage: String(info.stage || '') }
}
/** 部分 AAR stage 字段缺失,但 writeMs 相对 queued 前已增长 → 纸已出 */
if (writeMs > baselineWriteMs && writeMs > 0) {
return { writeMs, commandBytes, stage: stage || 'printCommandBytes:ok' }
}
if (onPoll) {
const elapsed = Date.now() - started
const cap = Math.min(timeoutMs, 90000)
onPoll(Math.min(99, Math.round((elapsed / cap) * 100)))
}
await sleepMs(150)
}
throw new Error('NATIVE_PRINT_COMMAND_BYTES_WRITE_TIMEOUT')
}
|
3ead62fc
杨鑫
优化
|
401
402
403
404
405
406
|
export function printNativeUposCommandBytes (options: {
base64: string
prefer?: 'builtin' | 'serial'
serialPath?: string
baudrate?: number
}) {
|
699ea6e8
杨鑫
完善打印逻辑
|
407
408
|
// 标签整页光栅的 TSC 指令可能很大,20s 过短会导致 Promise 先超时、底层仍可能在写/卡住。
return wrapCallback('printUposCommandBytes', 300000, (resolve, reject) => {
|
3ead62fc
杨鑫
优化
|
409
410
411
412
413
414
|
try {
const nativePlugin = ensureNativePlugin()
if (typeof (nativePlugin as any).printUposCommandBytes !== 'function') {
reject(new Error('NATIVE_UPOS_PRINT_NOT_SUPPORTED'))
return
}
|
699ea6e8
杨鑫
完善打印逻辑
|
415
416
417
|
updateNativeState({
lastAction: 'printUposCommandBytes:start',
})
|
3ead62fc
杨鑫
优化
|
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
|
;(nativePlugin as any).printUposCommandBytes({
base64: options.base64,
prefer: options.prefer || 'builtin',
serialPath: options.serialPath || '',
baudrate: options.baudrate || 9600,
}, (raw: any) => {
const res = parsePluginResult(raw)
updateNativeState({
...res,
lastAction: 'printUposCommandBytes',
})
if (res.code === 1 || res.success === true) {
resolve(res)
return
}
reject(new Error(res.msg || res.errMsg || 'NATIVE_UPOS_PRINT_FAILED'))
})
} catch (error: any) {
reject(error instanceof Error ? error : new Error(String(error || 'NATIVE_UPOS_PRINT_FAILED')))
}
})
}
|
a6f5c1af
“wangming”
开发了安卓基座
|
441
442
443
444
445
446
447
|
export function printNativeFastTemplate (options: {
deviceId: string
deviceName?: string
template: SystemLabelTemplate
data?: LabelTemplateData
dpi?: number
printQty?: number
|
699ea6e8
杨鑫
完善打印逻辑
|
448
449
450
451
|
outputTransport?: 'bluetooth' | 'upos'
uposPrefer?: 'builtin' | 'serial'
uposSerialPath?: string
uposBaudrate?: number
|
a6f5c1af
“wangming”
开发了安卓基座
|
452
|
}) {
|
699ea6e8
杨鑫
完善打印逻辑
|
453
454
|
const uposMs = options.outputTransport === 'upos' ? 600000 : 20000
return wrapCallback('printTemplate', uposMs, (resolve, reject) => {
|
a6f5c1af
“wangming”
开发了安卓基座
|
455
456
457
458
459
460
|
try {
const nativePlugin = ensureNativePlugin()
if (typeof nativePlugin.printTemplate !== 'function') {
reject(new Error('NATIVE_FAST_PRINTER_PRINT_METHOD_NOT_FOUND'))
return
}
|
699ea6e8
杨鑫
完善打印逻辑
|
461
|
const params: Record<string, unknown> = {
|
a6f5c1af
“wangming”
开发了安卓基座
|
462
463
464
465
466
467
|
deviceId: options.deviceId,
deviceName: options.deviceName || '',
templateJson: JSON.stringify(options.template),
dataJson: JSON.stringify(options.data || {}),
dpi: options.dpi || 203,
printQty: options.printQty || 1,
|
699ea6e8
杨鑫
完善打印逻辑
|
468
469
470
471
472
473
474
475
476
477
478
479
480
481
|
}
if (options.outputTransport === 'upos') {
params.outputTransport = 'upos'
params.uposPrefer = options.uposPrefer || 'builtin'
params.uposSerialPath = options.uposSerialPath || ''
params.uposBaudrate = Math.max(1200, options.uposBaudrate ?? 9600)
logBuiltinTscCapability('printTemplate_upos_invoke', {
deviceId: options.deviceId,
printQty: options.printQty || 1,
uposPrefer: params.uposPrefer,
uposBaudrate: params.uposBaudrate,
})
}
nativePlugin.printTemplate(params, (raw: any) => {
|
a6f5c1af
“wangming”
开发了安卓基座
|
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
|
const res = parsePluginResult(raw)
updateNativeState({
...res,
lastAction: 'printTemplate',
})
if (res.code === 1 || res.success === true) {
resolve(res)
return
}
reject(new Error(res.msg || res.errMsg || 'NATIVE_FAST_PRINTER_PRINT_FAILED'))
})
} catch (error: any) {
reject(error instanceof Error ? error : new Error(String(error || 'NATIVE_FAST_PRINTER_PRINT_FAILED')))
}
})
}
|