using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.IO.Ports;
using System.Drawing.Printing;
using HouseHeatingTerminal.Classes;


public enum LogType : byte { Log, Error, IO_Error, Data, TimeOut };



namespace HouseHeatingTerminal
{

    public partial class MainForm : Form
    {

        public MainForm()
        {
            InitializeComponent();
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SettingsForm settings = new SettingsForm();
            settings.ShowDialog();


            if (settings.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                refreshTimer.Interval = Properties.Settings.Default.refreshInterval * 1000;
                if (!serialComm.IsSerialConnected()) Connect();
            }

        }


        public static void Log(string logMessage, TextWriter w, LogType type)
        {
            switch (type)
            {
                case LogType.Log: w.Write("\r\nLOG: ");
                    break;
                case LogType.Error: w.Write("\r\nERR: ");
                    break;
                case LogType.IO_Error: w.Write("\r\nIOE: ");
                    break;
                case LogType.Data: w.Write("\r\nDAT: ");
                    break;
                case LogType.TimeOut: w.Write("\r\nTOU: ");
                    break;
                default: w.Write("\r\nLOG: ");
                    break;
            }
            w.Write("{0}, {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToShortDateString());
            w.Write(": {0}", logMessage);
        }

        public void Connect()
        {
            connectionStatusLabel.Text = "Connecting";
            if (SerialConnBackgroundWorker.IsBusy != true)
            {
                SerialConnBackgroundWorker.RunWorkerAsync();
            }
            StatusForm statusForm = new StatusForm(ConnectionStatus.Connecting);
            statusForm.ShowDialog();



        }
        public void Disconnect()
        {
            connectionStatusLabel.Text = "Disconnecting";

            if (SerialConnBackgroundWorker.IsBusy != true)
            {
                SerialConnBackgroundWorker.RunWorkerAsync();
            }
            StatusForm statusForm = new StatusForm(ConnectionStatus.Disconnecting);
            statusForm.ShowDialog();

        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            Left = Properties.Settings.Default.windowPosX;
            Top = Properties.Settings.Default.windowPosY;
            SerialConnBackgroundWorker.WorkerSupportsCancellation = true;
            SerialConnBackgroundWorker.WorkerReportsProgress = true;
            refreshBackgroundWorker.WorkerSupportsCancellation = true;
            refreshBackgroundWorker.WorkerReportsProgress = false;
            refreshTimer.Interval = Properties.Settings.Default.refreshInterval * 1000;

        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (serialComm.IsSerialConnected()) Disconnect();
            Properties.Settings.Default.windowPosX = Left;
            Properties.Settings.Default.windowPosY = Top;
            Properties.Settings.Default.Save();
            using (StreamWriter w = File.AppendText(Properties.Settings.Default.logPath))
            {
                Log("Application closed.", w, LogType.Log);
            }
        }

        private void backgroundWorkerSerialConnection_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;


            if ((worker.CancellationPending == true))
            {
                e.Cancel = true;
            }
            else
            {
                // Perform a time consuming operation and report progress.
                try
                {
                    if (!serialComm.IsSerialConnected())
                    {
                        worker.ReportProgress((int)ConnectionStatus.Connecting);
                        worker.ReportProgress((int)serialComm.OpenConn());

                    }
                    else
                    {
                        worker.ReportProgress((int)ConnectionStatus.Disconnecting);
                        worker.ReportProgress((int)serialComm.CloseConn());
                    }


                }
                catch (UnauthorizedAccessException)
                {
                    worker.ReportProgress((int)ConnectionStatus.ConErr);

                }
                catch (InvalidOperationException)
                {
                    worker.ReportProgress((int)ConnectionStatus.ConErr);
                }
                catch (IOException)
                {
                    worker.ReportProgress((int)ConnectionStatus.ConErr);
                }


            }
        }

