nativeFastPrinter.ts
7.3 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
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'
}
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)
updateNativeState({
...res,
lastAction: 'getDebugInfo',
})
resolve(res)
})
} 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')))
}
})
}
export function printNativeFastTemplate (options: {
deviceId: string
deviceName?: string
template: SystemLabelTemplate
data?: LabelTemplateData
dpi?: number
printQty?: number
}) {
return wrapCallback('printTemplate', 20000, (resolve, reject) => {
try {
const nativePlugin = ensureNativePlugin()
if (typeof nativePlugin.printTemplate !== 'function') {
reject(new Error('NATIVE_FAST_PRINTER_PRINT_METHOD_NOT_FOUND'))
return
}
nativePlugin.printTemplate({
deviceId: options.deviceId,
deviceName: options.deviceName || '',
templateJson: JSON.stringify(options.template),
dataJson: JSON.stringify(options.data || {}),
dpi: options.dpi || 203,
printQty: options.printQty || 1,
}, (raw: any) => {
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')))
}
})
}