Beispiel #1
0
        private void Parse(int sourceID, string message)
        {
            NMEAIncomingMessageReceived.Rise(this, new NMEAMessageEventArgs(sourceID, message));

            try
            {
                var pResult = NMEAParser.Parse(message);

                if (pResult is NMEAStandartSentence)
                {
                    NMEAStandartSentence sentence = (NMEAStandartSentence)pResult;
                    if (standardSenteceParsers.ContainsKey(sentence.SentenceID))
                    {
                        standardSenteceParsers[sentence.SentenceID](sourceID, sentence.TalkerID, sentence.parameters);
                    }
                    else
                    {
                        NMEAStandartUnsupportedSentenceParsed.Rise(this, new NMEAUnsupportedStandartEventArgs(sourceID, sentence));
                    }
                }
                else
                {
                    NMEAProprietaryUnsupportedSentenceParsed.Rise(this, new NMEAUnsupportedProprietaryEventArgs(sourceID, (pResult as NMEAProprietarySentence)));
                }
            }
            catch (Exception ex)
            {
                LogEventHandler.Rise(this, new LogEventArgs(LogLineType.ERROR, ex));
            }
        }
Beispiel #2
0
    private void OnReadFinished(string result)
    {
        string[] separators = { "\r\n" };
        var      sentences  = result.Split(separators, System.StringSplitOptions.RemoveEmptyEntries).ToList();

        foreach (var sentence in sentences)
        {
            var nmeaResult = parser.Parse(sentence);
            if (nmeaResult != null)
            {
                // the GoogleMap script from the asset store will pull new images every time we call refresh,
                // so we avoid this when the position is static to not get 403

                if (nmeaResult.Type == ResultType.Postion &&
                    Vector2.Distance(new Vector2(nmeaResult.Lat, nmeaResult.Lon), new Vector2(lastPositionResult.Lat, lastPositionResult.Lon)) != 0)
                {
                    googleMapComponent.centerLocation.latitude  = nmeaResult.Lat;
                    googleMapComponent.centerLocation.longitude = nmeaResult.Lon;
                    lastPositionResult = nmeaResult;

                    // we have to do the refresh on the map from the main thread, so we store a reference here to do it in the next frame
                    refreshMapObject = true;
                }
                else if (nmeaResult.Type == ResultType.Heading)
                {
                    // same here, we can not access the transform of a game object from outside the main thread
                    lastHeadingResult = nmeaResult;
                }
            }
        }

        status = RequestStatus.READY;
    }
Beispiel #3
0
        public void WXTMsgTest()
        {
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            string message      = "$WIXDR,A,204,D,0,A,219,D,1,A,248,D,2,S,0.9,M,0,S,1.2,M,1,S,1.6,M,2*5A" + Environment.NewLine;
            var    nmeaSentence = NMEAParser.Parse(message);

            stopWatch.Stop();
            Debug.WriteLine("Time 1:" + stopWatch.ElapsedTicks);

            var tmp                 = (NMEAStandardSentence)nmeaSentence;
            var talkerID            = tmp.TalkerID;
            var sentenceIdentifiers = tmp.SentenceID;


            stopWatch.Start();
            message      = "$WIXDR,C,22.7,C,0,H,41.5,P,0,P,1017.7,H,0*79" + Environment.NewLine;
            nmeaSentence = NMEAParser.Parse(message);
            stopWatch.Stop();
            Debug.WriteLine("Time 2:" + stopWatch.ElapsedTicks);

            stopWatch.Start();
            message      = "$WIXDR,A,204,D,0,A,219,D,1,A,248,D,2,S,0.9,M,0,S,1.2,M,1,S,1.6,M,2*5A" + Environment.NewLine;
            nmeaSentence = NMEAParser.Parse(message);
            stopWatch.Stop();
            Debug.WriteLine("Time 3:" + stopWatch.ElapsedTicks);
        }
Beispiel #4
0
        public void ParseGPGGAStringWithNullField()
        {
            string str = "$GPGGA,,,,,,,,,,,99.99,M,,*35";

            var parser = new NMEAParser();
            var res    = parser.Parse(str);

            FixData data = (FixData)res;
        }
Beispiel #5
0
        public void Parse_FourSatelliteData_FourListLength()
        {
            string testData      = "$GPGSV,3,1,12,30,72,253,36,05,70,124,42,24,37,082,43,02,37,112,45*76";
            int    expectedCount = 4;

            var entityList = NMEAParser.Parse(new List <string>(new string[] { testData })).Key.ToList();

            Assert.AreEqual(expectedCount, entityList.Count);
        }
Beispiel #6
0
        public void Parse_OneSatelliteData_OneListLength()
        {
            string testData      = "$GPGSV,3,1,12,30,72,253,36,,,,,,,,,,,,*76";
            int    expectedCount = 1;

            var entityList = NMEAParser.Parse(new List <string>(new string[] { testData })).Key.ToList();

            Assert.AreEqual(expectedCount, entityList.Count);
        }
Beispiel #7
0
        private void port_NewNMEAMessage(object sender, NewNMEAMessageEventArgs e)
        {
            try
            {
                var sentence = NMEAParser.Parse(e.Message);

                if (sentence is NMEAProprietarySentence)
                {
                    NMEAProprietarySentence snt = ((NMEAProprietarySentence)(sentence));

                    if (snt.SentenceIDString == "0")
                    {
                        // ACK - analyze error code
                        Process_ACK(snt.parameters);
                    }
                    else if (snt.SentenceIDString == "5")
                    {
                        // local data value
                        Process_LOC_DATA(snt.parameters);
                    }
                    else if (snt.SentenceIDString == "3")
                    {
                        // settings field value
                        Process_FLD_Value(snt.parameters);
                    }
                    else if (snt.SentenceIDString == "!")
                    {
                        // device info
                        Process_DEVICE_INFO(snt.parameters);
                    }
                    else if (snt.SentenceIDString == "!!")
                    {
                        Process_DEVICE_INFO_RN(snt.parameters);
                    }
                    else if (snt.SentenceIDString == "I")
                    {
                        // track point val
                        Process_TRACK_POINT_VAL(snt.parameters);
                    }
                    else if (snt.SentenceIDString == "L")
                    {
                        // waypoint value
                        Process_WAYPOINT_VAL(snt.parameters);
                    }
                }
                else
                {
                    // TODO: write log
                }
            }
            catch (Exception ex)
            {
                // TODO: write log
            }
        }
