Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

jxfdasilva

Delegates e eventos entre Form()

Recommended Posts

Caros forenses,

 

Estou encravado num problema e gostaria de ter a vossa ajuda. Tenho uma classe "public class NmeaInterpreter", aonde passo e recebo os eventos através de delegates/eventos:

 

//**********

public delegate void PositionReceivedEventHandler(string latitude, string longitude);

....

....

public event PositionReceivedEventHandler PositionReceived;

....

...

//************

 

Tenho mais dois Forms:

 

Form 2() - aonde ajusto a porta serial e faço o envios dos strings recebidos pelo GPS.

Form 1() - geral aonde analiso e recebo os valores e passo formatado para um TextBox.

 

Apesar de no Form1() tratar os eventos:

//****

NmeaInterpreter GPS = new NmeaInterpreter();

 

public Form1()
{
InitializeComponent();
GPS.PositionReceived += new NmeaInterpreter.PositionReceivedEventHandler(GPS_PositionReceived);

 

}

 

private void GPS_PositionReceived(string latitude, string longitude)
{
TestBox.Text = latitude.ToString();
}

 

//**************

- Eu não consigo ler nenhum valor nos TextBoxes! Alguma ideia?

 

Quando fasso o debug passo a passo, simplesmente reparo que ele ignora os metodos criados...

 

Outra coisa é, que se eu tiver apenas um Form() aonde trato os eventos e faço os ajustes das portas seriais, ele funciona... mas se quiser passar os dados/strings para outro Form(), não funciona! Aonde está o erro?

 

Obrigado pelo apoio

 

MC

 

Jose

Moçambique

 

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Bom dia Roberto,

 

Aqui vai o codigo da classe que faz o tratamento dos dados:

 


//*********************************************************************
//**  A high-precision NMEA interpreter
//**  Written by Jon Person, author of "GPS.NET" (www.gpsdotnet.com)
//*********************************************************************
using System;
using System.Globalization;
public class NmeaInterpreter
{
    // Represents the EN-US culture, used for numers in NMEA sentences
    public static CultureInfo NmeaCultureInfo = new CultureInfo("en-US");
    // Used to convert knots into miles per hour
    public static double MPHPerKnot = double.Parse("1.150779", NmeaCultureInfo);

    #region Delegates
    public delegate void PositionReceivedEventHandler(string latitude, string longitude);
    public delegate void DateTimeChangedEventHandler(System.DateTime dateTime);
    public delegate void BearingReceivedEventHandler(double bearing);
    public delegate void SpeedReceivedEventHandler(double speed);
    public delegate void SpeedLimitReachedEventHandler();
    public delegate void FixObtainedEventHandler();
    public delegate void FixLostEventHandler();
    public delegate void SatelliteReceivedEventHandler(int pseudoRandomCode, int azimuth, int elevation, int signalToNoiseRatio);
    public delegate void HDOPReceivedEventHandler(double value);
    public delegate void VDOPReceivedEventHandler(double value);
    public delegate void PDOPReceivedEventHandler(double value);
    public delegate void SatellitesInViewReceivedEventHandler(int value);
    public delegate void SatellitesUsedReceivedEventHandler(int value);
    public delegate void EllipsoidHeightReceivedEventHandler(double value);
    #endregion
   


    #region Events
    public event PositionReceivedEventHandler PositionReceived;
    public event DateTimeChangedEventHandler DateTimeChanged;
    public event BearingReceivedEventHandler BearingReceived;
    public event SpeedReceivedEventHandler SpeedReceived;
    public event SpeedLimitReachedEventHandler SpeedLimitReached;
    public event FixObtainedEventHandler FixObtained;
    public event FixLostEventHandler FixLost;
    public event SatelliteReceivedEventHandler SatelliteReceived;
    public event HDOPReceivedEventHandler HDOPReceived;
    public event VDOPReceivedEventHandler VDOPReceived;
    public event PDOPReceivedEventHandler PDOPReceived;
    public event SatellitesInViewReceivedEventHandler SatellitesInViewReceived;
    public event SatellitesUsedReceivedEventHandler SatellitesUsed;
    public event EllipsoidHeightReceivedEventHandler EllipsoidHeightReceived;
  #endregion

