001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io.nmea;
003
004import java.nio.charset.StandardCharsets;
005import java.time.Instant;
006import java.time.ZoneOffset;
007import java.time.format.DateTimeFormatter;
008import java.time.format.DateTimeFormatterBuilder;
009import java.time.format.DateTimeParseException;
010import java.time.format.ResolverStyle;
011import java.time.temporal.ChronoField;
012import java.util.ArrayList;
013import java.util.Arrays;
014import java.util.Collection;
015import java.util.Collections;
016import java.util.Locale;
017
018import org.openstreetmap.josm.data.coor.LatLon;
019import org.openstreetmap.josm.data.gpx.GpxConstants;
020import org.openstreetmap.josm.data.gpx.WayPoint;
021import org.openstreetmap.josm.io.IllegalDataException;
022import org.openstreetmap.josm.tools.Logging;
023
024/**
025 * Parses NMEA 0183 data. Based on information from
026 * <a href="https://gpsd.gitlab.io/gpsd/NMEA.html">https://gpsd.gitlab.io/gpsd</a>.
027 *
028 * NMEA data is in printable ASCII form and may include information such as position,
029 * speed, depth, frequency allocation, etc.
030 * Typical messages might be 11 to a maximum of 79 characters in length.
031 *
032 * NMEA standard aims to support one-way serial data transmission from a single "talker"
033 * to one or more "listeners". The type of talker is identified by a 2-character mnemonic.
034 *
035 * NMEA information is encoded through a list of "sentences".
036 * @since 18787
037 */
038public class NmeaParser {
039
040    /**
041     * Course Over Ground and Ground Speed.
042     * <p>
043     * The actual course and speed relative to the ground
044     */
045    enum VTG {
046        COURSE(1), COURSE_REF(2), // true course
047        COURSE_M(3), COURSE_M_REF(4), // magnetic course
048        SPEED_KN(5), SPEED_KN_UNIT(6), // speed in knots
049        SPEED_KMH(7), SPEED_KMH_UNIT(8), // speed in km/h
050        REST(9); // version-specific rest
051
052        final int position;
053
054        VTG(int position) {
055            this.position = position;
056        }
057    }
058
059    /**
060     * Recommended Minimum Specific GNSS Data.
061     * <p>
062     * Time, date, position, course and speed data provided by a GNSS navigation receiver.
063     * This sentence is transmitted at intervals not exceeding 2-seconds.
064     * RMC is the recommended minimum data to be provided by a GNSS receiver.
065     * All data fields must be provided, null fields used only when data is temporarily unavailable.
066     */
067    enum RMC {
068        TIME(1),
069        /** Warning from the receiver (A = data ok, V = warning) */
070        RECEIVER_WARNING(2),
071        WIDTH_NORTH(3), WIDTH_NORTH_NAME(4), // Latitude, NS
072        LENGTH_EAST(5), LENGTH_EAST_NAME(6), // Longitude, EW
073        SPEED(7), COURSE(8), DATE(9),           // Speed in knots
074        MAGNETIC_DECLINATION(10), UNKNOWN(11),  // magnetic declination
075        /**
076         * Mode (A = autonom; D = differential; E = estimated; N = not valid; S = simulated)
077         *
078         * @since NMEA 2.3
079         */
080        MODE(12);
081
082        final int position;
083
084        RMC(int position) {
085            this.position = position;
086        }
087    }
088
089    /**
090     * Global Positioning System Fix Data.
091     * <p>
092     * Time, position and fix related data for a GPS receiver.
093     */
094    enum GGA {
095        TIME(1), LATITUDE(2), LATITUDE_NAME(3), LONGITUDE(4), LONGITUDE_NAME(5),
096        /**
097         * Quality (0 = invalid, 1 = GPS, 2 = DGPS, 6 = estimanted (@since NMEA 2.3))
098         */
099        QUALITY(6), SATELLITE_COUNT(7),
100        HDOP(8), // HDOP (horizontal dilution of precision)
101        HEIGHT(9), HEIGHT_UNTIS(10), // height above NN (above geoid)
102        HEIGHT_2(11), HEIGHT_2_UNTIS(12), // height geoid - height ellipsoid (WGS84)
103        GPS_AGE(13), // Age of differential GPS data
104        REF(14); // REF station
105
106        final int position;
107        GGA(int position) {
108            this.position = position;
109        }
110    }
111
112    /**
113     * GNSS DOP and Active Satellites.
114     * <p>
115     * GNSS receiver operating mode, satellites used in the navigation solution reported by the GGA or GNS sentence,
116     * and DOP values.
117     * If only GPS, GLONASS, etc. is used for the reported position solution the talker ID is GP, GL, etc.
118     * and the DOP values pertain to the individual system. If GPS, GLONASS, etc. are combined to obtain the
119     * reported position solution multiple GSA sentences are produced, one with the GPS satellites, another with
120     * the GLONASS satellites, etc. Each of these GSA sentences shall have talker ID GN, to indicate that the
121     * satellites are used in a combined solution and each shall have the PDOP, HDOP and VDOP for the
122     * combined satellites used in the position.
123     */
124    enum GSA {
125        AUTOMATIC(1),
126        FIX_TYPE(2), // 1 = not fixed, 2 = 2D fixed, 3 = 3D fixed)
127        // PRN numbers for max 12 satellites
128        PRN_1(3), PRN_2(4), PRN_3(5), PRN_4(6), PRN_5(7), PRN_6(8),
129        PRN_7(9), PRN_8(10), PRN_9(11), PRN_10(12), PRN_11(13), PRN_12(14),
130        PDOP(15),   // PDOP (precision)
131        HDOP(16),   // HDOP (horizontal precision)
132        VDOP(17);   // VDOP (vertical precision)
133
134        final int position;
135        GSA(int position) {
136            this.position = position;
137        }
138    }
139
140    /**
141     * GST - GNSS Pseudorange Noise Statistics
142     * <p>
143     * RMS and Standard deviation estimated values.
144     */
145    enum GST {
146        TIME(1),
147        RMS_DEVIATION(2),        // Total RMS standard deviation of ranges inputs to the navigation solution
148        STDDEV_MAJOR(3),         // Standard deviation (meters) of semi-major axis of error ellipse
149        STDDEV_MINOR(4),         // Standard deviation (meters) of semi-minor axis of error ellipse
150        STDDEV_MAJOR_BEARING(5), // Orientation of semi-major axis of error ellipse (true north degrees)
151        STDDEV_LAT(6),           // Standard deviation (meters) of latitude error
152        STDDEV_LONG(7),          // Standard deviation (meters) of longitude error
153        STDDEV_HEIGHT(8);        // Standard deviation (meters) of altitude error
154        final int position;
155        GST(int position) {
156            this.position = position;
157        }
158    }
159
160    /**
161     * Geographic Position - Latitude/Longitude.
162     * <p>
163     * Latitude and Longitude of vessel position, time of position fix and status.
164     */
165    enum GLL {
166        LATITUDE(1), LATITUDE_NS(2), // Latitude, NS
167        LONGITUDE(3), LONGITUDE_EW(4), // Latitude, EW
168        UTC(5), // Universal Time Coordinated
169        STATUS(6), // Status: A = Data valid, V = Data not valid
170        /**
171         * Mode (A = autonom; D = differential; E = estimated; N = not valid; S = simulated)
172         * @since NMEA 2.3
173         */
174        MODE(7);
175
176        final int position;
177        GLL(int position) {
178            this.position = position;
179        }
180    }
181
182    /**
183     * NMEA defines time with "a variable number of digits for decimal-fraction of seconds"
184     */
185    private static final DateTimeFormatter RMC_TIME_FMT =
186        new DateTimeFormatterBuilder()
187                .appendPattern("ddMMyyHHmmss")
188                .optionalStart()
189                .appendFraction(ChronoField.NANO_OF_SECOND, 1, 9, true)
190                .optionalEnd()
191                .toFormatter(Locale.ENGLISH)
192                .withZone(ZoneOffset.UTC)
193                /* allow bad date information, we're mainly interested in the positions */
194                .withResolverStyle(ResolverStyle.LENIENT);
195
196    protected Collection<WayPoint> waypoints = new ArrayList<>();
197    protected String pTime;
198    protected String pDate;
199    /* Waypoint currently in work */
200    protected WayPoint pWp;
201    /* number of successfully parsed sentences */
202    protected int success;
203    protected int malformed;
204    protected int checksumErrors;
205    protected int noChecksum;
206    protected int unknown;
207    protected int zeroCoord;
208
209    /**
210     * Number of unknown sentences
211     * @return the number of unknown sentences encountered
212     */
213    public int getParserUnknown() {
214        return unknown;
215    }
216
217    /**
218     * Number of empty coordinates
219     * @return the number of coordinates which have been zero
220     */
221    public int getParserZeroCoordinates() {
222        return zeroCoord;
223    }
224
225    /**
226     * Number of checksum errors
227     * @return the number of sentences with checksum errors
228     */
229    public int getParserChecksumErrors() {
230        return checksumErrors+noChecksum;
231    }
232
233    /**
234     * Number of malformed errors
235     * @return the number of malformed sentences
236     */
237    public int getParserMalformed() {
238        return malformed;
239    }
240
241    /**
242     * Number of successful coordinates
243     * @return the number of successfully read coordinates
244     */
245    public int getSuccess() {
246        return success;
247    }
248
249    /**
250     * List of collected coordinates
251     * When parsing a stream the last entry may be still incomplete
252     * @return the collection of points collected
253     */
254    public Collection<WayPoint> getWaypoints() {
255        return Collections.unmodifiableCollection(waypoints);
256    }
257
258    /**
259     * Return list of collected coordinates and drop old data
260     * When parsing a stream the last entry may be still incomplete and usually
261     * will not be dropped
262     * @return the collection of points collected
263     */
264    public Collection<WayPoint> getAndDropWaypoints() {
265        Collection<WayPoint> r = getWaypoints();
266        dropOldWaypoints();
267        return r;
268    }
269
270    /**
271     * Get rid of older data no longer needed, drops everything except current
272     * coordinate
273     */
274    public void dropOldWaypoints() {
275        waypoints.clear();
276        if (pWp != null)
277            waypoints.add(pWp);
278    }
279
280    /**
281     * Constructs a new {@code NmeaParser}
282     */
283    public NmeaParser() {
284        pDate = "010100"; // TODO date problem
285    }
286
287    /**
288     * Determines if the given address denotes the given NMEA sentence formatter of a known talker.
289     * @param address first tag of an NMEA sentence
290     * @param formatter sentence formatter mnemonic code
291     * @return {@code true} if the {@code address} denotes the given NMEA sentence formatter of a known talker
292     */
293    static boolean isSentence(String address, Sentence formatter) {
294        return Arrays.stream(TalkerId.values())
295                .anyMatch(talker -> address.equals('$' + talker.name() + formatter.name()));
296    }
297
298    /**
299     * Parses split up sentences into WayPoints which are stored
300     * in the collection in the NMEAParserState object.
301     * @param s data to parse
302     * @return {@code true} if the input made sense,  {@code false} otherwise.
303     */
304    public boolean parseNMEASentence(String s) throws IllegalDataException {
305        try {
306            if (s.isEmpty()) {
307                throw new IllegalArgumentException("s is empty");
308            }
309
310            // checksum check:
311            // the bytes between the $ and the * are xored
312            // if there is no * or other meanities it will throw
313            // and result in a malformed packet.
314            String[] chkstrings = s.split("\\*", -1);
315            if (chkstrings.length > 1) {
316                byte[] chb = chkstrings[0].getBytes(StandardCharsets.UTF_8);
317                int chk = 0;
318                for (int i = 1; i < chb.length; i++) {
319                    chk ^= chb[i];
320                }
321                if (Integer.parseInt(chkstrings[1].substring(0, 2), 16) != chk) {
322                    checksumErrors++;
323                    pWp = null;
324                    return false;
325                }
326            } else {
327                // Since there is no checksum, we remove any line endings
328                chkstrings[0] = chkstrings[0].replaceAll("\\r|\\n", "");
329                noChecksum++;
330            }
331            // now for the content
332            String[] e = chkstrings[0].split(",", -1);
333            String accu;
334
335            WayPoint currentwp = pWp;
336            String currentDate = pDate;
337
338            // handle the packet content
339            if (isSentence(e[0], Sentence.GGA)) {
340                // Position
341                LatLon latLon = parseLatLon(
342                        e[GGA.LATITUDE_NAME.position],
343                        e[GGA.LONGITUDE_NAME.position],
344                        e[GGA.LATITUDE.position],
345                        e[GGA.LONGITUDE.position]
346                );
347                if (latLon == null) {
348                    throw new IllegalDataException("Malformed lat/lon");
349                }
350
351                if (LatLon.ZERO.equals(latLon)) {
352                    zeroCoord++;
353                    return false;
354                }
355
356                // time
357                accu = e[GGA.TIME.position];
358                Instant instant = Instant.from(RMC_TIME_FMT.parse(currentDate+accu));
359
360                if ((pTime == null) || (currentwp == null) || !pTime.equals(accu)) {
361                    // this node is newer than the previous, create a new waypoint.
362                    // no matter if previous WayPoint was null, we got something better now.
363                    pTime = accu;
364                    currentwp = new WayPoint(latLon);
365                }
366                if (!currentwp.attr.containsKey("time")) {
367                    // As this sentence has no complete time only use it
368                    // if there is no time so far
369                    currentwp.setInstant(instant);
370                }
371                // elevation
372                accu = e[GGA.HEIGHT_UNTIS.position];
373                if ("M".equals(accu)) {
374                    // Ignore heights that are not in meters for now
375                    accu = e[GGA.HEIGHT.position];
376                    if (!accu.isEmpty()) {
377                        Double.parseDouble(accu);
378                        // if it throws it's malformed; this should only happen if the
379                        // device sends nonstandard data.
380                        if (!accu.isEmpty()) { // FIX ? same check
381                            currentwp.put(GpxConstants.PT_ELE, accu);
382                        }
383                    }
384                }
385                // number of satellites
386                accu = e[GGA.SATELLITE_COUNT.position];
387                int sat = 0;
388                if (!accu.isEmpty()) {
389                    sat = Integer.parseInt(accu);
390                    currentwp.put(GpxConstants.PT_SAT, accu);
391                }
392                // h-dilution
393                accu = e[GGA.HDOP.position];
394                if (!accu.isEmpty()) {
395                    currentwp.put(GpxConstants.PT_HDOP, Float.valueOf(accu));
396                }
397                // fix
398                accu = e[GGA.QUALITY.position];
399                if (!accu.isEmpty()) {
400                    int fixtype = Integer.parseInt(accu);
401                    switch (fixtype) {
402                    case 0:
403                        currentwp.put(GpxConstants.PT_FIX, "none");
404                        break;
405                    case 1:
406                        if (sat < 4) {
407                            currentwp.put(GpxConstants.PT_FIX, "2d");
408                        } else {
409                            currentwp.put(GpxConstants.PT_FIX, "3d");
410                        }
411                        break;
412                    case 2:
413                        currentwp.put(GpxConstants.PT_FIX, "dgps");
414                        break;
415                    case 3:
416                        currentwp.put(GpxConstants.PT_FIX, "pps");
417                        break;
418                    case 4:
419                        currentwp.put(GpxConstants.PT_FIX, "rtk");
420                        break;
421                    case 5:
422                        currentwp.put(GpxConstants.PT_FIX, "float rtk");
423                        break;
424                    case 6:
425                        currentwp.put(GpxConstants.PT_FIX, "estimated");
426                        break;
427                    case 7:
428                        currentwp.put(GpxConstants.PT_FIX, "manual");
429                        break;
430                    case 8:
431                        currentwp.put(GpxConstants.PT_FIX, "simulated");
432                        break;
433                    default:
434                        break;
435                    }
436                }
437                // Age of differential correction
438                if (GGA.GPS_AGE.position < e.length) {
439                    accu = e[GGA.GPS_AGE.position];
440                    if (!accu.isEmpty() && currentwp != null) {
441                        currentwp.put(GpxConstants.PT_AGEOFDGPSDATA, Float.valueOf(accu));
442                    }
443                }
444                // reference ID
445                if (GGA.REF.position < e.length) {
446                    accu = e[GGA.REF.position];
447                    if (!accu.isEmpty()) {
448                        currentwp.put(GpxConstants.PT_DGPSID, accu);
449                    }
450                }
451            } else if (isSentence(e[0], Sentence.VTG)) {
452                // COURSE
453                accu = e[VTG.COURSE_REF.position];
454                if ("T".equals(accu)) {
455                    // other values than (T)rue are ignored
456                    accu = e[VTG.COURSE.position];
457                    if (!accu.isEmpty() && currentwp != null) {
458                        Double.parseDouble(accu);
459                        currentwp.put(GpxConstants.PT_COURSE, accu);
460                    }
461                }
462                // SPEED
463                accu = e[VTG.SPEED_KMH_UNIT.position];
464                if (accu.startsWith("K")) {
465                    accu = e[VTG.SPEED_KMH.position];
466                    if (!accu.isEmpty() && currentwp != null) {
467                        double speed = Double.parseDouble(accu);
468                        currentwp.put("speed", Double.toString(speed)); // speed in km/h
469                    }
470                }
471            } else if (isSentence(e[0], Sentence.GSA)) {
472                // vdop
473                accu = e[GSA.VDOP.position];
474                if (!accu.isEmpty() && currentwp != null) {
475                    currentwp.put(GpxConstants.PT_VDOP, Float.valueOf(accu));
476                }
477                // hdop
478                accu = e[GSA.HDOP.position];
479                if (!accu.isEmpty() && currentwp != null) {
480                    currentwp.put(GpxConstants.PT_HDOP, Float.valueOf(accu));
481                }
482                // pdop
483                accu = e[GSA.PDOP.position];
484                if (!accu.isEmpty() && currentwp != null) {
485                    currentwp.put(GpxConstants.PT_PDOP, Float.valueOf(accu));
486                }
487                // GST Sentence
488            } else if (isSentence(e[0], Sentence.GST)) {
489                // std horizontal deviation
490                accu = e[GST.STDDEV_MAJOR.position];
491                if (!accu.isEmpty() && currentwp != null) {
492                    currentwp.put(GpxConstants.PT_STD_HDEV, Float.valueOf(accu));
493                }
494                // std vertical deviation
495                accu = e[GST.STDDEV_HEIGHT.position];
496                if (!accu.isEmpty() && currentwp != null) {
497                    currentwp.put(GpxConstants.PT_STD_VDEV, Float.valueOf(accu));
498                }
499            } else if (isSentence(e[0], Sentence.RMC)) {
500                // coordinates
501                LatLon latLon = parseLatLon(
502                        e[RMC.WIDTH_NORTH_NAME.position],
503                        e[RMC.LENGTH_EAST_NAME.position],
504                        e[RMC.WIDTH_NORTH.position],
505                        e[RMC.LENGTH_EAST.position]
506                );
507                if (LatLon.ZERO.equals(latLon)) {
508                    zeroCoord++;
509                    return false;
510                }
511                // time
512                currentDate = e[RMC.DATE.position];
513                String time = e[RMC.TIME.position];
514
515                Instant instant = Instant.from(RMC_TIME_FMT.parse(currentDate+time));
516
517                if (pTime == null || currentwp == null || !pTime.equals(time)) {
518                    // this node is newer than the previous, create a new waypoint.
519                    pTime = time;
520                    currentwp = new WayPoint(latLon);
521                }
522                // time: this sentence has complete time so always use it.
523                currentwp.setInstant(instant);
524                // speed
525                accu = e[RMC.SPEED.position];
526                if (!accu.isEmpty() && !currentwp.attr.containsKey("speed")) {
527                    double speed = Double.parseDouble(accu);
528                    speed *= 0.514444444 * 3.6; // to km/h
529                    currentwp.put("speed", Double.toString(speed));
530                }
531                // course
532                accu = e[RMC.COURSE.position];
533                if (!accu.isEmpty() && !currentwp.attr.containsKey("course")) {
534                    Double.parseDouble(accu);
535                    currentwp.put(GpxConstants.PT_COURSE, accu);
536                }
537
538                // TODO fix?
539                // * Mode (A = autonom; D = differential; E = estimated; N = not valid; S = simulated)
540                // *
541                // * @since NMEA 2.3
542                //
543                //MODE(12);
544            } else if (isSentence(e[0], Sentence.GLL)) {
545                // coordinates
546                LatLon latLon = parseLatLon(
547                        e[GLL.LATITUDE_NS.position],
548                        e[GLL.LONGITUDE_EW.position],
549                        e[GLL.LATITUDE.position],
550                        e[GLL.LONGITUDE.position]
551                );
552                if (LatLon.ZERO.equals(latLon)) {
553                    zeroCoord++;
554                    return false;
555                }
556                // only consider valid data
557                if (!"A".equals(e[GLL.STATUS.position])) {
558                    return false;
559                }
560
561                // RMC sentences contain a full date while GLL sentences contain only time,
562                // so create new waypoints only of the NMEA file does not contain RMC sentences
563                if (pTime == null || currentwp == null) {
564                    currentwp = new WayPoint(latLon);
565                }
566            } else {
567                unknown++;
568                return false;
569            }
570            pDate = currentDate;
571            if (pWp != currentwp) {
572                if (pWp != null) {
573                    pWp.getInstant();
574                }
575                pWp = currentwp;
576                waypoints.add(currentwp);
577                success++;
578                return true;
579            }
580            return true;
581
582        } catch (IllegalArgumentException | IndexOutOfBoundsException | IllegalDataException | DateTimeParseException ex) {
583            if (malformed < 5) {
584                Logging.warn(ex);
585            } else {
586                Logging.debug(ex);
587            }
588            malformed++;
589            pWp = null;
590            return false;
591        }
592    }
593
594    private static LatLon parseLatLon(String ns, String ew, String dlat, String dlon) {
595        String widthNorth = dlat.trim();
596        String lengthEast = dlon.trim();
597
598        // return a zero latlon instead of null so it is logged as zero coordinate
599        // instead of malformed sentence
600        if (widthNorth.isEmpty() && lengthEast.isEmpty()) return LatLon.ZERO;
601
602        // The format is xxDDLL.LLLL
603        // xx optional whitespace
604        // DD (int) degres
605        // LL.LLLL (double) latidude
606        int latdegsep = widthNorth.indexOf('.') - 2;
607        if (latdegsep < 0) return null;
608
609        int latdeg = Integer.parseInt(widthNorth.substring(0, latdegsep));
610        double latmin = Double.parseDouble(widthNorth.substring(latdegsep));
611        if (latdeg < 0) {
612            latmin *= -1.0;
613        }
614        double lat = latdeg + latmin / 60;
615        if ("S".equals(ns)) {
616            lat = -lat;
617        }
618
619        int londegsep = lengthEast.indexOf('.') - 2;
620        if (londegsep < 0) return null;
621
622        int londeg = Integer.parseInt(lengthEast.substring(0, londegsep));
623        double lonmin = Double.parseDouble(lengthEast.substring(londegsep));
624        if (londeg < 0) {
625            lonmin *= -1.0;
626        }
627        double lon = londeg + lonmin / 60;
628        if ("W".equals(ew)) {
629            lon = -lon;
630        }
631        return new LatLon(lat, lon);
632    }
633}