Blame view

美国版/Food Labeling Management App UniApp/src/utils/print/manager/printerManager.ts 12.3 KB
961eecae   “wangming”   对打印机进行开发
1
2
3
4
5
6
7
8
9
10
  import {
    clearPrinter,
    getBluetoothConnection,
    getCurrentPrinterDriverKey,
    getPrinterType,
    sendToPrinter,
    setBluetoothConnection,
    setBuiltinPrinter,
  } from '../printerConnection'
  import classicBluetooth from '../bluetoothTool.js'
9927b97e   “wangming”   Improve GP_R3 pri...
11
12
13
  import { rasterizeImageData, rasterizeImageForPrinter } from '../imageRaster'
  import { buildEscPosImageData, buildEscPosTemplateData } from '../protocols/escPosBuilder'
  import { buildTscImageData, buildTscTemplateData } from '../protocols/tscProtocol'
a6f5c1af   “wangming”   开发了安卓基座
14
15
16
17
18
19
  import {
    connectNativeFastPrinter as connectNativeFastPrinterPlugin,
    disconnectNativeFastPrinter as disconnectNativeFastPrinterPlugin,
    isNativeFastPrinterAvailable,
    printNativeFastTemplate as printNativeFastTemplatePlugin,
  } from '../nativeFastPrinter'
9927b97e   “wangming”   Improve GP_R3 pri...
20
  import { adaptSystemLabelTemplate } from '../systemTemplateAdapter'
a6f5c1af   “wangming”   开发了安卓基座
21
  import { TEST_PRINT_SYSTEM_TEMPLATE, TEST_PRINT_TEMPLATE_DATA } from '../templates/testPrintTemplate'
961eecae   “wangming”   对打印机进行开发
22
23
24
25
  import { describePrinterCandidate, getPrinterDriverByKey, resolvePrinterDriver } from './driverRegistry'
  import type {
    CurrentPrinterSummary,
    LabelPrintPayload,
9927b97e   “wangming”   Improve GP_R3 pri...
26
27
28
    LabelTemplateData,
    RawImageDataSource,
    PrintImageOptions,
961eecae   “wangming”   对打印机进行开发
29
30
    PrinterCandidate,
    PrinterDriver,
9927b97e   “wangming”   Improve GP_R3 pri...
31
32
    StructuredLabelTemplate,
    SystemLabelTemplate,
961eecae   “wangming”   对打印机进行开发
33
34
  } from '../types/printer'
  
9927b97e   “wangming”   Improve GP_R3 pri...
35
36
37
38
39
40
  function getPrinterTypeDisplayName (type: '' | 'bluetooth' | 'builtin'): string {
    if (type === 'bluetooth') return 'Bluetooth'
    if (type === 'builtin') return 'Built-in'
    return ''
  }
  
