process.on('message', async (message, setHandle) => {
  let program
  let timer
  let st
  let icdev

  try {
    const ffi = require('ffi')
    const ref = require('ref')

    let dllPath = require('path').join(message)

    program = ffi.Library(dllPath, {
      'hex_a': ['int', ['int', 'char*', 'int']],
      'rf_usbopen': ['int', []],
      'rf_usbclose': ['int', ['int']],
      'rf_beep': ['int', ['int', 'int']],
      'rf_halt': ['int', ['int']],
      'rf_load_key': ['int', ['int', 'int', 'int', 'char*']],
      'rf_load_key_hex': ['int', ['int', 'int', 'int', 'char*']],
      'rf_request': ['int', ['int', 'int', 'char*']],
      'rf_anticoll': ['int', ['int', 'int', ref.refType('long')]],
      'rf_select': ['int', ['int', ref.refType('long'), 'char*']],
      'rf_card': ['int', ['int', 'int', 'char*']],
      'rf_authentication': ['int', ['int', 'int', 'int']],
      'rf_authentication_key': ['int', ['int', 'int', 'int', 'char*']],
      'rf_read': ['int', ['int', 'int', 'char*']]
    })

    icdev = program.rf_usbopen()

    if (icdev < 0) {
      exit(0) // 连接错误
    }

    readCard()
  } catch (e) {
    exit(e)
  }

  function exit (val) {
    if (icdev > 0) {
      program.rf_usbclose(icdev)
    }
    process.send(val)
    process.kill(process.pid)
    process.exit(0)
  }

  function readCard () {
    timer && clearTimeout(timer)

    // 装载密码
    loadKey()

    const snr = Buffer.alloc(4)

    st = program.rf_card(icdev, 0, snr)

    // 验证1扇区密码
    st = program.rf_authentication(icdev, 0, 1)

    const card = Buffer.alloc(16)

    // 1扇区0块，从4开始计算(每个扇区4个数据块[[0,1,2,3][4,5,6,7],....])
    st = program.rf_read(icdev, 4, card)

    timer = setTimeout(() => {
      readCard()
    }, 500)

    const result = snr.readUIntLE(0, 4)

    if (st !== 18 && result) {
      // 读卡器鸣叫
      program.rf_beep(icdev, 30)

      // 发送iccard号
      exit(result + '')
    }
  }

  function loadKey () {
    const key = Buffer.from([0xff, 0xff, 0xff, 0xff, 0xff, 0xff])

    const mode = 0
    let sector = 0
    for (let i = 0; i < 16; i++) {
      // console.log(icdev, mode, sector, key)
      const st = program.rf_load_key(icdev, mode, sector, key)
      if (st < 0) {
        console.log(st + '_' + sector + ' sector rf_load_key error!')
      }
      sector++
    }
  }

  // program.rf_usbclose(icdev)
})
