/// <summary>
        /// Fetches all the motes in the databases
        /// Has NO offline detection mechanism
        /// </summary>
        private void GetSensors()
        {
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>getAllTelosb</RequestName></Request></Requests>";
            try
            {
                SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                // Receiving data
                string xml_receive = socket_client.Connect(xml_send, true);

                XmlDocument tempdoc = new XmlDocument();
                tempdoc.LoadXml(xml_receive);

                XmlNodeList bookList = tempdoc.GetElementsByTagName("Sensor");
                foreach (XmlNode node in bookList)
                {
                    XmlElement ID = (XmlElement)(node);
                    try
                    {
                        string sensor = ID.GetElementsByTagName("sensor")[0].InnerText;
                        string idnode = ID.GetElementsByTagName("idnode")[0].InnerText;
                        Sensorlijst.Add(new SensorNames(sensor, idnode));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(ex.TargetSite);
                    }
                }

                Sensorlijst.ForEach(delegate(SensorNames SN)
                {
                    comboBox2.Items.Add(SN.Sensorname);
                    listBoxLoc.Items.Add(SN.Sensorname);
                    listBoxControl.Items.Add(SN.Sensorname);
                });
            }
            catch (ArgumentNullException nullex)
            {
                Console.WriteLine(nullex.Message);
                Console.WriteLine(nullex.TargetSite);
                SocketClient sc = new SocketClient(Port, controllerIP.Text);
                if (!sc.TryConnection())
                    buttonDisconnect_Click(this, EventArgs.Empty);
                MessageBox.Show("Lost connection to the controller");
            }
            catch { }
        }
        private void Discovery()
        {
            //we send the WSNactionRequest here
            //first
            //static part of the message
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><WSNReq xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><WSNReq><RequestAction><Discovery>1</Discovery>";

            SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
            // Receiving data
            string xml_receive = socket_client.Connect(xml_send, true);

            XmlDocument tempdoc = new XmlDocument();
            tempdoc.LoadXml(xml_receive);

            XmlNodeList bookList = tempdoc.GetElementsByTagName("Sensor");
            foreach (XmlNode node in bookList)
            {
                XmlElement ID = (XmlElement)(node);
                try
                {
                    string sensor = ID.GetElementsByTagName("sensor")[0].InnerText;
                    string idnode = ID.GetElementsByTagName("idnode")[0].InnerText;
                    Sensorlijst.Add(new SensorNames(sensor, idnode));
                }
                catch
                {
                    Console.WriteLine("Could not contact the WSN!");
                }
            }

            Sensorlijst.ForEach(delegate(SensorNames SN)
            {
                comboBox2.Items.Add(SN.Sensorname);
                listBoxLoc.Items.Add(SN.Sensorname);
                listBoxLoc.Items.Add(SN.Sensorname);
                listBoxControl.Items.Add(SN.Sensorname);
            });
        }
        /// <summary>
        /// Sub-function that is called when we detect an incoming message that ask for an action from a WSN (e.g. get LEDs to light up,...)
        /// </summary>
        /// <param name="WSNActionSet">The XML-message in a dataset</param>
        /// <returns>A reply of either 0 (failed) or 1 (succeeded) in xml (in the dataset)</returns>
        private DataSet WSNActionReqProcess(DataSet WSNActionSet)
        {
            //DataSet to store the result of the query (temporarily) and the final reply to the GUI
            DataSet WSNActionWSNSet = new DataSet();
            string cmd = "call getWSNid('" + WSNActionSet.Tables["RequestAction"].Rows[0]["NodeID"] + "');";
            SocketClient SendActionReq;
            int temp;

            try
            {
                if(UseMySQLForInfo)
                    WSNActionWSNSet = MySQLConn.Query(cmd);
                else
                    WSNActionWSNSet = DB2Conn.Query(cmd);

                WSNActionSet.Tables["RequestAction"].Rows[0]["NodeID"] = WSNActionWSNSet.Tables[0].Rows[0][0];


                /************************************************************************
                 *                                                                      *
                 *          HERE IS THE LOGIC TO DECIDE TO WHICH WSN                    *
                 *          WE HAVE TO SEND THE INCOMING ACTIONREQUEST                  *
                 *                                                                      *
                 *          In case that there are more then 2 wsn's,                   *
                 *          (1 telosb and 1 sunspot, routing might fail                 *
                 *                                                                      *
                 *                                                                      *
                 ***********************************************************************/
                if ((int.TryParse(WSNActionSet.Tables["RequestAction"].Rows[0]["NodeID"].ToString(), out temp))&&(WSNActionSet.Tables["RequestAction"].Rows[0]["NodeID"].ToString().Length < 10))
                {   //Parsing the NodeID to an int works (and the value in string-format is smaller than 10 characters); so we have a TelosB
                    SendActionReq = new SocketClient(
                        int.Parse(Options.Tables["SocketClient"].Select("Use = 'TelosB'")[0]["Port"].ToString()),
                        Options.Tables["SocketClient"].Select("Use = 'TelosB'")[0]["HostName"].ToString());

                    //Because TelosB expects a simple 1 or 0, but GUI might send a hexadecimal string
                    //Led on = 0 = white light = FFFFFF
                    foreach (DataColumn col in WSNActionSet.Tables[0].Columns)
                    {
                        if (col.ColumnName.IndexOf("LED", StringComparison.CurrentCultureIgnoreCase) != -1)
                        {
                            try
                            {
                                if (WSNActionSet.Tables[0].Rows[0][col].ToString().Length >= 2)
                                {
                                    int tempint;
                                    if (int.TryParse(WSNActionSet.Tables[0].Rows[0][col].ToString(), out tempint))
                                    {
                                        if (tempint == 0)
                                            WSNActionSet.Tables[0].Rows[0][col] = 0;
                                        else
                                            WSNActionSet.Tables[0].Rows[0][col] = 1;
                                    }
                                    else
                                        WSNActionSet.Tables[0].Rows[0][col] = 1;
                                }
                            }
                            catch (Exception)
                            { }
                        }
                    }
                }

                #region Sun SPOT!
                else
                {   //Parsing the NodeID to an int didn't work (or the value in string-format is longer than 10 characters); we have a SunSpot
                    SendActionReq = new SocketClient(
                        int.Parse(Options.Tables["SocketClient"].Select("Use = 'SunSpot'")[0]["Port"].ToString()),
                        Options.Tables["SocketClient"].Select("Use = 'SunSpot'")[0]["HostName"].ToString());

                    //Because SunSpot expects a hexadecimal 6-character string, but the GUI sends '1', we have to change this.
                    //Led on = white light = FFFFFF
                    foreach (DataColumn col in WSNActionSet.Tables[0].Columns)
                    {
                        if (col.ColumnName.IndexOf("LED", StringComparison.CurrentCultureIgnoreCase) != -1)
                        {
                            try
                            {
                                if (WSNActionSet.Tables[0].Rows[0][col].ToString().Length == 1)
                                {
                                    if (int.Parse(WSNActionSet.Tables[0].Rows[0][col].ToString()) == 1)
                                        WSNActionSet.Tables[0].Rows[0][col] = "FFFFFF";
                                    else if (int.Parse(WSNActionSet.Tables[0].Rows[0][col].ToString()) == 0)
                                        WSNActionSet.Tables[0].Rows[0][col] = "000000";
                                }
                            }
                            catch (Exception)
                            { }
                        }
                    }
                }
                #endregion
                /************************************************************************
                 *                                                                      *
                 *          HERE ENDS THE LOGIC TO DECIDE TO WHICH WSN                  *
                 *          WE HAVE TO SEND THE INCOMING ACTIONREQUEST                  *
                 *                                                                      *
                 *          In case that there are more then 2 wsn's,                   *
                 *          1 telosb and 1 sunspot, routing might fail                  *
                 *                                                                      *
                 *                                                                      *
                 ***********************************************************************/

                MemoryStream OutMemStream = new MemoryStream();
                WSNActionSet.WriteXml(OutMemStream);
                OutMemStream.Position = 0;
                StreamReader OutMemStreamReader = new StreamReader(OutMemStream);

                string replyWSN = SendActionReq.Connect(OutMemStreamReader.ReadToEnd().Replace("\r\n", ""), true);

                MemoryStream ReplyStream = new MemoryStream();
                StreamWriter ReplyWriter = new StreamWriter(ReplyStream);
                ReplyWriter.Write(replyWSN);
                ReplyWriter.Flush();
                ReplyStream.Position = 0;

                WSNActionWSNSet = new DataSet();
                WSNActionWSNSet.ReadXml(ReplyStream);

            }
            catch (Exception ex)
            {
                SocketServer.LogError(ex, "LogServer.txt");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.TargetSite);

                //Create an error-xml-msg
                WSNActionWSNSet = CreateReplyInt(0);
            }

            return WSNActionWSNSet;
        }
        /// <summary>
        /// Sub-function that is called when we detect an incoming message that ask for an action from a WSN (e.g. get LEDs to light up,...)
        /// </summary>
        /// <param name="WSNActionSet">The XML-message in a dataset</param>
        /// <returns>A reply of either 0 (failed) or 1 (succeeded) in xml (in the dataset)</returns>
        private DataSet WSNActionReqProcess(DataSet WSNActionSet)
        {
            //DataSet to store the result of the query (temporarily) and the final reply to the GUI
            DataSet WSNActionWSNSet = new DataSet();
            string cmd = "call getWSNid('" + WSNActionSet.Tables["RequestAction"].Rows[0]["NodeID"] + "');";
            SocketClient SendActionReq;
            int temp;

            try
            {
                if (MySQLAllowedConn)
                    WSNActionWSNSet = MySQLConn.Query(cmd);

                WSNActionSet.Tables["RequestAction"].Rows[0]["NodeID"] = WSNActionWSNSet.Tables[0].Rows[0][0];

                //check if telosb
                if ((int.TryParse(WSNActionSet.Tables["RequestAction"].Rows[0]["NodeID"].ToString(), out temp)) && (WSNActionSet.Tables["RequestAction"].Rows[0]["NodeID"].ToString().Length < 10))
                {   //Parsing the NodeID to an int works (and the value in string-format is smaller than 10 characters); so we have a TelosB

                    //fetch these from the config
                    SendActionReq = new SocketClient(
                        int.Parse(Options.Tables["SocketClient"].Select("Use = 'TelosB'")[0]["Port"].ToString()),
                        Options.Tables["SocketClient"].Select("Use = 'TelosB'")[0]["HostName"].ToString());

                    //Because TelosB expects a simple 1 or 0, but GUI might send a hexadecimal string
                    //Led on = 0 = white light = FFFFFF
                    foreach (DataColumn col in WSNActionSet.Tables[0].Columns)
                    {
                        if (col.ColumnName.IndexOf("LED", StringComparison.CurrentCultureIgnoreCase) != -1)
                        {
                            try
                            {
                                if (WSNActionSet.Tables[0].Rows[0][col].ToString().Length >= 2)
                                {
                                    int tempint;
                                    if (int.TryParse(WSNActionSet.Tables[0].Rows[0][col].ToString(), out tempint))
                                    {
                                        if (tempint == 0)
                                            WSNActionSet.Tables[0].Rows[0][col] = 0;
                                        else
                                            WSNActionSet.Tables[0].Rows[0][col] = 1;
                                    }
                                    else
                                        WSNActionSet.Tables[0].Rows[0][col] = 1;
                                }
                            }
                            catch (Exception)
                            { }
                        }
                    }
                }

                #region Sun SPOT!
                else
                {   //Parsing the NodeID to an int didn't work (or the value in string-format is longer than 10 characters); we have a SunSpot
                    SendActionReq = new SocketClient(
                        int.Parse(Options.Tables["SocketClient"].Select("Use = 'SunSpot'")[0]["Port"].ToString()),
                        Options.Tables["SocketClient"].Select("Use = 'SunSpot'")[0]["HostName"].ToString());

                    //Because SunSpot expects a hexadecimal 6-character string, but the GUI sends '1', we have to change this.
                    //Led on = white light = FFFFFF
                    foreach (DataColumn col in WSNActionSet.Tables[0].Columns)
                    {
                        if (col.ColumnName.IndexOf("LED", StringComparison.CurrentCultureIgnoreCase) != -1)
                        {
                            try
                            {
                                if (WSNActionSet.Tables[0].Rows[0][col].ToString().Length == 1)
                                {
                                    if (int.Parse(WSNActionSet.Tables[0].Rows[0][col].ToString()) == 1)
                                        WSNActionSet.Tables[0].Rows[0][col] = "FFFFFF";
                                    else if (int.Parse(WSNActionSet.Tables[0].Rows[0][col].ToString()) == 0)
                                        WSNActionSet.Tables[0].Rows[0][col] = "000000";
                                }
                            }
                            catch (Exception)
                            { }
                        }
                    }
                }
                #endregion

                MemoryStream OutMemStream = new MemoryStream();
                WSNActionSet.WriteXml(OutMemStream);
                OutMemStream.Position = 0;
                StreamReader OutMemStreamReader = new StreamReader(OutMemStream);

                string replyWSN = SendActionReq.Connect(OutMemStreamReader.ReadToEnd().Replace("\r\n", ""), true);

                MemoryStream ReplyStream = new MemoryStream();
                StreamWriter ReplyWriter = new StreamWriter(ReplyStream);
                ReplyWriter.Write(replyWSN);
                ReplyWriter.Flush();
                ReplyStream.Position = 0;

                WSNActionWSNSet = new DataSet();
                WSNActionWSNSet.ReadXml(ReplyStream);

            }
            catch (ArgumentNullException nullex)
            {
                Console.WriteLine(nullex.Message);
                Console.WriteLine(nullex.TargetSite);
                MessageBox.Show("WSN return an empty message");
            }
            catch (XmlException xmlex)
            {
                Console.Write(xmlex.Message);
                Console.WriteLine(xmlex.StackTrace);
                Console.WriteLine("The XML of the WSN reply was incorrect\n\n\n");
            }
            catch (SocketException sockex)
            {
                Console.WriteLine(sockex.Message);
                Console.WriteLine(sockex.TargetSite);
                MessageBox.Show("The WSN took to long to respond");
            }
            catch (Exception ex)
            {
                SocketServer.LogError(ex, "LogServer.txt");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.TargetSite);

                //Create an error-xml-msg
                WSNActionWSNSet = CreateReplyInt(0);
            }

            return WSNActionWSNSet;
        }
        ///<summary>
        ///Helper method for retreiving the nodeid of the framework
        /// </summary>
        /// <param name="selected">
        /// The MAC or TOSid of the mote
        /// </param>
        /// <returns>
        /// node id, unique identifier within Senseless
        /// </returns>
        private string getNodeID(string selected)
        {
            //first search local for the nodeid
            string nodeid;
            foreach (SensorNames telosb in Sensorlijst)
            {
                if (telosb.Sensorname == selected)
                {
                    nodeid = telosb.id;
                    return nodeid;
                }
            }
            try
            {
                //generate string
                string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>getNodeid</RequestName><arg>" + selected + "</arg></Request></Requests>";

                SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                // Receiving data
                string xml_receive = socket_client.Connect(xml_send, true);

                //process reply
                XmlDocument tempdoc = new XmlDocument();
                tempdoc.LoadXml(xml_receive);

                XmlNodeList bookList = tempdoc.GetElementsByTagName("NodeIDs");
                foreach (XmlNode node in bookList)
                {
                    XmlElement ID = (XmlElement)(node);
                    try
                    {
                        string idnode = ID.GetElementsByTagName("idnode")[0].InnerText;
                        Sensorlijst.Add(new SensorNames(selected, idnode));
                        return idnode;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.WriteLine("Node id not found in DB");
                    }
                }
            }
            catch (ArgumentNullException nullex)
            {
                Console.WriteLine(nullex.Message);
                Console.WriteLine(nullex.TargetSite);
                SocketClient sc = new SocketClient(Port, controllerIP.Text);
                if (!sc.TryConnection())
                    buttonDisconnect_Click(this, EventArgs.Empty);
                MessageBox.Show("Lost connection to the controller");
            }
            catch { }
            return "N/A";
        }
        //-----------------------------------------------------------------
        //
        //Options tab
        //
        //connect button
        //corrently the connection data is not checked, if it is incorrect the application will fail
        private void buttonConnect_Click(object sender, EventArgs e)
        {
            Port = Convert.ToInt32(controllerPort.Text);
            SocketClient sc = new SocketClient(Port, controllerIP.Text);

            if (sc.TryConnection())
            {
                timer1.Enabled = true;
                timerLoc.Enabled = true;
                //timerDiscovery.Enabled = true;

                //GUI tasks
                buttonConnect.Enabled = false;
                buttonDisconnect.Enabled = true;

                controllerIP.Enabled = false;
                controllerPort.Enabled = false;

                toolStripStatusLabel.Text = "Connected to controller at IP " + controllerIP.Text + ", port " + controllerPort.Text;

                //discovery
                GetSensors();
            }
            else
            {
                Console.WriteLine("Incorrect connection parameters");
                MessageBox.Show("Could not reach the controller!");
            }
        }
        /// <summary>
        /// Sends any changes to the control tab to the controller.
        /// Fields are accessible according to business rules
        /// An acknowledgment is sent back, this is compared with the current values in the control tab 
        /// to determine if the changes were applied succesfully
        /// </summary>
        private void AcceptChanges()
        {
            DialogResult result = DialogResult.OK;

            //disable status timer to prevent race conditions
            timerStatus.Enabled = false;

            //TODO: needs validation;
            buttonWSNControl.Enabled = false;

            if (
                oldChanges.Active != ActiveProperty || oldChanges.AN != AnchorProperty || oldChanges.X != textBoxControlX.Text ||
                oldChanges.Y != textBoxControlY.Text || oldChanges.locrate != textBoxLocRate.Text || oldChanges.samplerate != textBoxSampleRate.Text ||
                oldChanges.leds != LedsProperty || oldChanges.power != PowerProperty || oldChanges.frequency != FrequencyProperty)
            {
                //we send the WSNactionRequest here
                //static part of the message
                string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><WSNReq xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><WSNReq><RequestAction>";

                //return the nodeid with sensor as input
                try
                {
                    string selected = listBoxControl.SelectedItem.ToString();
                    string nodeid;
                    nodeid = getNodeID(selected);
                    xml_send += "<NodeID>" + nodeid + "</NodeID>";

                    //secondly we must check which fields have changed
                    //we can then add them ass nodes in the XML

                    //specific to our localization scheme
                    if (oldChanges.Active != ActiveProperty)
                        xml_send += "<active>" + ActiveProperty + "</active>";
                    //only process these parameters if the node is active in the localization algorithm
                    if (ActiveProperty == "1")
                    {
                        //if the AN status has changed send it
                        if (oldChanges.AN != AnchorProperty)
                            xml_send += "<AN>" + AnchorProperty + "</AN>";
                        //if the AN status has just changed to AN send all the parameters
                        if (AnchorProperty == "1" && oldChanges.AN != AnchorProperty)
                        {
                            xml_send += "<X>" + textBoxControlX.Text + "</X>";
                            xml_send += "<Y>" + textBoxControlY.Text + "</Y>";
                            xml_send += "<LocRate>" + textBoxLocRate.Text + "</LocRate>";

                            result = MessageBox.Show("Make this node an Anchor Node with these parameters?","Check parameters",MessageBoxButtons.OKCancel);
                        }
                        // if the node was an AN already we should still check if any of the parameters has changed
                        else if (AnchorProperty == "1")
                        {
                            if (oldChanges.X != textBoxControlX.Text)
                                xml_send += "<X>" + textBoxControlX.Text + "</X>";
                            if (oldChanges.Y != textBoxControlY.Text)
                                xml_send += "<Y>" + textBoxControlY.Text + "</Y>";
                            if (oldChanges.locrate != textBoxLocRate.Text)
                                xml_send += "<LocRate>" + textBoxLocRate.Text + "</LocRate>";
                        }
                    }

                    //these field are not unique to the localization algorithm and are thus independent
                    //sensor parameters
                    if (oldChanges.samplerate != textBoxSampleRate.Text)
                        xml_send += "<Samplerate>" + textBoxSampleRate.Text + "</Samplerate>";
                    //leds
                    if (oldChanges.leds != LedsProperty)
                        xml_send += "<Leds>" + LedsProperty + "</Leds>";
                    //radio parameters
                    if (oldChanges.power != PowerProperty)
                        xml_send += "<Power>" + PowerProperty + "</Power>";
                    if (oldChanges.frequency != FrequencyProperty)
                        xml_send += "<Frequency>" + FrequencyProperty + "</Frequency>";

                    xml_send += "</RequestAction></WSNReq></WSNReq>";

                    if (result == DialogResult.OK)
                    {
                    //we can now send the request, we will receive a status message as a response
                    SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                    // Sends: ActionRequest
                    // Receives: Status
                    string xml_receive = socket_client.Connect(xml_send, true);

                    XmlDocument tempdoc = new XmlDocument();
                    tempdoc.LoadXml(xml_receive);

                    if (tempdoc.DocumentElement.Name.ToString() == "Replies") 
                    {
                        DiscardChanges();
                        MessageBox.Show("The WSN did not reply in time");
                        buttonWSNControl.Enabled = true;
                        return;
                    }

                    XmlNodeList bookList = tempdoc.GetElementsByTagName("WSNReply");
                    foreach (XmlNode node in bookList)
                    {
                        XmlElement ID = (XmlElement)(node);
                        try
                        {
                            if (
                            ActiveProperty == ID.GetElementsByTagName("active")[0].InnerText &&
                            AnchorProperty == ID.GetElementsByTagName("AN")[0].InnerText &&
                            textBoxControlX.Text == ID.GetElementsByTagName("X")[0].InnerText &&
                            textBoxControlY.Text == ID.GetElementsByTagName("Y")[0].InnerText &&
                            textBoxSampleRate.Text == ID.GetElementsByTagName("Samplerate")[0].InnerText &&
                            textBoxLocRate.Text == ID.GetElementsByTagName("LocRate")[0].InnerText &&
                            LedsProperty == ID.GetElementsByTagName("Leds")[0].InnerText &&
                            PowerProperty == ID.GetElementsByTagName("Power")[0].InnerText &&
                            FrequencyProperty == ID.GetElementsByTagName("Frequency")[0].InnerText)
                            {
                                //WSN Succesfully replied to our request
                                //changes struct
                                oldChanges.Active = ActiveProperty;
                                oldChanges.AN = AnchorProperty;
                                oldChanges.X = textBoxControlX.Text;
                                oldChanges.Y = textBoxControlY.Text;
                                oldChanges.samplerate = textBoxSampleRate.Text;
                                oldChanges.locrate = textBoxLocRate.Text;
                                oldChanges.power = PowerProperty;
                                oldChanges.frequency = FrequencyProperty;
                                oldChanges.conn = textBoxConn.Text;
                                oldChanges.leds = LedsProperty;

                                Console.WriteLine("WSN succesfully replied");
                                MessageBox.Show("WSN succesfully replied");
                            }
                            else
                            {
                                //WSN did NOT! Succesfully replied to our request
                                //roll back to previous state;
                                DiscardChanges();

                                Console.WriteLine("WSN did not succesfully reply");
                                MessageBox.Show("WSN did not succesfully reply");
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Some field is not available");
                        }
                    }
                }
                }
                //good ol' catches
                catch (ArgumentNullException nullex)
                {
                    Console.WriteLine(nullex.Message);
                    Console.WriteLine(nullex.TargetSite);
                    SocketClient sc = new SocketClient(Port, controllerIP.Text);
                    if (!sc.TryConnection())
                        buttonDisconnect_Click(this, EventArgs.Empty);
                    MessageBox.Show("Lost connection to the controller");
                }
                catch (SocketException sockex)
                {
                    Console.WriteLine(sockex.Message);
                    Console.WriteLine(sockex.TargetSite);
                    SocketClient sc = new SocketClient(Port, controllerIP.Text);
                    if (!sc.TryConnection())
                        Disconnect();
                    MessageBox.Show("Lost connection to the controller");
                }
            }


            timerStatus.Enabled = true;
            buttonWSNControl.Enabled = true;
        }
        /// <summary>
        /// Retreives the sensordata from the controller
        /// </summary>
        public void GetSensorData()
        {
            //static part of the message
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>getnodeInfo</RequestName>";

            //return the nodeid with sensor as input
            try
            {
                if (listBoxLoc.SelectedItem != null)
                {
                    string nodeid = getNodeID(listBoxLoc.SelectedItem.ToString());

                    xml_send += "<arg>" + nodeid + "</arg></Request></Requests>";

                    SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                    // Receiving data
                    string xml_receive = socket_client.Connect(xml_send, true);


                    XmlDocument tempdoc = new XmlDocument();
                    tempdoc.LoadXml(xml_receive);

                    XmlNodeList bookList = tempdoc.GetElementsByTagName("SensorMeasurements");
                    foreach (XmlNode node in bookList)
                    {
                        XmlElement ID = (XmlElement)(node);
                        try
                        {
                            textBox1.Text = ID.GetElementsByTagName("Node")[0].InnerText;
                            textBox2.Text = ID.GetElementsByTagName("Sensortype")[0].InnerText;
                            textBox3.Text = ID.GetElementsByTagName("Temperature")[0].InnerText;
                            textBox4.Text = ID.GetElementsByTagName("Light")[0].InnerText;
                            textBox5.Text = ID.GetElementsByTagName("Humidity")[0].InnerText;
                            if (ID.GetElementsByTagName("Sensortype")[0].InnerText == "2")
                            {
                                textBox6.Text = ID.GetElementsByTagName("Power")[0].InnerText;
                            }
                            else
                            {
                                textBox6.Text = "N/A";
                            }
                            int index = ID.GetElementsByTagName("Time")[0].InnerText.IndexOf('T');
                            textBoxSensUpdate.Text = ID.GetElementsByTagName("Time")[0].InnerText.Substring(index);
                        }
                        //unable to parse some field
                        catch (Exception ex)
                        {
                            Console.WriteLine("Some field is not available");
                            Console.WriteLine(ex.Message);
                            Console.WriteLine(ex.TargetSite);
                        }
                    }
                }
                else
                    return;
            }
            catch (ArgumentNullException nullex)
            {
                Console.WriteLine(nullex.Message);
                Console.WriteLine(nullex.TargetSite);
                SocketClient sc = new SocketClient(Port, controllerIP.Text);
                if (!sc.TryConnection())
                    Disconnect();
                MessageBox.Show("Lost connection to the controller");
            }

        }
        /// <summary>
        /// Helper method for retreiving the WSNid of the framework
        /// </summary>
        /// <param name="selected">
        /// node id, unique identifier within Senseless
        /// </param>
        /// <returns>
        /// The MAC or TOSid of the mote
        /// </returns>
        private string getTelosbId(string selected)
        {
            string sensorname;
            foreach (SensorNames telosb in Sensorlijst)
            {
                if (telosb.id == selected)
                {
                    sensorname = telosb.Sensorname;
                    return sensorname;
                }
            }
            try
            {
                string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>getWSNID</RequestName><arg>" + selected + "</arg></Request></Requests>";

                SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                // Receiving data
                string xml_receive = socket_client.Connect(xml_send, true);

                XmlDocument tempdoc = new XmlDocument();
                tempdoc.LoadXml(xml_receive);

                XmlNodeList bookList = tempdoc.GetElementsByTagName("WSNID");
                foreach (XmlNode node in bookList)
                {
                    XmlElement ID = (XmlElement)(node);
                    try
                    {
                        string sensor = ID.GetElementsByTagName("sensor")[0].InnerText;
                        Sensorlijst.Add(new SensorNames(sensor, selected));
                        return sensor;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.WriteLine("Node id not found in DB");
                    }
                }
            }
            catch (ArgumentNullException nullex)
            {
                Console.WriteLine(nullex.Message);
                Console.WriteLine(nullex.TargetSite);
                SocketClient sc = new SocketClient(Port, controllerIP.Text);
                if (!sc.TryConnection())
                    Disconnect();
                MessageBox.Show("Lost connection to the controller");
            }
            catch { }
            return "N/A";
        }
        private void GetGraphData()
        {
            //request
                //static part
                string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>";

                //dynamic part
                if (comboBox1.SelectedItem.ToString() == "RSSI" || comboBox1.SelectedItem.ToString() == "Position")
                    xml_send += "getLocHistoryLast</RequestName>";
                else
                    xml_send += "getHistoryLast</RequestName>";

                //return the nodeid with sensor as input
                try
                {
                    string selectedNode = comboBox2.SelectedItem.ToString();

                    if (selectedNode != null)
                    {
                        string nodeid = getNodeID(selectedNode); ;

                        xml_send += "<arg>" + nodeid + "</arg>";

                        string selectedReading = comboBox1.SelectedItem.ToString();

                        if (selectedReading != null)
                        {
                            xml_send += "<arg>" + selectedReading + "</arg><arg>10</arg></Request></Requests>";
                        }
                        else
                            return;
                    }
                    else
                        return;

                    SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                    string xml_receive = socket_client.Connect(xml_send, true);

                    //proces the reply
                    XmlDocument tempdoc = new XmlDocument();
                    tempdoc.LoadXml(xml_receive);

                    listView2.Items.Clear();
                    XmlNodeList bookList = tempdoc.GetElementsByTagName("MeasurementValue");

                    foreach (XmlNode node in bookList)
                    {
                        string id_Measurement = node.InnerText.ToString();
                        listView2.Items.Add(id_Measurement);
                    }

                    CreateGraph(zg1, xml_receive);
                    SetSize();
                }
                catch  (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.HelpLink);
                }
        }
        /// <summary>
        /// Fetches all the motes in the databases
        /// Has NO offline detection mechanism
        /// </summary>
        private void GetSensors()
        {
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>getAllTelosb</RequestName></Request></Requests>";

            SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
            // Receiving data
            string xml_receive = socket_client.Connect(xml_send, true);

            #region alt. method: dataset
            ////Set up a memory-stream to store the xml
            //MemoryStream MemStream = new MemoryStream();
            ////Write the msg to the memory stream
            //StreamWriter SWriter = new StreamWriter(MemStream);
            //SWriter.WriteLine(xml_receive);
            //SWriter.Flush();
            //MemStream.Position = 0; //Reset the position so we start reading at the start
            ////store the xml data in a dataset
            //tempset.ReadXml(MemStream);

            //List<SensorNames> Sensorlijst = new List<SensorNames>();
            ////process the dataset
            //if (tempset.Tables.Count >= 1)
            //{   //Only send a reply if we actually got a correct Msg to send
            //    //(in other words, when the query actually succeeded)
            //    if ((tempset.Tables[0].Rows.Count <= 0))
            //    {   //We got a result back, but just nothing in it...
            //        //OutMsg = CreateReplyInt(0);
            //        ;
            //    }
            //    else
            //    {
            //        foreach (DataRow row in tempset.Tables[0].Rows) //Run through every sensor in the xml-message
            //        {
            //            Sensorlijst.Add(new SensorNames(row["nodeid"].ToString()));
            //        }
            //    }
            //}
            #endregion

            XmlDocument tempdoc = new XmlDocument();
            tempdoc.LoadXml(xml_receive);

            XmlNodeList bookList = tempdoc.GetElementsByTagName("Sensor");
            foreach (XmlNode node in bookList)
            {
                XmlElement ID = (XmlElement)(node);
                try
                {
                    string sensor = ID.GetElementsByTagName("sensor")[0].InnerText;
                    string idnode = ID.GetElementsByTagName("idnode")[0].InnerText;
                    Sensorlijst.Add(new SensorNames(sensor, idnode));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.TargetSite);
                }
            }

            Sensorlijst.ForEach(delegate(SensorNames SN)
            {
                comboBox2.Items.Add(SN.Sensorname);
                listBoxLoc.Items.Add(SN.Sensorname);
                listBoxControl.Items.Add(SN.Sensorname);
            });
        }
        private void GetStatData()
        {
            //static part of the message
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>getStatus</RequestName>";

            //return the nodeid with sensor as input
            try
            {
                string selected = listBoxControl.SelectedItem.ToString();
                string nodeid = getNodeID(selected);

                xml_send += "<arg>" + nodeid + "</arg></Request></Requests>";

                SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                // Receiving data
                string xml_receive = socket_client.Connect(xml_send, true);

                XmlDocument tempdoc = new XmlDocument();
                tempdoc.LoadXml(xml_receive);

                XmlNodeList bookList = tempdoc.GetElementsByTagName("Status");
                foreach (XmlNode node in bookList)
                {
                    XmlElement ID = (XmlElement)(node);
                    try
                    {
                        //assign the values of the textboxes

                        checkBoxActive.Checked = Convert.ToBoolean(ID.GetElementsByTagName("active")[0].InnerText);
                        textBoxActive.Text = ID.GetElementsByTagName("active")[0].InnerText;
                        textBoxAN.Text = ID.GetElementsByTagName("AN")[0].InnerText;
                        textBoxControlX.Text = ID.GetElementsByTagName("X")[0].InnerText;
                        textBoxControlY.Text = ID.GetElementsByTagName("Y")[0].InnerText;
                        textBoxSampleRate.Text = ID.GetElementsByTagName("Samplerate")[0].InnerText;
                        textBoxLocRate.Text = ID.GetElementsByTagName("LocRate")[0].InnerText;
                        //set the led bitmask
                        setLeds(ID.GetElementsByTagName("Leds")[0].InnerText);

                        //int bitmask = Convert.ToInt16(textBoxLeds.Text);
                        textBoxPower.Text = ID.GetElementsByTagName("Power")[0].InnerText;
                        textBoxFrequency.Text = ID.GetElementsByTagName("Frequency")[0].InnerText;
                        textBoxConn.Text = ID.GetElementsByTagName("Conn")[0].InnerText;

                        //changes struct
                        oldChanges.Active = textBoxActive.Text;
                        oldChanges.AN = textBoxAN.Text;
                        oldChanges.X = textBoxControlX.Text;
                        oldChanges.Y = textBoxControlY.Text;
                        oldChanges.samplerate = textBoxSampleRate.Text;
                        oldChanges.locrate = textBoxLocRate.Text;
                        oldChanges.power = textBoxPower.Text;
                        oldChanges.frequency = textBoxFrequency.Text;
                        oldChanges.conn = textBoxConn.Text;

                        oldChanges.ledRed = checkBoxLedRed.Checked;
                        oldChanges.ledGreen = checkBoxLedGreen.Checked;
                        oldChanges.ledBlue = checkBoxLedBlue.Checked;
                    }
                    catch
                    {
                        Console.WriteLine("Some field is not available");
                    }
                }
            }
            catch
            {
                Console.WriteLine("Error in getStatData");
            }
        }
        public void GetSensorData()
        {
            //static part of the message
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>getnodeInfo</RequestName>";

            //return the nodeid with sensor as input
            try
            {
                string selected = listBoxLoc.SelectedItem.ToString();
                if (selected != null)
                {
                    string nodeid;

                    nodeid = getNodeID(selected);

                    xml_send += "<arg>" + nodeid + "</arg></Request></Requests>";

                    SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                    // Receiving data
                    string xml_receive = socket_client.Connect(xml_send, true);

                    XmlDocument tempdoc = new XmlDocument();
                    tempdoc.LoadXml(xml_receive);

                    XmlNodeList bookList = tempdoc.GetElementsByTagName("SensorMeasurements");
                    foreach (XmlNode node in bookList)
                    {
                        XmlElement ID = (XmlElement)(node);
                        try
                        {
                            textBox1.Text = ID.GetElementsByTagName("Node")[0].InnerText;
                        }
                        catch
                        {
                            Console.WriteLine("No sensors avaible!");
                        }
                        try
                        {
                            textBox2.Text = ID.GetElementsByTagName("Sensortype")[0].InnerText;
                        }
                        catch
                        {
                            Console.WriteLine("No sensortype info avaible!");
                        }
                        try
                        {
                            textBox3.Text = ID.GetElementsByTagName("Temperature")[0].InnerText;
                        }
                        catch
                        {
                            Console.WriteLine("No temperature data avaible!");
                        }
                        try
                        {
                            textBox4.Text = ID.GetElementsByTagName("Light")[0].InnerText;
                        }
                        catch
                        {
                            Console.WriteLine("No light data avaible!");
                        }
                        try
                        {
                            textBox5.Text = ID.GetElementsByTagName("Humidity")[0].InnerText;
                        }
                        catch
                        {
                            Console.WriteLine("No humidity data avaible!");
                        }
                        try
                        {
                            if (ID.GetElementsByTagName("Sensortype")[0].InnerText == "2")
                            {
                                textBox6.Text = ID.GetElementsByTagName("Power")[0].InnerText;
                            }
                            else
                            {
                                textBox6.Text = "N/A";
                            }
                        }
                        catch
                        {
                            Console.WriteLine("No power data avaible!");
                        }
                        try
                        {
                            int index = ID.GetElementsByTagName("Time")[0].InnerText.IndexOf(' ');
                            textBoxSensUpdate.Text = ID.GetElementsByTagName("Time")[0].InnerText.Substring(index);
                        }
                        catch
                        {
                            Console.WriteLine("No time available");
                        }
                    }

                }
            }
            catch
            {
                Console.WriteLine("Exception in GetSensorData");
                return;
            }
            #region readfromdummyfile
            //
            // Get data from Dummy XML file
            //
            //XmlDocument doc3 = new XmlDocument();
            //doc3.Load(new XmlTextReader("C:\\Documents and Settings\\Gerrit\\Bureaublad\\GUI v0.50\\GUI\\GUI\\Schemes\\Antwoord1.xml"));
            //doc3.Load(new XmlTextReader("D:\\School\\4EA\\ICT - databases & WSN\\C#\\GUI v0.50\\GUI\\GUI\\Schemes\\Antwoord1.xml"));
            /*XmlNodeList bookList3 = doc3.GetElementsByTagName("SensorMeasurements");
            foreach (XmlNode node in bookList3)
            {
                XmlElement ID = (XmlElement)(node);
                string id_ID = ID.GetElementsByTagName("ID")[0].InnerText;
                string id_Type = ID.GetElementsByTagName("Type")[0].InnerText;
                string id_Temp = ID.GetElementsByTagName("Temp")[0].InnerText;
                string id_Light = ID.GetElementsByTagName("Light")[0].InnerText;
                string id_Hum = ID.GetElementsByTagName("Humidity")[0].InnerText;
                string id_Power = ID.GetElementsByTagName("Power")[0].InnerText;
                textBox1.Text = (id_ID);
                textBox2.Text = (id_Type);
                textBox3.Text = (id_Temp);
                textBox4.Text = (id_Light);
                textBox5.Text = (id_Hum);
                textBox6.Text = (id_Power);
            }*/
            #endregion
        }
        //apply changes
        private void buttonWSNControl_Click(object sender, EventArgs e)
        {
            //TODO: needs validation;
            panelControl.Enabled = false;
            buttonWSNControl.Enabled = false;

            string ledsmask = getLeds();

            //we send the WSNactionRequest here
            //first
            //static part of the message
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><WSNReq xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><WSNReq><RequestAction>";

            //return the nodeid with sensor as input
            try
            {
                string selected = listBoxControl.SelectedItem.ToString();
                string nodeid;
                nodeid = getNodeID(selected);
                xml_send += "<nodeid>" + nodeid + "</nodeid>";

                //secondly we must check which fields have changed
                //we can then add them ass nodes in the XML

                //specific to our localization scheme
                if (oldChanges.Active != textBoxActive.Text)
                    xml_send += "<active>" + textBoxActive.Text + "</active>";
                //only process these parameters if the node is active in the localization algorithm
                if (textBoxActive.Text == "1")
                {
                    if (oldChanges.AN != textBoxAN.Text)
                        xml_send += "<AN>" + textBoxAN.Text + "</AN>";
                    //only process these parameters if the node is an Anchor Node
                    if (textBoxAN.Text == "0")
                    {
                        if (oldChanges.X != textBoxControlX.Text)
                            xml_send += "<X>" + textBoxControlX.Text + "</X>";
                        if (oldChanges.Y != textBoxControlY.Text)
                            xml_send += "<Y>" + textBoxControlY.Text + "</y>";
                        if (oldChanges.locrate != textBoxLocRate.Text)
                            xml_send += "<locrate>" + textBoxLocRate.Text + "</locrate>";
                    }
                }

                //telosb general parameters
                //all independant
                if (oldChanges.samplerate != textBoxSampleRate.Text)
                    xml_send += "<samplerate>" + textBoxSampleRate.Text + "</samplerate>";
                if (oldChanges.leds != ledsmask)
                    xml_send += "<leds>" + ledsmask + "</leds>";
                if (oldChanges.power != textBoxPower.Text)
                    xml_send += "<power>" + textBoxPower.Text + "</power>";
                if (oldChanges.frequency != textBoxFrequency.Text)
                    xml_send += "<frequency>" + textBoxFrequency.Text + "</frequency>";

                //no use sending this as a request
                //if (oldChanges.conn != textBoxConn.Text)
                //    xml_send += "<conn>" + textBoxConn.Text + "</conn>";

                xml_send += "</RequestAction></WSNReq></WSNReq>";

                //we can now send the request, we will receive a status message as a response
                SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                // Sends: ActionRequest
                // Receives: Status
                string xml_receive = socket_client.Connect(xml_send, true);

                XmlDocument tempdoc = new XmlDocument();
                tempdoc.LoadXml(xml_receive);

                XmlNodeList bookList = tempdoc.GetElementsByTagName("Status");
                foreach (XmlNode node in bookList)
                {
                    XmlElement ID = (XmlElement)(node);
                    try
                    {
                        if (
                        textBoxActive.Text == ID.GetElementsByTagName("active")[0].InnerText &&
                        textBoxAN.Text == ID.GetElementsByTagName("AN")[0].InnerText &&
                        textBoxControlX.Text == ID.GetElementsByTagName("X")[0].InnerText &&
                        textBoxControlY.Text == ID.GetElementsByTagName("Y")[0].InnerText &&
                        textBoxSampleRate.Text == ID.GetElementsByTagName("Samplerate")[0].InnerText &&
                        textBoxLocRate.Text == ID.GetElementsByTagName("LocRate")[0].InnerText &&
                        ledsmask == ID.GetElementsByTagName("Leds")[0].InnerText &&
                        textBoxPower.Text == ID.GetElementsByTagName("Power")[0].InnerText &&
                        textBoxFrequency.Text == ID.GetElementsByTagName("Frequency")[0].InnerText &&
                        textBoxConn.Text == ID.GetElementsByTagName("Conn")[0].InnerText)
                        {
                            //WSN Succesfully replied to our request
                            //changes struct
                            oldChanges.Active = textBoxActive.Text;
                            oldChanges.AN = textBoxAN.Text;
                            oldChanges.X = textBoxControlX.Text;
                            oldChanges.Y = textBoxControlY.Text;
                            oldChanges.samplerate = textBoxSampleRate.Text;
                            oldChanges.locrate = textBoxLocRate.Text;
                            oldChanges.power = textBoxPower.Text;
                            oldChanges.frequency = textBoxFrequency.Text;
                            oldChanges.conn = textBoxConn.Text;
                            oldChanges.leds = ledsmask;

                            Console.WriteLine("WSN succesfully replied");
                            MessageBox.Show("WSN succesfully replied");
                        }
                        else
                        {
                            //WSN did NOT! Succesfully replied to our request
                            //roll back to previous state;
                            textBoxActive.Text = oldChanges.Active;
                            textBoxAN.Text = oldChanges.AN;
                            textBoxControlX.Text = oldChanges.X;
                            textBoxControlY.Text = oldChanges.Y;
                            textBoxSampleRate.Text = oldChanges.samplerate;
                            textBoxLocRate.Text = oldChanges.locrate;
                            textBoxPower.Text = oldChanges.power;
                            textBoxFrequency.Text = oldChanges.frequency;
                            textBoxConn.Text = oldChanges.conn;
                            setLeds(oldChanges.leds);

                            Console.WriteLine("WSN did not succesfully reply");
                            MessageBox.Show("WSN did not succesfully reply");
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Some field is not available");
                    }

                }
            }
            catch { Console.WriteLine("Error in getStatData"); }

            panelControl.Enabled = true;
            buttonWSNControl.Enabled = true;
        }
        private void Connect()
        {
            Port = Convert.ToInt32(controllerPort.Text);
            SocketClient sc = new SocketClient(Port, controllerIP.Text);

            if (sc.TryConnection())
            {
                timerSensor.Enabled = true;
                timerLoc.Enabled = true;

                //GUI tasks
                buttonConnect.Enabled = false;
                buttonDisconnect.Enabled = true;

                //Disable the connection fields
                controllerIP.Enabled = false;
                controllerPort.Enabled = false;

                toolStripStatusLabel.Text = "Connected to controller at IP " + controllerIP.Text + ", port " + controllerPort.Text;

                //Sensorfetch
                if (radioButtonGetSensors.Checked == true)
                    GetSensors();
                else if (radioButtonDiscovery.Checked == true)
                    timerSensorFetch.Enabled = true;
                else
                    SensorsTimeOut();
            }
            else
            {
                Console.WriteLine("Incorrect connection parameters");
                MessageBox.Show("Could not reach the controller!\n Are the connection parameters correct?");
            }
        }
        /// <summary>
        /// Event for the connect button in the options tab
        /// Allows the user to connect & disconnect to the controller and set various parameters
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonConnect_Click(object sender, EventArgs e)
        {
            Port = Convert.ToInt32(controllerPort.Text);
            SocketClient sc = new SocketClient(Port, controllerIP.Text);

            if (sc.TryConnection())
            {
                timer1.Enabled = true;
                timerLoc.Enabled = true;

                //GUI tasks
                buttonConnect.Enabled = false;
                buttonDisconnect.Enabled = true;

                //Disable the connection fields
                controllerIP.Enabled = false;
                controllerPort.Enabled = false;

                toolStripStatusLabel.Text = "Connected to controller at IP " + controllerIP.Text + ", port " + controllerPort.Text;

                //Sensorfetch
                //TODO: give the user the choice
                //discovery
                if (radioButtonGetSensors.Checked == true)
                    GetSensors();
                else if (radioButtonDiscovery.Checked == true)
                    timerDiscovery.Enabled = true;
                else
                    //not implemented yet
                    SensorsTimeOut();
            }
            else
            {
                Console.WriteLine("Incorrect connection parameters");
                MessageBox.Show("Could not reach the controller!\n Are the connection parameters correct?");
            }
        }
        /// <summary>
        /// Active nodes are selected when they have sent a packet within a given time limit
        /// TODO: process empty string
        /// </summary>
        private void SensorsTimeOut()
        {
            //clear the existing sensors
            Sensorlijst.Clear();
            listBoxControl.Items.Clear();
            listBoxLoc.Items.Clear();
            comboBox2.Items.Clear();
            
            //Get the TimeOut timespan and parse it into the correct string format (d hh:mm:ss)
            //TimeSpan TimeOut = new TimeSpan(maskedTextBox1.Text;
            //string TimeOutString = TimeOut.Days.ToString() + " " + TimeOut.Hours.ToString() + ":" + TimeOut.Minutes.ToString() + ":" + TimeOut.Seconds.ToString();
            //string TimeOut = maskedTextBox1.Text;
            //TimeOu
            //TimeSpan TimeOut = new TimeSpan();

            //string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>getTimeOutSensors</RequestName><arg>" + TimeOutString + "</arg></Request></Requests>";
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>getTimeOutSensors</RequestName><arg>" + maskedTextBox1.Text + "</arg></Request></Requests>";
            try
            {
                SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                // Receiving data
                string xml_receive = socket_client.Connect(xml_send, true);

                XmlDocument tempdoc = new XmlDocument();
                tempdoc.LoadXml(xml_receive);

                XmlNodeList bookList = tempdoc.GetElementsByTagName("Sensor");
                foreach (XmlNode node in bookList)
                {
                    XmlElement ID = (XmlElement)(node);
                    try
                    {
                        string sensor = ID.GetElementsByTagName("sensor")[0].InnerText;
                        string idnode = ID.GetElementsByTagName("idnode")[0].InnerText;
                        Sensorlijst.Add(new SensorNames(sensor, idnode));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(ex.TargetSite);
                    }
                }

                Sensorlijst.ForEach(delegate(SensorNames SN)
                {
                    comboBox2.Items.Add(SN.Sensorname);
                    listBoxLoc.Items.Add(SN.Sensorname);
                    listBoxControl.Items.Add(SN.Sensorname);
                });
            }
            catch (ArgumentNullException nullex)
            {
                Console.WriteLine(nullex.Message);
                Console.WriteLine(nullex.TargetSite);
                SocketClient sc = new SocketClient(Port, controllerIP.Text);
                if (!sc.TryConnection())
                    buttonDisconnect_Click(this, EventArgs.Empty);
                MessageBox.Show("Lost connection to the controller");
            }
            catch (Exception ex )
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.TargetSite);
            }
        }
        /// <summary>
        /// Sub-function that is called when we detect an incoming message that ask for an action from a WSN (e.g. get LEDs to light up,...)
        /// </summary>
        /// <param name="WSNActionSet">The XML-message in a dataset</param>
        /// <returns>A reply of either 0 (failed) or 1 (succeeded) in xml (in the dataset)</returns>
        private DataSet WSNActionReqProcess(DataSet WSNActionSet)
        {
            //DataSet to store the result of the query (temporarily) and the final reply to the GUI
            DataSet WSNActionWSNSet = new DataSet();

            SocketClient SendActionReq;
            int temp;

            //fetch these from the config
            SendActionReq = new SocketClient(
                int.Parse(Options.Tables["SocketClient"].Select("Use = 'TelosB'")[0]["Port"].ToString()),
                Options.Tables["SocketClient"].Select("Use = 'TelosB'")[0]["HostName"].ToString());

            //Because TelosB expects a simple 1 or 0, but GUI might send a hexadecimal string
            //Led on = 0 = white light = FFFFFF
            foreach (DataColumn col in WSNActionSet.Tables[0].Columns)
            {
                if (col.ColumnName.IndexOf("LED", StringComparison.CurrentCultureIgnoreCase) != -1)
                {
                    if (WSNActionSet.Tables[0].Rows[0][col].ToString().Length >= 2)
                    {
                        int tempint;
                        if (int.TryParse(WSNActionSet.Tables[0].Rows[0][col].ToString(), out tempint))
                        {
                            if (tempint == 0)
                                WSNActionSet.Tables[0].Rows[0][col] = 0;
                            else
                                WSNActionSet.Tables[0].Rows[0][col] = 1;
                        }
                        else
                            WSNActionSet.Tables[0].Rows[0][col] = 1;
                    }
                }
            }

                MemoryStream OutMemStream = new MemoryStream();
                WSNActionSet.WriteXml(OutMemStream);
                OutMemStream.Position = 0;
                StreamReader OutMemStreamReader = new StreamReader(OutMemStream);

            try
            {
                string replyWSN = SendActionReq.Connect(OutMemStreamReader.ReadToEnd().Replace("\r\n", ""), true, 30000);
                if (replyWSN == null)
                    throw new ArgumentNullException("The WSN did not reply in time");

                MemoryStream ReplyStream = new MemoryStream();
                StreamWriter ReplyWriter = new StreamWriter(ReplyStream);
                ReplyWriter.Write(replyWSN);
                ReplyWriter.Flush();
                ReplyStream.Position = 0;

                WSNActionWSNSet = new DataSet();
                WSNActionWSNSet.ReadXml(ReplyStream);

                foreach (DataRow row in WSNActionWSNSet.Tables[0].Rows)
                {
                    AddPosition(row);
                }
            }
            catch (ArgumentNullException nullex)
            {
                Logger.LogException(nullex);
                WSNActionWSNSet = CreateReplyInt(0);
                return WSNActionWSNSet;
            }
            catch (XmlException xmlex)
            {
                Logger.LogException(xmlex);
            }
            catch (SocketException sockex)
            {
                Logger.LogException(sockex);
            }

            return WSNActionWSNSet;
        }
        /// <summary>
        /// Retreives the graph data from the controller
        /// </summary>
        private void GetGraphData()
        {
                //static part
                string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>";

                //dynamic part
                if (comboBox1.SelectedItem.ToString() == "RSSI" || comboBox1.SelectedItem.ToString() == "Position")
                    xml_send += "getLocHistoryLast</RequestName>";
                else
                    xml_send += "getHistoryLast</RequestName>";

                //return the nodeid with sensor as input
                try
                {
                    if (comboBox2.SelectedItem != null)
                    {
                        string nodeid = getNodeID(comboBox2.SelectedItem.ToString()); ;

                        xml_send += "<arg>" + nodeid + "</arg>";

                        if (comboBox1.SelectedItem != null)
                        {
                            xml_send += "<arg>" + comboBox1.SelectedItem.ToString() + "</arg><arg>" + comboBoxGraphNumMeasurements.Text + "</arg></Request></Requests>";
                        }
                        else
                            return;
                    }
                    else
                        return;

                    //communication: send the command string to the controller and receive a response
                    SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                    string xml_receive = socket_client.Connect(xml_send, true);


                    //process the reply
                    XmlDocument tempdoc = new XmlDocument();
                    tempdoc.LoadXml(xml_receive);

                    //put the received values in the graph list
                    listViewGraphValues.Items.Clear();
                    XmlNodeList bookList = tempdoc.GetElementsByTagName("MeasurementValue");

                    foreach (XmlNode node in bookList)
                    {
                        string id_Measurement = node.InnerText.ToString();
                        listViewGraphValues.Items.Add(id_Measurement);
                    }

                    CreateGraph(zg1, xml_receive, "number of measurements", comboBox1.SelectedItem.ToString());
                    SetSize();
                }
                catch (ArgumentNullException nullex)
                {
                    Console.WriteLine(nullex.Message);
                    Console.WriteLine(nullex.TargetSite);
                    SocketClient sc = new SocketClient(Port, controllerIP.Text);
                    if (!sc.TryConnection())
                        Disconnect();
                    MessageBox.Show("Lost connection to the controller");
                }
        }
        /// <summary>
        /// Gets the statusdata off the selected node from the controller
        /// </summary>
        private void GetStatData()
        {
            //static part of the message
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>getStatus</RequestName>";

            //return the nodeid with sensor as input
            try
            {
                string selected = listBoxControl.SelectedItem.ToString();
                string nodeid = getNodeID(selected);

                xml_send += "<arg>" + nodeid + "</arg></Request></Requests>";

                SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                // Receiving data
                string xml_receive = socket_client.Connect(xml_send, true);

                XmlDocument tempdoc = new XmlDocument();
                tempdoc.LoadXml(xml_receive);

                XmlNodeList bookList = tempdoc.GetElementsByTagName("Status");
                foreach (XmlNode node in bookList)
                {
                    XmlElement ID = (XmlElement)(node);
                    try
                    {
                        //assign the values of the textboxes
                        ActiveProperty = ID.GetElementsByTagName("active")[0].InnerText;
                        AnchorProperty = ID.GetElementsByTagName("AN")[0].InnerText;

                        textBoxControlX.Text = ID.GetElementsByTagName("X")[0].InnerText;
                        textBoxControlY.Text = ID.GetElementsByTagName("Y")[0].InnerText;
                        textBoxSampleRate.Text = ID.GetElementsByTagName("Samplerate")[0].InnerText;
                        textBoxLocRate.Text = ID.GetElementsByTagName("LocRate")[0].InnerText;

                        //set the led bitmask
                        LedsProperty = ID.GetElementsByTagName("Leds")[0].InnerText;

                        PowerProperty = ID.GetElementsByTagName("Power")[0].InnerText;
                        FrequencyProperty = ID.GetElementsByTagName("Frequency")[0].InnerText;

                        textBoxConn.Text = ID.GetElementsByTagName("Conn")[0].InnerText;

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(ex.StackTrace);
                        Console.WriteLine("Some field is not available");
                    }

                    //backup these values in the changes struct
                    oldChanges.Active = ActiveProperty;
                    oldChanges.AN = AnchorProperty;

                    oldChanges.X = textBoxControlX.Text;
                    oldChanges.Y = textBoxControlY.Text;
                    oldChanges.samplerate = textBoxSampleRate.Text;
                    oldChanges.locrate = textBoxLocRate.Text;

                    oldChanges.power = PowerProperty;
                    oldChanges.frequency = FrequencyProperty;
                    oldChanges.conn = textBoxConn.Text;

                    oldChanges.leds = LedsProperty;
                }
            }
            catch (ArgumentNullException nullex)
            {
                Console.WriteLine(nullex.Message);
                Console.WriteLine(nullex.TargetSite);
                SocketClient sc = new SocketClient(Port, controllerIP.Text);
                if (!sc.TryConnection())
                    buttonDisconnect_Click(this, EventArgs.Empty);
                MessageBox.Show("Lost connection to the controller");
            }
            catch (SocketException sockex)
            {
                Console.WriteLine(sockex.Message);
                Console.WriteLine(sockex.TargetSite);
                SocketClient sc = new SocketClient(Port, controllerIP.Text);
                if (!sc.TryConnection())
                {
                    buttonDisconnect_Click(this, EventArgs.Empty);
                    MessageBox.Show("Lost connection to the controller");
                }
                else
                    MessageBox.Show("The WSN took to long to respond");
            }
            catch
            {
                Console.WriteLine("Error in getStatData");
            }
        }
        /// <summary>
        /// Retreives the localization data of the selected node from the controller
        /// </summary>
        private void GetLocData()
        {
            //static part of the message
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>getnodeLocInfo</RequestName>";

            //return the nodeid with sensor as input
            try
            {

                if (listBoxLoc.SelectedItem != null)
                {
                    string nodeid;
                    nodeid = getNodeID(listBoxLoc.SelectedItem.ToString());

                    xml_send += "<arg>" + nodeid + "</arg></Request></Requests>";

                    SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                    // Receiving data
                    string xml_receive = socket_client.Connect(xml_send, true);


                    XmlDocument tempdoc = new XmlDocument();
                    tempdoc.LoadXml(xml_receive);

                    XmlNodeList bookList = tempdoc.GetElementsByTagName("Position");
                    foreach (XmlNode node in bookList)
                    {
                        XmlElement ID = (XmlElement)(node);
                        try
                        {
                            textBoxNodeID.Text = ID.GetElementsByTagName("node")[0].InnerText;
                            textBoxANodeID.Text = getTelosbId(ID.GetElementsByTagName("ANode")[0].InnerText);
                            textBoxRSSI.Text = ID.GetElementsByTagName("RSSI")[0].InnerText;
                            textBoxX.Text = ID.GetElementsByTagName("X")[0].InnerText;
                            textBoxY.Text = ID.GetElementsByTagName("Y")[0].InnerText;

                            try
                            {
                                int index = ID.GetElementsByTagName("Time")[0].InnerText.IndexOf('T');
                                textBoxLocUpdate.Text = ID.GetElementsByTagName("Time")[0].InnerText.Substring(index);
                            }
                            catch
                            {
                                Console.WriteLine("No time available for loc info");
                            }

                            try
                            {
                                textBoxZ.Text = ID.GetElementsByTagName("Z")[0].InnerText;
                            }
                            catch
                            {
                                textBoxZ.Text = "N/A";
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Some field is not available");
                            Console.WriteLine(ex.Message);
                            Console.WriteLine(ex.TargetSite);
                        }
                    }
                }
                else
                    return;
            }
            catch (ArgumentNullException nullex)
            {
                Console.WriteLine(nullex.Message);
                Console.WriteLine(nullex.TargetSite);
                SocketClient sc = new SocketClient(Port, controllerIP.Text);
                if (!sc.TryConnection())
                    Disconnect();
                MessageBox.Show("Lost connection to the controller");
            }
        }
        /// <summary>
        /// Occurs when the apply changes button is click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonWSNControl_Click(object sender, EventArgs e)
        {
            //TODO: needs validation;
            panelControl.Enabled = false;
            buttonWSNControl.Enabled = false;

            //we send the WSNactionRequest here
            //first
            //static part of the message
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><WSNReq xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><WSNReq><RequestAction>";

            //return the nodeid with sensor as input
            try
            {
                string selected = listBoxControl.SelectedItem.ToString();
                string nodeid;
                nodeid = getNodeID(selected);
                xml_send += "<NodeID>" + nodeid + "</NodeID>";

                //secondly we must check which fields have changed
                //we can then add them ass nodes in the XML

                //specific to our localization scheme
                if (oldChanges.Active != ActiveProperty)
                    xml_send += "<active>" + ActiveProperty + "</active>";
                //only process these parameters if the node is active in the localization algorithm
                if (ActiveProperty == "1")
                {
                    if (oldChanges.AN != AnchorProperty)
                        xml_send += "<AN>" + AnchorProperty + "</AN>";
                    //only process these parameters if the node is an Anchor Node
                    if (AnchorProperty == "0")
                    {
                        if (oldChanges.X != textBoxControlX.Text)
                        {
                            xml_send += "<X>" + textBoxControlX.Text + "</X>";
                            if ((Convert.ToInt32(textBoxControlX.Text)) < (Convert.ToInt32(textBoxXmin.Text)) || (Convert.ToInt32(textBoxControlX.Text)) > (Convert.ToInt32(textBoxXmax.Text)))
                            {
                                MessageBox.Show("X is not within bounds");
                                textBoxControlX.Text = oldChanges.X;
                                return;
                            }
                        }
                        if (oldChanges.Y != textBoxControlY.Text)
                        {
                            xml_send += "<Y>" + textBoxControlY.Text + "</y>";
                            if ((Convert.ToInt32(textBoxControlX.Text)) < (Convert.ToInt32(textBoxYmin)) || (Convert.ToInt32(textBoxControlX.Text)) > (Convert.ToInt32(textBoxYmax)))
                            {
                                MessageBox.Show("Y is not within bounds");
                                textBoxControlX.Text = oldChanges.Y;
                                return;
                            }
                        }
                        if (oldChanges.locrate != textBoxLocRate.Text)
                        {
                            xml_send += "<LocRate>" + textBoxLocRate.Text + "</LocRate>";
                            if ((Convert.ToInt32(textBoxLocRate)) < (Convert.ToInt32(textBoxLocRateMin)) || (Convert.ToInt32(textBoxLocRate)) > (Convert.ToInt32(textBoxLocRateMax)))
                            {
                                MessageBox.Show("LocRate is not within bounds");
                                textBoxControlX.Text = oldChanges.locrate;
                                return;
                            }
                        }
                    }
                }

                //these field are not unique to the localization algorithm and are thus independent
                if (oldChanges.samplerate != textBoxSampleRate.Text)
                {
                    xml_send += "<Samplerate>" + textBoxSampleRate.Text + "</Samplerate>";
                    if ((Convert.ToInt32(textBoxSampleRate)) < (Convert.ToInt32(textBoxSensorRateMin)) || (Convert.ToInt32(textBoxSampleRate)) > (Convert.ToInt32(textBoxSensorRateMax)))
                    {
                        MessageBox.Show("SampleRate is not within bounds");
                        textBoxControlX.Text = oldChanges.samplerate;
                        return;
                    }
                }
                if (oldChanges.leds != LedsProperty)
                    xml_send += "<Leds>" + LedsProperty + "</Leds>";
                if (oldChanges.power != PowerProperty)
                    xml_send += "<Power>" + PowerProperty + "</Power>";
                if (oldChanges.frequency != FrequencyProperty)
                    xml_send += "<Frequency>" + FrequencyProperty+ "</Frequency>";

                xml_send += "</RequestAction></WSNReq></WSNReq>";

                //we can now send the request, we will receive a status message as a response
                SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                // Sends: ActionRequest
                // Receives: Status
                string xml_receive = socket_client.Connect(xml_send, true);

                XmlDocument tempdoc = new XmlDocument();
                tempdoc.LoadXml(xml_receive);

                XmlNodeList bookList = tempdoc.GetElementsByTagName("Status");
                foreach (XmlNode node in bookList)
                {
                    XmlElement ID = (XmlElement)(node);
                    try
                    {
                        if (
                        ActiveProperty == ID.GetElementsByTagName("active")[0].InnerText &&
                        AnchorProperty == ID.GetElementsByTagName("AN")[0].InnerText &&
                        textBoxControlX.Text == ID.GetElementsByTagName("X")[0].InnerText &&
                        textBoxControlY.Text == ID.GetElementsByTagName("Y")[0].InnerText &&
                        textBoxSampleRate.Text == ID.GetElementsByTagName("Samplerate")[0].InnerText &&
                        textBoxLocRate.Text == ID.GetElementsByTagName("LocRate")[0].InnerText &&
                        LedsProperty == ID.GetElementsByTagName("Leds")[0].InnerText &&
                        PowerProperty == ID.GetElementsByTagName("Power")[0].InnerText &&
                        FrequencyProperty == ID.GetElementsByTagName("Frequency")[0].InnerText)
                        {
                            //WSN Succesfully replied to our request
                            //changes struct
                            oldChanges.Active = ActiveProperty;
                            oldChanges.AN = AnchorProperty;
                            oldChanges.X = textBoxControlX.Text;
                            oldChanges.Y = textBoxControlY.Text;
                            oldChanges.samplerate = textBoxSampleRate.Text;
                            oldChanges.locrate = textBoxLocRate.Text;
                            oldChanges.power = PowerProperty;
                            oldChanges.frequency = FrequencyProperty;
                            oldChanges.conn = textBoxConn.Text;
                            oldChanges.leds = LedsProperty;

                            Console.WriteLine("WSN succesfully replied");
                            MessageBox.Show("WSN succesfully replied");
                        }
                        else
                        {
                            //WSN did NOT! Succesfully replied to our request
                            //roll back to previous state;
                            ActiveProperty = oldChanges.Active;
                            AnchorProperty = oldChanges.AN;
                            textBoxControlX.Text = oldChanges.X;
                            textBoxControlY.Text = oldChanges.Y;
                            textBoxSampleRate.Text = oldChanges.samplerate;
                            textBoxLocRate.Text = oldChanges.locrate;
                            FrequencyProperty = oldChanges.power;
                            FrequencyProperty = oldChanges.frequency;
                            textBoxConn.Text = oldChanges.conn;
                            LedsProperty = oldChanges.leds;

                            Console.WriteLine("WSN did not succesfully reply");
                            MessageBox.Show("WSN did not succesfully reply");
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Some field is not available");
                    }

                }
            }
            //good ol' catches
            catch (ArgumentNullException nullex)
            {
                Console.WriteLine(nullex.Message);
                Console.WriteLine(nullex.TargetSite);
                SocketClient sc = new SocketClient(Port, controllerIP.Text);
                if (!sc.TryConnection())
                    buttonDisconnect_Click(this, EventArgs.Empty);
                MessageBox.Show("Lost connection to the controller");
            }
            catch (SocketException sockex)
            {
                Console.WriteLine(sockex.Message);
                Console.WriteLine(sockex.TargetSite);
                SocketClient sc = new SocketClient(Port, controllerIP.Text);
                if (!sc.TryConnection())
                    buttonDisconnect_Click(this, EventArgs.Empty);
                MessageBox.Show("Lost connection to the controller");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.TargetSite);
            }

            panelControl.Enabled = true;
            buttonWSNControl.Enabled = true;
        }
        /// <summary>
        /// Gets the nodes status and compares it to the currently stored status.
        /// </summary>
        /// <returns>Bool indicating whether the statuses are different or not</returns>
        private bool CheckStatus()
        {
            //fetch status
            //static part of the message
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>getStatus</RequestName>";

            //return the nodeid with sensor as input
            try
            {
                //make the XML string to send
                string selected = listBoxControl.SelectedItem.ToString();
                string nodeid = getNodeID(selected);

                xml_send += "<arg>" + nodeid + "</arg></Request></Requests>";

                SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                // Receiving data
                string xml_receive = socket_client.Connect(xml_send, true);

                //set the textfields to the received XML nodes
                XmlDocument tempdoc = new XmlDocument();
                tempdoc.LoadXml(xml_receive);

                XmlNodeList bookList = tempdoc.GetElementsByTagName("Status");
                foreach (XmlNode node in bookList)
                {
                    XmlElement ID = (XmlElement)(node);
                    try
                    {
                        //compare status to changes
                        if (
                            oldChanges.Active == ID.GetElementsByTagName("active")[0].InnerText &&
                            oldChanges.AN == ID.GetElementsByTagName("AN")[0].InnerText &&
                            oldChanges.X == ID.GetElementsByTagName("X")[0].InnerText &&
                            oldChanges.Y == ID.GetElementsByTagName("Y")[0].InnerText &&
                            oldChanges.samplerate == ID.GetElementsByTagName("Samplerate")[0].InnerText &&
                            oldChanges.locrate == ID.GetElementsByTagName("LocRate")[0].InnerText &&
                            oldChanges.leds == ID.GetElementsByTagName("Leds")[0].InnerText &&
                            oldChanges.power == ID.GetElementsByTagName("Power")[0].InnerText &&
                            oldChanges.frequency == ID.GetElementsByTagName("Frequency")[0].InnerText)
                            return false;
                        else
                            return true;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(ex.StackTrace);
                        Console.WriteLine("Some field is not available");
                    }
                }
            }
            //catch the exceptions
            catch (ArgumentNullException nullex)
            {
                Console.WriteLine(nullex.Message);
                Console.WriteLine(nullex.TargetSite);
                SocketClient sc = new SocketClient(Port, controllerIP.Text);
                if (!sc.TryConnection())
                    Disconnect();
                MessageBox.Show("Lost connection to the controller");
            }
            catch (SocketException sockex)
            {
                Console.WriteLine(sockex.Message);
                Console.WriteLine(sockex.TargetSite);
                SocketClient sc = new SocketClient(Port, controllerIP.Text);
                if (!sc.TryConnection())
                {
                    buttonDisconnect_Click(this, EventArgs.Empty);
                    MessageBox.Show("Lost connection to the controller");
                }
                else
                    MessageBox.Show("The WSN took to long to respond");
            }
            return false;
        }
        //
        //Plot the graph
        //SP:
        //
        private void button2_Click_1(object sender, EventArgs e)
        {
            //static part of the message
            string xml_send = @"<?xml version=""1.0"" standalone=""yes""?><Requests xmlns:xsi=""='http://www.w3.org/2001/XMLSchema-instance'""  xmlns=""xmlns='http://tempuri.org/Requests.xsd\'""><Request><RequestName>getHistoryLast</RequestName>";

            //return the nodeid with sensor as input
            try
            {
                string selectedNode = comboBox2.SelectedItem.ToString();

                if (selectedNode != null)
                {
                    string nodeid = getNodeID(selectedNode); ;

                    xml_send += "<arg>" + nodeid + "</arg>";

                    string selectedReading = comboBox1.SelectedItem.ToString();

                    if (selectedReading != null)
                    {
                        xml_send += "<arg>" + selectedReading + "</arg><arg>10</arg></Request></Requests>";

                    }
                }

                SocketClient socket_client = new SocketClient(Port, controllerIP.Text);
                string xml_receive = socket_client.Connect(xml_send, true);

                //put the received data in the graph
                XmlDocument tempdoc = new XmlDocument();
                tempdoc.LoadXml(xml_receive);

                listView2.Items.Clear();
                XmlNodeList bookList = tempdoc.GetElementsByTagName("MeasurementValue");

                foreach (XmlNode node in bookList)
                {
                    string id_Measurement = node.InnerText.ToString();
                    listView2.Items.Add(id_Measurement);
                }

                CreateGraph(zg1, xml_receive);
                SetSize();
            }
            catch { }
        }