    // Processa a informação do Receptor GPS
    public bool Parse(string sentence)
    {
        // Discard the sentence if its checksum does not match our
        // calculated checksum
        if (!IsValid(sentence)) return false;
        // Look at the first word to decide where to go next
        switch (GetWords(sentence)[0])
        {
            case "$GPRMC":
                // A "Recommended Minimum" sentence was found!
                return ParseGPRMC(sentence);
            case "$GPGSV":
                // A "Satellites in View" sentence was recieved
                return ParseGPGSV(sentence);
            case "$GPGSA":
                return ParseGPGSA(sentence);
            case "$GPGGA":
                return ParseGPGGA(sentence);
            default:
                // Indicate that the sentence was not recognized
                return false;
        }
    }
    // Divide os dados em words individuais
    public string[] GetWords(string sentence)
    {
        //strip off the final * + checksum
        sentence = sentence.Substring(0, sentence.IndexOf("*"));
        //now split it up
        return sentence.Split(',');
    }
    // Interprets a $GPRMC message
    public bool ParseGPRMC(string sentence)
    {
        // Divide the sentence into words
        string[] Words = GetWords(sentence);
        // Do we have enough values to describe our location?
        if (Words[3] != "" & Words[4] != "" &
          Words[5] != "" & Words[6] != "")
        {
            // Yes. Extract latitude and longitude
            // Append hours
            string Latitude = Words[3].Substring(0, 2) + "°";
            // Append minutes
            Latitude = Latitude + Words[3].Substring(2) + "\"";
            // Append hours
            Latitude = Latitude + Words[4]; // Append the hemisphere
            string Longitude = Words[5].Substring(0, 3) + "°";
            // Append minutes
            Longitude = Longitude + Words[5].Substring(3) + "\"";
            // Append the hemisphere
            Longitude = Longitude + Words[6];
            // Notify the calling application of the change
            if (PositionReceived != null)
                PositionReceived(Latitude, Longitude);
        }
        // Do we have enough values to parse satellite-derived time?
        if (Words[1] != "")
        {
            // Yes. Extract hours, minutes, seconds and milliseconds
            int UtcHours = Convert.ToInt32(Words[1].Substring(0, 2));
            int UtcMinutes = Convert.ToInt32(Words[1].Substring(2, 2));
            int UtcSeconds = Convert.ToInt32(Words[1].Substring(4, 2));
            int UtcMilliseconds = 0;
            // Extract milliseconds if it is available
            if (Words[1].Length > 7)
            {
                UtcMilliseconds = Convert.ToInt32(Words[1].Substring(7));
            }
            // Now build a DateTime object with all values
            System.DateTime Today = System.DateTime.Now.ToUniversalTime();
            System.DateTime SatelliteTime = new System.DateTime(Today.Year,
              Today.Month, Today.Day, UtcHours, UtcMinutes, UtcSeconds,
              UtcMilliseconds);
            // Notify of the new time, adjusted to the local time zone
            if (DateTimeChanged != null)
                DateTimeChanged(SatelliteTime.ToLocalTime());
        }
        // Do we have enough information to extract the current speed?
        if (Words[7] != "")
        {
            // Yes.  Parse the speed and convert it to MPH
            double Speed = double.Parse(Words[7], NmeaCultureInfo) *
              MPHPerKnot;
            // Notify of the new speed
            if (SpeedReceived != null)
                SpeedReceived(Speed);
            // Are we over the highway speed limit?
            if (Speed > 55)
                if (SpeedLimitReached != null)
                    SpeedLimitReached();
        }
        // Do we have enough information to extract bearing?
        if (Words[8] != "")
        {
            // Indicate that the sentence was recognized
            double Bearing = double.Parse(Words[8], NmeaCultureInfo);
            if (BearingReceived != null)
                BearingReceived(Bearing);
        }
        // Does the device currently have a satellite fix?
        if (Words[2] != "")
        {
            switch (Words[2])
            {
                case "A":
                    if (FixObtained != null)
                        FixObtained();
                    break;
                case "V":
                    if (FixLost != null)
                        FixLost();
                    break;
            }
        }
        // Indicate that the sentence was recognized
        return true;
    }
    // Interprets a "Satellites in View" NMEA sentence
    public bool ParseGPGSV(string sentence)
    {
        int PseudoRandomCode = 0;
        int Azimuth = 0;
        int Elevation = 0;
        int SignalToNoiseRatio = 0;
        // Divide the sentence into words
        string[] Words = GetWords(sentence);
        // Each sentence contains four blocks of satellite information.
        // Read each block and report each satellite's information
        int Count = 0;
        for (Count = 1; Count <= 4; Count++)
        {
             // Do we have enough values to parse satellitesIinView?
            if (Words[3] != "")
            {
                if (SatellitesInViewReceived != null)
                    SatellitesInViewReceived(int.Parse(Words[3]));
      
            }   
                        
            // Does the sentence have enough words to analyze?
            if ((Words.Length - 1) >= (Count * 4 + 3))
            {
                // Yes.  Proceed with analyzing the block.
                // Does it contain any information?
                if (Words[Count * 4] != "" & Words[Count * 4 + 1] != ""
                  & Words[Count * 4 + 2] != "" & Words[Count * 4 + 3] != "")
                {
                    // Yes. Extract satellite information and report it
                    PseudoRandomCode = System.Convert.ToInt32(Words[Count * 4]);
                    Elevation = Convert.ToInt32(Words[Count * 4 + 1]);
                    Azimuth = Convert.ToInt32(Words[Count * 4 + 2]);
                    SignalToNoiseRatio = Convert.ToInt32(Words[Count * 4 + 3]);
                    // Notify of this satellite's information
                    if (SatelliteReceived != null)
                        SatelliteReceived(PseudoRandomCode, Azimuth,
                        Elevation, SignalToNoiseRatio);
                }
            }
        }
        // Indicate that the sentence was recognized
        return true;
    }
    // Interprets a "Fixed Satellites and DOP" NMEA sentence
    public bool ParseGPGSA(string sentence)
    {
        // Divide the sentence into words
        string[] Words = GetWords(sentence);
        // Update the DOP values
        if (Words[15] != "")
        {
            if (PDOPReceived != null)
                PDOPReceived(double.Parse(Words[15], NmeaCultureInfo));
        }
        if (Words[16] != "")
        {
            if (HDOPReceived != null)
                HDOPReceived(double.Parse(Words[16], NmeaCultureInfo));
        }
        if (Words[17] != "")
        {
            if (VDOPReceived != null)
                VDOPReceived(double.Parse(Words[17], NmeaCultureInfo));
        }
        return true;
    }
    // Returns True if a sentence's checksum matches the