Beispiel #8
0
        public void ParseGPVTGString()
        {
            string str    = "$GPVTG,055.7,T,034.4,M,005.5,N,010.2,K*49";
            var    parser = new NMEAParser();
            var    res    = parser.Parse(str);

            CourseData data = (CourseData)res;

            Assert.AreEqual(55.7, data.COG);
            Assert.AreEqual(5.5, data.KnotSOG);
            Assert.AreEqual(10.2, data.KphSOG);
        }
Beispiel #9
0
        public void ParseGPGGAStringFalseChecksum()
        {
            string str    = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*12";
            var    parser = new NMEAParser();

            try
            {
                var res = parser.Parse(str);
                Assert.Fail("Parsing message with invalid checksum should fail");
            }
            catch (Legacy.InvalidChecksumException)
            {
            }
        }
Beispiel #10
0
        public void ParseUnknownNMEAString()
        {
            string str    = "$GPABC,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*46";
            var    parser = new NMEAParser();

            try
            {
                var res = parser.Parse(str);
                Assert.Fail("Parsing message with unknown message type should fail");
            }
            catch (Legacy.UnknownMessageException)
            {
            }
        }
Beispiel #11
0
        public MeasMsg Parse(string message)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(message))
                {
                    return(null);
                }

                //   Debug.WriteLine("Parsing AWAC message:" + message);

                int dollarIndex = message.IndexOf("$");
                if (dollarIndex == -1)
                {
                    return(null);
                }

                int crLfIndex = message.IndexOf("/r/n");
                if (crLfIndex == -1)
                {
                    message = message + Environment.NewLine;
                }

                if (nameDictionary.Count == 0)
                {
                    InitDictionary();
                }

                int index = message.IndexOf("$PN");
                if (index == -1)
                {
                    return(null);
                }
                if (index > 0)
                {
                    message = message.Substring(index);
                }



                NMEAProprietarySentence nmeaSentence = (NMEAParser.Parse(message)) as NMEAProprietarySentence;
                return(ParseMsg(nmeaSentence));
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandleException(ex, "Error while parsing NMEA message." + message);
                return(null);
            }
        }
Beispiel #12
0
        void PortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
        {
            int bytesToRead = _port.BytesToRead;
            var buffer      = new byte[bytesToRead];

            _port.Read(buffer, 0, bytesToRead);

            var dataString = Encoding.ASCII.GetString(buffer);

            _buffer.Append(dataString);

            var temp = _buffer.ToString();

            int lIndex = temp.LastIndexOf(NMEAParser.SentenceEndDelimiter, StringComparison.InvariantCulture);

            if (lIndex >= 0)
            {
                _buffer = _buffer.Remove(0, lIndex + 2);
                if (lIndex + 2 < temp.Length)
                {
                    temp = temp.Remove(lIndex + 2);
                }

                temp = temp.Trim(_kTrimZeroChar);

                var lines = temp.Split(new[] { NMEAParser.SentenceEndDelimiter }, StringSplitOptions.RemoveEmptyEntries)
                            .Select(x => x + NMEAParser.SentenceEndDelimiter);

                foreach (var line in lines)
                {
                    try
                    {
                        var result = NMEAParser.Parse(line);
                        ProcessNMEASentence(result);
                    }
                    catch
                    {
                        // TODO errors
                    }
                }
            }

            if (_buffer.Length >= _port.ReadBufferSize * 2)
            {
                _buffer.Remove(0, _port.ReadBufferSize);
            }
        }
Beispiel #13
0
        private void port_NewNMEAMessage(object sender, NewNMEAMessageEventArgs e)
        {
            InvokeAppendText(commLogTxb, logger.Write(string.Format(">> {0}", e.Message)));
            try
            {
                var parseResult = NMEAParser.Parse(e.Message);

                if (parseResult is NMEAProprietarySentence)
                {
                    NMEAProprietarySentence pSentence = (parseResult as NMEAProprietarySentence);

                    if (pSentence.Manufacturer == ManufacturerCodes.TNT)
                    {
                        if (pSentence.SentenceIDString == "!")
                        {
                            Parse_DEVICE_INFO(pSentence.parameters);
                        }
                        else if (pSentence.SentenceIDString == "0")
                        {
                            Parse_ACK(pSentence.parameters);
                        }
                        else if (pSentence.SentenceIDString == "5")
                        {
                            Parse_LOC_DATA_VAL(pSentence.parameters);
                        }
                        else if (pSentence.SentenceIDString == "9")
                        {
                            Parse_SETTINGS(pSentence.parameters);
                        }
                        else
                        {
                            InvokeAppendText(commLogTxb, logger.Write(string.Format("ERROR: Unsupported sentence: \"{0}\"", pSentence.SentenceIDString)));
                        }
                    }
                    else
                    {
                        InvokeAppendText(commLogTxb, logger.Write(string.Format("ERROR: Unsupported manufacturer: \"{0}\"", pSentence.Manufacturer)));
                    }
                }
                else
                {
                    InvokeAppendText(commLogTxb, logger.Write(string.Format("ERROR: Unsupported sentence: \"{0}\"", (parseResult as NMEAStandartSentence).SentenceID)));
                }
            }
            catch (Exception ex) { InvokeAppendText(commLogTxb, logger.Write(ex)); }
        }
