printerConnection.ts
7.53 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
/**
* 打印机连接与下发:蓝牙(BLE) / 一体机(TCP localhost)
*/
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'
export type PrinterType = 'bluetooth' | 'builtin'
export type BtDeviceType = 'ble' | 'classic'
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,
} 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
}) {
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)
}
export function setBuiltinPrinter () {
uni.setStorageSync(STORAGE_PRINTER_TYPE, 'builtin')
}
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)
}
const BLE_MTU_DEFAULT = 20
export function getPrinterType (): PrinterType | '' {
return (uni.getStorageSync(STORAGE_PRINTER_TYPE) as PrinterType) || ''
}
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'
}
/**
* 发送打印数据到当前已选打印机
* @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 {
const classicBluetooth = (require('./bluetoothTool.js') as any).default
if (!classicBluetooth) {
reject(new Error('Classic Bluetooth not available'))
return
}
const sendData = data.map((byte) => {
const b = byte & 0xff
if (b >= 128) return b % 128 - 128
return b
})
const ok = classicBluetooth.sendByteData(sendData)
if (onProgress) onProgress(100)
if (ok) resolve()
else reject(new Error('Classic Bluetooth send failed'))
} catch (e: any) {
reject(e)
}
})
// #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('')
return new Promise((resolve, reject) => {
moeTcp.connect({ ip: '127.0.0.1', port: 9100 }, (res: string) => {
try {
const r = typeof res === 'string' ? JSON.parse(res) : res
if (r.code !== 1) {
reject(new Error(r.msg || 'Built-in printer connection failed'))
return
}
moeTcp.sendHexStr({ message: hexStr })
setTimeout(() => {
try { moeTcp.disconnect() } catch (_) {}
resolve()
}, 300)
} catch (e) {
reject(e)
}
})
})
} 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
}