    //  Interprets a $GPGGA message
    public bool ParseGPGGA(string sentence)
    {
        // Divide the sentence into words
        string[] Words = GetWords(sentence);
        // Satellites Used
        if (Words[7] != "")
        {
            if (SatellitesUsed != null)
                SatellitesUsed(int.Parse(Words[7]));
        }
        if (Words[8] != "")
        {
            if (HDOPReceived != null)
                HDOPReceived(double.Parse(Words[8], NmeaCultureInfo));
        }

        if (Words[9] != "")
        {
            if (EllipsoidHeightReceived != null)
                EllipsoidHeightReceived(double.Parse(Words[9]));
        }
        //

       return true;
    }
    // Returns True if a sentence's checksum matches the

    // calculated checksum
    public bool IsValid(string sentence)
    {
        // Compare the characters after the asterisk to the calculation
        return sentence.Substring(sentence.IndexOf("*") + 1) ==
          GetChecksum(sentence);
    }
    // Calculates the checksum for a sentence
    public string GetChecksum(string sentence)
    {
        // Loop through all chars to get a checksum
        int Checksum = 0;
        foreach (char Character in sentence)
        {
            if (Character == '$')
            {
                // Ignore the dollar sign
            }
            else if (Character == '*')
            {
                // Stop processing before the asterisk
                break;
            }
            else
            {
                // Is this the first value for the checksum?
                if (Checksum == 0)
                {
                    // Yes. Set the checksum to the value
                    Checksum = Convert.ToByte(Character);
                }
                else
                {
                    // No. XOR the checksum with this character's value
                    Checksum = Checksum ^ Convert.ToByte(Character);
                }
            }
        }
        // Return the checksum formatted as a two-character hexadecimal
        return Checksum.ToString("X2");
    }
}

 

 

//******************************************************************************************************************

//******************************************************************************************************************

//*******Aqui vai o Form 1 que funciona. Faz tratamento de dados, serial port, e recebe nos TextBox ***********

 

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using NMEA2OSGdemo.Properties;

namespace NMEA2OSGdemo
{
    public partial class Form1 : Form
    {
        #region declarations
        // NMEA interpreter
        NmeaInterpreter GPS = new NmeaInterpreter();
        // OSGridConverter
        NMEA2OSG OSGconv = new NMEA2OSG();
        