961eecae   “wangming”   对打印机进行开发
41
42
43
  function connectClassicBluetooth (device: PrinterCandidate, driver: PrinterDriver): Promise<void> {
    return new Promise((resolve, reject) => {
      // #ifdef APP-PLUS
a6f5c1af   “wangming”   开发了安卓基座
44
45
      if (isNativeFastPrinterAvailable()) {
        connectNativeFastPrinterPlugin({
961eecae   “wangming”   对打印机进行开发
46
47
          deviceId: device.deviceId,
          deviceName: device.name || 'Bluetooth Printer',
a6f5c1af   “wangming”   开发了安卓基座
48
49
50
51
52
53
54
55
56
57
58
        }).then(() => {
          setBluetoothConnection({
            deviceId: device.deviceId,
            deviceName: device.name || 'Bluetooth Printer',
            deviceType: 'classic',
            driverKey: driver.key,
            mtu: driver.preferredBleMtu || 20,
          })
          resolve()
        }).catch((error: any) => {
          reject(error instanceof Error ? error : new Error(String(error || 'Classic Bluetooth connection failed.')))
961eecae   “wangming”   对打印机进行开发
59
        })
a6f5c1af   “wangming”   开发了安卓基座
60
61
62
        return
      }
      reject(new Error('NATIVE_FAST_PRINTER_PLUGIN_NOT_FOUND. Please rebuild the custom base with native-fast-printer.'))
961eecae   “wangming”   对打印机进行开发
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
      // #endif
      // #ifndef APP-PLUS
      reject(new Error('Classic Bluetooth requires the app.'))
      // #endif
    })
  }
  
  function findBleWriteCharacteristic (deviceId: string): Promise<{ serviceId: string; characteristicId: string } | null> {
    return new Promise((resolve) => {
      uni.getBLEDeviceServices({
        deviceId,
        success: (serviceRes) => {
          const services = serviceRes.services || []
          const next = (index: number) => {
            if (index >= services.length) {
              resolve(null)
              return
            }
            const serviceId = services[index].uuid
            uni.getBLEDeviceCharacteristics({
              deviceId,
              serviceId,
              success: (charRes) => {
                const target = (charRes.characteristics || []).find((item: any) => item.properties && item.properties.write)
                if (target) {
                  resolve({
                    serviceId,
                    characteristicId: target.uuid,
                  })
                  return
                }
                next(index + 1)
              },
              fail: () => next(index + 1),
            })
          }
          next(0)
        },
        fail: () => resolve(null),
      })
    })
  }
  
  function connectBlePrinter (device: PrinterCandidate, driver: PrinterDriver): Promise<void> {
    const finalizeExistingBleConnection = async () => {
      const write = await findBleWriteCharacteristic(device.deviceId)
      if (!write) {
        throw new Error('No writable characteristic found. This device may not support printing.')
      }
      setBluetoothConnection({
        deviceId: device.deviceId,
        deviceName: device.name || 'Bluetooth Printer',
        serviceId: write.serviceId,
        characteristicId: write.characteristicId,
        deviceType: 'ble',
        mtu: driver.preferredBleMtu || 20,
        driverKey: driver.key,
      })
    }
  
    return new Promise((resolve, reject) => {
      uni.createBLEConnection({
        deviceId: device.deviceId,
        timeout: 10000,
        success: async () => {
          try {
            await finalizeExistingBleConnection()
            resolve()
          } catch (e: any) {
            reject(e)
          }
        },
        fail: (err: any) => {
          if (err?.errCode === -1) {
            finalizeExistingBleConnection().then(() => resolve()).catch(reject)
          } else {
            reject(new Error(err?.errMsg || 'BLE connection failed.'))
          }
        },
      })
    })
  }
  
  export async function connectBluetoothPrinter (device: PrinterCandidate): Promise<PrinterDriver> {
    const driver = resolvePrinterDriver(device)
    const resolvedType = driver.resolveConnectionType(device)
    if (resolvedType === 'classic') {
      await connectClassicBluetooth(device, driver)
    } else {
      await connectBlePrinter(device, driver)
    }
    return driver
  }
  
  export function useBuiltinPrinter (driverKey = 'generic-tsc') {
    setBuiltinPrinter(driverKey)
  }
  
  export function getCurrentPrinterDriver (): PrinterDriver {
    const type = getPrinterType()
    const storedKey = getCurrentPrinterDriverKey()
    if (storedKey) return getPrinterDriverByKey(storedKey)
    if (type === 'bluetooth') {
      const connection = getBluetoothConnection()
      if (connection) {
        return resolvePrinterDriver({
          deviceId: connection.deviceId,
          name: connection.deviceName,
          type: connection.deviceType,
        })
      }
    }
    return getPrinterDriverByKey('generic-tsc')
  }
  
  export function getCurrentPrinterSummary (): CurrentPrinterSummary {
    const type = getPrinterType()
    const driver = getCurrentPrinterDriver()
    if (type === 'builtin') {
      return {
        type,
9927b97e   “wangming”   Improve GP_R3 pri...
184
        displayName: getPrinterTypeDisplayName(type),
961eecae   “wangming”   对打印机进行开发
185
186
187
188
189
190
191
192
193
194
195
196
        deviceId: 'builtin',
        driverKey: driver.key,
        driverName: driver.displayName,
        protocol: driver.protocol,
        deviceType: '',
      }
    }
    if (type === 'bluetooth') {
      const connection = getBluetoothConnection()
      if (connection) {
        return {
          type,
9927b97e   “wangming”   Improve GP_R3 pri...
197
          displayName: getPrinterTypeDisplayName(type),
961eecae   “wangming”   对打印机进行开发
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
          deviceId: connection.deviceId,
          driverKey: driver.key,
          driverName: driver.displayName,
          protocol: driver.protocol,
          deviceType: connection.deviceType,
        }
      }
    }
    return {
      type: '',
      displayName: '',
      deviceId: '',
      driverKey: driver.key,
      driverName: driver.displayName,
      protocol: driver.protocol,
      deviceType: '',
    }
  }
  
