let mainHdApi;
let too_many_open_files = false;
let heartbeatTime = 0;
setInterval(() => {
  if (Date.now() - heartbeatTime > 1000 * 20) {
    console.log('和主进程心跳间隔大于20秒退出子进程');
    process.exit(1);
  }
}, 1000 * 10);
// 当父级发送信息
process.on('message', function (data) {
  try {
    // console.log("接收到主进程发送信息", data);
    if (HdApi[data.cmd]) {
      HdApi[data.cmd](data.data);
    }
    heartbeatTime = Date.now();
  } catch (error) {
    ktLog('子进程发生错误：' + error);
    process.send({
      cmd: 'hdCall',
      data: {
        cmd: data.cmd,
        resultCode: -1,
      },
    });
  }
});
// 给主进程发送信息
// process.send();
// 日志信息发送给主进程
function ktLog(msg) {
  process.send({ cmd: 'ktLog', msg });
}
let HdApi = {
  /* 硬件库初始化 */
  hdHardWareInit({ deviceList = [], authorizationCode = '754a0b2598ffa1839ea165829918396d1a06967e7de87304', dllpath, logPath, mainPath }) {
    mainHdApi = require(mainPath);
    deviceList = JSON.stringify({ deviceList });
    ktLog(` 子进程硬件库初始化： \n authorizationCode=${authorizationCode} \n dllpath=${dllpath} \n logPath=${logPath} \n deviceList=${deviceList}`);
    mainHdApi.hdHardWareInit(authorizationCode, dllpath, logPath, deviceList, (res) => {
      // ktLog(`执行硬件库回调：${res}`);
      res = JSON.parse(res);
      process.send({ cmd: 'hdCall', data: res });
    });
  },

  /* 读取硬件库版本号 */
  hdHardWareVer(deviceList = []) {
    deviceList = JSON.stringify({
      deviceList: ['mainHardWare', ...deviceList],
    });
    ktLog(`获取硬件库版本号：${deviceList}`);
    // 硬件库版本号
    mainHdApi.hdHardWareVer(deviceList);
  },

  /* 硬件指令 */
  hdHardWareCMD(cmdData) {
    if (cmdData.cmd === 'getAllStatusCode' && !too_many_open_files) {
      // 部分设备上  process.memoryUsage() 打印多了会报 （EMFILE: too many open files, uv_resident_set_memory） 错误，
      //如果发生错误就不在打印了
      try {
        ktLog(`hardwareChildren process.memoryUsage：${JSON.stringify(process.memoryUsage())}`);
      } catch (error) {
        too_many_open_files = true;
      }
    }
    cmdData = JSON.stringify(cmdData);
    mainHdApi.hdHardWareCMD(cmdData);
  },

  /* 释放硬件库 */
  hdHardWareRelease() {
    mainHdApi.hdHardWareRelease();
  },
};