        // The main control for communicating through the RS-232 port
        private SerialPort comport = new SerialPort("COM1", 4800, Parity.None, 8, StopBits.One);
        public string[] gpsString;
        public string instring;
        public string[] nrthest;
        public double ellipHeight;

        #endregion

        public Form1()
        {
            // Build the form
            InitializeComponent();
            // Restore the users settings
           InitialiseControlValues();

            comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

            GPS.PositionReceived += new NmeaInterpreter.PositionReceivedEventHandler(GPS_PositionReceived);
            GPS.SatellitesInViewReceived += new NmeaInterpreter.SatellitesInViewReceivedEventHandler(GPS_SatellitesInViewReceived);
            GPS.SatellitesUsed += new NmeaInterpreter.SatellitesUsedReceivedEventHandler(GPS_SatellitesUsed);
            GPS.SpeedReceived += new NmeaInterpreter.SpeedReceivedEventHandler(GPS_SpeedReceived);
            GPS.BearingReceived += new NmeaInterpreter.BearingReceivedEventHandler(GPS_BearingReceived);
            GPS.FixLost += new NmeaInterpreter.FixLostEventHandler(GPS_FixLost);
            GPS.FixObtained += new NmeaInterpreter.FixObtainedEventHandler(GPS_FixObtained);
            GPS.HDOPReceived += new NmeaInterpreter.HDOPReceivedEventHandler(GPS_HDOPReceived);
            GPS.EllipsoidHeightReceived += new NmeaInterpreter.EllipsoidHeightReceivedEventHandler(GPS_EllipsoidHeightReceived);
            GPS.SatelliteReceived += new NmeaInterpreter.SatelliteReceivedEventHandler(GPS_SatReceiveDados);
            OSGconv.NorthingEastingReceived += new NMEA2OSG.NorthingEastingReceivedEventHandler(OSGconv_NorthingEastingReceived);
            OSGconv.NatGridRefReceived += new NMEA2OSG.NatGridRefReceivedEventHandler(OSGconv_NatGridRefReceived);
        }

        
        #region serialport
        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
           // This method will be called when there is data waiting in the port's buffer
           // Read all the data waiting in the buffer and pasrse it

            /* http://forums.microsoft.com/MSDN/ShowPost.aspx?PageIndex=2&SiteID=1&PostID=293187
             * You would need to use Control.Invoke() to update the GUI controls
             * because unlike Windows Forms events like Button.Click which are processed
             * in the GUI thread, SerialPort events are processed in a non-GUI thread
             * (more precisely a ThreadPool thread).
             */
            this.Invoke(new EventHandler(HandleGPSstring));
        }
        private void HandleGPSstring(object s, EventArgs e)
        {
            string inbuff;
            inbuff = comport.ReadExisting();
            if (inbuff != null)
            {
                if (inbuff.StartsWith("$"))
                {
                    instring = inbuff;
                }
                else
                {
                    instring += inbuff;
                }
                gpsString = instring.Split();
                foreach (string item in gpsString) GPS.Parse(item);/////envia GPS sentence a classe NmeaInterpreter**********
            }
        }
        #endregion
        