Beispiel #14
0
        private void port_NewNMEAMessage(object sender, NewNMEAMessageEventArgs e)
        {
            if (IsLogIncoming)
            {
                LogEventHandler.Rise(this, new LogEventArgs(LogLineType.INFO, string.Format("{0} ({1}) >> {2}", PortName, PortDescription, e.Message)));
            }

            try
            {
                var _result = NMEAParser.Parse(e.Message);
                ProcessIncoming(_result);
            }
            catch (Exception ex)
            {
                LogEventHandler.Rise(this, new LogEventArgs(LogLineType.ERROR, string.Format("{0} ({1}) >> {2} Caused error ({3})", PortName, PortDescription, e.Message, ex.Message)));
            }
        }
Beispiel #15
0
        private void port_NewNMEAMessage(object sender, NewNMEAMessageEventArgs e)
        {
            try
            {
                var parseResult = NMEAParser.Parse(e.Message);

                if (parseResult is NMEAProprietarySentence)
                {
                    NMEAProprietarySentence sentence = (parseResult as NMEAProprietarySentence);

                    if (sentence.Manufacturer == ManufacturerCodes.TNT)
                    {
                        if (sentence.SentenceIDString == "!")
                        {
                            // DEVICE INFO
                            DEVICE_INFO_Parse(sentence.parameters);
                        }
                        else if (sentence.SentenceIDString == "0")
                        {
                            // ACK
                            ACK_Parse(sentence.parameters);
                        }
                        else if (sentence.SentenceIDString == "5")
                        {
                            // LOC_DATA_VAL
                            LOC_DATA_VAL_Parse(sentence.parameters);
                        }
                        else if (sentence.SentenceIDString == "9")
                        {
                            // SETTINGS_VAL
                            SETTINGS_VAL_Parse(sentence.parameters);
                        }
                    }
                    else
                    {
                        // WTF?
                    }
                }
            }
            catch (Exception ex)
            {
                // WTF?
            }
        }
Beispiel #16
0
        public void Parse_ValidSatelliteData_ValidEntity()
        {
            string          testData       = "$GPGSV,3,2,12,04,32,058,44,,,,,,,,,,,,*71";
            SatelliteEntity expectedEntity = new SatelliteEntity()
            {
                PRN       = "04",
                Elevation = 32,
                Azimuth   = 58,
                SNR       = 44
            };

            var             entityList = NMEAParser.Parse(new List <string>(new string[] { testData })).Key.ToList();
            SatelliteEntity entity     = entityList[0];

            Assert.AreEqual(expectedEntity.PRN, entity.PRN);
            Assert.AreEqual(expectedEntity.Elevation, entity.Elevation);
            Assert.AreEqual(expectedEntity.Azimuth, entity.Azimuth);
            Assert.AreEqual(expectedEntity.SNR, entity.SNR);
        }
Beispiel #17
0
        public ActionResult Open(string fileName)
        {
            if (!String.IsNullOrEmpty(fileName))
            {
                var lines = FileHandler.Open(fileName);

                var entityList = NMEAParser.Parse(lines);

                NMEAModel model = new NMEAModel
                {
                    UserCoordinatesList = entityList.Value.ToList(),
                    SatelliteList       = GetSatelliteList(entityList.Key).ToList(),
                };

                return(Json(model));
            }

            return(Json(""));
        }
Beispiel #18
0
        private void port_MessageReceived(object sender, NewNMEAMessageEventArgs e)
        {
            NMEASentence sentence = null;
            bool         isParsed = false;

            try
            {
                sentence = NMEAParser.Parse(e.Message);
                isParsed = true;
            }
            catch (Exception ex)
            {
                /// TODO:
            }

            if (isParsed)
            {
                if (sentence is NMEAProprietarySentence)
                {
                    var pSentence = (sentence as NMEAProprietarySentence);
                    if (pSentence.Manufacturer == ManufacturerCodes.MCP)
                    {
                        if (parsers.ContainsKey(pSentence.SentenceIDString))
                        {
                            parsers[pSentence.SentenceIDString](pSentence.parameters);
                        }
                    }
                    else
                    {
                        /// TODO: skip unsupported manufacturer
                    }
                }
                else
                {
                    /// TODO: skip standard sentence
                }
            }
        }
Beispiel #19
0
        private void port_NewMessage(object sender, NewNMEAMessageEventArgs e)
        {
            try
            {
                var result = NMEAParser.Parse(e.Message);

                if (result is NMEAStandartSentence)
                {
                    var sResult = (result as NMEAStandartSentence);
                    if (cmdProcessor.ContainsKey(sResult.SentenceID))
                    {
                        cmdProcessor[sResult.SentenceID].Invoke(sResult.TalkerID, sResult.parameters);
                    }
                }
            }
            catch (Exception ex)
            {
                if (LogEvent != null)
                {
                    LogEvent(this, new LogEventArgs(LogLineType.ERROR, ex));
                }
            }
        }
Beispiel #20
0
        public void ParseGPGGAString()
        {
            string str    = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47";
            var    parser = new NMEAParser();
            var    res    = parser.Parse(str);

            FixData data = (FixData)res;

            Assert.AreEqual(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 12, 35, 19, 0), data.CurrentTime);
            Assert.AreEqual(48, data.Latitude.Value.Degree);
            Assert.AreEqual(7.038, data.Latitude.Value.Minutes);
            Assert.AreEqual(LatitudeDegree.DirectionType.North, data.Latitude.Value.Direction);

            Assert.AreEqual(11, data.Longitude.Value.Degree);
            Assert.AreEqual(31, data.Longitude.Value.Minutes);
            Assert.AreEqual(LongitudeDegree.DirectionType.East, data.Longitude.Value.Direction);

            Assert.AreEqual(8, data.SateliteUsed);
            Assert.AreEqual(0.9, data.HDOP);

            Assert.AreEqual(545.4, data.MeanSeaLevel);
            Assert.AreEqual(46.9, data.GeoidSeparation);
        }
