9e371380
“wangming”
把打印机的联通了
|
1
2
3
|
/**
* 打印机连接与下发:蓝牙(BLE) / 一体机(TCP localhost)
*/
|
961eecae
“wangming”
对打印机进行开发
|
4
5
|
import type { ActiveBtDeviceType, PrinterType } from './types/printer'
import classicBluetooth from './bluetoothTool.js'
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
6
|
import { getDeviceFingerprint } from '../deviceInfo'
|
9e371380
“wangming”
把打印机的联通了
|
7
8
9
10
11
12
13
14
|
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'
|
499e4a42
“wangming”
Enhance Bluetooth...
|
15
|
const STORAGE_BUILTIN_PORT = 'builtinPort'
|
961eecae
“wangming”
对打印机进行开发
|
16
|
const STORAGE_PRINTER_DRIVER_KEY = 'printerDriverKey'
|
499e4a42
“wangming”
Enhance Bluetooth...
|
17
18
|
const BUILTIN_PROBE_PORTS = [9100, 4000, 9000, 6000]
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
19
20
21
22
|
const BUILTIN_PRINTER_DEVICE_KEYWORDS: string[] = [
// 在这里补充需要走 Built-in 的设备型号关键字(小写匹配)
// 例如:'desktop-aio', 'pos-terminal-x1'
]
|
961eecae
“wangming”
对打印机进行开发
|
23
|
export type BtDeviceType = ActiveBtDeviceType
|
9e371380
“wangming”
把打印机的联通了
|
24
25
26
27
28
29
30
31
32
|
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,
|
961eecae
“wangming”
对打印机进行开发
|
33
|
driverKey: STORAGE_PRINTER_DRIVER_KEY,
|
9e371380
“wangming”
把打印机的联通了
|
34
35
36
37
38
39
40
41
42
43
44
45
46
|
} 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
|
961eecae
“wangming”
对打印机进行开发
|
47
|
driverKey?: string
|
9e371380
“wangming”
把打印机的联通了
|
48
49
50
51
52
53
54
55
|
}) {
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)
|
961eecae
“wangming”
对打印机进行开发
|
56
|
uni.setStorageSync(STORAGE_PRINTER_DRIVER_KEY, info.driverKey || '')
|
9e371380
“wangming”
把打印机的联通了
|
57
58
|
}
|
961eecae
“wangming”
对打印机进行开发
|
59
|
export function setBuiltinPrinter (driverKey = 'generic-tsc') {
|
9e371380
“wangming”
把打印机的联通了
|
60
|
uni.setStorageSync(STORAGE_PRINTER_TYPE, 'builtin')
|
961eecae
“wangming”
对打印机进行开发
|
61
|
uni.setStorageSync(STORAGE_PRINTER_DRIVER_KEY, driverKey)
|
9e371380
“wangming”
把打印机的联通了
|
62
63
64
65
66
67
68
69
70
71
|
}
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)
|
499e4a42
“wangming”
Enhance Bluetooth...
|
72
|
uni.removeStorageSync(STORAGE_BUILTIN_PORT)
|
961eecae
“wangming”
对打印机进行开发
|
73
|
uni.removeStorageSync(STORAGE_PRINTER_DRIVER_KEY)
|
9e371380
“wangming”
把打印机的联通了
|
74
75
76
77
78
|
}
const BLE_MTU_DEFAULT = 20
export function getPrinterType (): PrinterType | '' {
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
79
80
81
82
83
|
const type = (uni.getStorageSync(STORAGE_PRINTER_TYPE) as PrinterType) || ''
if (!type) return ''
if (getAvailablePrinterTypes().includes(type)) return type
clearPrinter()
return ''
|
9e371380
“wangming”
把打印机的联通了
|
84
85
|
}
|
961eecae
“wangming”
对打印机进行开发
|
86
87
88
89
|
export function getCurrentPrinterDriverKey (): string {
return String(uni.getStorageSync(STORAGE_PRINTER_DRIVER_KEY) || '')
}
|
9e371380
“wangming”
把打印机的联通了
|
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
|
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'
}
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
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
|
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)
}
}
|
9e371380
“wangming”
把打印机的联通了
|
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
|
/**
* 发送打印数据到当前已选打印机
* @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 {
|
9e371380
“wangming”
把打印机的联通了
|
260
261
262
263
|
if (!classicBluetooth) {
reject(new Error('Classic Bluetooth not available'))
return
}
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
264
265
266
267
268
269
|
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'))
|
961eecae
“wangming”
对打印机进行开发
|
270
271
272
273
274
|
: true
if (!ready) {
const errorMessage = typeof classicBluetooth.getLastError === 'function'
? classicBluetooth.getLastError()
: ''
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
|
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
))
})
|
961eecae
“wangming”
对打印机进行开发
|
296
297
298
|
return
}
|
9e371380
“wangming”
把打印机的联通了
|
299
300
|
const ok = classicBluetooth.sendByteData(sendData)
if (onProgress) onProgress(100)
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
301
302
303
|
if (ok) {
resolve()
return
|
961eecae
“wangming”
对打印机进行开发
|
304
|
}
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
305
306
307
308
|
const errorMessage = typeof classicBluetooth.getLastError === 'function'
? classicBluetooth.getLastError()
: ''
reject(buildClassicBluetoothError(errorMessage || 'Classic Bluetooth send failed', conn.deviceId))
|
9e371380
“wangming”
把打印机的联通了
|
309
|
} catch (e: any) {
|
9927b97e
“wangming”
Improve GP_R3 pri...
|
310
|
reject(buildClassicBluetoothError(e?.message || String(e || 'Classic Bluetooth send exception'), conn.deviceId))
|
9e371380
“wangming”
把打印机的联通了
|
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
|
}
})
// #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('')
|
499e4a42
“wangming”
Enhance Bluetooth...
|
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
|
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) {
|
9e371380
“wangming”
把打印机的联通了
|
365
|
try { moeTcp.disconnect() } catch (_) {}
|
499e4a42
“wangming”
Enhance Bluetooth...
|
366
367
368
|
tryPort(idx + 1).then(resolve).catch(reject)
}
})
|
9e371380
“wangming”
把打印机的联通了
|
369
|
})
|
499e4a42
“wangming”
Enhance Bluetooth...
|
370
371
|
}
return tryPort(0)
|
9e371380
“wangming”
把打印机的联通了
|
372
373
374
375
376
377
378
379
|
} 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
}
|