a6f5c1af   “wangming”   开发了安卓基座
217
218
219
220
221
222
223
224
225
226
227
228
229
  function canUseNativeFastTemplatePrint (driver: PrinterDriver): boolean {
    const connection = getBluetoothConnection()
    return driver.protocol === 'tsc'
      && connection?.deviceType === 'classic'
      && isNativeFastPrinterAvailable()
  }
  
  function getNativeClassicConnection () {
    const connection = getBluetoothConnection()
    if (!connection || connection.deviceType !== 'classic') return null
    return connection
  }
  
961eecae   “wangming”   对打印机进行开发
230
231
  export async function testPrintCurrentPrinter (onProgress?: (percent: number) => void): Promise<PrinterDriver> {
    const driver = getCurrentPrinterDriver()
a6f5c1af   “wangming”   开发了安卓基座
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
    const connection = getBluetoothConnection()
    if (driver.protocol === 'tsc' && connection?.deviceType === 'classic' && !isNativeFastPrinterAvailable()) {
      throw new Error('NATIVE_FAST_PRINTER_PLUGIN_NOT_FOUND. Please rebuild the custom base with native-fast-printer.')
    }
    if (canUseNativeFastTemplatePrint(driver)) {
      const nativeConnection = getNativeClassicConnection()
      if (nativeConnection) {
        await printNativeFastTemplatePlugin({
          deviceId: nativeConnection.deviceId,
          deviceName: nativeConnection.deviceName,
          template: TEST_PRINT_SYSTEM_TEMPLATE,
          data: TEST_PRINT_TEMPLATE_DATA,
          dpi: driver.imageDpi || 203,
          printQty: 1,
        })
        if (onProgress) onProgress(100)
        return driver
      }
    }
961eecae   “wangming”   对打印机进行开发
251
252
253
254
255
256
257
258
259
260
261
262
263
    await sendToPrinter(driver.buildTestPrintData(), onProgress)
    return driver
  }
  
  export async function printLabelForCurrentPrinter (
    payload: LabelPrintPayload,
    onProgress?: (percent: number) => void
  ): Promise<PrinterDriver> {
    const driver = getCurrentPrinterDriver()
    await sendToPrinter(driver.buildLabelData(payload), onProgress)
    return driver
  }
  
