'use strict';

const { Service } = require('ee-core');
// 串口的功能
const { SerialPort } = require('serialport')
// 保存串口实例
var seriaPortIns = undefined;

// 这个是处理时间的库
var moment = require('moment')
// Modbus TCP 
// create an empty modbus client
const ModbusRTU = require("modbus-serial")
var client = new ModbusRTU();

// open connection to a tcp line
// 创建Modbus TCP连接，IP是15.18.200.23,端口502
// client.connectTCP("15.18.200.23", { port: 502 });
//-------

/**
 * hardware（service层为单例）
 * @class
 */
class HardwareService extends Service {

  constructor(ctx) {
    super(ctx);
  }

  /**
  * 发送消息
  * @param {*} seriaPort 串口实例
  */
  sendSeriaPort(args) {
    const port = seriaPortIns;
    const msg = args.msg;
    port.write(msg, 'hex')
    console.log('测试发送消息' + msg);

  }
  /**
 * 连接串口 只执行一次
 * @param {*} options 串口参数
 * @param {*} event 回调. 
 */
  connectSeriaPort(options, event) {

    if (seriaPortIns != undefined) {
      console.log("SerialPort is have");
      return;
    }
    const channel = 'controller.hardware.connectSeriaPort';
    const port = new SerialPort(options, (e) => {
      console.log("SerialPort open");
      console.log(e);
      if (e === null) {
        // 打开成功 把串口发送出去
        let data2 = {
          type: 'connect'
        }
        event.reply(`${channel}`, data2)
      }

    })

    port.on('data', (data) => {
      let data2 = {
        type: 'received',
        data: data
      }
      console.log(`Received data: ${data2}`)
      event.reply(`${channel}`, data2)
    })
    setInterval(() => {
      // console.log('setInterval')
      if (!port.isOpen) {
        // console.log('setInterval open')
        port.open();
      }

    }, 1000)
    port.on('close', () => {
      let data2 = {
        type: 'close'
      }
      console.log(`SerialPort close: ${data2}`)
      event.reply(`${channel}`, data2)
    })
    port.on('error', (e) => {
      let data2 = {
        type: 'error'
      }
      console.log(`SerialPort error: ${e}`)
      event.reply(`${channel}`, data2)
    })

    seriaPortIns = port;

  }
  /**
   * test
   */
  async test(args) {
    let obj = {
      status: 'ok',
      params: args
    }

    return obj;
  }

  // 样例 ModbusTCP 
  tempModbusTCP() {
    //http://momentjs.cn/  时间库
    //https://www.jianshu.com/p/50954625b158
    // 读取非甲烷总烃的关于总烃、甲烷、NMHC这3个寄存器（寄存器地址分别为22,25,28）中的浓度
    // 每隔5秒钟读取保持寄存器的值，从寄存器地址22开始读取，读10个寄存器到data数组中
    setInterval(function () {
      // 要连接后才能用 
      client.readHoldingRegisters(22, 10, function (err, data) {
        // 获取当前时间
        //moment.locale('zh-cn');
        // console.log("----------------------------------------------------------------------");
        // console.log("数据时间是：" + moment().format('YYYY年MM月DD日 HH时mm分ss秒'));
        // console.log("总烃的浓度是:" + data.data[0] * 0.01 + "ppmV");  // 总烃浓度对应的寄存器地址为22
        // console.log("CH4的浓度是:" + data.data[3] * 0.01 + "ppmV"); // CH4浓度对应的寄存器地址为22
        // console.log("NHMC的浓度是:" + data.data[6] * 0.01 + "ppmV"); // NHMC浓度对应的寄存器地址为22
        // console.log("----------------------------------------------------------------------");

        //console.log(data.data);
      });
    }, 5000);
  }
}

HardwareService.toString = () => '[class HardwareService]';
module.exports = HardwareService;  