printerConnection.ts 7.53 KB
/**
 * 打印机连接与下发:蓝牙(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
}