source: josm/trunk/src/org/openstreetmap/josm/io/NmeaReader.java@ 9746

Last change on this file since 9746 was 9740, checked in by simon04, 11 years ago

see #12485 - Add unit test for nmea reading

  • Property svn:eol-style set to native
File size: 17.1 KB
RevLine 
[8378]1// License: GPL. For details, see LICENSE file.
[738]2package org.openstreetmap.josm.io;
3
4import java.io.BufferedReader;
[7596]5import java.io.IOException;
[738]6import java.io.InputStream;
7import java.io.InputStreamReader;
[7082]8import java.nio.charset.StandardCharsets;
[1167]9import java.text.ParsePosition;
10import java.text.SimpleDateFormat;
[738]11import java.util.ArrayList;
12import java.util.Collection;
[2907]13import java.util.Collections;
[1167]14import java.util.Date;
[738]15
[6287]16import org.openstreetmap.josm.Main;
[738]17import org.openstreetmap.josm.data.coor.LatLon;
[7518]18import org.openstreetmap.josm.data.gpx.GpxConstants;
[738]19import org.openstreetmap.josm.data.gpx.GpxData;
[2907]20import org.openstreetmap.josm.data.gpx.ImmutableGpxTrack;
[738]21import org.openstreetmap.josm.data.gpx.WayPoint;
22
23/**
[7049]24 * Reads a NMEA file. Based on information from
25 * <a href="http://www.kowoma.de/gps/zusatzerklaerungen/NMEA.htm">http://www.kowoma.de</a>
[1167]26 *
[738]27 * @author cbrill
28 */
29public class NmeaReader {
30
[1169]31 /** Handler for the different types that NMEA speaks. */
[8836]32 public enum NMEA_TYPE {
[738]33
[1169]34 /** RMC = recommended minimum sentence C. */
35 GPRMC("$GPRMC"),
36 /** GPS positions. */
37 GPGGA("$GPGGA"),
38 /** SA = satellites active. */
39 GPGSA("$GPGSA"),
40 /** Course over ground and ground speed */
41 GPVTG("$GPVTG");
[738]42
[1169]43 private final String type;
[738]44
[1169]45 NMEA_TYPE(String type) {
46 this.type = type;
47 }
[738]48
[1169]49 public String getType() {
50 return this.type;
51 }
52 }
[738]53
[1169]54 // GPVTG
[8836]55 public enum GPVTG {
[8510]56 COURSE(1), COURSE_REF(2), // true course
[1169]57 COURSE_M(3), COURSE_M_REF(4), // magnetic course
58 SPEED_KN(5), SPEED_KN_UNIT(6), // speed in knots
59 SPEED_KMH(7), SPEED_KMH_UNIT(8), // speed in km/h
60 REST(9); // version-specific rest
[738]61
[1169]62 public final int position;
[1167]63
[1169]64 GPVTG(int position) {
65 this.position = position;
66 }
67 }
[1167]68
[1169]69 // The following only applies to GPRMC
[8836]70 public enum GPRMC {
[1169]71 TIME(1),
72 /** Warning from the receiver (A = data ok, V = warning) */
73 RECEIVER_WARNING(2),
74 WIDTH_NORTH(3), WIDTH_NORTH_NAME(4), // Latitude, NS
75 LENGTH_EAST(5), LENGTH_EAST_NAME(6), // Longitude, EW
76 SPEED(7), COURSE(8), DATE(9), // Speed in knots
77 MAGNETIC_DECLINATION(10), UNKNOWN(11), // magnetic declination
78 /**
79 * Mode (A = autonom; D = differential; E = estimated; N = not valid; S
80 * = simulated)
81 *
82 * @since NMEA 2.3
83 */
84 MODE(12);
[738]85
[1169]86 public final int position;
[738]87
[1169]88 GPRMC(int position) {
89 this.position = position;
90 }
91 }
[738]92
[1169]93 // The following only applies to GPGGA
[8836]94 public enum GPGGA {
[1169]95 TIME(1), LATITUDE(2), LATITUDE_NAME(3), LONGITUDE(4), LONGITUDE_NAME(5),
96 /**
97 * Quality (0 = invalid, 1 = GPS, 2 = DGPS, 6 = estimanted (@since NMEA
98 * 2.3))
99 */
100 QUALITY(6), SATELLITE_COUNT(7),
101 HDOP(8), // HDOP (horizontal dilution of precision)
102 HEIGHT(9), HEIGHT_UNTIS(10), // height above NN (above geoid)
103 HEIGHT_2(11), HEIGHT_2_UNTIS(12), // height geoid - height ellipsoid (WGS84)
[8510]104 GPS_AGE(13), // Age of differential GPS data
[1169]105 REF(14); // REF station
[738]106
[1169]107 public final int position;
108 GPGGA(int position) {
109 this.position = position;
110 }
111 }
[738]112
[8836]113 public enum GPGSA {
[1169]114 AUTOMATIC(1),
115 FIX_TYPE(2), // 1 = not fixed, 2 = 2D fixed, 3 = 3D fixed)
116 // PRN numbers for max 12 satellites
117 PRN_1(3), PRN_2(4), PRN_3(5), PRN_4(6), PRN_5(7), PRN_6(8),
118 PRN_7(9), PRN_8(10), PRN_9(11), PRN_10(12), PRN_11(13), PRN_12(14),
119 PDOP(15), // PDOP (precision)
120 HDOP(16), // HDOP (horizontal precision)
[8449]121 VDOP(17); // VDOP (vertical precision)
[738]122
[1169]123 public final int position;
124 GPGSA(int position) {
125 this.position = position;
126 }
127 }
[738]128
[1169]129 public GpxData data;
[738]130
[7049]131 private final SimpleDateFormat rmcTimeFmt = new SimpleDateFormat("ddMMyyHHmmss.SSS");
132 private final SimpleDateFormat rmcTimeFmtStd = new SimpleDateFormat("ddMMyyHHmmss");
[1167]133
[6889]134 private Date readTime(String p) {
[7049]135 Date d = rmcTimeFmt.parse(p, new ParsePosition(0));
[2626]136 if (d == null) {
[7049]137 d = rmcTimeFmtStd.parse(p, new ParsePosition(0));
[2626]138 }
[1381]139 if (d == null)
[2626]140 throw new RuntimeException("Date is malformed"); // malformed
[1381]141 return d;
142 }
143
[1169]144 // functons for reading the error stats
145 public NMEAParserState ps;
[1167]146
[1169]147 public int getParserUnknown() {
148 return ps.unknown;
149 }
[8510]150
[1169]151 public int getParserZeroCoordinates() {
[8346]152 return ps.zeroCoord;
[1169]153 }
[8510]154
[1169]155 public int getParserChecksumErrors() {
[8346]156 return ps.checksumErrors+ps.noChecksum;
[1169]157 }
[8510]158
[1169]159 public int getParserMalformed() {
160 return ps.malformed;
161 }
[8510]162
[1169]163 public int getNumberOfCoordinates() {
164 return ps.success;
165 }
[1167]166
[7596]167 public NmeaReader(InputStream source) throws IOException {
[1167]168
[1169]169 // create the data tree
170 data = new GpxData();
[7005]171 Collection<Collection<WayPoint>> currentTrack = new ArrayList<>();
[738]172
[7082]173 try (BufferedReader rd = new BufferedReader(new InputStreamReader(source, StandardCharsets.UTF_8))) {
[6822]174 StringBuilder sb = new StringBuilder(1024);
[1169]175 int loopstart_char = rd.read();
[1453]176 ps = new NMEAParserState();
[8510]177 if (loopstart_char == -1)
[1169]178 //TODO tell user about the problem?
179 return;
[8510]180 sb.append((char) loopstart_char);
181 ps.pDate = "010100"; // TODO date problem
182 while (true) {
[1169]183 // don't load unparsable files completely to memory
[8510]184 if (sb.length() >= 1020) {
[2626]185 sb.delete(0, sb.length()-1);
186 }
[1169]187 int c = rd.read();
[8510]188 if (c == '$') {
[6287]189 parseNMEASentence(sb.toString(), ps);
[1169]190 sb.delete(0, sb.length());
191 sb.append('$');
[8510]192 } else if (c == -1) {
[1169]193 // EOF: add last WayPoint if it works out
[8510]194 parseNMEASentence(sb.toString(), ps);
[1169]195 break;
[2626]196 } else {
[8510]197 sb.append((char) c);
[2626]198 }
[1169]199 }
[2907]200 currentTrack.add(ps.waypoints);
201 data.tracks.add(new ImmutableGpxTrack(currentTrack, Collections.<String, Object>emptyMap()));
[1167]202
[7596]203 } catch (IllegalDataException e) {
[6287]204 Main.warn(e);
[1169]205 }
206 }
[7037]207
[2626]208 private static class NMEAParserState {
[7005]209 protected Collection<WayPoint> waypoints = new ArrayList<>();
[8346]210 protected String pTime;
211 protected String pDate;
212 protected WayPoint pWp;
[738]213
[8840]214 protected int success; // number of successfully parsed sentences
215 protected int malformed;
216 protected int checksumErrors;
217 protected int noChecksum;
218 protected int unknown;
219 protected int zeroCoord;
[1169]220 }
[738]221
[1169]222 // Parses split up sentences into WayPoints which are stored
223 // in the collection in the NMEAParserState object.
224 // Returns true if the input made sence, false otherwise.
[6287]225 private boolean parseNMEASentence(String s, NMEAParserState ps) throws IllegalDataException {
[1169]226 try {
[6287]227 if (s.isEmpty()) {
228 throw new IllegalArgumentException("s is empty");
229 }
[1167]230
[1169]231 // checksum check:
[6296]232 // the bytes between the $ and the * are xored
[1169]233 // if there is no * or other meanities it will throw
234 // and result in a malformed packet.
235 String[] chkstrings = s.split("\\*");
[8395]236 if (chkstrings.length > 1) {
[7082]237 byte[] chb = chkstrings[0].getBytes(StandardCharsets.UTF_8);
[8510]238 int chk = 0;
[6248]239 for (int i = 1; i < chb.length; i++) {
[2626]240 chk ^= chb[i];
241 }
[8510]242 if (Integer.parseInt(chkstrings[1].substring(0, 2), 16) != chk) {
[8346]243 ps.checksumErrors++;
[8510]244 ps.pWp = null;
[1388]245 return false;
246 }
[2626]247 } else {
[8346]248 ps.noChecksum++;
[1169]249 }
250 // now for the content
251 String[] e = chkstrings[0].split(",");
252 String accu;
[1167]253
[8346]254 WayPoint currentwp = ps.pWp;
255 String currentDate = ps.pDate;
[1167]256
[1169]257 // handle the packet content
[8510]258 if ("$GPGGA".equals(e[0]) || "$GNGGA".equals(e[0])) {
[1169]259 // Position
260 LatLon latLon = parseLatLon(
261 e[GPGGA.LATITUDE_NAME.position],
262 e[GPGGA.LONGITUDE_NAME.position],
263 e[GPGGA.LATITUDE.position],
264 e[GPGGA.LONGITUDE.position]
[2626]265 );
[8510]266 if (latLon == null) {
[6287]267 throw new IllegalDataException("Malformed lat/lon");
268 }
[1167]269
[8384]270 if (LatLon.ZERO.equals(latLon)) {
[8346]271 ps.zeroCoord++;
[1169]272 return false;
273 }
[1167]274
[1169]275 // time
276 accu = e[GPGGA.TIME.position];
[1381]277 Date d = readTime(currentDate+accu);
[1167]278
[8510]279 if ((ps.pTime == null) || (currentwp == null) || !ps.pTime.equals(accu)) {
[1169]280 // this node is newer than the previous, create a new waypoint.
[8510]281 // no matter if previous WayPoint was null, we got something better now.
282 ps.pTime = accu;
[1169]283 currentwp = new WayPoint(latLon);
284 }
[8510]285 if (!currentwp.attr.containsKey("time")) {
[1169]286 // As this sentence has no complete time only use it
287 // if there is no time so far
[9740]288 currentwp.setTime(d);
[1169]289 }
290 // elevation
[8510]291 accu = e[GPGGA.HEIGHT_UNTIS.position];
292 if ("M".equals(accu)) {
[2626]293 // Ignore heights that are not in meters for now
[8510]294 accu = e[GPGGA.HEIGHT.position];
295 if (!accu.isEmpty()) {
[1169]296 Double.parseDouble(accu);
297 // if it throws it's malformed; this should only happen if the
298 // device sends nonstandard data.
[8510]299 if (!accu.isEmpty()) { // FIX ? same check
[7518]300 currentwp.put(GpxConstants.PT_ELE, accu);
[2626]301 }
[1169]302 }
303 }
304 // number of sattelites
[8510]305 accu = e[GPGGA.SATELLITE_COUNT.position];
[1169]306 int sat = 0;
[8510]307 if (!accu.isEmpty()) {
[1169]308 sat = Integer.parseInt(accu);
[7518]309 currentwp.put(GpxConstants.PT_SAT, accu);
[1169]310 }
311 // h-dilution
[8510]312 accu = e[GPGGA.HDOP.position];
313 if (!accu.isEmpty()) {
[8390]314 currentwp.put(GpxConstants.PT_HDOP, Float.valueOf(accu));
[2626]315 }
[1169]316 // fix
[8510]317 accu = e[GPGGA.QUALITY.position];
318 if (!accu.isEmpty()) {
[1169]319 int fixtype = Integer.parseInt(accu);
320 switch(fixtype) {
321 case 0:
[7518]322 currentwp.put(GpxConstants.PT_FIX, "none");
[1169]323 break;
324 case 1:
[8510]325 if (sat < 4) {
[7518]326 currentwp.put(GpxConstants.PT_FIX, "2d");
[2626]327 } else {
[7518]328 currentwp.put(GpxConstants.PT_FIX, "3d");
[2626]329 }
[1169]330 break;
331 case 2:
[7518]332 currentwp.put(GpxConstants.PT_FIX, "dgps");
[1169]333 break;
334 default:
335 break;
336 }
337 }
[8510]338 } else if ("$GPVTG".equals(e[0]) || "$GNVTG".equals(e[0])) {
[1169]339 // COURSE
340 accu = e[GPVTG.COURSE_REF.position];
[8510]341 if ("T".equals(accu)) {
[1169]342 // other values than (T)rue are ignored
343 accu = e[GPVTG.COURSE.position];
[8510]344 if (!accu.isEmpty()) {
[1169]345 Double.parseDouble(accu);
[7518]346 currentwp.put("course", accu);
[1169]347 }
348 }
349 // SPEED
350 accu = e[GPVTG.SPEED_KMH_UNIT.position];
[8510]351 if (accu.startsWith("K")) {
[1169]352 accu = e[GPVTG.SPEED_KMH.position];
[8510]353 if (!accu.isEmpty()) {
[1169]354 double speed = Double.parseDouble(accu);
355 speed /= 3.6; // speed in m/s
[7518]356 currentwp.put("speed", Double.toString(speed));
[1169]357 }
358 }
[8510]359 } else if ("$GPGSA".equals(e[0]) || "$GNGSA".equals(e[0])) {
[1169]360 // vdop
[8510]361 accu = e[GPGSA.VDOP.position];
362 if (!accu.isEmpty()) {
[8390]363 currentwp.put(GpxConstants.PT_VDOP, Float.valueOf(accu));
[2626]364 }
[1169]365 // hdop
[8510]366 accu = e[GPGSA.HDOP.position];
367 if (!accu.isEmpty()) {
[8390]368 currentwp.put(GpxConstants.PT_HDOP, Float.valueOf(accu));
[2626]369 }
[1169]370 // pdop
[8510]371 accu = e[GPGSA.PDOP.position];
372 if (!accu.isEmpty()) {
[8390]373 currentwp.put(GpxConstants.PT_PDOP, Float.valueOf(accu));
[2626]374 }
[8510]375 } else if ("$GPRMC".equals(e[0]) || "$GNRMC".equals(e[0])) {
[1169]376 // coordinates
377 LatLon latLon = parseLatLon(
378 e[GPRMC.WIDTH_NORTH_NAME.position],
379 e[GPRMC.LENGTH_EAST_NAME.position],
380 e[GPRMC.WIDTH_NORTH.position],
381 e[GPRMC.LENGTH_EAST.position]
[2626]382 );
[8384]383 if (LatLon.ZERO.equals(latLon)) {
[8346]384 ps.zeroCoord++;
[1169]385 return false;
386 }
387 // time
388 currentDate = e[GPRMC.DATE.position];
389 String time = e[GPRMC.TIME.position];
[1167]390
[1381]391 Date d = readTime(currentDate+time);
[1167]392
[8510]393 if (ps.pTime == null || currentwp == null || !ps.pTime.equals(time)) {
[1169]394 // this node is newer than the previous, create a new waypoint.
[8510]395 ps.pTime = time;
[1169]396 currentwp = new WayPoint(latLon);
397 }
398 // time: this sentence has complete time so always use it.
[9740]399 currentwp.setTime(d);
[1169]400 // speed
401 accu = e[GPRMC.SPEED.position];
[8510]402 if (!accu.isEmpty() && !currentwp.attr.containsKey("speed")) {
[1169]403 double speed = Double.parseDouble(accu);
404 speed *= 0.514444444; // to m/s
[7518]405 currentwp.put("speed", Double.toString(speed));
[1169]406 }
407 // course
408 accu = e[GPRMC.COURSE.position];
[8510]409 if (!accu.isEmpty() && !currentwp.attr.containsKey("course")) {
[1169]410 Double.parseDouble(accu);
[7518]411 currentwp.put("course", accu);
[1169]412 }
[1167]413
[1169]414 // TODO fix?
415 // * Mode (A = autonom; D = differential; E = estimated; N = not valid; S
416 // * = simulated)
417 // *
418 // * @since NMEA 2.3
419 //
420 //MODE(12);
421 } else {
422 ps.unknown++;
423 return false;
424 }
[8346]425 ps.pDate = currentDate;
[8510]426 if (ps.pWp != currentwp) {
427 if (ps.pWp != null) {
[8346]428 ps.pWp.setTime();
[1169]429 }
[8346]430 ps.pWp = currentwp;
[1169]431 ps.waypoints.add(currentwp);
432 ps.success++;
433 return true;
434 }
435 return true;
[1167]436
[6248]437 } catch (RuntimeException x) {
[1169]438 // out of bounds and such
439 ps.malformed++;
[8510]440 ps.pWp = null;
[1169]441 return false;
442 }
443 }
[738]444
[8870]445 private static LatLon parseLatLon(String ns, String ew, String dlat, String dlon)
[2626]446 throws NumberFormatException {
[1169]447 String widthNorth = dlat.trim();
448 String lengthEast = dlon.trim();
[1167]449
[1169]450 // return a zero latlon instead of null so it is logged as zero coordinate
451 // instead of malformed sentence
[9214]452 if (widthNorth.isEmpty() && lengthEast.isEmpty()) return LatLon.ZERO;
[1167]453
[1169]454 // The format is xxDDLL.LLLL
455 // xx optional whitespace
456 // DD (int) degres
457 // LL.LLLL (double) latidude
458 int latdegsep = widthNorth.indexOf('.') - 2;
459 if (latdegsep < 0) return null;
[1167]460
[1169]461 int latdeg = Integer.parseInt(widthNorth.substring(0, latdegsep));
462 double latmin = Double.parseDouble(widthNorth.substring(latdegsep));
[8510]463 if (latdeg < 0) {
[1388]464 latmin *= -1.0;
[2626]465 }
[1169]466 double lat = latdeg + latmin / 60;
467 if ("S".equals(ns)) {
468 lat = -lat;
469 }
[738]470
[1169]471 int londegsep = lengthEast.indexOf('.') - 2;
472 if (londegsep < 0) return null;
[1167]473
[1169]474 int londeg = Integer.parseInt(lengthEast.substring(0, londegsep));
475 double lonmin = Double.parseDouble(lengthEast.substring(londegsep));
[8510]476 if (londeg < 0) {
[1388]477 lonmin *= -1.0;
[2626]478 }
[1169]479 double lon = londeg + lonmin / 60;
480 if ("W".equals(ew)) {
481 lon = -lon;
482 }
483 return new LatLon(lat, lon);
484 }
[738]485}
Note: See TracBrowser for help on using the repository browser.