9927b97e   “wangming”   Improve GP_R3 pri...
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
  export async function printImageForCurrentPrinter (
    imageSource: string,
    options: PrintImageOptions = {},
    onProgress?: (percent: number) => void
  ): Promise<PrinterDriver> {
    const driver = getCurrentPrinterDriver()
    const raster = await rasterizeImageForPrinter(imageSource, driver, options)
    if (onProgress) onProgress(5)
    let data: number[] = []
  
    if (driver.protocol === 'esc') {
      data = buildEscPosImageData(raster, options)
    } else {
      data = buildTscImageData(raster, options, driver.imageDpi || 203)
    }
  
    await sendToPrinter(data, onProgress)
    return driver
  }
  
  export async function printImageDataForCurrentPrinter (
    imageData: RawImageDataSource,
    options: PrintImageOptions = {},
    onProgress?: (percent: number) => void
  ): Promise<PrinterDriver> {
    const driver = getCurrentPrinterDriver()
    const raster = rasterizeImageData(imageData, options)
    if (onProgress) onProgress(5)
    const data = driver.protocol === 'esc'
      ? buildEscPosImageData(raster, options)
      : buildTscImageData(raster, options, driver.imageDpi || 203)
    await sendToPrinter(data, onProgress)
    return driver
  }
  
  export async function printTemplateForCurrentPrinter (
    template: StructuredLabelTemplate,
    data: LabelTemplateData = {},
    onProgress?: (percent: number) => void
  ): Promise<PrinterDriver> {
    const driver = getCurrentPrinterDriver()
    const bytes = driver.protocol === 'esc'
      ? buildEscPosTemplateData(template, data)
      : buildTscTemplateData(template, data)
    await sendToPrinter(bytes, onProgress)
    return driver
  }
  
  export async function printSystemTemplateForCurrentPrinter (
    template: SystemLabelTemplate,
    data: LabelTemplateData = {},
    options: {
      printQty?: number
    } = {},
    onProgress?: (percent: number) => void
  ): Promise<PrinterDriver> {
    const driver = getCurrentPrinterDriver()
a6f5c1af   “wangming”   开发了安卓基座
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
    const connection = getBluetoothConnection()
    if (driver.protocol === 'tsc' && connection?.deviceType === 'classic' && !isNativeFastPrinterAvailable()) {
      throw new Error('NATIVE_FAST_PRINTER_PLUGIN_NOT_FOUND. Please rebuild the custom base with native-fast-printer.')
    }
    if (canUseNativeFastTemplatePrint(driver)) {
      const nativeConnection = getNativeClassicConnection()
      if (nativeConnection) {
        await printNativeFastTemplatePlugin({
          deviceId: nativeConnection.deviceId,
          deviceName: nativeConnection.deviceName,
          template,
          data,
          dpi: driver.imageDpi || 203,
          printQty: options.printQty || 1,
        })
        if (onProgress) onProgress(100)
        return driver
      }
    }
  
9927b97e   “wangming”   Improve GP_R3 pri...
341
342
343
344
345
346
347
348
349
350
351
    const structuredTemplate = adaptSystemLabelTemplate(template, data, {
      dpi: driver.imageDpi || 203,
      printQty: options.printQty || 1,
    })
    const bytes = driver.protocol === 'esc'
      ? buildEscPosTemplateData(structuredTemplate)
      : buildTscTemplateData(structuredTemplate)
    await sendToPrinter(bytes, onProgress)
    return driver
  }
  
961eecae   “wangming”   对打印机进行开发
352
353
354
355
356
357
358
359
360
361
362
  export function describeDiscoveredPrinter (device: PrinterCandidate) {
    return describePrinterCandidate(device)
  }
  
  export function disconnectCurrentPrinter (): Promise<void> {
    return new Promise((resolve) => {
      const type = getPrinterType()
      const connection = getBluetoothConnection()
  
      if (type === 'bluetooth' && connection?.deviceType === 'classic') {
        // #ifdef APP-PLUS
a6f5c1af   “wangming”   开发了安卓基座
363
364
365
366
367
368
369
370
371
        if (isNativeFastPrinterAvailable()) {
          disconnectNativeFastPrinterPlugin().catch((e: any) => {
            console.error('Disconnect native fast printer failed', e)
          }).finally(() => {
            clearPrinter()
            resolve()
          })
          return
        }
961eecae   “wangming”   对打印机进行开发
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
        try {
          const classic = classicBluetooth
          if (classic && classic.disConnDevice) classic.disConnDevice()
        } catch (e) {
          console.error('Disconnect classic bluetooth failed', e)
        }
        // #endif
        clearPrinter()
        resolve()
        return
      }
  
      clearPrinter()
      if (type === 'bluetooth' && connection?.deviceId) {
        uni.closeBLEConnection({
          deviceId: connection.deviceId,
          complete: () => resolve(),
        })
        return
      }
      resolve()
    })
  }