コード例 #1
0
ファイル: NmeaTests.cs プロジェクト: janmariu/ais
        public void Parse_InvalidNmeaString()
        {
            //The norwegian costal authority seems to send garbled messages these days.
            NmeaMessage msg = NmeaParser.Parse("\\s:2573315,c:1606586568*09\\!BSVDM,1,1,,B,13nP7p?PAfPMiF2SmT=S4ROP0<1q,0*3E");

            Assert.AreEqual("!BSVDM", msg.MessageType);
            Assert.AreEqual("0*3E", msg.Checksum);
        }
コード例 #2
0
        private NmeaMessage[] DeserializeMessages(byte[] bytes)
        {
            var rawText = Encoding.UTF8.GetString(bytes);
            var lines   = rawText.Split('\n').Where(x => !x.StartsWith("$GNTXT")).ToArray();

            var nmeas = lines.Select(x => NmeaParser.Parse(x)).ToArray();

            return(nmeas);
        }
コード例 #3
0
        static void Main(string[] args)
        {
            var parser = new NmeaParser();

            Console.WriteLine($"Parsing GPGGA message: {GgaMessage1}");
            var result = parser.Parse(GgaMessage1);

            Console.WriteLine($"Result: {result}");

            Console.WriteLine($"Parsing GPRMC message: {RmcMessage1}");
            result = parser.Parse(RmcMessage1);
            Console.WriteLine($"Result: {result}");

            Console.WriteLine($"Parsing GPRMC message 2: {RmcMessage2}");
            result = parser.Parse(RmcMessage2);
            Console.WriteLine($"Result: {result}");

            Console.WriteLine("Press enter to continue...");
            Console.ReadKey();
        }