Beispiel #21
0
        public void MNEAFormatTest()
        {
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            string message      = "$PNORI,3,WAV6103,3,20,0.51,2.00,0*16" + Environment.NewLine;
            var    nmeaSentence = NMEAParser.Parse(message);

            stopWatch.Stop();
            Debug.WriteLine("Time 1:" + stopWatch.ElapsedTicks);

            var tmp                 = (NMEAProprietarySentence)nmeaSentence;
            var talkerID            = tmp.Manufacturer;
            var sentenceIdentifiers = tmp.SentenceIDString;


            stopWatch.Start();
            message      = "$PNORS,073010,050000,00,B0,13.4,1520.6,114.9,-0.5,1.6,22.314,18.92,1039,0*0B" + Environment.NewLine;
            nmeaSentence = NMEAParser.Parse(message);
            stopWatch.Stop();
            Debug.WriteLine("Time 2:" + stopWatch.ElapsedTicks);

            stopWatch.Start();
            message      = "$PNORC,073010,050000,1,0.10,-0.11,-0.01,0.15,137.2,C,88,83,87,,,*37" + Environment.NewLine;
            nmeaSentence = NMEAParser.Parse(message);
            stopWatch.Stop();
            Debug.WriteLine("Time 3:" + stopWatch.ElapsedTicks);

            stopWatch.Start();
            message      = "$PNORC,073010,050000,2,0.15,-0.16,-0.02,0.22,138.1,C,76,71,74,,,*3D" + Environment.NewLine;
            nmeaSentence = NMEAParser.Parse(message);
            stopWatch.Stop();
            Debug.WriteLine("Time 3:" + stopWatch.ElapsedTicks);

            stopWatch.Start();
            message      = "$PNORW,073010,051001,3,4,0.55,0.51,0.63,0.82,2.76,3.33,2.97,55.06,78.91,337.62,0.48,22.35,0,1,0.27,129.11,0000*4E" + Environment.NewLine;
            nmeaSentence = NMEAParser.Parse(message);
            stopWatch.Stop();
            Debug.WriteLine("Time 3:" + stopWatch.ElapsedTicks);

            stopWatch.Start();
            message      = "$PNORE,073010,051001,3,0.02,0.01,98,0.000,0.000,0.000,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.002,0.002,0.002,0.002,0.002,0.002,0.003,0.003,0.004,0.006,0.010,0.023,0.049,0.091,0.162,0.176,0.213,0.179,0.160,0.104,0.097,0.072,0.056,0.036,0.032,0.034,0.040,0.032,0.028,0.021,0.017,0.017,0.014,0.012,0.009,0.011,0.010,0.012,0.009,0.010,0.009,0.007,0.006,0.007,0.007,0.008,0.007,0.006,0.005,0.004,0.004,0.003,0.003,0.003,0.003,0.002,0.003,0.003,0.002,0.002,0.002,0.002,0.002,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001,0.001*7E" + Environment.NewLine;
            nmeaSentence = NMEAParser.Parse(message);
            stopWatch.Stop();
            Debug.WriteLine("Time 3:" + stopWatch.ElapsedTicks);

            stopWatch.Start();
            message      = "$PNORB,073010,051001,3,4,0.02,0.20,0.06,7.06,5.00,262.39,80.27,23.39,0000*62" + Environment.NewLine;
            nmeaSentence = NMEAParser.Parse(message);
            stopWatch.Stop();
            Debug.WriteLine("Time 3:" + stopWatch.ElapsedTicks);

            stopWatch.Start();
            message      = "$PNORB,073010,051001,3,4,0.21,0.49,0.52,3.06,3.33,57.06,78.91,24.66,0000*50" + Environment.NewLine;
            nmeaSentence = NMEAParser.Parse(message);
            stopWatch.Stop();
            Debug.WriteLine("Time 3:" + stopWatch.ElapsedTicks);

            stopWatch.Start();
            message      = "$PNORF,A1,073010,051001,3,0.02,0.01,48,-0.0216,-0.0521,-0.0563,-0.0565,-0.0287,-0.0149,-0.0099,-0.0531,-0.0445,-0.0431,-0.0204,-0.0141,0.0697,0.0833,0.0540,0.0190,-0.0195,-0.0367,-0.0025,-0.0143,0.0318,-0.0307,-0.0051,0.0041,0.0440,0.0114,0.0831,0.0527,0.0284,0.0104,0.0040,0.0030,0.0049,-0.0005,0.0001,-0.0007,0.0018,0.0011,0.0012,0.0008,0.0029,0.0035,0.0021,-9.0000,-9.0000,-9.0000,-9.0000,-9.0000*0B" + Environment.NewLine;
            nmeaSentence = NMEAParser.Parse(message);
            stopWatch.Stop();
            Debug.WriteLine("Time 3:" + stopWatch.ElapsedTicks);
        }
