private void bt_closeall_Click(object sender, EventArgs e)
        {

            try
            {
                UDPComm.oktoReceive = false;

                closeThread(tstartMissonPlannerConn);
                closeThread(tstartmyServerConn);
                closeThread(tstartTrimaresConn);
                closeThread(tstartExoReadings);
                closeThread(Treadings);


                if (TCPClientConn != null)
                    TCPClientConn = null;

                if (TCPClientData != null)
                    TCPClientData = null;


                if (TCPMavLinkClient != null)
                    TCPMavLinkClient = null;

                            

                if (TrimaresUDPServerConn != null)
                    TrimaresUDPServerConn = null;

                if (TrimaresUDPServerData != null)
                    TrimaresUDPServerData = null;

                if (TrimaresUDPMavLinkServer != null)
                    TrimaresUDPMavLinkServer = null;
            }
            catch { }


            
            //Application.ExitThread();
            //Application.Exit(); 
        }
        public MsgRouter()
        {
            try
            {
                InitializeComponent();
                ListBox.CheckForIllegalCrossThreadCalls = false;
                PropertyGrid.CheckForIllegalCrossThreadCalls = false;
                listBox1.Items.Clear();
            }
            catch (Exception ex) 
            {
                MessageBox.Show(ex.ToString());
            }


            try
            {

              //  DevExpress.Data.CurrencyDataController.DisableThreadingProblemsDetection = true;
              //  DevExpress.XtraGrid.GridControl.CheckForIllegalCrossThreadCalls = false;


                TCPClientData = new MainCrossData();
                TCPClientData.myLink.BaseStream.BaudRate = 115200;


                string[] portnames = MAVcomm.Comms.SerialPort.GetPortNames();


                if (portnames.Length == 0)
                {
                    listBox1.Items.Add("ardupilot not found, going on as fake robot...");
                    Thread.Sleep(1000);
                    //   Thread.CurrentThread.Abort();
                }
                else
                {
                    gb_simulador.Enabled = true;
                   // gb_tcpclient.Enabled = false;
                   //' gb_realtrimares.Enabled = false;
                    tx_APcomport.Text = portnames[0];
                   // cbCType.Text = cbCType.Items[0].ToString();
                    //  ClientData.comPortName = cbCType.Text;
                    //  ClientData.myLink.BaseStream.PortName = ClientData.comPortName;
                }




            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }



        }
        /// <summary>
        /// inicializa comunicacao do router com o trimares
        /// </summary>
        private void startTrimaresConn()
        {
            try
            {
                TrimaresServer = new MAVcomm.Comms.UdpSerialServer();
                TrimaresServer.HostIP = tx_udpIP.Text;
                TrimaresServer.Port = tx_udpport.Text;
                TrimaresServer.newMsg += TrimaresUDP_PacketReceived;
                TrimaresServer.Open();
                TrimaresServer.rMessage += showMessages;
                //TrimaresUDPServerData = new MainCrossData();
                //TrimaresUDPServerConn = new MavLinkConnection("UDPSERVER", ref TrimaresUDPServerData);
                //TrimaresUDPServerConn.mydata.setMavlinkPointer(ref TrimaresUDPMavLinkServer);
                //TrimaresUDPServerConn.mydata.myLink.BaseStream.HostIP = tx_udpIP.Text;
                //TrimaresUDPServerConn.mydata.myLink.BaseStream.Port = tx_udpport.Text;
                //TrimaresUDPServerConn.PacketReceived += TrimaresUDP_PacketReceived;
                //TrimaresUDPServerConn.mydata.myLink.BaseStream.Open();
                //TrimaresUDPServerConn.mydata.myLink.BaseStream.rMessage += showMessages;
            }
            catch 
            {
                TrimaresServer.Close();
                TrimaresServer = null;

                TrimaresUDPMavLinkServer = null;
                TrimaresUDPServerData = null;
                TrimaresUDPServerConn = null;

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

            try
            {

                if (tstartMissonPlannerConn != null)
                {
                    tstartMissonPlannerConn.Abort();
                    Thread.Sleep(100);
                    tstartMissonPlannerConn = null;
                }

                closeThread(tstartMissonPlannerConn);
                closeThread(tstartmyServerConn);
                closeThread(tstartTrimaresConn);
                closeThread(tstartExoReadings);
                closeThread(Treadings);

                UDPComm.oktoReceive = false;

                if (MissionPlannerServer != null) 
                {
                    MissionPlannerServer.Close();
                    MissionPlannerServer = null;
                }

                if (TrimaresServer != null)
                {
                    TrimaresServer.Close();
                    TrimaresServer = null;
                }

                



                if (TCPClientConn != null)
                {
                    CloseStream(TCPClientConn.mydata.myLink.BaseStream);
                    TCPClientConn = null;
                }

                if (TCPMavLinkClient != null)
                {
                    TCPMavLinkClient = null;
                }

                if (TCPClientData != null)
                {
                    TCPClientData = null;
                }



                if (TrimaresUDPServerConn != null)
                {
                    CloseStream(TrimaresUDPServerConn.mydata.myLink.BaseStream);
                    TrimaresUDPServerConn = null;
                }

                if (TrimaresUDPServerData != null)
                    TrimaresUDPServerData = null;

                if (TrimaresUDPMavLinkServer != null)
                    TrimaresUDPMavLinkServer = null;

                foreach (Process p in System.Diagnostics.Process.GetProcessesByName("AP_Mavlink_router.exe"))
                {
                    p.Kill();
                    p.WaitForExit();
                }
            }
            catch 
            {
                Application.ExitThread();
                Application.Exit();
            }

            Application.ExitThread();
            Application.Exit();
         

        }
        void startAPMsimulation()
        {
            try
            {
                TrimaresUDPServerData = new MainCrossData();
                TrimaresUDPServerConn = new MavLinkConnection(tx_APcomport.Text, ref TrimaresUDPServerData);
                // TrimaresUDPServerConn.mydata.setMavlinkPointer(ref TrimaresUDPMavLinkServer);
                TrimaresUDPServerConn.connect();
                TrimaresUDPServerConn.PacketReceived += TrimaresUDP_PacketReceived;
               // TrimaresUDPServerConn.mydata.myLink.BaseStream.rMessage += showMessages;
                TrimaresUDPServerConn.mydata.myLink.requestDatastream(MAVLink.MAV_DATA_STREAM.ALL, MainCrossData.cs.rateattitude);
            }
            catch
            {
                TrimaresUDPMavLinkServer = null;
                TrimaresUDPServerData = null;
                TrimaresUDPServerConn = null;

            }

            //TCPClientData = new MainCrossData();
            //TCPClientConn = new MavLinkConnection(tx_APcomport.Text, ref TCPClientData);
            //TCPClientConn.mydata.setMavlinkPointer(ref TCPMavLinkClient);
            ////TCPClientConn.mydata.myLink.BaseStream.Open();

            //TCPClientConn.connect();

            //TCPClientConn.mydata.myLink.BaseStream.rMessage += showMessages;
            //TCPClientConn.PacketReceived += APSerialConn_PacketReceived; 
            //TCPClientData.myLink.requestDatastream(MAVLink.MAV_DATA_STREAM.ALL, MainCrossData.cs.rateattitude);



            gb_robot.Enabled = false;
        }
        private void bt_client_Click(object sender, EventArgs e)
        {
            try
            {
                TCPClientData = new MainCrossData();
                TCPClientConn = new MavLinkConnection("TCP", ref TCPClientData);
                TCPClientConn.mydata.setMavlinkPointer(ref TCPMavLinkClient);
                TCPClientConn.mydata.myLink.BaseStream.HostIP = tx_clientIP.Text;
                TCPClientConn.mydata.myLink.BaseStream.Port = tx_clientPort.Text;
                TCPClientConn.PacketReceived += APSerialConn_PacketReceived;
                TCPClientConn.mydata.myLink.BaseStream.Open();
                TCPClientConn.mydata.myLink.BaseStream.rMessage += showMessages;

                //MavLinkClient = new MAVLink();
                //MavLinkClient.DefaultConnection("TCP", 115200);
                //MavLinkClient.BaseStream.HostIP = tx_clientIP.Text;
                //MavLinkClient.BaseStream.Port = tx_clientPort.Text;
                //MavLinkClient.BaseStream.newMsg += Client_PacketReceived;
                //MavLinkClient.BaseStream.Open();

                gb_robot.Enabled = false;
            }
            catch { }


        }
       // private readonly ConnectionControl _connectionControl;



        public MavLinkConnection(string portName, ref MainCrossData mynewdata) 
        {
            mydata = mynewdata;
            mydata.comPortName = portName;
   

            if (portName == "TCP")
             {
                 mydata.myLink.DefaultConnection("TCP", 115200);
                 //MavLinkClient = new MAVLink();
                 //MavLinkClient.DefaultConnection("TCP", 115200);
                 //MavLinkClient.BaseStream.HostIP = tx_clientIP.Text;
                 //MavLinkClient.BaseStream.Port = tx_clientPort.Text;
                 //MavLinkClient.BaseStream.newMsg += Client_PacketReceived;
                 //MavLinkClient.BaseStream.Open();
                 //if (mydata.comPortName == "TCP")
                 //    mydata.myLink.BaseStream = new UdpSerial();
               // mydata.myLink.DefaultConnection("TCPSERVER", 115200); // BaseStream = new TCPCommServer();                 
                mydata.myLink.BaseStream.newMsg+=BaseStream_newMsg;
               // mydata.myLink.BaseStream.Open();
          
             }
            else if (portName == "UDP")
            {
                mydata.myLink.BaseStream = new MAVcomm.Comms.UdpSerial();
            //    mydata.myLink.DefaultConnection("UDP", 115200);
                mydata.myLink.BaseStream.newMsg += BaseStream_newMsg;
            }
            else if (portName == "UDPSERVER")
            {
                mydata.myLink.BaseStream = new MAVcomm.Comms.UdpSerialServer();
                mydata.myLink.BaseStream.BaudRate = 115200;
                mydata.myLink.BaseStream.newMsg += BaseStream_newMsg;
            }
            else
            {
                mydata.myLink.BaseStream = new MAVcomm.Comms.SerialPort();
            }

            try
            {
                mydata.myLink.BaseStream.PortName = portName;

                mydata.myLink.BaseStream.BaudRate = 115200;

                // check for saved baud rate and restore
                if (mydata.config[portName + "_BAUD"] != null)
                {
                    Console.WriteLine(mydata.config[portName + "_BAUD"].ToString());
                }
            }
            catch { }

            if (mydata.comPortName == "TCP" || mydata.comPortName == "TCPSERVER" || mydata.comPortName == "UDPSERVER")
            {
              //  mydata.myLink.BaseStream.newMsgReceived += BaseStream_newMsg;
                new Thread(sendOneHBperSecond)
                {
                    IsBackground = true,
                    Name = "one hb per sec",
                    Priority = ThreadPriority.BelowNormal,
                }.Start();


                return;
            }

            // setup main serial reader
            new Thread(SerialReader)
            {
                IsBackground = true,
                Name = "Main Serial reader",
                Priority = ThreadPriority.AboveNormal
            }.Start();


        }
        public MavLinkConnection(string portName, ref MainCrossData mynewdata, string serverport)
        {
            mydata = mynewdata;
            mydata.comPortName = portName;


            switch (portName) 
            {
                case "TCPSERVER":
                    mydata.myLink.DefaultConnection(portName, 115200);
                    mydata.myLink.BaseStream.Port = serverport;
                    mydata.myLink.BaseStream.Open();
                    mydata.myLink.BaseStream.newMsg += BaseStream_newMsg;
                    break;
                case "UDP":
                    mydata.myLink.BaseStream = new MAVcomm.Comms.UdpSerial(serverport, 14550);
                    //    mydata.myLink.DefaultConnection("UDP", 115200);
                    mydata.myLink.BaseStream.newMsg += BaseStream_newMsg;
                    break;
                default:
                    //throw new Exception("PORTA NAO ABERTA - NAO E SERVIDOR TCP");
                    break;
            }



            //try
            //{
            //   // mydata.myLink.BaseStream.PortName = portName;

            //    //mydata.myLink.BaseStream.BaudRate = 115200;

            //    // check for saved baud rate and restore
            //    //if (mydata.config[portName + "_BAUD"] != null)
            //    //{
            //    //    Console.WriteLine(mydata.config[portName + "_BAUD"].ToString());
            //    //}
            //}
            //catch { }

            if (mydata.comPortName == "UDP" || mydata.comPortName == "TCP" || mydata.comPortName == "TCPSERVER")
            {
                //  mydata.myLink.BaseStream.newMsgReceived += BaseStream_newMsg;
                runingthread = new Thread(sendOneHBperSecond);
                runingthread.IsBackground = true;
                runingthread.Priority = ThreadPriority.AboveNormal;
                runingthread.Start();

                return;
            }

            // setup main serial reader
            runingthread = new Thread(SerialReader);
            runingthread.IsBackground = true;
            runingthread.Priority = ThreadPriority.AboveNormal;
            runingthread.Start();


        }
 public MavLinkConnection() 
 {
     mydata = new MainCrossData();
 }