コード例 #4
0
 private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
 {
     try
     {
         var result = _parser.Parse(_port.ReadExisting());
         Console.WriteLine($"Result: {result}");
     }
     catch (UnknownTypeException ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
コード例 #5
0
ファイル: NmeaTests.cs プロジェクト: janmariu/ais
        public void Parse_NonMultipartNmea()
        {
            NmeaMessage msg = NmeaParser.Parse("!AIVDM,1,1,,A,14eG;o@034o8sd<L9i:a;WF>062D,0*7D");

            Assert.AreEqual("!AIVDM", msg.MessageType);
            Assert.AreEqual(1, msg.NumberOfSentences);
            Assert.AreEqual(1, msg.SentenceNumber);
            Assert.AreEqual(null, msg.SequentialMessageId);
            Assert.AreEqual("A", msg.Channel);
            Assert.AreEqual("14eG;o@034o8sd<L9i:a;WF>062D", msg.EncodedPayload);
            Assert.AreEqual("0*7D", msg.Checksum);
        }
コード例 #6
0
        public void VtgMessageTest2()
        {
            var parser = new NmeaParser();
            var result = parser.Parse(VtgMessage2);

            Assert.IsInstanceOfType(result, typeof(GpvtgMessage));
            var message = (GpvtgMessage)result;

            Assert.AreEqual(141.92f, message.TrackDegrees);
            Assert.AreEqual(float.NaN, message.MagneticTrack);
            Assert.AreEqual(0.89f, message.GroundSpeetKnots);
            Assert.AreEqual(1.64f, message.GroundSpeed);
        }
コード例 #7
0
        public void VtgMessageTest1()
        {
            var parser = new NmeaParser();
            var result = parser.Parse(VtgMessage1);

            Assert.IsInstanceOfType(result, typeof(GpvtgMessage));
            var message = (GpvtgMessage)result;

            Assert.AreEqual(054.7f, message.TrackDegrees);
            Assert.AreEqual(034.4f, message.MagneticTrack);
            Assert.AreEqual(005.5f, message.GroundSpeetKnots);
            Assert.AreEqual(010.2f, message.GroundSpeed);
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: DaniAsh551/ArDrone2
        static void Main(string[] args)
        {
            var parser = new NmeaParser();

            var dummy = File.ReadAllText("/home/lubuntu/sample.nmea");
            //var dummyBytes = Encoding.UTF8.GetBytes(dummy);
            var nm = parser.Parse(dummy);

            return;

            var portNames = SerialDevice.GetPortNames();

            var serial = new SerialDevice("/dev/ttyACM0", BaudRate.B1152000);

            serial.DataReceived += (o, eventArgs) =>
            {
            };


            serial.Open();

            while (true)
            {
                Thread.Sleep(200);
            }
            return;

            var client = new UdpClient(5554);
            var sender = new UdpClient(5556);

            var ip     = "192.168.100.55";
            var exitBs = Encoding.ASCII.GetBytes("AT*CONFIG=\"general:navdata_demo\",\"TRUE\"\r");
            var ack    = Encoding.ASCII.GetBytes("AT*CTRL=0\r");

            sender.Send(exitBs, exitBs.Length, ip, 5556);
            sender.Send(ack, ack.Length, ip, 5556);
            client.Send(new byte[] { 1 }, 1, ip, 5554);

            var nav = new NavDataRetriever("192.168.100.55", 5554, 2000, client);

            nav.SendMessage = i => client.Send(new byte[] { (byte)i }, 1, ip, 5554);
            nav.Start();
            nav.WaitForFirstMessageToArrive();
            var navData = nav.CurrentNavigationData;

            while (true)
            {
                navData = nav.CurrentNavigationData;
            }
        }
コード例 #9
0
        public void GsaMessageTest1()
        {
            var parser = new NmeaParser();
            var result = parser.Parse(GsaMessage1);

            Assert.IsInstanceOfType(result, typeof(GpgsaMessage));
            var message = (GpgsaMessage)result;

            Assert.AreEqual(true, message.GpsStatusAuto);
            Assert.AreEqual(3, (int)message.SatelliteFix);
            Assert.AreEqual("04,05,,09,12,,,24,,,,,", message.Pnrs);
            Assert.AreEqual(2.5f, message.Pdop);
            Assert.AreEqual(1.3f, message.Hdop);
            Assert.AreEqual(2.1f, message.Vdop);
        }
コード例 #10
0
    static void serialDataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try {
            SerialPort sp     = (SerialPort)sender;
            var        inData = _serialPort.ReadLine();
            // Console.WriteLine(_serialPort.ReadLine());
            Console.WriteLine($"inData: {inData}");

            var result = _parser.Parse(_serialPort.ReadLine());
            Console.WriteLine($"Result: {result}");
        }
        catch (UnknownTypeException ex) {
            Console.WriteLine(ex.Message);
        }
    }
コード例 #11
0
        static void Main(string[] args)
        {
            if (args.Length != 4)
            {
                Console.WriteLine(@"Please provide an input arguments as follows:
1st - Input file with NMEA data,
2nd - Output JSON file path,
3rd - Time offset in seconds,
4th - Speed multipler constant.");
                return;
            }

            if (!ValidateInputArguments(args))
            {
                return;
            }


            StreamReader       sr       = new StreamReader(inputFile.FullName);
            List <NmeaMessage> messages = new List <NmeaMessage>();

            while (!sr.EndOfStream)
            {
                string line = sr.ReadLine();

                if (line.Contains("$GPGGA") || line.Contains("$GPRMC"))
                {
                    var parser = new NmeaParser();
                    messages.Add(parser.Parse(line));
                }

                if (messages.Count == 2)
                {
                    string message = NmeaSenteceToJson(messages, timeOffset, speedMultiplier);

                    StreamWriter sw = new StreamWriter(outputFile.FullName);
                    sw.WriteLine(message);

                    Console.WriteLine(message);

                    sw.Close();

                    messages.Clear();
                    Thread.Sleep(1000);
                }
            }
            sr.Close();
        }
コード例 #12
0
        public void RmcMessageTest1()
        {
            var parser = new NmeaParser();
            var result = parser.Parse(RmcMessage1);

            Assert.IsInstanceOfType(result, typeof(GprmcMessage));
            var message = (GprmcMessage)result;

            Assert.AreEqual("091317.75".ToTimeSpan(), message.FixTime);
            Assert.AreEqual(true, message.IsActive);
            Assert.AreEqual("5037.0967674".ToCoordinates("N", CoordinateType.Latitude), message.Latitude);
            Assert.AreEqual("00534.6232070".ToCoordinates("E", CoordinateType.Longitude), message.Longitude);
            Assert.AreEqual(0.019f, message.Speed);
            Assert.AreEqual(215.1f, message.Course);
            Assert.AreEqual(DateTime.ParseExact("220816", "ddMMyy", CultureInfo.InvariantCulture), message.UpdateDate);
            Assert.AreEqual(0.0f, message.MagneticVariation);
        }
コード例 #13
0
        public void RmcMessageTest2()
        {
            var parser = new NmeaParser();
            var result = parser.Parse(RmcMessage2);

            Assert.IsInstanceOfType(result, typeof(GprmcMessage));
            var message = (GprmcMessage)result;

            Assert.AreEqual("153007".ToTimeSpan(), message.FixTime);
            Assert.AreEqual(true, message.IsActive);
            Assert.AreEqual("5050.10288".ToCoordinates("N", CoordinateType.Latitude), message.Latitude);
            Assert.AreEqual("00419.91808".ToCoordinates("E", CoordinateType.Longitude), message.Longitude);
            Assert.AreEqual(000.1f, message.Speed);
            Assert.AreEqual(078.9f, message.Course);
            Assert.AreEqual(DateTime.ParseExact("100217", "ddMMyy", CultureInfo.InvariantCulture), message.UpdateDate);
            Assert.AreEqual(float.NaN, message.MagneticVariation);
        }
コード例 #14
0
        public void GgaMessageTest1()
        {
            var parser = new NmeaParser();
            var result = parser.Parse(GgaMessage1);

            Assert.IsInstanceOfType(result, typeof(GpggaMessage));
            var message = (GpggaMessage)result;

            Assert.AreEqual("091317.80".ToTimeSpan(), message.FixTime);
            Assert.AreEqual("5037.0968".ToCoordinates("N", CoordinateType.Latitude), message.Latitude);
            Assert.AreEqual("00534.6232".ToCoordinates("E", CoordinateType.Longitude), message.Longitude);
            Assert.AreEqual(9, (int)message.FixQuality);
            Assert.AreEqual(7, message.NumberOfSatellites);
            Assert.AreEqual(1.4f, message.Hdop);
            Assert.AreEqual(73.65f, message.Altitude);
            Assert.AreEqual("M", message.AltitudeUnits);
            Assert.AreEqual(46.60f, message.HeightOfGeoId);
            Assert.AreEqual("M", message.HeightOfGeoIdUnits);
            Assert.AreEqual(5, message.TimeSpanSinceDgpsUpdate);
            Assert.AreEqual(136, message.DgpsStationId);
        }
コード例 #15
0
 private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
 {
     try
     {
         var readString = _serialPort.ReadExisting();
         OnRawGpsDataReceived(readString);
         var result = _parser.Parse(readString);
         if (typeof(GprmcMessage) != result.GetType())
         {
             return;
         }
         if (_previousReadTime != null && GpsInfo.ReadFrequenty != 0 && ((GprmcMessage)result).UpdateDate.Subtract(new TimeSpan(0, 0, 0, 0, GpsInfo.ReadFrequenty)) <= _previousReadTime)
         {
             return;
         }
         OnGpsDataReceived(new GpsDataEventArgs((GprmcMessage)result));
     }
     catch (UnknownTypeException ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
コード例 #16
0
        private void Connect(IAsyncResult result)
        {
            if (result.IsCompleted)
            {
                var data = bluetoothClient.GetStream();
                while (true)
                {
                    if (data.CanRead)
                    {
                        GpggaMessage parsedMessage   = new GpggaMessage();
                        var          message         = new byte[256];
                        var          completeMessage = new StringBuilder();

                        do
                        {
                            var numberOfBytesRead = data.Read(message, 0, message.Length);
                            completeMessage.AppendFormat("{0}", Encoding.ASCII.GetString(message, 0, numberOfBytesRead));
                        }while (data.DataAvailable);
                        try
                        {
                            var nmeaParser = new NmeaParser();
                            var messages   = completeMessage.ToString();
                            parsedMessage = (GpggaMessage)nmeaParser.Parse(completeMessage.ToString());
                            if (parsedMessage != null)
                            {
                                ParseCoordinates(completeMessage, parsedMessage);
                            }
                        }
                        catch
                        {
                            ;
                        }
                    }
                }
            }
        }
コード例 #17
0
        static async Task Main(string[] args)
        {
            string port     = "/dev/ttyUSB0";
            bool   notDone  = true;
            var    msgQueue = Channel.CreateUnbounded <string>();

            try {
                if (args.Length < 1)
                {
                    System.Console.WriteLine("Please retry, & enter the name of a [string] serialport argument.");
                }
                else if (args[0].Contains("-f"))
                {
                    string[] s = string.Join(" ", args).Split("-f ");

                    // Console.WriteLine($"total command string was: {s}");
                    string l;
                    var    fs = new FileStream(s[1], FileMode.Open, FileAccess.Read);
                    using (var sr = new StreamReader(fs, Encoding.UTF8)) {
                        // Attempt to read & parse the line...
                        while ((l = sr.ReadLine()) != null)
                        {
                            try {
                                var m = _parser.Parse(l);
                                Console.WriteLine(m);
                            } catch (System.FormatException) {
                                Console.WriteLine($"<dropped {l}>");
                            } catch (UnknownTypeException) {
                                Console.WriteLine($"<dropped unknown class {l.Split(",")[0]}>");
                            }
                        }
                    }
                }
                else
                {
                    // Create a new SerialPort on indicated serial device (port)
                    //    then Set the read/write timeouts
                    _serialPort = new SerialPort(port, int.Parse(baudrate));

                    // Set the read/write timeouts
                    _serialPort.ReadTimeout  = 1500;
                    _serialPort.WriteTimeout = 1500;
                    _serialPort.Open();

                    _ = Task.Factory.StartNew(async() => {
                        while (notDone)
                        {
                            string bufr = _serialPort.ReadLine();
                            try {
                                // Console.WriteLine($"forwarded: {bufr.Split(",")[0]}");
                                NmeaMessage m = _parser.Parse(bufr);
                                Console.WriteLine(m);
                                await msgQueue.Writer.WriteAsync(bufr);
                                //   msgQueue.Writer.Complete();
                            } catch (System.FormatException) {
                                Console.WriteLine($"<dropped {bufr}>");
                            } catch (UnknownTypeException) {
                                Console.WriteLine($"<dropped unknown class {bufr.Split(",")[0]}>");
                                // file.Close();
                            }
                        }
                        msgQueue.Writer.Complete();
                    });

                    await foreach (var item in msgQueue.Reader.ReadAllAsync())
                    {
                        Console.WriteLine($"+ {item}");
                        await Task.Delay(100);
                    }
                    _serialPort.Close();
                }
                _serialPort.Close();
            } catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
コード例 #18
0
        public override SensorFile ImportFile(string path, Boat boat)
        {
            int           line = 0;
            StringBuilder log  = new StringBuilder();

            try
            {
                FileInfo   fi   = new FileInfo(path);
                SensorFile file = new SensorFile("nmea", fi.Name, DateTime.Now);
                file.Save();

                StreamReader reader = new StreamReader(path);
                Dictionary <string, Dictionary <string, string> > first = null;
                if (!reader.EndOfStream)
                {
                    while (first == null && !reader.EndOfStream)
                    {
                        try
                        {
                            string lineText = reader.ReadLine();
                            first = NmeaParser.Parse(lineText);
                        }
                        catch (NMEAIgnoredSentenceException) { }
                        catch (NMEAUnkownSentenceException) { }
                        catch (NMEAEmptySentenceException) { }
                        catch (Exception e)
                        {
                            log.Append("Line " + line + ": " + e.Message);
                            log.Append(Environment.NewLine);
                        }
                        line++;
                    }
                    while (!reader.EndOfStream)
                    {
                        try
                        {
                            Dictionary <string, Dictionary <string, string> > current = first;
                            bool      newGroup          = true;
                            double    latitude          = 0;
                            double    longitude         = 0;
                            double    speed             = 0;
                            double    waterTemperature  = 0;
                            double    depth             = 0;
                            double    relativeWindSpeed = 0;
                            double    relativeWindAngle = 0;
                            double    heading           = 0;
                            TimeSpan? time           = null;
                            Exception groupException = null;
                            while (newGroup || (current.Keys.ElementAt(0) != first.Keys.ElementAt(0) && !reader.EndOfStream))
                            {
                                try
                                {
                                    //process current
                                    if (current.Keys.ElementAt(0) == "Global Positioning System Fix Data")
                                    {
                                        //time
                                        string   timestring = current[current.Keys.ElementAt(0)]["Time"];
                                        char[]   splitter   = { '.' };
                                        string[] parts      = timestring.Split(splitter);
                                        if (parts[0].Length == 6)
                                        {
                                            int hour        = int.Parse(parts[0].Substring(0, 2));
                                            int minute      = int.Parse(parts[0].Substring(2, 2));
                                            int second      = int.Parse(parts[0].Substring(4, 2));
                                            int millisecond = 0;
                                            if (parts.Length > 1)
                                            {
                                                millisecond =
                                                    (int)
                                                    (double.Parse("0." + parts[1], _numberCulture.NumberFormat) *
                                                     1000.0);
                                            }
                                            time = new TimeSpan(0, hour, minute, second, millisecond);
                                        }
                                        else
                                        {
                                            throw new Exception("Invalid Time Format");
                                        }

                                        //latitude
                                        string latitudeString          = current[current.Keys.ElementAt(0)]["Latitude"];
                                        string latitudeDirectionString =
                                            current[current.Keys.ElementAt(0)]["Latitude Direction"];
                                        if (latitudeString.Length > 2)
                                        {
                                            int    latdegrees = int.Parse(latitudeString.Substring(0, 2));
                                            double latminute  = double.Parse(latitudeString.Substring(2),
                                                                             _numberCulture.NumberFormat);
                                            latitude = Coordinate.CoordinateToDouble(latdegrees, latminute, 0);
                                            if (latitudeDirectionString.ToLower() == "s")
                                            {
                                                latitude = -latitude;
                                            }
                                        }
                                        else
                                        {
                                            throw new Exception("Invalid Latitude format");
                                        }

                                        //longitude
                                        string longitudeString          = current[current.Keys.ElementAt(0)]["Longitude"];
                                        string longitudeDirectionString =
                                            current[current.Keys.ElementAt(0)]["Longitude Direction"];
                                        if (longitudeString.Length > 2)
                                        {
                                            int    longdegrees = int.Parse(longitudeString.Substring(0, 3));
                                            double longminute  = double.Parse(longitudeString.Substring(3),
                                                                              _numberCulture.NumberFormat);
                                            longitude = Coordinate.CoordinateToDouble(longdegrees, longminute, 0);
                                            if (longitudeDirectionString.ToLower() == "w")
                                            {
                                                longitude = -longitude;
                                            }
                                        }
                                        else
                                        {
                                            throw new Exception("Invalid Longitude format");
                                        }
                                    }
                                    else if (current.Keys.ElementAt(0) == "Recommended Minimum Specific GPS/TRANSIT Data")
                                    {
                                        //time
                                        string   timestring = current[current.Keys.ElementAt(0)]["Time of Fix"];
                                        char[]   splitter   = { '.' };
                                        string[] parts      = timestring.Split(splitter);
                                        if (parts[0].Length == 6)
                                        {
                                            int hour   = int.Parse(parts[0].Substring(0, 2));
                                            int minute = int.Parse(parts[0].Substring(2, 2));
                                            int second = int.Parse(parts[0].Substring(4, 2));
                                            time = new TimeSpan(0, hour, minute, second, 0);
                                        }
                                        else
                                        {
                                            throw new Exception("Invalid Time Format");
                                        }

                                        //latitude
                                        string latitudeString          = current[current.Keys.ElementAt(0)]["Latitude"];
                                        string latitudeDirectionString =
                                            current[current.Keys.ElementAt(0)]["Latitude Direction"];
                                        if (latitudeString.Length > 2)
                                        {
                                            int    latdegrees = int.Parse(latitudeString.Substring(0, 2));
                                            double latminute  = double.Parse(latitudeString.Substring(2),
                                                                             _numberCulture.NumberFormat);
                                            latitude = Coordinate.CoordinateToDouble(latdegrees, latminute, 0);
                                            if (latitudeDirectionString.ToLower() == "s")
                                            {
                                                latitude = -latitude;
                                            }
                                        }
                                        else
                                        {
                                            throw new Exception("Invalid Latitude format");
                                        }

                                        //longitude
                                        string longitudeString          = current[current.Keys.ElementAt(0)]["Longitude"];
                                        string longitudeDirectionString =
                                            current[current.Keys.ElementAt(0)]["Longitude Direction"];
                                        if (longitudeString.Length > 2)
                                        {
                                            int    longdegrees = int.Parse(longitudeString.Substring(0, 3));
                                            double longminute  = double.Parse(longitudeString.Substring(3),
                                                                              _numberCulture.NumberFormat);
                                            longitude = Coordinate.CoordinateToDouble(longdegrees, longminute, 0);
                                            if (longitudeDirectionString.ToLower() == "w")
                                            {
                                                longitude = -longitude;
                                            }
                                        }
                                        else
                                        {
                                            throw new Exception("Invalid Longitude format");
                                        }

                                        string speedString = current[current.Keys.ElementAt(0)]["Speed over ground"];
                                        double.TryParse(speedString, out speed);
                                        //speed = double.Parse(speedString, _numberCulture.NumberFormat);

                                        string datestring = current[current.Keys.ElementAt(0)]["Date of Fix"];
                                        if (datestring.Length == 6)
                                        {
                                            int      day   = int.Parse(datestring.Substring(0, 2));
                                            int      month = int.Parse(datestring.Substring(2, 2));
                                            int      year  = 2000 + int.Parse(datestring.Substring(4, 2));
                                            DateTime dt    = new DateTime(year, month, day);
                                            dt        = ZeroTime(dt);
                                            StartDate = dt;
                                            time      = new TimeSpan(0, time.Value.Hours, time.Value.Minutes,
                                                                     time.Value.Seconds, time.Value.Milliseconds);
                                        }
                                        else
                                        {
                                            throw new Exception("Invalid Time Format");
                                        }
                                    }
                                    else if (current.Keys.ElementAt(0) == "Data and Time")
                                    {
                                        //time
                                        string   timestring = current[current.Keys.ElementAt(0)]["Time"];
                                        char[]   splitter   = { '.' };
                                        string[] parts      = timestring.Split(splitter);
                                        if (parts[0].Length == 6)
                                        {
                                            int hour        = int.Parse(parts[0].Substring(0, 2));
                                            int minute      = int.Parse(parts[0].Substring(2, 2));
                                            int second      = int.Parse(parts[0].Substring(4, 2));
                                            int millisecond =
                                                (int)
                                                (double.Parse("0." + parts[1], _numberCulture.NumberFormat) *
                                                 1000.0);
                                            int      day   = int.Parse(current[current.Keys.ElementAt(0)]["Day"]);
                                            int      month = int.Parse(current[current.Keys.ElementAt(0)]["Month"]);
                                            int      year  = int.Parse(current[current.Keys.ElementAt(0)]["Year"]);
                                            DateTime dt    = new DateTime(year, month, day);
                                            dt        = ZeroTime(dt);
                                            StartDate = dt;
                                            time      = new TimeSpan(0, hour, minute, second, millisecond);
                                        }
                                        else
                                        {
                                            throw new Exception("Invalid Time Format");
                                        }
                                    }
                                    else if (current.Keys.ElementAt(0) == "Water Temperature")
                                    {
                                        string tempString     = current[current.Keys.ElementAt(0)]["Water Temperature"];
                                        string tempUnitString =
                                            current[current.Keys.ElementAt(0)]["Water Temperature Unit"];
                                        waterTemperature = double.Parse(tempString, _numberCulture.NumberFormat);
                                        //convert fahrenheit to celsius
                                        if (tempUnitString.ToLower() == "f")
                                        {
                                            waterTemperature = (5.0 / 9.0) * (waterTemperature - 32.0);
                                        }
                                    }
                                    else if (current.Keys.ElementAt(0) == "Depth")
                                    {
                                        string depthString = current[current.Keys.ElementAt(0)]["Depth"];
                                        depth = double.Parse(depthString, _numberCulture.NumberFormat);
                                    }
                                    else if (current.Keys.ElementAt(0) == "Wind Speed and Angle")
                                    {
                                        string windAngleString     = current[current.Keys.ElementAt(0)]["Wind Angle"];
                                        string windspeedString     = current[current.Keys.ElementAt(0)]["Wind Speed"];
                                        string windspeedUnitString =
                                            current[current.Keys.ElementAt(0)]["Wind Speed Unit"];
                                        relativeWindAngle = double.Parse(windAngleString,
                                                                         _numberCulture.NumberFormat);
                                        relativeWindSpeed =
                                            ConvertValueWithUnit(windspeedString + " " + windspeedUnitString);
                                    }
                                    else if (current.Keys.ElementAt(0) == "NovaSail")
                                    {
                                        string latitudeString  = current[current.Keys.ElementAt(0)]["Latitude"];
                                        string longitudeString = current[current.Keys.ElementAt(0)]["Longitude"];
                                        string headingString   = current[current.Keys.ElementAt(0)]["Heading"];
                                        string speedString     = current[current.Keys.ElementAt(0)]["Speed"];
                                        string rollString      = current[current.Keys.ElementAt(0)]["Roll"];
                                        string dayString       = current[current.Keys.ElementAt(0)]["Day"];
                                        string monthString     = current[current.Keys.ElementAt(0)]["Month"];
                                        string yearString      = current[current.Keys.ElementAt(0)]["Year"];
                                        string hourString      = current[current.Keys.ElementAt(0)]["Hour"];
                                        string minuteString    = current[current.Keys.ElementAt(0)]["Minute"];
                                        string secondString    = current[current.Keys.ElementAt(0)]["Second"];

                                        latitude  = double.Parse(latitudeString, _numberCulture.NumberFormat);
                                        longitude = double.Parse(longitudeString, _numberCulture.NumberFormat);

                                        speed   = double.Parse(speedString, _numberCulture.NumberFormat);
                                        heading = double.Parse(headingString, _numberCulture.NumberFormat);
                                        //roll
                                        DateTime dt = new DateTime(int.Parse(yearString), int.Parse(monthString),
                                                                   int.Parse(dayString));
                                        dt        = ZeroTime(dt);
                                        StartDate = dt;
                                        time      = new TimeSpan(0, int.Parse(hourString), int.Parse(minuteString),
                                                                 int.Parse(secondString), 0);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    groupException = ex;
                                }
                                line++;
                                string lineText = reader.ReadLine();
                                current  = NmeaParser.Parse(lineText);
                                newGroup = false;
                            }
                            if (time != null && groupException == null)
                            {
                                file.AddReading(StartDate + time.Value, latitude, longitude, 0, speed, heading, depth, waterTemperature, 0, relativeWindAngle, relativeWindSpeed, 0, 0);
                            }
                            else
                            {
                                //log something?
                                log.Append("The date and time could not be determined at line " + line);
                                log.Append(Environment.NewLine);
                            }
                            first = current;
                        }
                        catch (NMEAIgnoredSentenceException) {}
                        catch (NMEAUnkownSentenceException) {}
                        catch (NMEAEmptySentenceException) {}
                        catch (Exception e)
                        {
                            log.Append("Line " + line + ": " + e.Message);
                            log.Append(Environment.NewLine);
                        }
                    }

                    boat.AddFile(file);
                    if (log.Length > 0)
                    {
                        if (log.ToString().Length > 1000)
                        {
                            MessageBox.Show(log.ToString().Substring(0, 1000));
                        }
                        else
                        {
                            MessageBox.Show(log.ToString());
                        }
                    }
                    return(file);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }
コード例 #19
0
ファイル: AisDecoder.cs プロジェクト: nypan/ais
 public NmeaMessage GetNmeaMessage(string nmea)
 {
     return(NmeaParser.Parse(nmea));
 }
コード例 #20
0
        public async Task Parse(string[] files, bool recursive, int?max, CancellationToken token)
        {
            _logger.LogInformation($"Parsing files, Recursive={recursive}, Max={max}, {(files.Select(x => $"File: {x}").ToStringVector(Environment.NewLine))}");

            using var monitorToken = CancellationTokenSource.CreateLinkedTokenSource(token);
            Stopwatch sw = Stopwatch.StartNew();

            Console.CancelKeyPress += (sender, e) =>
            {
                e.Cancel = false;
                monitorToken.Cancel();
            };

            var parseOption = new ExecutionDataflowBlockOptions {
                MaxDegreeOfParallelism = 20, BoundedCapacity = 1000
            };
            var batchOption = new GroupingDataflowBlockOptions {
                BoundedCapacity = 1000
            };
            var writeOption = new ExecutionDataflowBlockOptions {
                MaxDegreeOfParallelism = 1, BoundedCapacity = 1000
            };
            var linkOption = new DataflowLinkOptions {
                PropagateCompletion = true
            };

            TransformBlock <string, NmeaRecord?> toParse     = new TransformBlock <string, NmeaRecord?>(x => _parseNmea.Parse(x), parseOption);
            BatchBlock <NmeaRecord?>             toSaveBatch = new BatchBlock <NmeaRecord?>(100, batchOption);
            ActionBlock <NmeaRecord?[]>          toSave      = new ActionBlock <NmeaRecord?[]>(x => _store.Write(x), writeOption);

            toParse.LinkTo(toSaveBatch, linkOption);
            _ = toParse.Completion.ContinueWith(delegate { toSaveBatch.Complete(); });

            toSaveBatch.LinkTo(toSave, linkOption);
            _ = toSaveBatch.Completion.ContinueWith(delegate { toSave.Complete(); });

            _counters.Clear();
            _tracking.Load();

            _counters.Sampler = x =>
            {
                x.Set(Counter.ToParseIn, toParse.InputCount);
                x.Set(Counter.ToParseOut, toParse.OutputCount);
                x.Set(Counter.ToSaveIn, toParse.InputCount);
                x.Set(Counter.ToSaveOut, toParse.OutputCount);
            };

            // Start the process
            IReadOnlyList <string> readFiles = files
                                               .SelectMany(x => _fileReader.GetFiles(x !, true))
                                               .Select(x => _tracking.Check(x))
                                               .Where(x => x != null)
                                               .TakeWhile((x, i) => max == null || i < (int)max)
                                               .ToList() !;

            _counters.Monitor(monitorToken.Token);
            _counters.Set(Counter.FileQueued, readFiles.Count);

            foreach (var file in readFiles)
            {
                if (monitorToken.IsCancellationRequested)
                {
                    break;
                }

                _tracking.Add(file);
                await _fileReader.ReadFile(file, toParse);
            }

            toParse.Complete();
            await toSave.Completion;

            await _counters.Completion(monitorToken.Token);

            _logger.LogInformation("Shutting down");
            monitorToken.Cancel();

            _store.Close();
            _tracking.Save();

            // Report on performance
            sw.Stop();
            _logger.LogInformation($"Final: {_counters.FinalScore(sw.Elapsed)}");
        }
コード例 #21
0
 public static NmeaMessage ParseNmea(string nmea)
 {
     return(NmeaParser.Parse(nmea));
 }
コード例 #22
0
        private static void NmeaSentenceReceived(object sender, NmeaSentence e)
        {
            _streamWriter.WriteLine(e.Sentence);

            _parser.Parse(e.Sentence);
        }
コード例 #23
0
ファイル: GpsSensor.cs プロジェクト: gandy92/MrGibbs
        /// <summary>
        /// update the state object with the current gps data
        /// TODO: possibly consider finding an external NMEA lib, this is kindof a mess
        /// </summary>
        /// <param name="state">state to add data to</param>
        public virtual void Update(Models.State state)
        {
            lock (_buffer)
            {
                double latitude  = double.MinValue;
                double longitude = double.MinValue;
                double speed     = double.MinValue;
                double height    = double.MinValue;
                double courseOverGroundByLocation = double.MinValue;

                double magneticCourseMadeGood = double.MinValue;
                double trueCourseMadeGood     = double.MinValue;

                double   magneticDeviation = double.MinValue;
                DateTime?date = null;

                double altitude = double.MinValue;

                while (_buffer.Count > 0)
                {
                    string line = _buffer.Dequeue();
                    try
                    {
                        var parsed = _parser.Parse(line);

                        foreach (var sentence in parsed.Keys)
                        {
                            _logger.Debug("GPS Parsed: " + sentence);
                            if (sentence == "Global Positioning System Fix Data")
                            {
                                //time
                                string   timestring = parsed[sentence]["Time"];
                                char[]   splitter   = { '.' };
                                string[] parts      = timestring.Split(splitter);
                                if (parts[0].Length == 6)
                                {
                                    int hour        = int.Parse(parts[0].Substring(0, 2));
                                    int minute      = int.Parse(parts[0].Substring(2, 2));
                                    int second      = int.Parse(parts[0].Substring(4, 2));
                                    int millisecond = 0;
                                    if (parts.Length > 1)
                                    {
                                        millisecond = (int)(double.Parse("0." + parts[1], _numberCulture.NumberFormat) * 1000.0);
                                    }

                                    if (!date.HasValue)
                                    {
                                        date = DateTime.UtcNow;
                                    }

                                    date = new DateTime(date.Value.Year, date.Value.Month, date.Value.Day, hour, minute, second, millisecond);
                                }
                                else
                                {
                                    throw new Exception("Invalid Time Format");
                                }

                                //latitude
                                string latitudeString          = parsed[sentence]["Latitude"];
                                string latitudeDirectionString = parsed[sentence]["Latitude Direction"];
                                int    latdegrees = int.Parse(latitudeString.Substring(0, 2));
                                double latminute  = double.Parse(latitudeString.Substring(2), _numberCulture.NumberFormat);
                                latitude = Coordinate.CoordinateToDouble(latdegrees, latminute, 0);
                                if (latitudeDirectionString.ToLower() == "s")
                                {
                                    latitude = -latitude;
                                }

                                //longitude
                                string longitudeString          = parsed[sentence]["Longitude"];
                                string longitudeDirectionString = parsed[sentence]["Longitude Direction"];
                                int    longdegrees = int.Parse(longitudeString.Substring(0, 3));
                                double longminute  = double.Parse(longitudeString.Substring(3), _numberCulture.NumberFormat);
                                longitude = Coordinate.CoordinateToDouble(longdegrees, longminute, 0);
                                if (longitudeDirectionString.ToLower() == "w")
                                {
                                    longitude = -longitude;
                                }

                                string altitudeString     = parsed[sentence]["Altitude"];
                                string altitudeUnitString = parsed[sentence]["Altitude Unit"];
                                if (double.TryParse(altitudeString, out altitude))
                                {
                                    if (altitudeUnitString.Trim().ToLower() == "m")
                                    {
                                        //do nothing, it's meters
                                    }
                                    else if (altitudeUnitString.Trim().ToLower() == "k")
                                    {
                                        altitude = altitude * 1000.0;
                                    }
                                }
                            }
                            else if (sentence == "Recommended Minimum Specific GPS/TRANSIT Data")
                            {
                                //time
                                //don't uuse this because it doesn't have millis
                                //string timestring = parsed[sentence]["Time of Fix"];
                                //char[] splitter = { '.' };
                                //string[] parts = timestring.Split(splitter);
                                //if (parts[0].Length == 6)
                                //{
                                //    int hour = int.Parse(parts[0].Substring(0, 2));
                                //    int minute = int.Parse(parts[0].Substring(2, 2));
                                //    int second = int.Parse(parts[0].Substring(4, 2));
                                //    time = new TimeSpan(0, hour, minute, second, 0);
                                //}
                                //else
                                //{
                                //    throw new Exception("Invalid Time Format");
                                //}


                                //latitude
                                string latitudeString          = parsed[sentence]["Latitude"];
                                string latitudeDirectionString = parsed[sentence]["Latitude Direction"];
                                if (latitudeString.Length >= 3)
                                {
                                    int    latdegrees = int.Parse(latitudeString.Substring(0, 2));
                                    double latminute  = double.Parse(latitudeString.Substring(2), _numberCulture.NumberFormat);
                                    latitude = Coordinate.CoordinateToDouble(latdegrees, latminute, 0);
                                    if (latitudeDirectionString.ToLower() == "s")
                                    {
                                        latitude = -latitude;
                                    }
                                }

                                //longitude
                                string longitudeString          = parsed[sentence]["Longitude"];
                                string longitudeDirectionString = parsed[sentence]["Longitude Direction"];
                                if (longitudeString.Length >= 3)
                                {
                                    int    longdegrees = int.Parse(longitudeString.Substring(0, 3));
                                    double longminute  = double.Parse(longitudeString.Substring(3), _numberCulture.NumberFormat);
                                    longitude = Coordinate.CoordinateToDouble(longdegrees, longminute, 0);
                                    if (longitudeDirectionString.ToLower() == "w")
                                    {
                                        longitude = -longitude;
                                    }
                                }

                                string speedString = parsed[sentence]["Speed over ground"];
                                double.TryParse(speedString, out speed);
                                //speed = double.Parse(speedString, _numberCulture.NumberFormat);

                                string cogString = parsed[sentence]["Course Made Good"];
                                double.TryParse(cogString, out courseOverGroundByLocation);

                                string datestring = parsed[sentence]["Date of Fix"];
                                if (datestring.Length == 6)
                                {
                                    int day   = int.Parse(datestring.Substring(0, 2));
                                    int month = int.Parse(datestring.Substring(2, 2));
                                    int year  = 2000 + int.Parse(datestring.Substring(4, 2));

                                    if (!date.HasValue)
                                    {
                                        date = DateTime.UtcNow;
                                    }

                                    date = new DateTime(year, month, day, date.Value.Hour, date.Value.Minute, date.Value.Second, date.Value.Millisecond);
                                }
                                else
                                {
                                    throw new Exception("Invalid Time Format");
                                }

                                string magneticVariationString = parsed[sentence]["Magnetic Variation"];
                                if (double.TryParse(magneticVariationString, out magneticDeviation))
                                {
                                    if (parsed[sentence]["Magnetic Variation Direction"].ToLower() == "w")
                                    {
                                        magneticDeviation = -magneticDeviation;
                                    }
                                }
                            }
                            else if (sentence == "Data and Time")
                            {
                                //time
                                string   timestring = parsed[sentence]["Time"];
                                char[]   splitter   = { '.' };
                                string[] parts      = timestring.Split(splitter);
                                if (parts[0].Length == 6)
                                {
                                    int hour        = int.Parse(parts[0].Substring(0, 2));
                                    int minute      = int.Parse(parts[0].Substring(2, 2));
                                    int second      = int.Parse(parts[0].Substring(4, 2));
                                    int millisecond = (int)(double.Parse("0." + parts[1], _numberCulture.NumberFormat) * 1000.0);
                                    int day         = int.Parse(parsed[sentence]["Day"]);
                                    int month       = int.Parse(parsed[sentence]["Month"]);
                                    int year        = int.Parse(parsed[sentence]["Year"]);

                                    if (!date.HasValue)
                                    {
                                        date = DateTime.UtcNow;
                                    }

                                    date = new DateTime(year, month, day, hour, minute, second, millisecond);
                                }
                                else
                                {
                                    throw new Exception("Invalid Time Format");
                                }
                            }
                            else if (sentence == "Track Made Good and Ground Speed")
                            {
                                string trueCourseString = parsed[sentence]["True Course Made Good Over Gound"];
                                double.TryParse(trueCourseString, out trueCourseMadeGood);
                                string magneticCourseStrin = parsed[sentence]["Magnetic Course Made Good over Ground"];
                                double.TryParse(magneticCourseStrin, out magneticCourseMadeGood);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.Debug("Exception parsing gps line:" + line);
                    }
                }

                lock (state)
                {
                    if (latitude != double.MinValue && longitude != double.MinValue)
                    {
                        state.Location = new CoordinatePoint(new Coordinate(latitude), new Coordinate(longitude), height);
                    }
                    if (speed != double.MinValue)
                    {
                        state.StateValues[StateValue.SpeedInKnots] = speed;

                        //don't set COG if we're not really moving
                        if (courseOverGroundByLocation != double.MinValue && speed > _minimumSpeed)
                        {
                            state.StateValues[StateValue.CourseOverGroundDirection] = courseOverGroundByLocation;
                        }
                    }

                    if (date.HasValue)
                    {
                        state.GpsTime = date.Value;
                    }

                    if (trueCourseMadeGood != double.MinValue)
                    {
                        state.StateValues[StateValue.TrueCourseMadeGood] = trueCourseMadeGood;
                    }
                    if (magneticCourseMadeGood != double.MinValue)
                    {
                        state.StateValues[StateValue.MagneticCourseMadeGood] = magneticCourseMadeGood;
                    }
                    //if (magneticDeviation != double.MinValue)
                    //{
                    //    _logger.Info("GPS set variation to "+magneticDeviation);
                    //    state.MagneticDeviation = magneticDeviation;
                    //}

                    if (altitude != double.MinValue)
                    {
                        //_logger.Info("GPS set altitude to " + altitude);
                        state.StateValues[StateValue.AltitudeInMeters] = altitude;
                    }
                }
                //update the state
            }
        }
コード例 #24
0
ファイル: FileGpsClient.cs プロジェクト: sakatuba/GPS.NET
        public override bool Connect()
        {
            var data = (FileGpsInfo)GpsInfo;

            IsRunning = true;
            OnGpsStatusChanged(GpsStatus.Connecting);

            var parser         = new NmeaParser();
            var gpsdDataParser = new GpsdDataParser();

            var headerLine      = true;
            var latColumnIndex  = 0;
            var longColumnIndex = 0;
            var minArraySize    = 0;

            try
            {
                using (var streamReader = File.OpenText(data.FilePath))
                {
                    string line;
                    OnGpsStatusChanged(GpsStatus.Connected);
                    while (IsRunning && (line = streamReader.ReadLine()) != null)
                    {
                        OnRawGpsDataReceived(line);
                        switch (data.FileType)
                        {
                        case FileType.Nmea:
                            var nmeaResult = parser.Parse(line);
                            var result     = nmeaResult as GprmcMessage;
                            if (result == null)
                            {
                                continue;
                            }
                            OnGpsDataReceived(new GpsDataEventArgs(result));
                            break;

                        case FileType.Gpsd:
                            var gpsdResult  = gpsdDataParser.GetGpsData(line);
                            var gpsLocation = gpsdResult as GpsLocation;
                            if (gpsLocation == null)
                            {
                                continue;
                            }
                            OnGpsDataReceived(new GpsDataEventArgs(gpsLocation));
                            break;

                        case FileType.LatitudeLongitude:
                            if (headerLine)
                            {
                                var headers = line.Split(';');

                                for (var i = 0; i < headers.Length; i++)
                                {
                                    if (headers[i] == Properties.Settings.Default.File_Latitude_Header)
                                    {
                                        latColumnIndex = i;
                                    }
                                    if (headers[i] == Properties.Settings.Default.File_Longitude_Header)
                                    {
                                        longColumnIndex = i;
                                    }
                                }
                                minArraySize = Math.Max(latColumnIndex, longColumnIndex);
                                headerLine   = false;
                            }
                            else
                            {
                                var latLongResult = line.Split(';');
                                if (latLongResult.Length < 2)
                                {
                                    throw new InvalidFileFormatException(data.FilePath);
                                }
                                if (latLongResult.Length < minArraySize)
                                {
                                    continue;
                                }

                                double latitude;
                                if (
                                    !double.TryParse(latLongResult[latColumnIndex], NumberStyles.Any,
                                                     CultureInfo.InvariantCulture, out latitude))
                                {
                                    continue;
                                }
                                double longitude;
                                if (
                                    !double.TryParse(latLongResult[longColumnIndex], NumberStyles.Any,
                                                     CultureInfo.InvariantCulture, out longitude))
                                {
                                    continue;
                                }

                                var message = new GpsDataEventArgs(latitude, longitude);
                                OnGpsDataReceived(message);
                            }
                            break;

                        default:
                            throw new ArgumentOutOfRangeException();
                        }
                        Thread.Sleep(data.ReadFrequenty);
                    }
                    Disconnect();
                    return(true);
                }
            }
            catch
            {
                Disconnect();
                throw;
            }
        }