using System;
using GcDevicePc.Common;

namespace GcDevicePc.Module
{
    class WTD424XOutput
    {
        private GCModbus485 rtumodbus = new GCModbus485(6, 9600, 2000);
        private bool workflag = false;

        public WTD424XOutput()
        {

        }

        public int WTD424X_Open()
        {

            int ret = 0;
            int count = 3;
            try
            {
                ret = rtumodbus.ModbusOpen();
                if (ret == 0)
                {
                    workflag = true;
                    UInt16[] buf = new UInt16[4] { 1, 1, 1, 1 };
                    ret = rtumodbus.WriteMultipleRegs(1, 11, 4, ref buf);
                    while (ret != 0 && count > 0)
                    {
                        ret = rtumodbus.WriteMultipleRegs(1, 11, 4, ref buf);
                        count--;
                    }
                }
                   
            }
            catch (Exception ex)
            {
               Log.Error(ex.Message);
            }

            return ret;
        }

        public int WTD424X_Close()
        {

            int ret = 0;
            try
            {
                ret = rtumodbus.ModbusClose();
                if (ret == 0)
                    workflag = false;
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
            return ret;
        }

        private void GetMaVal(float[] data, ref UInt16[] buf)
        {
            if (data[0] >= 0 && data[0] <= 150.0f)
                buf[0] = (UInt16) (data[0] * 20.0f / 150.0f * 4095 / 20.0f);
            if (data[1] >= 0 && data[1] <= 10.0f)
                buf[1] = (UInt16) (data[1] * 20.0f / 10.0f * 4095 / 20.0f);
            if (data[2] >= 0 && data[2] <= 20.0f)
                buf[2] = (UInt16) (data[2] * 20.0f / 20.0f * 4095 / 20.0f);
            if (data[3] >= 0 && data[3] <= 30.0f)
                buf[3] = (UInt16) (data[3] * 20.0f / 30.0f * 4095 / 20.0f);
        }

        public int UpdateData(float[] data)
        {
            UInt16[] buf = new UInt16[4] { 0, 4095, 2047, 1024 };
            int ret =  rtumodbus.WriteMultipleRegs(1, 1, 4, ref buf);
            return ret;
        }

        public int UpdateData2(float[] data)
        {
            UInt16[] buf = new UInt16[4] { 0, 0, 0, 0 };
            int ret = 1;
            if (workflag)
            {
                GetMaVal(data, ref buf);
                ret = rtumodbus.WriteMultipleRegs(1, 1, 4, ref buf);
            }
            return ret;
        }

    }
}