        private void SerialConnBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            using (StreamWriter w = File.AppendText(Properties.Settings.Default.logPath))
            {

                var form = Program.GetWindow<StatusForm>();
                switch ((ConnectionStatus)e.ProgressPercentage)
                {

                    case ConnectionStatus.Connecting:
                        {
                            form.StatusForm_ChangeState(ConnectionStatus.Connecting);
                            Log("Connecting to terminal...", w, LogType.Log);
                            break;
                        }
                    case ConnectionStatus.Connected:
                        {
                            form.StatusForm_ChangeState(ConnectionStatus.Connected);
                            Log("Connected to terminal.", w, LogType.Log);
                            break;
                        }
                    case ConnectionStatus.Disconnecting:
                        {
                            form.StatusForm_ChangeState(ConnectionStatus.Disconnecting);
                            Log("Disconnecting from terminal...", w, LogType.Log);
                            break;
                        }
                    case ConnectionStatus.Disconnected:
                        {
                            form.StatusForm_ChangeState(ConnectionStatus.Disconnected);
                            Log("Disconnected from terminal.", w, LogType.Log);
                            break;
                        }
                    case ConnectionStatus.Error:
                        {
                            form.StatusForm_ChangeState(ConnectionStatus.Error);
                            Log("COM Port not found on this computer.", w, LogType.IO_Error);
                            break;
                        }
                    case ConnectionStatus.ConErr:
                        {
                            form.StatusForm_ChangeState(ConnectionStatus.ConErr);
                            Log("The terminal is not connected to this computer or is not enabled to communicate.", w, LogType.Error);
                            break;
                        }
                    default: break;
                }

            }

        }

        private void backgroundWorkerSerialConnection_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            if ((e.Cancelled == true))
            {

            }