        private void InitialiseControlValues()
        {
            cmbParity.Items.Clear(); cmbParity.Items.AddRange(Enum.GetNames(typeof(Parity)));
            cmbStopBits.Items.Clear(); cmbStopBits.Items.AddRange(Enum.GetNames(typeof(StopBits)));

            cmbParity.Text = Settings.Default.Parity.ToString();
            cmbStopBits.Text = Settings.Default.StopBits.ToString();
            cmbDataBits.Text = Settings.Default.DataBits.ToString();
            cmbParity.Text = Settings.Default.Parity.ToString();
            cmbBaudRate.Text = Settings.Default.BaudRate.ToString();
            
            cmbPortName.Items.Clear();
            foreach (string s in SerialPort.GetPortNames())
                cmbPortName.Items.Add(s);

            if (cmbPortName.Items.Count > 0) cmbPortName.SelectedIndex = 0;
            else
            {
                MessageBox.Show(this, "There are no COM Ports detected on this computer.\nPlease install a COM Port and restart this app.", "No COM Ports Installed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (comport.IsOpen)
            {
                comport.Close();
                button1.Text = "Open Port";
            }
            else
            {
                // Set the port's settings
                comport.BaudRate = int.Parse(cmbBaudRate.Text);
                comport.DataBits = int.Parse(cmbDataBits.Text);
                comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);
                comport.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);
                comport.PortName = cmbPortName.Text;

                // Open the port
                comport.Open();
                button1.Text = "Close Port";
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            ExitProg();
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            ExitProg();
        }
        private void ExitProg()
        {
            if (comport.IsOpen) comport.Close();
            Environment.Exit(0);
        }

        #region GPS data recebido e tratado na public class NmeaInterpreter

        private void GPS_SatReceiveDados(int pseudoRandomCode, int azimuth, int elevation, int signalToNoiseRatio)
        {
            textBox3.Text = azimuth.ToString();
        }


        private void GPS_PositionReceived(string Lat, string Lon)
        {
            textBoxLat.Text = Lat;
            textBoxLon.Text = Lon;
            
            //convert to OS grid
            if (OSGconv.ParseNMEA(Lat, Lon, ellipHeight))
            {
                //display decimal values of lat and lon
                textBox1.Text = Convert.ToString(OSGconv.deciLat);
                textBox2.Text = Convert.ToString(OSGconv.deciLon);
            }
        }

        private void GPS_SatellitesInViewReceived(int SatInView)
        {
            textBoxSatInView.Text = Convert.ToString(SatInView);
        }

        private void GPS_SatellitesUsed(int SatInUse)
        {
            textBoxSatInUse.Text = Convert.ToString(SatInUse);
        }

        private void GPS_SpeedReceived(double Speed)
        {
            textBoxSpeed.Text = Convert.ToString(Speed);
        }

        private void GPS_BearingReceived(double Bearing)
        {
            textBoxBearing.Text = Convert.ToString(Bearing);
        }
        
        void GPS_FixLost()
        {
            textBoxFix.Text = "Lost";
        }

        void GPS_FixObtained()
        {
            textBoxFix.Text = "Obtained";
        }

        void GPS_HDOPReceived(double value)
        {
            textBoxHDOP.Text = Convert.ToString(value);
        }

        void GPS_EllipsoidHeightReceived(double value)
        {
            ellipHeight = value;
            textBoxEllipsoidHeight.Text = Convert.ToString(ellipHeight);
        }
        
        #endregion

        #region OSGconv data

        void OSGconv_NatGridRefReceived(string ngr)
        {
            textBoxGridRef.Text = ngr;
        }

        void OSGconv_NorthingEastingReceived(double northing, double easting)
        {
            textBoxNorthing.Text = Convert.ToString(northing);
            textBoxEasting.Text = Convert.ToString(easting);
        }

        #endregion

        private void button3_Click(object sender, EventArgs e)
        {
            Form2 form2 =new Form2();
            form2.Show();
        }

      
    }
}

 

 

//******************************************************************************************************************

//*****************************************************************************************************************

//************* Aqui vai o 2º Form que deveria receber os dados mas que não funciona ******************

 

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using NMEA2OSGdemo.Properties;




namespace NMEA2OSGdemo
{
    public partial class Form2 : Form
    {

        NmeaInterpreter GPS = new NmeaInterpreter();
        NMEA2OSG OSGconv = new NMEA2OSG();

        public Form2()
        {
            InitializeComponent();
            this.GPS.SatelliteReceived += new NmeaInterpreter.SatelliteReceivedEventHandler(GPS_SatReceiveDados);
        }


  //**********************Não funciona! ****************

        private void GPS_SatReceiveDados(int pseudoRandomCode, int azimuth, int elevation, int signalToNoiseRatio)
        {
          this.textBox1.Text = pseudoRandomCode.ToString();
           textBox2.Text = azimuth.ToString();
        }
   
    }
}

 

 

Existe uma terceira classe mas que não faz falta para a analise que pretendemos.

 

Abraço

 

Jose

Moçambique

Compartilhar este post


Link para o post
Compartilhar em outros sites

Bom dia,

 

No Form2() eu quero instanciar e criar os métodos que recebam valores dos eventos gerados na Class:

 

public class NmeaInterpreter

 

 

Acontece que eu só consigo receber se fizer no Form() aonde está o tratamento das Portas Seriais. Fora daí fica complicado.

 

Gostaria de entender o porquê e se existe uma forma de contornar.

 

Abraço

 

Jose

Compartilhar este post


Link para o post
Compartilhar em outros sites

Então, existem algumas restrições quanto a passagem de dados de um objeto para o outro, verifique se suas variáveis estão com o modificador public ou static, pois só assim elas serão acessíveis entre objetos.

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.