using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using XBee_Library;

namespace _004_Serial_port_control
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        XBee_main_program XBee = new XBee_main_program();
        Boolean ATMode = false;
        Boolean ATGoOn = false;
        string answer = null;
        Byte[] SPISetup = new Byte[5];
        
        
        

        private void Form1_Load(object sender, EventArgs e)
        {  
            XBee.CreateFiles();  //tvorba Souboru
            LoadBoxes();  //inicializace polozek v okne
            SPISetup[0] = Convert.ToByte(0x06);  //prvni byte urcuje pristup k SPI nastaveni
            
        }

        //////////Nachazi se v XBee_main_program!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        /*private void CreateFiles()  //tvorba souboru a popisu zapsanych informaci
        {
            if(!System.IO.File.Exists("Measured_Data.txt"))
            {
                System.IO.File.AppendAllText("Measured_Data.txt", "Cas (hodiny:minuty:sekundy:milisekundy), Prijata data" + Environment.NewLine);
            }

            if(!System.IO.File.Exists("Communication_parameters_history.txt"))
            {
                System.IO.File.AppendAllText("Communication_parameters_history.txt", "Time(Date, Hours:Minutes:Seconds), Baudrate, DataBits, Encoding, Handshake, Parity, Portname, StopBits" + Environment.NewLine);
            }
        }*/

        private void LoadBoxes()  //nastavi defaultni vlastnosti Combo a Text Boxu
        {
            try
            {
                //zjisteni pouzitelnych portu pocitace a jejich ulozeni v comboBoxu
                String[] ports = System.IO.Ports.SerialPort.GetPortNames();
                comboBoxSetPort.Items.AddRange((object[])ports);

                //inicializace pocatecnich hodnot comboBoxu
                comboBoxSetBaudrate.SelectedIndex = 3;
                comboBoxParity.SelectedIndex = 0;
                comboBoxEncoding.SelectedIndex = 0;
                comboBoxSetPort.SelectedIndex = 0;

                //inicializace textBoxu
                textBoxViewStatus.Text = "Disconnected";
                textBoxViewPort.Text = "Not selected";
                textBoxViewBaudrate.Text = "Not selected";
                textBoxViewParity.Text = "Not selected";
                textBoxViewEncoding.Text = "Not selected";

                //inicializace toolStripStatusLabelu
                toolStripStatusLabel1.Text = "";
            }
            catch (Exception ex)
            {
                toolStripStatusLabel1.Text = ex.Message;
            }
        }

        private void LoadLastCommunicationParameters()  //nacita posledne nastavene parametry XBee
        {
            if (System.IO.File.Exists("Communication_parameters_history.txt"))
            {
                int countData = 0;
                int countSwitch = 0;
                string memory = null;
                string data = null;
                System.IO.StreamReader SR = new System.IO.StreamReader("Communication_parameters_history.txt");
                //System.IO.File.Delete();
                while (SR.EndOfStream != true)  //preskoci historii pripojeni, zustane ulozen posledni radek
                {
                   data = SR.ReadLine();
                }
                while (countData != data.Length)  //cyklime dokud neprojede vsechny znaky stringu data
                {
                    switch (countSwitch)
                    {
                        case 0:  //preskakujem datum
                            {
                                while (data[countData] != ' ')
                                { countData++; }
                                countData++;
                                countSwitch++;
                                break;
                            }
                        case 1:  //preskakujem cas
                            {
                                while (data[countData] != ' ')
                                { countData++; }
                                countData++;
                                countData++;
                                countSwitch++;
                                break;
                            }
                        case 2:  //kopirujeme hodnotu BaudRate do comboBoxu
                            {
                                while (data[countData] != ' ')
                                {
                                    memory = memory + data[countData].ToString();
                                    countData++;
                                }
                                comboBoxSetBaudrate.SelectedItem = memory;
                                memory = null;
                                countData++;
                                countSwitch++;
                                break;
                            }
                        case 3:  //preskakujem pocet datovych bitu
                            {
                                while (data[countData] != ' ')
                                {
                                    countData++;
                                }
                                countData++;
                                countSwitch++;
                                break;
                            }
                        case 4:  //nastavujeme Encoding
                            {
                                while (data[countData] != ' ')
                                {
                                    memory = memory + data[countData].ToString();
                                    countData++;
                                }
                                if (memory == "System.Text.ASCIIEncoding")
                                {
                                    comboBoxEncoding.SelectedIndex = 0;
                                }
                                else if (memory == "System.Text.UnicodeEncoding")
                                {
                                    comboBoxEncoding.SelectedIndex = 1;
                                }
                                else
                                {
                                    toolStripStatusLabel1.Text = "Kodovani neni ani ASCII, ani Unicode.";
                                }
                                memory = null;
                                countData++;
                                countSwitch++;
                                break;
                            }
                        case 5:
                            {
                                while (data[countData] != ' ')  //preskakujeme Handshake
                                {
                                    countData++;
                                }
                                countData++;
                                countSwitch++;
                                break;
                            }
                        case 6:  //nastavujeme paritu
                            {
                                while (data[countData] != ' ')
                                {
                                    memory = memory + data[countData].ToString();
                                    countData++;
                                }
                                comboBoxParity.SelectedItem = memory;
                                memory = null;
                                countData++;
                                countSwitch++;
                                break;
                            }
                        case 7:  //nastavujeme jmeno portu
                            {
                                while (data[countData] != ' ')
                                {
                                    memory = memory + data[countData].ToString();
                                    countData++;
                                }
                                comboBoxSetPort.Text = memory;
                                memory = null;
                                countData++;
                                countSwitch++;
                                break;
                            }
                        case 8:  //nastavujeme pocet stopBitu
                            {    //pocet stopBitu nelze nastavit, XBee tento prikaz nezna
                                while (countData != data.Length)
                                {
                                    memory = memory + data[countData].ToString();
                                    countData++;
                                }
                                //comboBoxStopBits.SelectedItem = memory.ToString();
                                memory = null;
                                break;
                            }
                        default: break;
                    }
                }

                
            }
        }

        private void Connect()  //metoda vytvori seriove pripojeni programu na port pocitace
        {
            if (!serialPort1.IsOpen)
            {
                try
                {
                    setCommunicationParameters();
                    serialPort1.Open();
                    XBeeSetUp();
                    ViewInfo();
                }
                catch (Exception ex)
                {
                    toolStripStatusLabel1.Text = ex.Message;
                }
            }
            else
            {
                toolStripStatusLabel1.Text = "Port is already connected.";
            }
        }

        private void LoadDefaultSetup()
        {
                comboBoxSetBaudrate.SelectedIndex = 3;
                comboBoxParity.SelectedIndex = 0;
                comboBoxEncoding.SelectedIndex = 0;
                comboBoxSetPort.SelectedIndex = 0;
        }


        private void setCommunicationParameters()  //metoda nastavujici parametry komunikace
        {
            try
            {
                serialPort1.PortName = comboBoxSetPort.Text;
                serialPort1.BaudRate = Convert.ToInt32(comboBoxSetBaudrate.Text);
                serialPort1.Handshake = Handshake.None;  //pevne dane modulem XBee 
                serialPort1.StopBits = StopBits.One;
                serialPort1.DataBits = 8;  //pevne dane modulem XBee

                switch (comboBoxEncoding.SelectedIndex)
                {
                    case 0: serialPort1.Encoding = Encoding.ASCII; break;
                    case 1: serialPort1.Encoding = Encoding.Unicode; break;
                    default: break;
                }

                switch (comboBoxParity.SelectedIndex)
                {
                    case 0: serialPort1.Parity = Parity.None; break;
                    case 1: serialPort1.Parity = Parity.Even; break;
                    case 2: serialPort1.Parity = Parity.Odd; break;
                    case 3: serialPort1.Parity = Parity.Mark; break;
                    default: break;
                }
            }
            catch (Exception ex)
            {
                toolStripStatusLabel1.Text = ex.Message;
            }
        }

        private void Disconnect()  //metoda zrusi pripojeni programu na seriovy port pocitace
        {
            if (serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.Close();
                    ViewInfo();               
                }
                catch (Exception ex)
                {
                    toolStripStatusLabel1.Text = ex.Message;
                }
            }
            else
            {
                toolStripStatusLabel1.Text = "Port is already disconnected.";
            }
        }

        private void ViewInfo()  //zobrazuje parametry pripojeni
        {
            if (serialPort1.IsOpen)
            {
                textBoxViewStatus.Text = "Connected";
                textBoxViewPort.Text = comboBoxSetPort.Text;
                textBoxViewBaudrate.Text = comboBoxSetBaudrate.Text;
                textBoxViewParity.Text = comboBoxParity.Text;
                textBoxViewEncoding.Text = comboBoxEncoding.Text;
                toolStripStatusLabel1.Text = "";
            }
            else
            {
                textBoxViewStatus.Text = "Disconnected";
                textBoxViewPort.Text = "Not selected";
                textBoxViewBaudrate.Text = "Not selected";
                textBoxViewParity.Text = "Not selected";
                textBoxViewEncoding.Text = "Not selected";
                toolStripStatusLabel1.Text = "";
            }
        }

        private void SetCommunication()  //metoda meni nastaveni komunikacnich parametru
        {
            if (serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.BaudRate = Convert.ToInt32(comboBoxSetBaudrate.Text);

                    switch (comboBoxEncoding.SelectedIndex)
                    {
                        case 0: serialPort1.Encoding = Encoding.ASCII; break;
                        case 1: serialPort1.Encoding = Encoding.Unicode; break;
                        default: break;
                    }

                    switch (comboBoxParity.SelectedIndex)
                    {
                        case 0: serialPort1.Parity = Parity.None; break;
                        case 1: serialPort1.Parity = Parity.Even; break;
                        case 2: serialPort1.Parity = Parity.Odd; break;
                        case 3: serialPort1.Parity = Parity.Mark; break;
                        default: break;
                    }
                    ViewInfo();
                }
                catch (Exception ex)
                {
                    toolStripStatusLabel1.Text = ex.Message;
                }
            }
            else
            {
                toolStripStatusLabel1.Text = "Port is disconnected";
            }
        }

        private void SaveCommunicationParameters()  //metoda k ukladani parametru komunikace
        {                                           //pro znalost posledne zadanych parametru
            DateTime time = DateTime.Now;
            string parameters = serialPort1.BaudRate.ToString() + " " + serialPort1.DataBits.ToString() + " " + serialPort1.Encoding.ToString() + " " + serialPort1.Handshake.ToString() + " " + serialPort1.Parity.ToString() + " " + serialPort1.PortName.ToString() + " " + serialPort1.StopBits.ToString() + Environment.NewLine;
            string timeinfo = time.Year.ToString() + "." + time.Month.ToString() + "." + time.Day.ToString() + " " + time.Hour.ToString() + ":" + time.Minute.ToString() + ":" + time.Second.ToString() + " " + serialPort1.ReadExisting() + " ";
            System.IO.File.AppendAllText("Communication_parameters_history.txt", timeinfo + parameters);
        }
        

        private void SendData()  //metoda posila znaky na seriovy port pocitace
        {                        //hlavicka je 0xAA, nahrada je 0xBB a nahrada 0xBB je 0xBB01
            try
            {
                string SendDataMemory = textBoxSendData.Text;
                //hledame znaky 0xBB a nahrazujememe je znaky 0xBB55

                    if (SendDataMemory.Contains("╗"))  //najde-li ASCII znak 0xBB
                    {
                        SendDataMemory = SendDataMemory.Replace("╗", "╗7");  //nahradi ho znakem 0xBB55 
                    }
                

                //hledame znaky 0xAA a nahrazujeme je znaky 0xBB
                    if (SendDataMemory.Contains("¬"))  //najde-li ASCII znak 0xAA
                    {
                        SendDataMemory = SendDataMemory.Replace("¬", "╗");  //nahradi ho znakem 0xBB
                    }

                    textBoxRecievedData.Text = SendDataMemory + Environment.NewLine;
                    serialPort1.Write(SendDataMemory);
            }
            catch (Exception ex)
            {
                toolStripStatusLabel1.Text = ex.Message;
            }
        }

        public void RecieveData()  //metoda prijima data, vypisuje je do textboxu a uklada do souboru
        {            
            string DataRecieved = null;
            Boolean ControlMode = false;
            try
            {
                while (serialPort1.BytesToRead > 0)  //nacteme prijata data do stringu
                {
                    DataRecieved = serialPort1.ReadExisting();
                }

                if(DataRecieved.Contains("¬"))  //obsahuji-li prijata data znak 0xAA, jde o hlavicku
                {
                    if (DataRecieved.Contains("OK"))
                    {
                        textBoxRecievedData.Text = "Parametry vzdaleneho modulu XBee uspesne nastaveny.";
                        ControlMode = true;
                    }
                    else if (DataRecieved.Contains("ER"))  //ERROR
                    {
                        ControlMode = true;
                        textBoxRecievedData.Text = "Chyba! Parametry vzdaleneho modulu XBee nebyly nastaveny.";
                    }
                    else
                    {
                    }
                }

                if (DataRecieved.Contains("╗7"))  //najde-li ASCII znaky 0xBB a 0x55
                {
                    DataRecieved = DataRecieved.Replace("╗7", "╗");  //nahradi ho znakem 0xBB 
                }

                if (DataRecieved.Contains("╗"))  //najde-li ASCII znak 0xBB
                {
                    DataRecieved = DataRecieved.Replace("¬", "╗");  //nahradi ho znakem 0xAA
                }           
            }
            catch (Exception ex)
            {
                toolStripStatusLabel1.Text = ex.Message;
            }

            
            if (!ATMode && (ControlMode == false))
            {
                DateTime time = DateTime.Now;
                string message = time.Hour.ToString() + ":" + time.Minute.ToString() + ":" + time.Second.ToString() + ":" + time.Millisecond.ToString() + " " + DataRecieved + Environment.NewLine;
                System.IO.File.AppendAllText("Measured_Data.txt", message);
                this.Invoke((MethodInvoker)delegate { textBoxRecievedData.Text += message; });
            }
            else if (ATMode && (ControlMode == false))
            {
                if (DataRecieved.Contains("OK"))
                {
                    ATGoOn = true;
                }
                else if (DataRecieved.Contains("ERROR"))
                {
                    return;
                }
                else if (DataRecieved != null)
                {
                    answer = DataRecieved;
                    ATGoOn = true;
                }
            }
            else
            {
            }

        }

        private void XBeeSetUp()
        {
            if (serialPort1.IsOpen)
            {
                try
                {
                    ATMode = true;
                    textBoxRecievedData.Clear();
                    textBoxRecievedData.Text += "Probiha nastaveni parametru komunikace s XBee:" + Environment.NewLine;

                    //vstup do AT modu
                    enterATCommandMode();
                    WaitForATGoOn();
                    textBoxRecievedData.Text += "Byl proveden uspeny vstup do command modu." + Environment.NewLine;

                    //precti adresu
                    string address = null;
                    address = sendATRequest("ATMY \r");//precti mou adresu
                    WaitForATGoOn();
                    textBoxRecievedData.Text += "Adresa pripojeneho XBee modulu je: " + address + Environment.NewLine;

                    //precti cilovou adresu
                    address = sendATRequest("ATDH \r");  //precti cilovou adresu hornich 32 bitu
                    WaitForATGoOn();
                    textBoxRecievedData.Text += "Hornich 32 bitu adresy ciloveho XBee modulu je: " + address + Environment.NewLine;
                    address = sendATRequest("ATDL \r");  //precti cilovou adresu spodnich 32 bitu
                    WaitForATGoOn();
                    textBoxRecievedData.Text += "Dolnich 32 bitu adresy ciloveho XBee modulu je: " + address + Environment.NewLine;

                    //nastaveni parity
                    sendATCommand("ATNB " + comboBoxParity.SelectedIndex.ToString() + "\r");  //parita
                    WaitForATGoOn();
                    textBoxRecievedData.Text += "Parita byla nastavena." + Environment.NewLine;

                    //pocet stop bitu nelze nastavit, neodpovida to na prikaz, asi ho nezna!!!

                    //nastaveni Baudrate
                    sendATCommand("ATBD " + comboBoxSetBaudrate.SelectedIndex.ToString() + "\r");  //BaudRate
                    WaitForATGoOn();
                    textBoxRecievedData.Text += "Velikost Baudrate nastavena." + Environment.NewLine;

                    //Aplikovani vsech nastavenych parametru
                    sendATCommand("ATAC \r");  //aplikuj nastavene parametry
                    WaitForATGoOn();
                    textBoxRecievedData.Text += "Nastavene parametry byly aktivovany" + Environment.NewLine;

                    //prenastavi nastaveni portu
                    SetCommunication();

                    //ukonci AT mod
                    sendATCommand("ATCN\r");  //ukonci AT mod
                    WaitForATGoOn();
                    textBoxRecievedData.Text += "Command mod byl ukoncen." + Environment.NewLine;
                    SaveCommunicationParameters();
                    ATMode = false;
                }
                catch (Exception ex)
                {
                    toolStripStatusLabel1.Text = ex.Message;
                }
            }
            else
            {
                toolStripStatusLabel1.Text = "Serial port is disconnected.";
            }
        }

        private void WaitForATGoOn()
        {
            while (!ATGoOn)
            {
                Thread.Sleep(10);
            }
            ATGoOn = false;
        }

        public void enterATCommandMode()
        {
            System.Threading.Thread.Sleep(1000);  //cekej sekundu
            serialPort1.Write("+++");  //odesli znaky +++
            System.Threading.Thread.Sleep(1000);  //cekej sukundu
        }

        public void sendATCommand(string command)
        {
            serialPort1.Write(command);
        }

        public string sendATRequest(string command)
        {
            serialPort1.Write(command);
            while (answer == null)
            {
                Thread.Sleep(10);
            }
            string memoryAnswer = answer;
            answer = null;
            return memoryAnswer;
            
        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            RecieveData();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            SendData();
        }

        private void buttonClearRecievedData_Click(object sender, EventArgs e)
        {
            textBoxRecievedData.Clear();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Disconnect();
        }


        private void connectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Connect();
        }

        private void setToolStripMenuItem_Click(object sender, EventArgs e)
        {
            XBeeSetUp();
        }

        private void disconnectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Disconnect();
        }

        private void aboutProgramToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBoxRecievedData.Clear();
            textBoxRecievedData.Text = "Tento program je urcen pro sber namerenych dat z modulu XBee, posilani dat senzoru a take slouzi k nastaveni parametru komunikace.";
        }

        private void connectToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            textBoxRecievedData.Clear();
            textBoxRecievedData.Text = "Tlacitko Connect ulozi nastaveni komunikace a pokusí se spojit s modulem XBee.";
        }

        private void disconnectToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            textBoxRecievedData.Clear();
            textBoxRecievedData.Text = "Tlacitko Disconnect ukonci komunikaci.";
        }

        private void setToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            textBoxRecievedData.Clear();
            textBoxRecievedData.Text = "Tlacitko Set umoznuje zmenit parametry komunikace za jejiho behu.";
        }

        private void buttonLoadLastSetup_Click(object sender, EventArgs e)
        {
            LoadLastCommunicationParameters();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            LoadDefaultSetup();
        }

 


        //
        //Cast pro nastaveni vzdaleneho mikrokontroleru
        //
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            //prikaz XBee modulu na strane mikrokontroleru pro zmenu na baudRate 1200
            //serialPort1.BaseStream.WriteByte(0xAA);  //hlavicka
            //serialPort1.BaseStream.WriteByte(0x02);  //rozliseni pro program v mikrokontroleru
            //serialPort1.BaseStream.WriteByte(0x00);  //rozliseni pro baudrate v mikrokontroleru
            //serialPort1.BaseStream.WriteByte(0x00);  //nastaveni parity, v ATMEGA ale nefunguje
            textBoxRecievedData.Clear();
            textBoxRecievedData.Text = "Tato komunikacni rychlost momentalne nefunguje!!!";
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            //prikaz XBee modulu na strane mikrokontroleru pro zmenu na baudRate 2400
            //serialPort1.BaseStream.WriteByte(0xAA);  //hlavicka
            //serialPort1.BaseStream.WriteByte(0x02);  //rozliseni pro program v mikrokontroleru
            //serialPort1.BaseStream.WriteByte(0x01);  //rozliseni pro baudrate v mikrokontroleru
            //serialPort1.BaseStream.WriteByte(0x00);  //nastaveni parity, v ATMEGA ale nefunguje
            textBoxRecievedData.Clear();
            textBoxRecievedData.Text = "Tato komunikacni rychlost momentalne nefunguje!!!";
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            //prikaz XBee modulu na strane mikrokontroleru pro zmenu na baudRate 4800
            serialPort1.BaseStream.WriteByte(0xAA);
            serialPort1.BaseStream.WriteByte(0x02);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x02);  //rozliseni pro baudrate v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x00);  //nastaveni parity, v ATMEGA ale nefunguje
        }

        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            //prikaz XBee modulu na strane mikrokontroleru pro zmenu na baudRate 9600
            serialPort1.BaseStream.WriteByte(0xAA);
            serialPort1.BaseStream.WriteByte(0x02);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x03);  //rozliseni pro baudrate v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x00);  //nastaveni parity, v ATMEGA ale nefunguje
        }

        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {
            //prikaz XBee modulu na strane mikrokontroleru pro zmenu na baudRate 19200
            serialPort1.BaseStream.WriteByte(0xAA);
            serialPort1.BaseStream.WriteByte(0x02);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x04);  //rozliseni pro baudrate v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x00);  //nastaveni parity, v ATMEGA ale nefunguje
        }

        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            //prikaz XBee modulu na strane mikrokontroleru pro zmenu na baudRate 38400
            serialPort1.BaseStream.WriteByte(0xAA);
            serialPort1.BaseStream.WriteByte(0x02);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x05);  //rozliseni pro baudrate v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x00);  //nastaveni parity, v ATMEGA ale nefunguje
        }

        private void toolStripMenuItem8_Click(object sender, EventArgs e)
        {
            //prikaz XBee modulu na strane mikrokontroleru pro zmenu na baudRate 57600
            serialPort1.BaseStream.WriteByte(0xAA);
            serialPort1.BaseStream.WriteByte(0x02);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x06);  //rozliseni pro baudrate v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x00);  //nastaveni parity, v ATMEGA ale nefunguje
        }

        private void toolStripMenuItem9_Click(object sender, EventArgs e)
        {
            //prikaz XBee modulu na strane mikrokontroleru pro zmenu na baudRate 115200
            serialPort1.BaseStream.WriteByte(0xAA);
            serialPort1.BaseStream.WriteByte(0x02);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x07);  //rozliseni pro baudrate v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x00);  //nastaveni parity, v ATMEGA ale nefunguje
        }

        private void changeBaudRateToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void toolStripMenuItem10_Click(object sender, EventArgs e)
        {
            //prikaz mikrokontroleru pro zmenu USART u senzoru na baudRate 1200
            //serialPort1.BaseStream.WriteByte(0xAA);  //hlavicka
            //serialPort1.BaseStream.WriteByte(0x01);  //rozliseni pro program v mikrokontroleru
            //serialPort1.BaseStream.WriteByte(0x00);  //rozliseni pro baudrate v mikrokontroleru
            //serialPort1.BaseStream.WriteByte(0x00);  //nastaveni parity, v ATMEGA ale nefunguje
            textBoxRecievedData.Clear();
            textBoxRecievedData.Text = "Tato komunikacni rychlost momentalne nefunguje!!!";
        }

        private void toolStripMenuItem11_Click(object sender, EventArgs e)
        {
            //prikaz mikrokontroleru pro zmenu USART u senzoru na baudRate 2400
            //serialPort1.BaseStream.WriteByte(0xAA);  //hlavicka
            //serialPort1.BaseStream.WriteByte(0x01);  //rozliseni pro program v mikrokontroleru
            //serialPort1.BaseStream.WriteByte(0x01);  //rozliseni pro baudrate v mikrokontroleru
            //serialPort1.BaseStream.WriteByte(0x00);  //nastaveni parity, v ATMEGA ale nefunguje
            textBoxRecievedData.Clear();
            textBoxRecievedData.Text = "Tato komunikacni rychlost momentalne nefunguje!!!";
        }

        private void toolStripMenuItem12_Click(object sender, EventArgs e)
        {
            //prikaz mikrokontroleru pro zmenu USART u senzoru na baudRate 4800
            serialPort1.BaseStream.WriteByte(0xAA);  //hlavicka  
            serialPort1.BaseStream.WriteByte(0x01);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x02);  //rozliseni pro baudrate v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x00);  //nastaveni parity, v ATMEGA ale nefunguje
        }

        private void toolStripMenuItem13_Click(object sender, EventArgs e)
        {
            //prikaz mikrokontroleru pro zmenu USART u senzoru na baudRate 9600
            serialPort1.BaseStream.WriteByte(0xAA);  //hlavicka  
            serialPort1.BaseStream.WriteByte(0x01);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x03);  //rozliseni pro baudrate v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x00);  //nastaveni parity, v ATMEGA ale nefunguje
        }

        private void toolStripMenuItem14_Click(object sender, EventArgs e)
        {
            //prikaz mikrokontroleru pro zmenu USART u senzoru na baudRate 19200
            serialPort1.BaseStream.WriteByte(0xAA);  //hlavicka  
            serialPort1.BaseStream.WriteByte(0x01);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x04);  //rozliseni pro baudrate v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x00);  //nastaveni parity, v ATMEGA ale nefunguje
        }

        private void toolStripMenuItem15_Click(object sender, EventArgs e)
        {
            //prikaz mikrokontroleru pro zmenu USART u senzoru na baudRate 38400
            serialPort1.BaseStream.WriteByte(0xAA);  //hlavicka  
            serialPort1.BaseStream.WriteByte(0x01);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x05);  //rozliseni pro baudrate v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x00);  //nastaveni parity, v ATMEGA ale nefunguje
        }

        private void toolStripMenuItem16_Click(object sender, EventArgs e)
        {
            //prikaz mikrokontroleru pro zmenu USART u senzoru na baudRate 57600
            serialPort1.BaseStream.WriteByte(0xAA);  //hlavicka  
            serialPort1.BaseStream.WriteByte(0x01);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x06);  //rozliseni pro baudrate v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x00);  //nastaveni parity, v ATMEGA ale nefunguje
        }

        private void toolStripMenuItem17_Click(object sender, EventArgs e)
        {
            //prikaz mikrokontroleru pro zmenu USART u senzoru na baudRate 115200
            serialPort1.BaseStream.WriteByte(0xAA);  //hlavicka  
            serialPort1.BaseStream.WriteByte(0x01);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x07);  //rozliseni pro baudrate v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x00);  //nastaveni parity, v ATMEGA ale nefunguje
        }

        private void turnLEDDiodesOnToolStripMenuItem_Click(object sender, EventArgs e)
        {
            serialPort1.BaseStream.WriteByte(0xAA);  //hlavicka   
            serialPort1.BaseStream.WriteByte(0x03);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x00);  //zapnuti LED diod
        }

        private void turnLEDOffToolStripMenuItem_Click(object sender, EventArgs e)
        {
            serialPort1.BaseStream.WriteByte(0xAA);  //hlavicka   
            serialPort1.BaseStream.WriteByte(0x03);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x01);  //vypnuti LED diod
        }

        private void startSendingTestDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            serialPort1.BaseStream.WriteByte(0xAA);  //hlavicka   
            serialPort1.BaseStream.WriteByte(0x04);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x00);  //zacni posilat testovaci data
        }

        private void stopSendingTestDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            serialPort1.BaseStream.WriteByte(0xAA);  //hlavicka   
            serialPort1.BaseStream.WriteByte(0x04);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x01);  //prestan posilat testovaci data
        }

        private void startSendingDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            serialPort1.BaseStream.WriteByte(0xAA);  //hlavicka   
            serialPort1.BaseStream.WriteByte(0x05);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x00);  //zacni preposilat data ze senzoru na modul XBee
        }

        private void stopSendingDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            serialPort1.BaseStream.WriteByte(0xAA);  //hlavicka   
            serialPort1.BaseStream.WriteByte(0x05);  //rozliseni pro program v mikrokontroleru
            serialPort1.BaseStream.WriteByte(0x01);  //prestan preposilat data ze senzoru na modul XBee
        }

        private void lSBToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            SPISetup[2] = 0x00;  //LSB
        }

        private void mSBToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SPISetup[2] = 0x01;  //MSB
        }

        private void startSendingDataToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            SPISetup[1] = 0x00;  //Start sending data
        }

        private void stopSendingDataToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            SPISetup[1] = 0x01;  //Stop sending data
        }

        private void cToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SPISetup[3] = 0x00;  //CPOL = 0; CPHA = 0;
        }

        private void cPHA0CPOL0ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SPISetup[3] = 0x01;  //CPOL = 1; CPHA = 0;
        }

        private void cPHA0CPOL0ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            SPISetup[3] = 0x02;  //CPOL = 0; CPHA = 1;
        }

        private void cPHA0CPOL0ToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            SPISetup[3] = 0x03;  //CPOL = 1; CPHA = 1;
        }

        private void crystalFrequency4ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SPISetup[4] = 0x00;  //crystal frequency / 4
        }

        private void crystalFrequency4ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            SPISetup[4] = 0x01;  //crystal frequency / 16
        }

        private void crystalFrequency4ToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            SPISetup[4] = 0x02;  //crystal frequency / 64
        }

        private void crystalFrequency4ToolStripMenuItem3_Click(object sender, EventArgs e)
        {
            SPISetup[4] = 0x03;  //crystal frequency / 128
        }

        private void loadSettingsToMicrocontrolerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            serialPort1.BaseStream.WriteByte(0xAA);  //hlavicka
            for (int count = 0; count < 5; count++)
            {
                serialPort1.BaseStream.WriteByte(SPISetup[count]);  //hlavicka 
            }
        }

        private void sendAndRecieveDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBoxRecievedData.Text += "Jedna se o data pro senzor. Data se odeslou stisknutim tlacitka Send data. Odeslana data se opisi do okna Recieved data." + Environment.NewLine;
        }

        private void recievedDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBoxRecievedData.Text += "Zde se zobrazuji data ktera jsme odeslali a ktera jsme prijali. Námi odeslaná data u sebe nemají uveden čas příchodu. Data ze senzoru u sebe mají uveden čas." + Environment.NewLine;
        }

        private void communicationPanelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBoxRecievedData.Clear();
            textBoxRecievedData.Text += "Nastaveni komunikace se provadi pomoci volitelnych parametru v prvnim radku." + Environment.NewLine;
            textBoxRecievedData.Text += "Jake jsou prave nastavene parametry komunikace videme pomoci text boxu v druhem radku." + Environment.NewLine;
            textBoxRecievedData.Text += "Text box status na rika zda-li jsme uspesne otevreli komunikaci mezi programem a portem PC." + Environment.NewLine;
            textBoxRecievedData.Text += "XBee modul neumi nastavit pocet stop bitu, handshake a pocet datovych bitu." + Environment.NewLine;
            textBoxRecievedData.Text += "Data budou v tomto projektu posilany v ASCII kodu. Unicode je rezervovan pro budouci projekty." + Environment.NewLine;
            textBoxRecievedData.Text += "Data budou v tomto projektu posilany bez parity. Jine nastaveni je rezervovano pro budouci projekty." + Environment.NewLine;
        }

        private void xBeeChangeBaudRateUSARTToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBoxRecievedData.Text += "Tento prikaz meni komunikacni rychlost mezi mikrokontrolerem a modulem XBee." + Environment.NewLine;
        }

        private void sensorChangeBaudRateUSARTToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBoxRecievedData.Text += "Tento prikaz meni komunikacni rychlost mezi mikrokontrolerem a k nemu pripojenym senzorem." + Environment.NewLine;
        }

        private void sensorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBoxRecievedData.Text += "Tento prikaz povoluje nebo zakazuje preposilani dat prijatych ze senzoru do PC." + Environment.NewLine;
        }

        private void sensorSPIOptionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBoxRecievedData.Text += "Bit sequence: Zde se nastavuje MSB nebo LSB." + Environment.NewLine;
            textBoxRecievedData.Text += "Data stage and clock polarity: Zde se nastavuje faze dat a polarita hodin." + Environment.NewLine;
            textBoxRecievedData.Text += "Communication Speed: Zde se nastavuje rychlost komunikace. Jde o nasobky frekvence hodin mikrokontroleru ktere jsou mensi nez 1." + Environment.NewLine;
            textBoxRecievedData.Text += "Data: Tento prikaz povoluje nebo zakazuje preposilani dat prijatych ze senzoru do PC." + Environment.NewLine;
            textBoxRecievedData.Text += "Load settings to microcontroller: Tento prikaz nahraje do mikrokontroleru vsechny predchozi nastavene parametry v polozce SPI Options. Pokud tento prikaz nebude odeslan, parametry SPI jednotky nebudou zmeneny." + Environment.NewLine;
        }

        private void lEDDiodesToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            textBoxRecievedData.Text += "Pomoci tohoto prikazu lze rozsvitit nebo zhasnout LED diody." + Environment.NewLine;
        }

        private void testDataToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            textBoxRecievedData.Text += "Pomoci tohoto prikazu lze otestovat komunikaci mezi dvema XBee moduly. Na portu PC bychom meli zacit prijimat retezec cisel 0 az 9 porad dokola." + Environment.NewLine;
        }
        
    }
}