            else if (!(e.Error == null))
            {

            }
            else
            {


            }
            if (serialComm.IsTerminalConnected() && Properties.Settings.Default.updTimeAtConn)
            {
                serialComm.UpdateTime();
            }
            refreshConnState();



        }


        public void measurementComplete(byte[] data, SCIRegAddress reg)
        {

            if (reg >= SCIRegAddress.LM75_1 && reg <= SCIRegAddress.OUTDOOR_HUM)
            {
                Control control = null;
                float value = serialComm.ConvertDataToValue(data);
                switch (reg)
                {
                    case SCIRegAddress.LM75_1: control = LM75_1TextBox; break;
                    case SCIRegAddress.LM75_2: control = LM75_2TextBox; break;
                    case SCIRegAddress.MCP9808_1: control = MCP9808_1TextBox; break;
                    case SCIRegAddress.MCP9808_2: control = MCP9808_2TextBox; break;
                    case SCIRegAddress.MCP9808_3: control = MCP9808_3TextBox; break;
                    case SCIRegAddress.HTU21D_TEMP: control = HTU21D_TEMPTextBox; break;
                    case SCIRegAddress.HTU21D_HUM: control = HTU21D_HUMTextBox; break;
                    case SCIRegAddress.ROOM_TEMP: control = roomTempTextBox; break;
                    case SCIRegAddress.WATER_OUT_TEMP: control = waterOutTempTextBox; break;
                    case SCIRegAddress.WATER_RETURN_TEMP: control = waterReturnTempTextBox; break;
                    case SCIRegAddress.AVG_TEMP: control = avgTempTextBox; break;
                    case SCIRegAddress.OUTDOOR_TEMP: control = outTempTextBox; break;
                    case SCIRegAddress.OUTDOOR_HUM: control = outHumTextBox; break;
                    default: break;
                }
                if (control != null)
                {
                    Program.ControlInvoke<byte[], SCIRegAddress>(control, measurementComplete, data, reg);
                    if (!((control == roomTempTextBox && setRoomTempCheckBox.Checked) || (control == waterOutTempTextBox && setWaterOutTempCheckBox.Checked) || (control == waterReturnTempTextBox && setWaterReturnTempCheckBox.Checked) || (control == avgTempTextBox && setAvgTempCheckBox.Checked) || (control == outTempTextBox && setOutTempCheckBox.Checked) || (control == outHumTextBox && setOutHumCheckBox.Checked)))
                    {
                        if (reg == SCIRegAddress.HTU21D_HUM || reg == SCIRegAddress.OUTDOOR_HUM)
                        {
                            control.Text = value.ToString("0.00") + "%";
                        }
                        else
                        {
                            control.Text = value.ToString("0.00") + "°C";
                        }
                    }
                }
            }
            else if (reg >= SCIRegAddress.REGULATE_DAY_TEMP && reg <= SCIRegAddress.OFF_AVG_TEMP)
            {
                NumericUpDown control = null;
                float value = serialComm.ConvertDataToValue(data);
                switch (reg)
                {
                    case SCIRegAddress.REGULATE_DAY_TEMP: control = regRoomDayTemp; break;
                    case SCIRegAddress.REGULATE_NIGHT_TEMP: control = regRoomNightTemp; break;
                    case SCIRegAddress.REGULATE_TEMP_HYST: control = regRoomTempHyst; break;
                    case SCIRegAddress.REGULATE_WATER_MAX_TEMP: control = waterMaxTemp; break;
                    case SCIRegAddress.REGULATE_WATER_DIFF: control = waterDiff; break;
                    case SCIRegAddress.ON_AVG_TEMP: control = autoSwOnTemp; break;
                    case SCIRegAddress.OFF_AVG_TEMP: control = autoSwOffTemp; break;
                    default: break;
                }


                Program.ControlInvoke<byte[], SCIRegAddress>(control, measurementComplete, data, reg);
                if (!((control == regRoomDayTemp && setRegRoomDayTempCheckBox.Checked) || (control == regRoomNightTemp && setRegRoomNightTempCheckBox.Checked) || (control == regRoomTempHyst && setRegRoomTempHystCheckBox.Checked)
                    || (control == waterMaxTemp && setWaterMaxTempCheckBox.Checked) || (control == waterDiff && setWaterDiffCheckBox.Checked) || (control == autoSwOnTemp && setAutoSwOnTempCheckBox.Checked) || (control == autoSwOffTemp && setAutoSwOffTempCheckBox.Checked)))
                {
                    if (Convert.ToDecimal(value) > control.Maximum)
                    {
                        control.Value = control.Maximum;
                    }
                    else if (Convert.ToDecimal(value) < control.Minimum)
                    {
                        control.Value = control.Minimum;
                    }
                    else
                    {
                        control.Value = Convert.ToDecimal(value);
                    }
                }
            }
            else if (reg >= SCIRegAddress.DAY_START_TIME && reg <= SCIRegAddress.PUMP_DELAY_TIME)
            {
                NumericUpDown control = null;
                int value = (int)data[0];
                switch (reg)
                {
                    case SCIRegAddress.DAY_START_TIME: control = dayStart; break;
                    case SCIRegAddress.DAY_END_TIME: control = dayEnd; break;
                    case SCIRegAddress.PUMP_DELAY_TIME: control = pumpDelayTime; break;
                    default: break;
                }
                if (control != null)
                {
                    Program.ControlInvoke<byte[], SCIRegAddress>(control, measurementComplete, data, reg);
                    if (!((control == dayStart && setDayStartCheckBox.Checked) || (control == dayEnd && setDayEndCheckBox.Checked) || (control == pumpDelayTime && setPumpDelayTimeCheckBox.Checked)))
                    {
                        control.Value = Convert.ToDecimal(value);
                    }
                }
            }

        }

        public void statusGetComplete(byte[] data, SCIRegAddress reg)
        {

            bool value = serialComm.ConvertDataToStatus(data);
            if (reg == SCIRegAddress.SYST_TYPE)
            {
                RadioButton control;
                if (value)
                {
                    control = gasSystTypeRadioButton;
                }
                else
                {
                    control = woodSystTypeRadioButton;
                }
                if (control != null)
                {
                    Program.ControlInvoke<byte[], SCIRegAddress>(control, statusGetComplete, data, reg);
                    if (!((control == gasSystTypeRadioButton || control == woodSystTypeRadioButton) && setSystTypeCheckBox.Checked))
                    {
                        control.Checked = true;
                    }
                }

            }
            else
            {
                CheckBox control = null;
                switch (reg)
                {
                    case SCIRegAddress.HEATER: control = heaterStatusCheckBox; break;
                    case SCIRegAddress.PUMP: control = pumpStatusCheckBox; break;
                    case SCIRegAddress.AUTOSW: control = autoSwitchingEnableCheckBox; break;
                    default: break;
                }
                if (control != null)
                {
                    Program.ControlInvoke<byte[], SCIRegAddress>(control, statusGetComplete, data, reg);
                    if (!((control == heaterStatusCheckBox && setHeaterStatusCheckBox.Checked) || (control == pumpStatusCheckBox && setPumpStateCheckBox.Checked) || (control == autoSwitchingEnableCheckBox && setAutoSwitchingEnableCheckBox.Checked)))
                    {
                        control.Checked = value;
                    }
                }
            }
            refreshTimer.Start();
        }


        private void connectBtn_Click(object sender, EventArgs e)
        {
            if (!serialComm.IsSerialConnected())
            {
                Connect();

            }
            else
            {

                refreshTimer.Stop();
                while (serialComm.IsCommActive()) ;
                Disconnect();

            }

        }


        private void MainForm_Shown(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.firstRun)
            {
                Properties.Settings.Default.firstRun = false;
                SettingsForm settings = new SettingsForm();
                settings.ShowDialog();
                string sStartupPath = Application.StartupPath;
                Properties.Settings.Default.logPath = sStartupPath + @"\HeatingLog.log";
                if (settings.DialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    refreshTimer.Interval = Properties.Settings.Default.refreshInterval * 1000;
                    if (!serialComm.IsSerialConnected()) Connect();
                }
            }
            else if (Properties.Settings.Default.autoConnect && !serialComm.IsSerialConnected())
            {

                Connect();
            }
            using (StreamWriter w = File.AppendText(Properties.Settings.Default.logPath))
            {
                Log("Application started.", w, LogType.Log);
            }
        }


        private void refreshTimer_Tick(object sender, EventArgs e)
        {
            if (refreshBackgroundWorker.IsBusy != true)
            {
                refreshBackgroundWorker.RunWorkerAsync();
            }




        }

        private void measBtn_Click(object sender, EventArgs e)
        {
            if (serialComm.IsTerminalConnected())
            {
                if (!refreshTimer.Enabled)
                {
                    refreshTimer.Interval = Properties.Settings.Default.refreshInterval * 1000;
                    logBtn.Enabled = true;
                    using (StreamWriter w = File.AppendText(Properties.Settings.Default.logPath))
                    {
                        Log("Measuring started.", w, LogType.Log);
                    }
                    MeasureBtn.Text = "Stop";
                    refreshTimer.Start();
                    refreshTimer_Tick(null, null);
                }
                else if (refreshTimer.Enabled)
                {
                    using (StreamWriter w = File.AppendText(Properties.Settings.Default.logPath))
                    {
                        Log("Measuring stopped.", w, LogType.Log);
                    }
                    MeasureBtn.Text = "Measure";
                    refreshTimer.Stop();
                }

            }

        }

        private void getFromTerminal(SCIRegAddress register)
        {
            serialComm.GetData(register);
        }

        private void getSerializedFromTerminal(SCIRegAddress[] registers)
        {
            serialComm.GetSerData(registers);
        }


        private void timeUPDBtn_Click(object sender, EventArgs e)
        {
            while (serialComm.IsCommWaitingForAnswer()) ;
            serialComm.UpdateTime();
        }

        private void refreshBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            if ((worker.CancellationPending == true))
            {
                e.Cancel = true;
            }
            else
            {
                // Perform a time consuming operation and report progress.
                try
                {
                    List<SCIRegAddress> registers = new List<SCIRegAddress>();
                    if (getLM75_1CheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.LM75_1);
                    }
                    if (getLM75_2CheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.LM75_2);
                    }
                    if (getMCP9808_1CheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.MCP9808_1);
                    }
                    if (getMCP9808_2CheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.MCP9808_2);
                    }
                    if (getMCP9808_3CheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.MCP9808_3);
                    }
                    if (getHTU21D_TEMPCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.HTU21D_TEMP);
                    }
                    if (getHTU21D_HUMCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.HTU21D_HUM);
                    }
                    if (!setRoomTempCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.ROOM_TEMP);
                    }
                    if (!setWaterOutTempCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.WATER_OUT_TEMP);
                    }
                    if (!setWaterReturnTempCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.WATER_RETURN_TEMP);
                    }
                    if (!setAvgTempCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.AVG_TEMP);
                    }
                    if (!setOutTempCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.OUTDOOR_TEMP);
                    }
                    if (!setOutHumCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.OUTDOOR_HUM);
                    }
                    if (!setRegRoomDayTempCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.REGULATE_DAY_TEMP);
                    }
                    if (!setRegRoomNightTempCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.REGULATE_NIGHT_TEMP);
                    }
                    if (!setRegRoomTempHystCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.REGULATE_TEMP_HYST);
                    }
                    if (!setWaterMaxTempCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.REGULATE_WATER_MAX_TEMP);
                    }
                    if (!setWaterDiffCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.REGULATE_WATER_DIFF);
                    }
                    if (!setPumpDelayTimeCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.PUMP_DELAY_TIME);
                    }
                    if (!setAutoSwOnTempCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.ON_AVG_TEMP);
                    }
                    if (!setAutoSwOffTempCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.OFF_AVG_TEMP);
                    }
                    if (!setSystTypeCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.SYST_TYPE);
                    }
                    if (!setHeaterStatusCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.HEATER);
                    }
                    if (!setPumpStateCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.PUMP);
                    }
                    if (!setAutoSwitchingEnableCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.AUTOSW);
                    }
                    if (!setDayStartCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.DAY_START_TIME);
                    }
                    if (!setDayEndCheckBox.Checked)
                    {
                        registers.Add(SCIRegAddress.DAY_END_TIME);
                    }

                    if (registers.Count == 1)
                    {
                        getFromTerminal(registers.ToArray().First());
                    }
                    else if (registers.Count > 1)
                    {
                        getSerializedFromTerminal(registers.ToArray());
                    }
                    refreshConnState();


                }
                catch (UnauthorizedAccessException)
                {
                    worker.ReportProgress(1);

                }


            }
        }

        private void resetTerminalBtn_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = DialogResult.None;

            dialogResult = MessageBox.Show("Warning!\nResetting the terminal clears all settings!\nDo you really want to continue?", "Reset warning", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);

            if (dialogResult == DialogResult.Yes)
            {
                serialComm.ResetTerminal();
                System.Threading.Thread.Sleep(500);
                Disconnect();

            }
        }

        public void ChangeStatusLabel(string text)
        {
            this.connectionStatusLabel.Text = text;
        }

        public static void refreshConnState()
        {
            var form = Program.GetWindow<MainForm>();
            Program.FormInvoke(form, refreshConnState);
            Program.ControlInvoke(form.connectBtn, refreshConnState);
            Program.ControlInvoke(form.MeasureBtn, refreshConnState);
            Program.ControlInvoke(form.timeUPDBtn, refreshConnState);
            Program.ControlInvoke(form.resetTerminalBtn, refreshConnState);
            Program.ControlInvoke(form.setTerminalBtn, refreshConnState);
            if (serialComm.IsSerialConnected())
            {

                form.connectionStatusLabel.Text = "Port opened";
                if (serialComm.IsTerminalConnected())
                {
                    form.connectBtn.Text = "Disconnect";
                    form.connectionStatusLabel.Text = "Connected";
                    form.MeasureBtn.Enabled = true;
                    form.timeUPDBtn.Enabled = true;
                    form.resetTerminalBtn.Enabled = true;
                    form.setTerminalBtn.Enabled = true;
                }
                else
                {
                    serialComm.disconnectSerialPort();
                }
            }
            else
            {
                form.connectBtn.Text = "Connect";
                form.MeasureBtn.Text = "Measure";
                form.connectionStatusLabel.Text = "Disconnected";
                form.MeasureBtn.Enabled = false;
                form.timeUPDBtn.Enabled = false;
                form.resetTerminalBtn.Enabled = false;
                form.logBtn.Enabled = false;
                form.setTerminalBtn.Enabled = false;

            }
            Program.GetWindow<StatusForm>().StatusForm_Finish();

        }

        public static void TimeoutOccured()
        {
            var form = Program.GetWindow<MainForm>();
            using (StreamWriter w = File.AppendText(Properties.Settings.Default.logPath))
            {
                Log("Measurement Timeout.", w, LogType.TimeOut);
            }
            form.ChangeStatusLabel("Measurement Timeout");
            form.refreshTimer.Stop();
            form.Disconnect();
            form.Refresh();

        }

        public static void NoAnswerTimeout()
        {
            using (StreamWriter w = File.AppendText(Properties.Settings.Default.logPath))
            {
                Log("Terminal not answering...", w, LogType.TimeOut);
            }
            Program.GetWindow<MainForm>().ChangeStatusLabel("Terminal not answering");
        }

        public static void StatusMessage(string message)
        {
            Program.GetWindow<MainForm>().ChangeStatusLabel(message);

        }

        private void setRoomTempCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            roomTempTextBox.Enabled = setRoomTempCheckBox.Checked;
        }

        private void setWaterOutTempCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            waterOutTempTextBox.Enabled = setWaterOutTempCheckBox.Checked;
        }

        private void setWaterReturnTempCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            waterReturnTempTextBox.Enabled = setWaterReturnTempCheckBox.Checked;
        }

        private void setHeaterValueCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            heaterStatusCheckBox.Enabled = setHeaterStatusCheckBox.Checked;
        }

        private void setPumpStateCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            pumpStatusCheckBox.Enabled = setPumpStateCheckBox.Checked;
        }

        private void SetBtn_Click(object sender, EventArgs e)
        {
            byte[] message = new byte[200];
            int i = 0;
            if (setRoomTempCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.ROOM_TEMP;
                message[i++] = serialComm.ConvertValueToMessage(float.Parse(roomTempTextBox.Text, System.Globalization.CultureInfo.InvariantCulture))[0];
                message[i++] = serialComm.ConvertValueToMessage(float.Parse(roomTempTextBox.Text, System.Globalization.CultureInfo.InvariantCulture))[1];
            }
            if (setWaterOutTempCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.WATER_OUT_TEMP;
                message[i++] = serialComm.ConvertValueToMessage(float.Parse(waterOutTempTextBox.Text, System.Globalization.CultureInfo.InvariantCulture))[0];
                message[i++] = serialComm.ConvertValueToMessage(float.Parse(waterOutTempTextBox.Text, System.Globalization.CultureInfo.InvariantCulture))[1];
            }
            if (setWaterReturnTempCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.WATER_RETURN_TEMP;
                message[i++] = serialComm.ConvertValueToMessage(float.Parse(waterReturnTempTextBox.Text, System.Globalization.CultureInfo.InvariantCulture))[0];
                message[i++] = serialComm.ConvertValueToMessage(float.Parse(waterReturnTempTextBox.Text, System.Globalization.CultureInfo.InvariantCulture))[1];
            }
            if (setAvgTempCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.AVG_TEMP;
                message[i++] = serialComm.ConvertValueToMessage(float.Parse(avgTempTextBox.Text, System.Globalization.CultureInfo.InvariantCulture))[0];
                message[i++] = serialComm.ConvertValueToMessage(float.Parse(avgTempTextBox.Text, System.Globalization.CultureInfo.InvariantCulture))[1];
            }
            if (setOutTempCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.OUTDOOR_TEMP;
                message[i++] = serialComm.ConvertValueToMessage(float.Parse(outTempTextBox.Text, System.Globalization.CultureInfo.InvariantCulture))[0];
                message[i++] = serialComm.ConvertValueToMessage(float.Parse(outTempTextBox.Text, System.Globalization.CultureInfo.InvariantCulture))[1];
            }
            if (setOutHumCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.OUTDOOR_HUM;
                message[i++] = serialComm.ConvertValueToMessage(float.Parse(outHumTextBox.Text, System.Globalization.CultureInfo.InvariantCulture))[0];
                message[i++] = serialComm.ConvertValueToMessage(float.Parse(outHumTextBox.Text, System.Globalization.CultureInfo.InvariantCulture))[1];
            }
            if (setRegRoomDayTempCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.REGULATE_DAY_TEMP;
                message[i++] = serialComm.ConvertValueToMessage((float)regRoomDayTemp.Value)[0];
                message[i++] = serialComm.ConvertValueToMessage((float)regRoomDayTemp.Value)[1];
            }
            if (setRegRoomNightTempCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.REGULATE_NIGHT_TEMP;
                message[i++] = serialComm.ConvertValueToMessage((float)regRoomNightTemp.Value)[0];
                message[i++] = serialComm.ConvertValueToMessage((float)regRoomNightTemp.Value)[1];
            }
            if (setRegRoomTempHystCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.REGULATE_TEMP_HYST;
                message[i++] = serialComm.ConvertValueToMessage((float)regRoomTempHyst.Value)[0];
                message[i++] = serialComm.ConvertValueToMessage((float)regRoomTempHyst.Value)[1];
            }
            if (setWaterMaxTempCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.REGULATE_WATER_MAX_TEMP;
                message[i++] = serialComm.ConvertValueToMessage((float)waterMaxTemp.Value)[0];
                message[i++] = serialComm.ConvertValueToMessage((float)waterMaxTemp.Value)[1];
            }
            if (setWaterDiffCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.REGULATE_WATER_DIFF;
                message[i++] = serialComm.ConvertValueToMessage((float)waterDiff.Value)[0];
                message[i++] = serialComm.ConvertValueToMessage((float)waterDiff.Value)[1];
            }
            if (setPumpDelayTimeCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.PUMP_DELAY_TIME;
                message[i++] = Convert.ToByte(pumpDelayTime.Value);
            }
            if (setSystTypeCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.SYST_TYPE;
                if (gasSystTypeRadioButton.Checked)
                {
                    message[i++] = Convert.ToByte(true);
                }
                else
                {
                    message[i++] = Convert.ToByte(false);
                }
            }
            if (setAutoSwOnTempCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.ON_AVG_TEMP;
                message[i++] = serialComm.ConvertValueToMessage((float)autoSwOnTemp.Value)[0];
                message[i++] = serialComm.ConvertValueToMessage((float)autoSwOnTemp.Value)[1];
            }
            if (setAutoSwOffTempCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.OFF_AVG_TEMP;
                message[i++] = serialComm.ConvertValueToMessage((float)autoSwOffTemp.Value)[0];
                message[i++] = serialComm.ConvertValueToMessage((float)autoSwOffTemp.Value)[1];
            }
            if (setHeaterStatusCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.HEATER;
                message[i++] = Convert.ToByte(heaterStatusCheckBox.Checked);
            }
            if (setPumpStateCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.PUMP;
                message[i++] = Convert.ToByte(pumpStatusCheckBox.Checked);
            }
            if (setAutoSwitchingEnableCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.AUTOSW;
                message[i++] = Convert.ToByte(autoSwitchingEnableCheckBox.Checked);
            }
            if (setDayStartCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.DAY_START_TIME;
                message[i++] = Convert.ToByte(dayStart.Value);
            }
            if (setDayEndCheckBox.Checked)
            {
                message[i++] = (byte)SCIRegAddress.DAY_END_TIME;
                message[i++] = Convert.ToByte(dayEnd.Value);
            }
            if (i > 0)
            {
                serialComm.SerSet((byte)i, message);
            }

        }

        private void logBtn_Click(object sender, EventArgs e)
        {
            logData();
        }

        public void logData()
        {
            using (StreamWriter w = File.AppendText(Properties.Settings.Default.logPath))
            {
                string data;
                data = "LM75_1: " + LM75_1TextBox.Text + "; LM75_2: " + LM75_2TextBox.Text + "; MCP9808_1: " + MCP9808_1TextBox.Text +
                    "; MCP9808_2: " + MCP9808_2TextBox.Text + "; MCP9808_3: " + MCP9808_3TextBox.Text + "; HTU21D_TEMP: " + HTU21D_TEMPTextBox.Text +
                    "; HTU21D_HUM: " + HTU21D_HUMTextBox.Text + "; RoomTemp: " + roomTempTextBox.Text + "; WaterOutTemp: " + waterOutTempTextBox.Text +
                    "; WaterReturnTemp: " + waterReturnTempTextBox.Text + "; Heater: " + Convert.ToString(heaterStatusCheckBox.Checked) + "; Pump: " + Convert.ToString(pumpStatusCheckBox.Checked);
                Log(data, w, LogType.Data);
            }
        }

        private void setRegRoomDayTempCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            regRoomDayTemp.Enabled = setRegRoomDayTempCheckBox.Checked;
        }

        private void setRegRoomNightTempCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            regRoomNightTemp.Enabled = setRegRoomNightTempCheckBox.Checked;
        }

        private void setRegRoomTempHystCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            regRoomTempHyst.Enabled = setRegRoomTempHystCheckBox.Checked;
        }

        private void setWaterMaxTempCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            waterMaxTemp.Enabled = setWaterMaxTempCheckBox.Checked;
        }

        private void setSystTypeCheckBox_CheckedChanged(object sender, EventArgs e)
        {
           gasSystTypeRadioButton.Enabled = setSystTypeCheckBox.Checked;
           woodSystTypeRadioButton.Enabled = setSystTypeCheckBox.Checked;
        }

        private void setDayEndCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            dayEnd.Enabled = setDayEndCheckBox.Checked;
        }

        private void setDayStartCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            dayStart.Enabled = setDayStartCheckBox.Checked;
        }

        private void setAutoSwitchingEnableCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            autoSwitchingEnableCheckBox.Enabled = setAutoSwitchingEnableCheckBox.Checked;
        }

        private void setWaterDiffCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            waterDiff.Enabled = setWaterDiffCheckBox.Checked;
        }

        private void setAutoSwOnTempCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            autoSwOnTemp.Enabled = setAutoSwOnTempCheckBox.Checked;
        }

        private void setAutoSwOffTempCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            autoSwOffTemp.Enabled = setAutoSwOffTempCheckBox.Checked;
        }

        private void setAvgTempCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            avgTempTextBox.Enabled = setAvgTempCheckBox.Checked;
        }

        private void setOutTempCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            outTempTextBox.Enabled = setOutTempCheckBox.Checked;
        }

        private void setOutHumCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            outHumTextBox.Enabled = setOutHumCheckBox.Checked;
        }

        private void setPumpDelayTimeCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            pumpDelayTime.Enabled = setPumpDelayTimeCheckBox.Checked;
        }











    }
}
