printerConnection.ts 26.7 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 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 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 321 322 323 324 325 326 327 328 329 330 331 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 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
/**
 * 打印机连接与下发:蓝牙(BLE) / 一体机(TCP localhost)
 */
import type { ActiveBtDeviceType, PrinterType } from './types/printer'
import classicBluetooth from './bluetoothTool.js'
import { getDeviceFingerprint } from '../deviceInfo'
import {
  blePairRequiresWriteNoResponse,
  isNordicUartStyleBleService,
  normalizeBleUuid,
} from './bleWriteModeRules'
import { getPrinterDriverByKey } from './manager/driverRegistry'

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_BT_TRANSPORT_MODE = 'btTransportMode' // 'native-plugin' | 'generic'
const STORAGE_BLE_MTU = 'bleMTU'
/** '1' = 仅支持 writeNoResponse 的特征,需在 writeBLECharacteristicValue 里指定 writeType */
const STORAGE_BLE_WRITE_NO_RESPONSE = 'bleWriteNoResponse'
const STORAGE_BUILTIN_PORT = 'builtinPort'
const STORAGE_PRINTER_DRIVER_KEY = 'printerDriverKey'

const BUILTIN_PROBE_PORTS = [9100, 4000, 9000, 6000]
const BUILTIN_PRINTER_DEVICE_KEYWORDS: string[] = [
  // 在这里补充需要走 Built-in 的设备型号关键字(小写匹配)
  // 例如:'desktop-aio', 'pos-terminal-x1'
]
export type BtDeviceType = ActiveBtDeviceType

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,
  btTransportMode: STORAGE_BT_TRANSPORT_MODE,
  bleMTU: STORAGE_BLE_MTU,
  bleWriteNoResponse: STORAGE_BLE_WRITE_NO_RESPONSE,
  driverKey: STORAGE_PRINTER_DRIVER_KEY,
} 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
  transportMode?: 'native-plugin' | 'generic'
  mtu?: number
  driverKey?: string
  /** 当前特征是否必须走 writeNoResponse(仅 write 为 false 时) */
  bleWriteUsesNoResponse?: boolean
}) {
  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_BT_TRANSPORT_MODE,
    info.transportMode || (info.deviceType === 'classic' ? 'native-plugin' : 'generic')
  )
  uni.setStorageSync(STORAGE_BLE_MTU, info.mtu != null ? info.mtu : BLE_MTU_DEFAULT)
  uni.setStorageSync(STORAGE_PRINTER_DRIVER_KEY, info.driverKey || '')
  if (info.deviceType === 'ble' || !info.deviceType) {
    uni.setStorageSync(STORAGE_BLE_WRITE_NO_RESPONSE, info.bleWriteUsesNoResponse ? '1' : '0')
  } else {
    uni.setStorageSync(STORAGE_BLE_WRITE_NO_RESPONSE, '0')
  }
}

export function setBuiltinPrinter (driverKey = 'generic-tsc') {
  uni.setStorageSync(STORAGE_PRINTER_TYPE, 'builtin')
  uni.setStorageSync(STORAGE_PRINTER_DRIVER_KEY, driverKey)
}

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_BT_TRANSPORT_MODE)
  uni.removeStorageSync(STORAGE_BLE_MTU)
  uni.removeStorageSync(STORAGE_BLE_WRITE_NO_RESPONSE)
  uni.removeStorageSync(STORAGE_BUILTIN_PORT)
  uni.removeStorageSync(STORAGE_PRINTER_DRIVER_KEY)
}

const BLE_MTU_DEFAULT = 20

export function getPrinterType (): PrinterType | '' {
  const type = (uni.getStorageSync(STORAGE_PRINTER_TYPE) as PrinterType) || ''
  if (!type) return ''
  if (getAvailablePrinterTypes().includes(type)) return type
  clearPrinter()
  return ''
}

export function getCurrentPrinterDriverKey (): string {
  return String(uni.getStorageSync(STORAGE_PRINTER_DRIVER_KEY) || '')
}