Beispiel #22
0
        private void ParseTrackFromFile(string fileName)
        {
            bool          isOk  = false;
            List <string> lines = new List <string>();

            try
            {
                lines.AddRange(File.ReadAllLines(fileName));
                isOk = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            if (isOk)
            {
                track.Clear();

                foreach (var item in lines)
                {
                    if (item.Contains("$PTNTC"))
                    {
                        int wspIdx  = item.IndexOf(' ');
                        var timeStr = item.Substring(0, wspIdx);

                        var splits = timeStr.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                        int    hrs  = Convert.ToInt32(splits[0]);
                        int    mins = Convert.ToInt32(splits[1]);
                        double secs = Convert.ToDouble(splits[2], CultureInfo.InvariantCulture);
                        secs += mins * 60 + hrs * 3600;

                        int sIdx   = item.IndexOf("$PTNTC");
                        var subStr = item.Substring(sIdx);

                        if (!subStr.EndsWith("\r\n"))
                        {
                            subStr = subStr + "\r\n";
                        }

                        try
                        {
                            var pSentence = NMEAParser.Parse(subStr);
                            if (pSentence is NMEAProprietarySentence)
                            {
                                var ps = (pSentence as NMEAProprietarySentence);
                                if ((ps.Manufacturer == ManufacturerCodes.TNT) && (ps.SentenceIDString == "C"))
                                {
                                    TrackRecord newRecord = new TrackRecord();

                                    newRecord.Second = secs;

                                    newRecord.Location = new GeoPoint3DE((double)ps.parameters[0],
                                                                         (double)ps.parameters[1],
                                                                         (double)ps.parameters[2],
                                                                         (double)ps.parameters[3]);

                                    newRecord.Buoy0Location = new GeoPoint((double)ps.parameters[4], (double)ps.parameters[5]);
                                    newRecord.Buoy1Location = new GeoPoint((double)ps.parameters[6], (double)ps.parameters[7]);
                                    newRecord.Buoy2Location = new GeoPoint((double)ps.parameters[8], (double)ps.parameters[9]);
                                    newRecord.Buoy3Location = new GeoPoint((double)ps.parameters[10], (double)ps.parameters[11]);

                                    if (newRecord.Location.RadialError <= settingsProvider.Data.RadialErrorThreshold)
                                    {
                                        track.Add(newRecord);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }

                if (track.Count > 0)
                {
                    saveTrackToolStripMenuItem_Click(this, new EventArgs());
                }
            }
        }
        private async void OnIncomingData(string data)
        {
            _buffer.Append(data);
            var temp = _buffer.ToString();

            var lIndex = temp.LastIndexOf(NMEAParser.SentenceEndDelimiter, StringComparison.Ordinal);

            if (lIndex >= 0)
            {
                _buffer = _buffer.Remove(0, lIndex + 2);
                if (lIndex + 2 < temp.Length)
                {
                    temp = temp.Remove(lIndex + 2);
                }

                temp = temp.Trim('\0');

                var lines = temp.Split(NMEAParser.SentenceEndDelimiter.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                if (DateTime.Now > _nextCheck)
                {
                    foreach (var t in lines)
                    {
                        try
                        {
                            var result = NMEAParser.Parse(t + NMEAParser.SentenceEndDelimiter);

                            var sResult = result as NMEAStandartSentence;
                            if (sResult?.SentenceID == SentenceIdentifiers.GGA)
                            {
                                var parameters          = sResult.parameters;
                                var gpsQualityIndicator = (string)parameters[5];
                                if (gpsQualityIndicator != "Fix not availible")
                                {
                                    try
                                    {
                                        var lat        = _doubleNullChecker(parameters[1]);
                                        var northSouth = (string)(parameters[2] ?? string.Empty);
                                        Debug.WriteLine("{0} {1} {2} {3}", parameters[1], parameters[2], parameters[3], parameters[4]);
                                        lat = northSouth == "N" ? lat : -lat;
                                        var lon      = _doubleNullChecker(parameters[3]);
                                        var eastWest = (string)(parameters[4] ?? string.Empty);
                                        lon = eastWest == "E" ? lon : -lon;
                                        Debug.WriteLine("Lat: {0} Long: {1}", lat, lon);
                                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                        {
                                            UpdatePosition(lat, lon);
                                        });
                                    }
                                    catch (Exception)
                                    {
                                        // ignored
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex);
                        }
                    }
                    _nextCheck = DateTime.Now.AddSeconds(2);
                }
            }

            if (_buffer.Length >= ushort.MaxValue)
            {
                _buffer.Remove(0, short.MaxValue);
            }
        }
Beispiel #24
0
        private void DataReceivedEvent(object sender, SerialDataReceivedEventArgs e)
        {
            String inBuff;

            if (port.IsOpen)
            {
                inBuff = port.ReadExisting();
                if (inBuff != null)
                {
                    if (inBuff.StartsWith("$"))
                    {
                        inString = inBuff;
                    }
                    else
                    {
                        inString += inBuff;
                    }

                    if ((inString.StartsWith("$GPRMC") || inString.StartsWith("$GPGGA")) && inString.EndsWith("\r\n"))
                    {
                        try
                        {
                            NMEASentence sentence = NMEAParser.Parse(inString);
                            String       text     = "";
                            foreach (Object obj in sentence.parameters)
                            {
                                String outString;
                                if (obj == null)
                                {
                                    outString = "null";
                                }
                                else
                                {
                                    outString = obj.ToString();
                                }
                                text += outString + System.Environment.NewLine;
                            }

                            if (inString.StartsWith("$GPGGA"))
                            {
                                if (sentence.parameters[5].Equals("Fix not availible"))
                                {
                                    this.fix = false;
                                    this.setValue(-1f);
                                }
                                else
                                {
                                    this.fix = true;
                                }
                            }
                            else
                            {
                                if (fix)
                                {
                                    float f;
                                    float.TryParse(sentence.parameters[6].ToString(), out f);

                                    //Convert to m/s
                                    f = f * (463f / 900f);

                                    //Convert to km/h
                                    f = f * 3.6f;

                                    this.setValue(f);
                                    this.status = SensorStatus.CONNECTED;
                                }
                            }
                        }
                        catch (ArgumentException aex)
                        {
                            Console.WriteLine(inString, aex);
                        }
                    }
                }
            }
        }
Beispiel #25
0
        private void port_NewNMEAMessage(object sender, NewNMEAMessageEventArgs e)
        {
            if (LogEvent != null)
            {
                LogEvent(this, new LogEventArgs(LogLineType.INFO, string.Format("<< {0}", e.Message)));
            }

            try
            {
                var sentence = NMEAParser.Parse(e.Message);

                if (sentence is NMEAProprietarySentence)
                {
                    NMEAProprietarySentence snt = ((NMEAProprietarySentence)(sentence));

                    if (snt.SentenceIDString == "0")
                    {
                        // ACK - analyze error code
                        Process_ACK(snt.parameters);
                    }
                    else if (snt.SentenceIDString == "5")
                    {
                        // local data value
                        Process_LOC_DATA(snt.parameters);
                    }
                    else if (snt.SentenceIDString == "!")
                    {
                        // device info
                        Process_DEVICE_INFO(snt.parameters);
                    }
                    else if (snt.SentenceIDString == "C")
                    {
                        Process_FIX_UPDATE(snt.parameters);
                    }
                    else if (snt.SentenceIDString == "M")
                    {
                        Process_BUOYS_STATUS(snt.parameters);
                    }
                    else if (snt.SentenceIDString == "N")
                    {
                        Process_DPTTMP(snt.parameters);
                    }
                    else if (snt.SentenceIDString == "O")
                    {
                        Process_PRETMP(snt.parameters);
                    }
                    else
                    {
                        if (LogEvent != null)
                        {
                            LogEvent(this, new LogEventArgs(LogLineType.ERROR, string.Format("Unsupported sentence ID: {0}", snt.SentenceIDString)));
                        }
                    }
                }
                else
                {
                    NMEAStandartSentence snt = ((NMEAStandartSentence)(sentence));

                    if (snt.SentenceID == SentenceIdentifiers.GGA)
                    {
                        Process_GGA(snt.parameters);
                    }
                    else if (snt.SentenceID == SentenceIdentifiers.RMC)
                    {
                        Process_RMC(snt.parameters);
                    }
                    else if (snt.SentenceID == SentenceIdentifiers.MTW)
                    {
                        Process_MTW(snt.parameters);
                    }
                    else
                    {
                        if (LogEvent != null)
                        {
                            LogEvent(this, new LogEventArgs(LogLineType.ERROR, string.Format("Unsupported sentence ID: {0}", snt.SentenceID)));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (LogEvent != null)
                {
                    LogEvent(this, new LogEventArgs(LogLineType.ERROR, ex));
                }
            }
        }
Beispiel #26
0
        private void gtrPort_NewNMEAMessage(object sender, NewNMEAMessageEventArgs e)
        {
            logger.Write(string.Format("{0} (RedGTR) >> {1}", gtrPort.PortName, e.Message));

            try
            {
                var result = NMEAParser.Parse(e.Message);

                if (result is NMEAProprietarySentence)
                {
                    NMEAProprietarySentence pResult = result as NMEAProprietarySentence;

                    if (pResult.Manufacturer == ManufacturerCodes.TNT)
                    {
                        if (pResult.SentenceIDString == "0") // ACK
                        {
                            Parse_ACK(pResult.parameters);
                        }
                        else if (pResult.SentenceIDString == "!") // Device info
                        {
                            Parse_DEVICE_INFO(pResult.parameters);
                        }
                        else if (pResult.SentenceIDString == "5")
                        {
                            Parse_LOC_DATA_VAL(pResult.parameters);
                        }
                        else if (pResult.SentenceIDString == "9")
                        {
                            Parse_REM_RECEIVED(pResult.parameters);
                        }
                        else if (pResult.SentenceIDString == "B")
                        {
                            Parse_REM_TOUT(pResult.parameters);
                        }
                        else if (pResult.SentenceIDString == "C")
                        {
                            Parse_REM_PONG(pResult.parameters);
                        }
                        else if (pResult.SentenceIDString == "D")
                        {
                            Parse_REM_PONGEX(pResult.parameters);
                        }
                        else if (pResult.SentenceIDString == "O")
                        {
                            Parse_PRETMP_VAL(pResult.parameters);
                        }
                    }
                    else
                    {
                        // not supported manufacturer code
                    }
                }
                else
                {
                    NMEAStandartSentence sSentence = result as NMEAStandartSentence;

                    if (sSentence.SentenceID == SentenceIdentifiers.RMC)
                    {
                        Parse_RMC(sSentence.parameters);
                    }
                }
            }
            catch (Exception ex)
            {
                ProcessException(ex, false);
            }
        }
        private string SentenceNMEA2GPX(List <String> sentences)
        {
            List <String> sb          = new List <String>();
            int           lastchecked = 0; //for speed-up lookup for already updated records

            sb.Add("<gpx>\n<trk>\n");
            sb.Add(String.Format("<name>{0}</name>\n", "Something what can be changed easily"));
            sb.Add("<trkseg>\n");

            foreach (string textsentence in sentences)
            {
                var parsedSentence = NMEAParser.Parse(textsentence);
                if (parsedSentence is NMEAStandartSentence)
                {
                    NMEAStandartSentence sentence = (parsedSentence as NMEAStandartSentence);

                    if (sentence.TalkerID == TalkerIdentifiers.GP) //generic GPS
                    {
                        if (sentence.SentenceID == SentenceIdentifiers.GGA)
                        {
                            //http://www.gpsinformation.org/dale/nmea.htm#GGA

                            //parsing in library is not precise, but easy
                            //sb.Add(String.Format("  <trkpt lat=\"{0}\" lon=\"{1}\">\n", string.Format("{0}", sentence.parameters[1]), string.Format("{0}", sentence.parameters[3])));

                            //extra parsing for lon, lat, speed
                            string[] parsed = textsentence.Split(',');
                            string   lat    = String.Format("{0}", Convert.ToInt32(parsed[2].Substring(0, 2)) + ((parsed[3] == "N") ? Convert.ToDouble(parsed[2].Substring(2)) / 60 : Convert.ToDouble(parsed[2].Substring(2)) / -60)).ToString();
                            string   lon    = String.Format("{0}", Convert.ToInt32(parsed[4].Substring(0, 3)) + ((parsed[5] == "E") ? Convert.ToDouble(parsed[4].Substring(3)) / 60 : Convert.ToDouble(parsed[2].Substring(4)) / -60)).ToString();
                            sb.Add(String.Format("<trkpt lat=\"{0}\" lon=\"{1}\">\n", string.Format("{0}", lat), string.Format("{0}", lon)));

                            sb.Add(String.Format("   <ele>{0}</ele>\n", sentence.parameters[8]));                                                                                                            //elevation
                            sb.Add(String.Format("   <time>{0}</time>\n", (global.Keys.Contains("time") && global.Keys.Contains("date")) ? String.Format("{0}T{1}Z", global["date"], global["time"]) : "")); //inserted in case that global record is provided otherwise updated later //chyba formátu
                            sb.Add(String.Format("   <course>{0}</course>\n", global.Keys.Contains("course") ? global["course"] : ""));
                            sb.Add(String.Format("   <speed>{0}</speed>\n", global.Keys.Contains("speed") ? global["speed"] : ""));
                            sb.Add(String.Format("   <sat>{0}</sat>\n", sentence.parameters[6]));
                            sb.Add(String.Format("   <hdop>{0}</hdop>\n", sentence.parameters[7]));
                            sb.Add("</trkpt>\n");
                        }

                        if (sentence.SentenceID == SentenceIdentifiers.RMC) //control sentence
                        {
                            //http://www.gpsinformation.org/dale/nmea.htm#RMC

                            //sets global variables for post-update
                            string[] dates = sentence.parameters[8].ToString().Split(new char[] { ' ' });
                            string   date  = dates[0];
                            string   year  = date.Split(new char[] { '/' })[2]; //EN settings above!
                            string   month = date.Split(new char[] { '/' })[1];
                            string   day   = date.Split(new char[] { '/' })[0];

                            string[] times = sentence.parameters[0].ToString().Split(new char[] { ' ' });
                            string   time  = times[1];

                            //update if new RMC
                            global["date"]   = String.Format("{0}-{1}-{2}", year, month, day);
                            global["time"]   = time;                                                               //update
                            global["course"] = sentence.parameters[7].ToString();
                            global["speed"]  = Convert.ToString(Convert.ToDouble(sentence.parameters[6]) * 0.514); //convert value

                            for (int i = lastchecked; i < sb.Count; i++)                                           //post-update
                            {
                                if (sb[i].Equals("   <time></time>\n"))
                                {
                                    sb[i] = String.Format("   <time>{0}T{1}Z</time>\n", global["date"], global["time"]); //if missing generally then actual
                                }
                                else if (sb[i].Equals("   <course></course>\n"))
                                {
                                    sb[i] = String.Format("   <course>{0}</course>\n", global["course"]);
                                }
                                else if (sb[i].Equals("   <speed></speed>\n"))
                                {
                                    sb[i] = String.Format("   <speed>{0}</speed>\n", global["speed"]);
                                }
                            }
                            lastchecked = sb.Count;
                        }
                    }
                }
            }
            sb.Add("</trkseg>\n");
            sb.Add("</trk>\n</gpx>\n");
            return(String.Join("", sb.ToArray()));
        }
Beispiel #28
0
        private void inPort_NewNMEAMessage(object sender, NewNMEAMessageEventArgs e)
        {
            NMEASentence parsedSentence = null;
            bool         isParsed       = false;

            logger.Write(string.Format("{0} >> {1}", inPort.PortName, e.Message));

            try
            {
                parsedSentence = NMEAParser.Parse(e.Message);
                isParsed       = true;
            }
            catch (Exception ex)
            {
                ProcessException(ex, false);
            }

            if (isParsed && (parsedSentence is NMEAProprietarySentence))
            {
                NMEAProprietarySentence pResult = (parsedSentence as NMEAProprietarySentence);
                if ((pResult.Manufacturer == ManufacturerCodes.VLB) &&
                    (pResult.SentenceIDString == "L"))
                {
                    // $PVLBL,ownLat,ownLon,ownDepth,ownBatV,targetDataID,targetDataValue,propagationTime,MSR
                    double        ownLat  = doubleNullChecker(pResult.parameters[0]);
                    double        ownLon  = doubleNullChecker(pResult.parameters[1]);
                    double        ownDpt  = doubleNullChecker(pResult.parameters[2]);
                    double        ownBatV = doubleNullChecker(pResult.parameters[3]);
                    RC_CODES_Enum dataID  = (RC_CODES_Enum)Enum.ToObject(typeof(RC_CODES_Enum), intNullChecker(pResult.parameters[4]));
                    double        dataVal = doubleNullChecker(pResult.parameters[5]);
                    double        pTime   = doubleNullChecker(pResult.parameters[6]);
                    double        msr     = doubleNullChecker(pResult.parameters[7]);

                    if ((!double.IsNaN(ownLat)) && (!double.IsNaN(ownLon)))
                    {
                        ownLatitude.Value  = ownLat;
                        ownLongitude.Value = ownLon;

                        if (!is_g_updated)
                        {
                            g            = UCNLPhysics.PHX.PHX_GravityConstant_Calc(ownLat);
                            is_g_updated = true;
                            logger.Write(string.Format(CultureInfo.InvariantCulture, "Gravity constant updated: {0:F04} m/s^2", g));
                        }
                    }

                    if (!double.IsNaN(ownDpt))
                    {
                        ownDepth.Value = ownDpt;
                    }

                    if (!double.IsNaN(ownBatV))
                    {
                        ownBatteryVoltage.Value = ownBatV;
                    }

                    if (!double.IsNaN(pTime))
                    {
                        targetPTime.Value = pTime;
                    }

                    if (!double.IsNaN(msr))
                    {
                        targetMSR.Value = msr;
                    }

                    if (!double.IsNaN(dataVal))
                    {
                        if (dataID == RC_CODES_Enum.RC_DPT_GET)
                        {
                            targetDepth.Value = dataVal;
                        }
                        else if (dataID == RC_CODES_Enum.RC_TMP_GET)
                        {
                            targetTemperature.Value = dataVal;
                            TryUpdateSoundSpeed();
                        }
                        else if (dataID == RC_CODES_Enum.RC_BAT_V_GET)
                        {
                            targetBatVoltage.Value = dataVal;
                        }
                    }

                    if (!double.IsNaN(ownLat) && !double.IsNaN(ownLon) && !double.IsNaN(ownDpt))
                    {
                        if (!double.IsNaN(pTime) &&
                            targetDepth.IsInitializedAndNotObsolete)
                        {
                            vlblCore.TargetDepth = targetDepth.Value;
                            vlblCore.AddMeasurement(new VLBLTOAMeasurement(ownLat, ownLon, ownDpt, pTime * soundSpeedMps));

                            UpdateTrack("Measurements", new GeoPoint3D(ownLat, ownLon, ownDpt));
                        }
                        else
                        {
                            UpdateTrack("Rover", new GeoPoint3D(ownLat, ownLon, ownDpt));
                        }
                    }
                }
            }
        }
Beispiel #29
0
        private void port_NewNMEAMessageReceived(object sender, NewNMEAMessageEventArgs e)
        {
            bool         isParsed = false;
            NMEASentence result   = null;

            OnInfoEvent(string.Format(">> {0}", e.Message));

            try
            {
                result   = NMEAParser.Parse(e.Message);
                isParsed = true;
            }
            catch (Exception ex)
            {
                OnInfoEvent(string.Format("\"{0}\" caused \"{1}\", TargetSite: {2}", e.Message, ex.Message, ex.TargetSite));
            }

            if (isParsed)
            {
                if (result is NMEAProprietarySentence)
                {
                    NMEAProprietarySentence pResult = (result as NMEAProprietarySentence);

                    if (pResult.Manufacturer == ManufacturerCodes.UWV)
                    {
                        ICs sentenceID = uWAVE.ICsByMessageID(pResult.SentenceIDString);

                        if (sentenceID != ICs.IC_INVALID)
                        {
                            if (parsers.ContainsKey(sentenceID))
                            {
                                parsers[sentenceID](pResult.parameters);
                            }
                            else
                            {
                                // skip unsupported sentence
                                if (UnknownSentenceReceived != null)
                                {
                                    UnknownSentenceReceived.Rise(this, new UnknownSentenceEventArgs(result));
                                }
                                else
                                {
                                    OnInfoEvent(string.Format("WARNING: unsupported sentence identifier \"{0}\" (\"{1}\") in \"{2}\"", sentenceID, pResult.SentenceIDString, e.Message));
                                }
                            }
                        }
                        else
                        {
                            // skip unknown sentence ID
                            if (UnknownSentenceReceived != null)
                            {
                                UnknownSentenceReceived.Rise(this, new UnknownSentenceEventArgs(result));
                            }
                            else
                            {
                                OnInfoEvent(string.Format("WARNING: unsupported sentence identifier \"{0}\" in \"{1}\"", pResult.SentenceIDString, e.Message));
                            }
                        }
                    }
                    else
                    {
                        // skip unsupported manufacturer ID
                        if (UnknownSentenceReceived != null)
                        {
                            UnknownSentenceReceived.Rise(this, new UnknownSentenceEventArgs(result));
                        }
                        else
                        {
                            OnInfoEvent(string.Format("WARNING: unsupported manufacturer identifier \"{0}\" in \"{1}\"", pResult.SentenceIDString, e.Message));
                        }
                    }
                }
                else
                {
                    // skip standard sentence
                    if (UnknownSentenceReceived != null)
                    {
                        UnknownSentenceReceived.Rise(this, new UnknownSentenceEventArgs(result));
                    }
                    else
                    {
                        OnInfoEvent(string.Format("WARNING: unsupported standard sentence \"{0}\"", e.Message));
                    }
                }
            }
        }
Beispiel #30
0
        private void nmeaPort_NewMessage(object sender, NewNMEAMessageEventArgs e)
        {
            NMEAProprietarySentence nmeaMsg = new NMEAProprietarySentence();
            bool isParsed = false;

            InvokeWriteLogString(string.Format("<< {0}", e.Message));

            #region try parse

            try
            {
                var tempMsg = NMEAParser.Parse(e.Message);

                if (tempMsg is NMEAProprietarySentence)
                {
                    nmeaMsg  = (tempMsg as NMEAProprietarySentence);
                    isParsed = true;
                }
                else
                {
                    InvokeWriteLogString(string.Format("Skipping sentence {0}", (tempMsg as NMEAStandartSentence).SentenceID));
                }
            }
            catch (Exception ex)
            {
                ProcessException(ex, false);
            }

            #endregion

            if (isParsed)
            {
                timer.Stop();
                if (nmeaMsg.Manufacturer == ManufacturerCodes.UCN)
                {
                    if (nmeaMsg.SentenceIDString == "L")
                    {
                        repeats = 0;
                        UCNL_SRV_CMD cmdID = (UCNL_SRV_CMD)(int)nmeaMsg.parameters[0];

                        switch (cmdID)
                        {
                        case UCNL_SRV_CMD.DEV_INFO_VAL:
                        {
                            // $PUCNL,x,x,c--c
                            InvokeWriteLogString(Utils.ParseDevInfoStr((string)nmeaMsg.parameters[2]));
                            action = UCNL_FW_ACTION.INVOKE_FW_REQ;

                            if (isExtraPauseBeforeFWUPDATE)
                            {
                                MessageBox.Show("Turn off S_MODE in your device and press OK", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }


                            RequestFWUpdate(IsRedNAVRedNODE);
                            break;
                        }

                        case UCNL_SRV_CMD.ACK:
                        {
                            // $PUCNL,x,x,c--c
                            InvokeWriteLogString("DEVICE: Firmware update mode ON\r\n");
                            nmeaPort.IsRawModeOnly = true;

                            if (InitialBaudrate != BaudRate.baudRate115200)
                            {
                                action = UCNL_FW_ACTION.PORT_REOPENING;
                                ReopenPort();
                            }
                            else
                            {
                                action = UCNL_FW_ACTION.FW_UPDATE_INIT;
                                RequestTransferSize();
                            }

                            break;
                        }
                        }
                    }
                }
                else
                {
                    InvokeWriteLogString(string.Format("Skipping sentence {0}", nmeaMsg.SentenceIDString));
                }
            }
        }