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

Last change on this file since 9703 was 9703, checked in by simon04, 8 years ago

see #12472 - Fix warnings identified by error-prone

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