export function getBluetoothConnection (): {
  deviceId: string
  deviceName: string
  serviceId: string
  characteristicId: string
  deviceType: BtDeviceType
  transportMode: 'native-plugin' | 'generic'
  mtu: number
  bleWriteUsesNoResponse: boolean
} | null {
  const deviceId = uni.getStorageSync(STORAGE_BT_DEVICE_ID)
  const deviceType = (uni.getStorageSync(STORAGE_BT_DEVICE_TYPE) as BtDeviceType) || 'ble'
  const transportMode = (uni.getStorageSync(STORAGE_BT_TRANSPORT_MODE) as 'native-plugin' | 'generic') || 'generic'
  if (!deviceId) return null
  if (deviceType === 'classic') {
    return {
      deviceId,
      deviceName: uni.getStorageSync(STORAGE_BT_DEVICE_NAME) || 'Printer',
      serviceId: '',
      characteristicId: '',
      deviceType: 'classic',
      transportMode,
      mtu: BLE_MTU_DEFAULT,
      bleWriteUsesNoResponse: false,
    }
  }
  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',
    transportMode,
    mtu: Number(uni.getStorageSync(STORAGE_BLE_MTU)) || BLE_MTU_DEFAULT,
    bleWriteUsesNoResponse: uni.getStorageSync(STORAGE_BLE_WRITE_NO_RESPONSE) === '1',
  }
}

export function isBuiltinConnected (): boolean {
  return getPrinterType() === 'builtin'
}

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)
  }
}

/**
 * 发送打印数据到当前已选打印机
 * @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.'))
}

/** 与打印机页扫描/连接一致:未 open 适配器时 writeBLECharacteristicValue 报 fail not init */
function bleOpenAdapter (): Promise<void> {
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
    uni.openBluetoothAdapter({
      success: () => resolve(),
      fail: (err: any) => {
        const msg = String(err?.errMsg || '')
        const code = err?.errCode
        if (msg.includes('already') || code === 10001) resolve()
        else reject(new Error(msg || 'openBluetoothAdapter failed'))
      },
    })
    // #endif
    // #ifndef APP-PLUS
    resolve()
    // #endif
  })
}

/** 设置页 onUnmounted 可能已 closeBluetoothAdapter,需重新建链后才能写特征值 */
function bleEnsureDeviceConnected (deviceId: string): Promise<void> {
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
    uni.createBLEConnection({
      deviceId,
      timeout: 15000,
      success: () => resolve(),
      fail: (err: any) => {
        const msg = String(err?.errMsg || '')
        const code = err?.errCode
        if (
          code === -1 ||
          msg.includes('already') ||
          msg.includes('Connected') ||
          msg.includes('connected') ||
          msg.includes('已连接')
        ) {
          resolve()
          return
        }
        reject(new Error(msg || 'createBLEConnection failed'))
      },
    })
    // #endif
    // #ifndef APP-PLUS
    resolve()
    // #endif
  })
}

/**
 * 每次打印前会 createBLEConnection,链路 MTU 可能回到默认 23;若仍按 storage 里 512 分包,实机常丢数据但 write 仍 success。
 */
let bleNordicUartValueListenerAttached = false

function attachBleNordicUartValueListener (): void {
  if (bleNordicUartValueListenerAttached) return
  bleNordicUartValueListenerAttached = true
  try {
    if (typeof uni.onBLECharacteristicValueChange === 'function') {
      uni.onBLECharacteristicValueChange(() => {})
    }
  } catch (_) {}
}

/**
 * Nordic UART 类标签机:未对 TX 打开 notify 时,部分安卓栈第二包起对 RX 写会统一报 property not support (10007)。
 * 连接后、大批量 write 前各调用一次(幂等)。
 */
