printerReadiness.ts 1.06 KB
import {
  getBluetoothConnection,
  getPrinterType,
  isBuiltinConnected,
} from './printerConnection'

/** 同步:是否已选择并保存了可用的打印机连接(蓝牙已配对写入 storage / 或内置) */
export function isPrinterReadySync(): boolean {
  const type = getPrinterType()
  if (type === 'builtin') return isBuiltinConnected()
  if (type === 'bluetooth') return !!getBluetoothConnection()
  return false
}

/**
 * 检测 uni 蓝牙适配器状态(APP 端)。注意:若本页未调用过 openBluetoothAdapter,
 * getBluetoothAdapterState 常返回 available: false,易误判;打印流程请以 isPrinterReadySync + 实际 write 结果为准。
 * H5 返回 false。
 */
export function checkBluetoothAdapterAvailable(): Promise<boolean> {
  return new Promise((resolve) => {
    // #ifdef APP-PLUS
    uni.getBluetoothAdapterState({
      success: (res) => {
        resolve(res.available === true)
      },
      fail: () => {
        resolve(false)
      },
    })
    // #endif
    // #ifndef APP-PLUS
    resolve(false)
    // #endif
  })
}