printerConnection.ts
12.9 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
/**
* 打印机连接与下发:蓝牙(BLE) / 一体机(TCP localhost)
*/
import type { ActiveBtDeviceType, PrinterType } from './types/printer'
import classicBluetooth from './bluetoothTool.js'
import { getDeviceFingerprint } from '../deviceInfo'
const STORAGE_PRINTER_TYPE = 'printerType'
const STORAGE_BT_DEVICE_ID = 'btDeviceId'
const STORAGE_BT_DEVICE_NAME = 'btDeviceName'
const STORAGE_BT_SERVICE_ID = 'btServiceId'
const STORAGE_BT_CHARACTERISTIC_ID = 'btCharacteristicId'
const STORAGE_BT_DEVICE_TYPE = 'btDeviceType' // 'ble' | 'classic'
const STORAGE_BLE_MTU = 'bleMTU'
const STORAGE_BUILTIN_PORT = 'builtinPort'
const STORAGE_PRINTER_DRIVER_KEY = 'printerDriverKey'
const BUILTIN_PROBE_PORTS = [9100, 4000, 9000, 6000]
const BUILTIN_PRINTER_DEVICE_KEYWORDS: string[] = [
// 在这里补充需要走 Built-in 的设备型号关键字(小写匹配)
// 例如:'desktop-aio', 'pos-terminal-x1'
]
export type BtDeviceType = ActiveBtDeviceType
export const PrinterStorageKeys = {
type: STORAGE_PRINTER_TYPE,
btDeviceId: STORAGE_BT_DEVICE_ID,
btDeviceName: STORAGE_BT_DEVICE_NAME,
btServiceId: STORAGE_BT_SERVICE_ID,
btCharacteristicId: STORAGE_BT_CHARACTERISTIC_ID,
btDeviceType: STORAGE_BT_DEVICE_TYPE,
bleMTU: STORAGE_BLE_MTU,
driverKey: STORAGE_PRINTER_DRIVER_KEY,
} as const
export function setPrinterType (type: PrinterType) {
uni.setStorageSync(STORAGE_PRINTER_TYPE, type)
}
export function setBluetoothConnection (info: {
deviceId: string
deviceName: string
serviceId?: string
characteristicId?: string
deviceType?: BtDeviceType
mtu?: number
driverKey?: string
}) {
uni.setStorageSync(STORAGE_PRINTER_TYPE, 'bluetooth')
uni.setStorageSync(STORAGE_BT_DEVICE_ID, info.deviceId)
uni.setStorageSync(STORAGE_BT_DEVICE_NAME, info.deviceName)
uni.setStorageSync(STORAGE_BT_SERVICE_ID, info.serviceId || '')
uni.setStorageSync(STORAGE_BT_CHARACTERISTIC_ID, info.characteristicId || '')
uni.setStorageSync(STORAGE_BT_DEVICE_TYPE, info.deviceType || 'ble')
uni.setStorageSync(STORAGE_BLE_MTU, info.mtu != null ? info.mtu : BLE_MTU_DEFAULT)
uni.setStorageSync(STORAGE_PRINTER_DRIVER_KEY, info.driverKey || '')
}
export function setBuiltinPrinter (driverKey = 'generic-tsc') {
uni.setStorageSync(STORAGE_PRINTER_TYPE, 'builtin')
uni.setStorageSync(STORAGE_PRINTER_DRIVER_KEY, driverKey)
}
export function clearPrinter () {
uni.removeStorageSync(STORAGE_PRINTER_TYPE)
uni.removeStorageSync(STORAGE_BT_DEVICE_ID)
uni.removeStorageSync(STORAGE_BT_DEVICE_NAME)
uni.removeStorageSync(STORAGE_BT_SERVICE_ID)
uni.removeStorageSync(STORAGE_BT_CHARACTERISTIC_ID)
uni.removeStorageSync(STORAGE_BT_DEVICE_TYPE)
uni.removeStorageSync(STORAGE_BLE_MTU)
uni.removeStorageSync(STORAGE_BUILTIN_PORT)
uni.removeStorageSync(STORAGE_PRINTER_DRIVER_KEY)
}
const BLE_MTU_DEFAULT = 20
export function getPrinterType (): PrinterType | '' {
const type = (uni.getStorageSync(STORAGE_PRINTER_TYPE) as PrinterType) || ''
if (!type) return ''
if (getAvailablePrinterTypes().includes(type)) return type
clearPrinter()
return ''
}
export function getCurrentPrinterDriverKey (): string {
return String(uni.getStorageSync(STORAGE_PRINTER_DRIVER_KEY) || '')
}
export function getBluetoothConnection (): {
deviceId: string
deviceName: string
serviceId: string
characteristicId: string
deviceType: BtDeviceType
mtu: number
} | null {
const deviceId = uni.getStorageSync(STORAGE_BT_DEVICE_ID)
const deviceType = (uni.getStorageSync(STORAGE_BT_DEVICE_TYPE) as BtDeviceType) || 'ble'
if (!deviceId) return null
if (deviceType === 'classic') {
return {
deviceId,
deviceName: uni.getStorageSync(STORAGE_BT_DEVICE_NAME) || 'Printer',
serviceId: '',
characteristicId: '',
deviceType: 'classic',
mtu: BLE_MTU_DEFAULT,
}
}
const serviceId = uni.getStorageSync(STORAGE_BT_SERVICE_ID)
const characteristicId = uni.getStorageSync(STORAGE_BT_CHARACTERISTIC_ID)
if (!serviceId || !characteristicId) return null
return {
deviceId,
deviceName: uni.getStorageSync(STORAGE_BT_DEVICE_NAME) || 'Printer',
serviceId,
characteristicId,
deviceType: 'ble',
mtu: Number(uni.getStorageSync(STORAGE_BLE_MTU)) || BLE_MTU_DEFAULT,
}
}
export function isBuiltinConnected (): boolean {
return getPrinterType() === 'builtin'
}
export function isBuiltinPrinterAvailable (): boolean {
// #ifdef APP-PLUS
try {
const plugin = (uni as any)?.requireNativePlugin
? (uni as any).requireNativePlugin('moe-tcp-client')
: null
return !!plugin
} catch (_) {
return false
}
// #endif
// #ifndef APP-PLUS
return false
// #endif
}
export function isBuiltinPrinterEnabledByDeviceModel (): boolean {
const fingerprint = getDeviceFingerprint()
if (!fingerprint) return false
return BUILTIN_PRINTER_DEVICE_KEYWORDS.some(keyword => fingerprint.includes(String(keyword || '').toLowerCase()))
}
export function getAvailablePrinterTypes (): PrinterType[] {
if (isBuiltinPrinterAvailable() && isBuiltinPrinterEnabledByDeviceModel()) {
return ['builtin']
}
return ['bluetooth']
}
function buildClassicBluetoothError (message: string, deviceId?: string): Error {
const baseMessage = String(message || 'Classic Bluetooth error')
if (!classicBluetooth || typeof classicBluetooth.getDebugState !== 'function') {
return new Error(baseMessage)
}
try {
const debugState = classicBluetooth.getDebugState() || {}
const details: string[] = []
if (deviceId) details.push(`device=${deviceId}`)
if (debugState.lastSocketStrategy) details.push(`socket=${debugState.lastSocketStrategy}`)
if (debugState.connectionState) details.push(`state=${debugState.connectionState}`)
if (typeof debugState.socketConnected === 'boolean') details.push(`connected=${debugState.socketConnected}`)
if (typeof debugState.outputReady === 'boolean') details.push(`outputReady=${debugState.outputReady}`)
if (debugState.lastSendMode) details.push(`sendMode=${debugState.lastSendMode}`)
if (debugState.lastSendError) details.push(`sendError=${debugState.lastSendError}`)
else if (debugState.lastError) details.push(`lastError=${debugState.lastError}`)
if (details.length === 0) return new Error(baseMessage)
return new Error(`${baseMessage}\n${details.join('\n')}`)
} catch (_) {
return new Error(baseMessage)
}
}
/**
* 发送打印数据到当前已选打印机
* @param data 字节数组(TSC 指令)
* @param onProgress 可选进度回调 0~100
*/
export function sendToPrinter (
data: number[],
onProgress?: (percent: number) => void
): Promise<void> {
const type = getPrinterType()
if (type === 'bluetooth') {
const conn = getBluetoothConnection()
if (conn && conn.deviceType === 'classic') {
return sendViaClassic(data, onProgress)
}
return sendViaBle(data, onProgress)
}
if (type === 'builtin') {
return sendViaBuiltin(data)
}
return Promise.reject(new Error('No printer connected. Please connect a Bluetooth or built-in printer first.'))
}
function sendViaBle (
data: number[],
onProgress?: (percent: number) => void
): Promise<void> {
const conn = getBluetoothConnection()
if (!conn) {
return Promise.reject(new Error('Bluetooth printer not connected.'))
}
const { deviceId, serviceId, characteristicId, mtu } = conn
const chunks: number[][] = []
for (let i = 0; i < data.length; i += mtu) {
chunks.push(data.slice(i, i + mtu))
}
const total = chunks.length
let sent = 0
function sendNext (): Promise<void> {
if (sent >= total) {
if (onProgress) onProgress(100)
return Promise.resolve()
}
const chunk = chunks[sent]
const buffer = new ArrayBuffer(chunk.length)
const view = new DataView(buffer)
for (let j = 0; j < chunk.length; j++) {
view.setUint8(j, chunk[j] & 0xff)
}
return new Promise((resolve, reject) => {
uni.writeBLECharacteristicValue({
deviceId,
serviceId,
characteristicId,
value: buffer,
success: () => {
sent++
if (onProgress) onProgress(Math.round((sent / total) * 100))
setTimeout(() => sendNext().then(resolve).catch(reject), 10)
},
fail: (err: any) => reject(new Error(err.errMsg || 'BLE write failed')),
})
})
}
return sendNext()
}
function sendViaClassic (
data: number[],
onProgress?: (percent: number) => void
): Promise<void> {
// #ifdef APP-PLUS
const conn = getBluetoothConnection()
if (!conn || conn.deviceType !== 'classic') {
return Promise.reject(new Error('Classic Bluetooth printer not connected.'))
}
return new Promise((resolve, reject) => {
try {
if (!classicBluetooth) {
reject(new Error('Classic Bluetooth not available'))
return
}
const debugState = typeof classicBluetooth.getDebugState === 'function'
? classicBluetooth.getDebugState()
: null
const connectionState = String(debugState?.connectionState || '').trim().toLowerCase()
const ready = debugState
? (!!debugState.outputReady && (!!debugState.socketConnected || connectionState === 'connected'))
: true
if (!ready) {
const errorMessage = typeof classicBluetooth.getLastError === 'function'
? classicBluetooth.getLastError()
: ''
reject(buildClassicBluetoothError(errorMessage || 'Classic Bluetooth connection is not ready', conn.deviceId))
return
}
const sendData = data.map((byte) => {
const value = byte & 0xff
return value >= 128 ? value - 256 : value
})
if (typeof classicBluetooth.sendByteDataAsync === 'function') {
classicBluetooth.sendByteDataAsync(sendData, (ok: boolean, errorMessage?: string) => {
if (onProgress) onProgress(100)
if (ok) {
resolve()
return
}
reject(buildClassicBluetoothError(
errorMessage || classicBluetooth.getLastError?.() || 'Classic Bluetooth send failed',
conn.deviceId
))
})
return
}
const ok = classicBluetooth.sendByteData(sendData)
if (onProgress) onProgress(100)
if (ok) {
resolve()
return
}
const errorMessage = typeof classicBluetooth.getLastError === 'function'
? classicBluetooth.getLastError()
: ''
reject(buildClassicBluetoothError(errorMessage || 'Classic Bluetooth send failed', conn.deviceId))
} catch (e: any) {
reject(buildClassicBluetoothError(e?.message || String(e || 'Classic Bluetooth send exception'), conn.deviceId))
}
})
// #endif
// #ifndef APP-PLUS
return Promise.reject(new Error('Classic Bluetooth is only available in the app.'))
// #endif
}
function sendViaBuiltin (data: number[]): Promise<void> {
// #ifdef APP-PLUS
try {
const u = uni as any
const moeTcp = u.requireNativePlugin ? u.requireNativePlugin('moe-tcp-client') : null
if (!moeTcp) {
return Promise.reject(new Error('BUILTIN_PLUGIN_NOT_FOUND'))
}
const uint8 = new Uint8Array(data.length)
for (let i = 0; i < data.length; i++) uint8[i] = data[i] & 0xff
const hexStr = Array.from(uint8)
.map(b => ('0' + (b & 0xff).toString(16)).slice(-2))
.join('')
const savedPort = parseInt(uni.getStorageSync(STORAGE_BUILTIN_PORT)) || 0
const ports = savedPort > 0
? [savedPort, ...BUILTIN_PROBE_PORTS.filter(p => p !== savedPort)]
: [...BUILTIN_PROBE_PORTS]
function tryPort (idx: number): Promise<void> {
if (idx >= ports.length) {
return Promise.reject(new Error(
'Built-in printer: all ports failed (tried ' + BUILTIN_PROBE_PORTS.join(', ') +
'). Check if the printer service is running on this device.'
))
}
const port = ports[idx]
return new Promise((resolve, reject) => {
console.log('[builtin] trying 127.0.0.1:' + port)
moeTcp.connect({ ip: '127.0.0.1', port }, (res: string) => {
try {
const r = typeof res === 'string' ? JSON.parse(res) : res
if (r.code !== 1) {
console.log('[builtin] port ' + port + ' failed: ' + (r.msg || ''))
try { moeTcp.disconnect() } catch (_) {}
tryPort(idx + 1).then(resolve).catch(reject)
return
}
console.log('[builtin] connected on port ' + port)
uni.setStorageSync(STORAGE_BUILTIN_PORT, String(port))
moeTcp.sendHexStr({ message: hexStr })
setTimeout(() => {
try { moeTcp.disconnect() } catch (_) {}
resolve()
}, 300)
} catch (e) {
try { moeTcp.disconnect() } catch (_) {}
tryPort(idx + 1).then(resolve).catch(reject)
}
})
})
}
return tryPort(0)
} catch (e) {
return Promise.reject(e)
}
// #endif
// #ifndef APP-PLUS
return Promise.reject(new Error('Built-in printer is only available in the app. Use Bluetooth printer on this device.'))
// #endif
}