export function ensureBleUartNotifyIfNeeded (
  deviceId: string,
  serviceId: string,
  rxCharacteristicId?: string
): Promise<void> {
  // #ifndef APP-PLUS
  return Promise.resolve()
  // #endif
  // #ifdef APP-PLUS
  if (!isNordicUartStyleBleService(serviceId)) {
    return Promise.resolve()
  }
  const rx = normalizeBleUuid(rxCharacteristicId || '')
  return new Promise((resolve) => {
    uni.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        const chars = ((res as any).characteristics || []) as Array<{ uuid?: string; properties?: Record<string, unknown> }>
        const notifyChar = chars.find((c) => {
          const p = c.properties || {}
          const n =
            p.notify === true ||
            p.notify === 'true' ||
            p.indicate === true ||
            p.indicate === 'true'
          if (!n) return false
          const cid = normalizeBleUuid(String(c.uuid || ''))
          if (rx && cid === rx) return false
          return true
        })
        if (!notifyChar?.uuid) {
          console.warn('[BLE] Nordic 串口:未找到可订阅的 notify/indicate 特征,跳过后续写入可能仍 10007')
          resolve()
          return
        }
        const cid = String(notifyChar.uuid)
        uni.notifyBLECharacteristicValueChange({
          deviceId,
          serviceId,
          characteristicId: cid,
          state: true,
          success: () => {
            attachBleNordicUartValueListener()
            console.log('[BLE] Nordic 串口已订阅 notify:', cid)
            setTimeout(() => resolve(), 80)
          },
          fail: () => {
            resolve()
          },
        })
      },
      fail: () => resolve(),
    })
  })
  // #endif
}

