using System;
using System.Net;
using System.Windows.Forms;


namespace FeanorConfig
{   
    public partial class RS485_Comm : Form
    {    
        public RS485_Comm()
        {
            InitializeComponent();
        }

        private void RS485_Comm_Load(object sender, EventArgs e)
        {

        }

        private void SendButton_Click(object sender, EventArgs e)
        {
            RS485_Sender(@RSurl.Text, commandTxt.Text); // send command to chamber, receive response from chamber
        }

        private void RSurl_TextChanged(object sender, EventArgs e)
        {

        }

       
        private void ConditionsButton_Click(object sender, EventArgs e)
        {
            string url = RS485_Sender(@RSurl.Text, "MON?");         // send command to chamber, receive response from chamber
            
            string[] split_url = url.Split(',');                    // split response from chamber

            RStemp.Text = split_url[0].ToString();                  // temp
            RShumi.Text = split_url[1].ToString();                  // humidity
            RSmode.Text = split_url[2].ToString();                  // mode
            RSalarm.Text = split_url[3].ToString();                 // number of alarms occured            
        }

        public void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {            
            //Console.WriteLine(numAddress.Value);
                       
            if (numAddress.Value < 10)                          // add 0 before the address (example 02)
            {
                Globals.RSaddress = "0" + numAddress.Value.ToString();
            }
            else                                                // don't add 0 before address
            {
                Globals.RSaddress = numAddress.Value.ToString();
            }
            //Console.WriteLine(Globals.RSaddress);
        }

        private void label8_Click(object sender, EventArgs e)
        {

        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnSetParameters_Click(object sender, EventArgs e)
        { // Set chamber parameters for constant mode
           
            // Temperature parameters
            double Temptarget = Double.Parse(TempTarget.Text);
            string TemptargetString = String.Format("{0:0.0}", Temptarget);     // convert to one decimal 
            double Temphigh = Double.Parse(TempHigh.Text);
            string TemphighString = String.Format("{0:0.0}", Temphigh);         // convert to one decimal 
            double Templow = Double.Parse(TempLow.Text);
            string TemplowString = String.Format("{0:0.0}", Templow);           // convert to one decimal 

            string tempstring = "TEMP, S";
            tempstring += TemptargetString;
            tempstring += " H";
            tempstring += TemphighString;
            tempstring += " L";
            tempstring += TemplowString;
            //Console.WriteLine(tempstring);
            RS485_Sender(@RSurl.Text, tempstring);

            double Humitarget, Humihigh, Humilow;
            string HumitargetString, HumihighString, HumilowString;                        

            // Humidity parameters
            if (String.IsNullOrEmpty(HumiTarget.Text))                      // If humi textbox is not filled
            {
                RS485_Sender(@RSurl.Text, "HUMI,SOFF");
            }
            else
            {                                                                // if humi textbox is filled
                Humitarget = Double.Parse(HumiTarget.Text);
                HumitargetString = String.Format("{0:0.0}", Humitarget);     // convert to one decimal 

                Humihigh = Double.Parse(HumiHigh.Text);
                HumihighString = String.Format("{0:0.0}", Humihigh);         // convert to one decimal 

                Humilow = Double.Parse(HumiLow.Text);
                HumilowString = String.Format("{0:0.0}", Humilow);           // convert to one decimal 

                string humistring = "HUMI,S";
                humistring += HumitargetString;
                humistring += " H";
                humistring += HumihighString;
                humistring += " L";
                humistring += HumilowString;
                //Console.WriteLine(humistring);
                RS485_Sender(@RSurl.Text, humistring);
            }
        }

        private void RS485_ErrorCheck(string RS_String)
        {
            try
            {
                if (RS_String == "NA:CMD_ERR")
                {
                    MessageBox.Show("Chamber could not recognize the command data");
                }
                if (RS_String == "NA:ADDR_ERR")
                {
                    MessageBox.Show("Invalid address expression");
                }
            }
            catch
            {

            }            
        }


        private string RS485_Sender(string URL, string command)
        {
            RSinput.Text = ""; // clear textbox
            Console.WriteLine(Globals.RSaddress);
            // HTTP string format: <RS485>,Chamber address [01..16],Command,\r\n</RS485>
            // Construct command for chamber:
            string http = "<RS485>,";
            http += Globals.RSaddress;
            http += ",";
            http += command; 
            http += "\r\n";
            http += "</RS485>";

            try
            {
                using (WebClient client = new WebClient())
                {
                    Console.WriteLine(http);
                    string url = client.UploadString(URL, http);
                    Console.WriteLine(url);
                    RSinput.Text = url;
                    RS485_ErrorCheck(url);                   
                    return url;
                }
            }
            catch
            {
                // Continue with next object, ignoring exception
                RSinput.Text = null;  // if no response --> empty text field
                return null;
            }
        }

        private void btnRunConstant_Click(object sender, EventArgs e)
        { // Set operating mode constant
            RS485_Sender(@RSurl.Text, "MODE,CONSTANT"); // send command to chamber, receive response from chamber
        }

        private void btnStandby_Click(object sender, EventArgs e)
        { // Set operating mode standby
            RS485_Sender(@RSurl.Text, "MODE,STANDBY"); // send command to chamber, receive response from chamber
        }

        private void btnOff_Click(object sender, EventArgs e)
        {
            RS485_Sender(@RSurl.Text, "MODE,OFF"); // send command to chamber, receive response from chamber
        }

        private void btnRunProgram_Click(object sender, EventArgs e)
        {
            Console.WriteLine(numProgramNumber.Value);
            string runProgram = "PRGM, RUN, RAM :";
            runProgram += numProgramNumber.Value;
            runProgram += ", STEP1";
            RS485_Sender(@RSurl.Text, runProgram); // send command to chamber, receive response from chamber
        }

        private void btnPauseProgram_Click(object sender, EventArgs e)
        {                   
            RS485_Sender(@RSurl.Text, "PRGM,PAUSE"); // send command to chamber, receive response from chamber
        }

        private void btnContinueProgram_Click(object sender, EventArgs e)
        {
            RS485_Sender(@RSurl.Text, "PRGM,CONTINUE"); // send command to chamber, receive response from chamber
        }

        private void btnEndProgram_Click(object sender, EventArgs e)
        {
            RS485_Sender(@RSurl.Text, "PRGM,END, STANDBY"); // send command to chamber, receive response from chamber
        }
    }

    public static class Globals
    {
        public static string RSaddress = "01";      // RS485 chamber address (01...16)  
    }

}