function requestBleMtuNegotiation (deviceId: string, preferredMtu: number): Promise<number> {
  return new Promise((resolve) => {
    // #ifdef APP-PLUS
    const targetMtu = Math.max(20, Math.min(512, Math.round(preferredMtu || 20)))
    if (targetMtu <= 20 || typeof (uni as any).setBLEMTU !== 'function') {
      resolve(20)
      return
    }
    let settled = false
    const done = (value: number) => {
      if (settled) return
      settled = true
      clearTimeout(timer)
      const m = Math.max(20, Math.round(value || 20))
      try {
        uni.setStorageSync(STORAGE_BLE_MTU, m)
      } catch (_) {}
      resolve(m)
    }
    const timer = setTimeout(() => done(20), 3000)
    ;(uni as any).setBLEMTU({
      deviceId,
      mtu: targetMtu,
      success: (res: any) => done(Number(res?.mtu) || targetMtu),
      fail: () => done(20),
    })
    // #endif
    // #ifndef APP-PLUS
    resolve(20)
    // #endif
  })
}

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, bleWriteUsesNoResponse } = conn

  const runWritesWithPayloadSize = (payloadSize: number): Promise<void> => {
    const chunks: number[][] = []
    for (let i = 0; i < data.length; i += payloadSize) {
      chunks.push(data.slice(i, i + payloadSize))
    }
    const total = chunks.length
    let sent = 0
    let completed = false
    let timeoutId: ReturnType<typeof setTimeout> | null = setTimeout(() => {}, 0)
    /** Nordic 大包连续 0ms 间隔时,部分机型第二包起 10007;与 enable notify 配合 */
    const nordicUart = isNordicUartStyleBleService(serviceId)
    const writeDelayMs =
      nordicUart && payloadSize >= 64
        ? 18
        : payloadSize >= 180
          ? 0
          : payloadSize > 20
            ? 2
            : 10

    /** Nordic 白名单:仅用于失败时是否禁止翻到带响应写(佳博等);写入方式以连接时写入 storage 的 bleWriteUsesNoResponse 为准 */
    const blePairForceNoResponse = blePairRequiresWriteNoResponse(serviceId, characteristicId)

    /** 本 job 内若因 property not support 翻过模式,后续包统一用 effectiveUseNoResp */
    let effectiveUseNoResp = bleWriteUsesNoResponse
    let hasFlippedWriteModeThisJob = false
    let pendingPersistUseNoResp: boolean | null = null

    const resetTimeout = (reject: (reason?: any) => void) => {
      if (timeoutId) clearTimeout(timeoutId)
      timeoutId = setTimeout(() => {
        if (completed) return
        completed = true
        reject(new Error('BLE write timeout'))
      }, Math.max(60000, total * 500))
    }

    function logBleWriteFail (err: any, useNoResp: boolean, bufferLen: number) {
      const msg = String(err?.errMsg ?? err?.message ?? '')
      let errSerialized = ''
      try {
        errSerialized = JSON.stringify(err)
      } catch {
        errSerialized = String(err)
      }
      console.error('[sendViaBle] writeBLECharacteristicValue fail — 完整信息供真机调试复制', {
        errMsg: msg,
        errCode: err?.errCode,
        errno: err?.errno,
        code: err?.code,
        writeTypeUsed: useNoResp ? 'writeNoResponse' : '(omitted, default write)',
        effectiveUseNoResp,
        bleWriteUsesNoResponseSaved: bleWriteUsesNoResponse,
        bufferLen,
        sentIndex: sent,
        totalChunks: total,
        serviceId,
        characteristicId,
        deviceId,
        rawErr: err,
        errSerialized,
        blePairForcedNoResponse: blePairForceNoResponse,
      })
    }

    function writeOneBuffer (buffer: ArrayBuffer): Promise<void> {
      return new Promise((resolve, reject) => {
        const tryWrite = (useNoResp: boolean, allowFlip: boolean) => {
          const opts: UniApp.WriteBLECharacteristicValueOption = {
            deviceId,
            serviceId,
            characteristicId,
            value: buffer,
          }
          /** 仅无响应写显式声明;带响应写不传 writeType,与 uni 历史默认一致,避免部分机型报 property not support */
          if (useNoResp) {
            opts.writeType = 'writeNoResponse'
          }
          uni.writeBLECharacteristicValue({
            ...opts,
            success: () => {
              if (pendingPersistUseNoResp != null) {
                try {
                  uni.setStorageSync(
                    PrinterStorageKeys.bleWriteNoResponse,
                    pendingPersistUseNoResp ? '1' : '0'
                  )
                } catch (_) {}
                pendingPersistUseNoResp = null
              }
              resolve()
            },
            fail: (err: any) => {
              const msg = String(err?.errMsg ?? err?.message ?? '')
              logBleWriteFail(err, useNoResp, buffer.byteLength)
              const notSupport =
                msg.includes('property not support') ||
                msg.includes('not support') ||
                String(err?.errCode) === '10007'
              if (allowFlip && !hasFlippedWriteModeThisJob && notSupport) {
                const nextUseNoResp = !useNoResp
                /**
                 * 佳博等 Nordic 串口:GATT 虽声明 write,实测只接受 writeNoResponse。
                 * 若 writeNoResponse 偶发失败后翻到「默认写」,首包可能仍 success,从第二包起必现 10007(打印量变长更易触发)。
                 */
                if (blePairForceNoResponse && !nextUseNoResp) {
                  console.warn(
                    '[sendViaBle] 白名单串口禁止切到带响应写;请保持 writeNoResponse 或检查连接/MTU'
                  )
                  reject(new Error(msg || 'BLE write failed'))
                  return
                }
                hasFlippedWriteModeThisJob = true
                effectiveUseNoResp = nextUseNoResp
                pendingPersistUseNoResp = effectiveUseNoResp
                console.warn('[sendViaBle] property not support → 切换写入方式重试本包', {
                  nextMode: effectiveUseNoResp ? 'writeNoResponse' : 'defaultWrite(no writeType)',
                })
                tryWrite(effectiveUseNoResp, false)
                return
              }
              reject(new Error(msg || 'BLE write failed'))
            },
          })
        }
        tryWrite(effectiveUseNoResp, !hasFlippedWriteModeThisJob)
      })
    }

    function sendNext (): Promise<void> {
      if (completed) {
        return Promise.reject(new Error('BLE write timeout'))
      }
      if (sent >= total) {
        completed = true
        if (timeoutId) clearTimeout(timeoutId)
        /** 末包 write 成功后立刻 resolve 时,部分机芯尚未吃完缓冲;短延迟再结束,减少「界面成功但不出纸」 */
        const settleMs = data.length > 400 ? 180 : 50
        return new Promise<void>((resolve) => {
          setTimeout(() => {
            if (onProgress) onProgress(100)
            resolve()
          }, settleMs)
        })
      }
      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) => {
        resetTimeout(reject)
        writeOneBuffer(buffer)
          .then(() => {
            if (completed) return
            sent++
            if (onProgress) onProgress(Math.round((sent / total) * 100))
            if (writeDelayMs <= 0) {
              sendNext().then(resolve).catch(reject)
              return
            }
            setTimeout(() => sendNext().then(resolve).catch(reject), writeDelayMs)
          })
          .catch((e: any) => {
            if (completed) return
            completed = true
            if (timeoutId) clearTimeout(timeoutId)
            reject(e instanceof Error ? e : new Error(String(e?.message || e || 'BLE write failed')))
          })
      })
    }

    return sendNext()
  }

  /**
   * 单包 ATT 可写字节数:理论为 mtu-3;MTU≤23 时旧代码误用 mtu 本值(如 23)会超过链路真上限 20,导致截断/无出纸却 write success。
   * 协商到 512 时不少佳博/安卓组合仍不能稳定传 500+ 字节/包,需再压到安全上限。
   */
  const mtuToPayloadSize = (negotiatedMtu: number) => {
    const mtu = Math.max(23, Math.min(512, Math.round(negotiatedMtu || 23)))
    const attPayload = Math.max(20, mtu - 3)
    const SAFE_BLE_WRITE_CAP = 182
    return Math.min(attPayload, SAFE_BLE_WRITE_CAP)
  }

  // #ifdef APP-PLUS
  if (conn.deviceType === 'ble') {
    const driver = getPrinterDriverByKey(getCurrentPrinterDriverKey())
    const preferred = driver.preferredBleMtu || BLE_MTU_DEFAULT
    return bleOpenAdapter()
      .then(() => bleEnsureDeviceConnected(deviceId))
      .then(() => new Promise<void>((r) => setTimeout(r, 100)))
      .then(() => ensureBleUartNotifyIfNeeded(deviceId, serviceId, characteristicId))
      .then(() => requestBleMtuNegotiation(deviceId, preferred))
      .then((negotiated) => runWritesWithPayloadSize(mtuToPayloadSize(negotiated)))
  }
  // #endif
  return runWritesWithPayloadSize(mtuToPayloadSize(conn.mtu || BLE_MTU_DEFAULT))
}

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) => {
    let settled = false
    const finish = (fn: () => void) => {
      if (settled) return
      settled = true
      clearTimeout(timeoutId)
      fn()
    }
    const timeoutId = setTimeout(() => {
      finish(() => {
        reject(buildClassicBluetoothError('Classic Bluetooth send timeout', conn.deviceId))
      })
    }, 15000)

    try {
      if (!classicBluetooth) {
        finish(() => reject(new Error('Classic Bluetooth not available')))
        return
      }
      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'))
        : true
      if (!ready) {
        const errorMessage = typeof classicBluetooth.getLastError === 'function'
          ? classicBluetooth.getLastError()
          : ''
        finish(() => 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) => {
          finish(() => {
            if (onProgress) onProgress(100)
            if (ok) {
              resolve()
              return
            }
            reject(buildClassicBluetoothError(
              errorMessage || classicBluetooth.getLastError?.() || 'Classic Bluetooth send failed',
              conn.deviceId
            ))
          })
        })
        return
      }

      const ok = classicBluetooth.sendByteData(sendData)
      finish(() => {
        if (onProgress) onProgress(100)
        if (ok) {
          resolve()
          return
        }
        const errorMessage = typeof classicBluetooth.getLastError === 'function'
          ? classicBluetooth.getLastError()
          : ''
        reject(buildClassicBluetoothError(errorMessage || 'Classic Bluetooth send failed', conn.deviceId))
      })
    } catch (e: any) {
      finish(() => reject(buildClassicBluetoothError(e?.message || String(e || 'Classic Bluetooth send exception'), conn.deviceId)))
    }
  })
  // #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('')

    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) {
            try { moeTcp.disconnect() } catch (_) {}
            tryPort(idx + 1).then(resolve).catch(reject)
          }
        })
      })
    }
    return tryPort(0)
  } 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
}