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

Last change on this file since 8415 was 8395, checked in by Don-vip, 9 years ago

convention - An open curly brace should be located at the end of a line

  • 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 static 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 public boolean equals(String type) {
55 return this.type.equals(type);
56 }
57 }
58
59 // GPVTG
60 public static enum GPVTG {
61 COURSE(1),COURSE_REF(2), // true course
62 COURSE_M(3), COURSE_M_REF(4), // magnetic course
63 SPEED_KN(5), SPEED_KN_UNIT(6), // speed in knots
64 SPEED_KMH(7), SPEED_KMH_UNIT(8), // speed in km/h
65 REST(9); // version-specific rest
66
67 public final int position;
68
69 GPVTG(int position) {
70 this.position = position;
71 }
72 }
73
74 // The following only applies to GPRMC
75 public static enum GPRMC {
76 TIME(1),
77 /** Warning from the receiver (A = data ok, V = warning) */
78 RECEIVER_WARNING(2),
79 WIDTH_NORTH(3), WIDTH_NORTH_NAME(4), // Latitude, NS
80 LENGTH_EAST(5), LENGTH_EAST_NAME(6), // Longitude, EW
81 SPEED(7), COURSE(8), DATE(9), // Speed in knots
82 MAGNETIC_DECLINATION(10), UNKNOWN(11), // magnetic declination
83 /**
84 * Mode (A = autonom; D = differential; E = estimated; N = not valid; S
85 * = simulated)
86 *
87 * @since NMEA 2.3
88 */
89 MODE(12);
90
91 public final int position;
92
93 GPRMC(int position) {
94 this.position = position;
95 }
96 }
97
98 // The following only applies to GPGGA
99 public static enum GPGGA {
100 TIME(1), LATITUDE(2), LATITUDE_NAME(3), LONGITUDE(4), LONGITUDE_NAME(5),
101 /**
102 * Quality (0 = invalid, 1 = GPS, 2 = DGPS, 6 = estimanted (@since NMEA
103 * 2.3))
104 */
105 QUALITY(6), SATELLITE_COUNT(7),
106 HDOP(8), // HDOP (horizontal dilution of precision)
107 HEIGHT(9), HEIGHT_UNTIS(10), // height above NN (above geoid)
108 HEIGHT_2(11), HEIGHT_2_UNTIS(12), // height geoid - height ellipsoid (WGS84)
109 GPS_AGE(13),// Age of differential GPS data
110 REF(14); // REF station
111
112 public final int position;
113 GPGGA(int position) {
114 this.position = position;
115 }
116 }
117
118 public static enum GPGSA {
119 AUTOMATIC(1),
120 FIX_TYPE(2), // 1 = not fixed, 2 = 2D fixed, 3 = 3D fixed)
121 // PRN numbers for max 12 satellites
122 PRN_1(3), PRN_2(4), PRN_3(5), PRN_4(6), PRN_5(7), PRN_6(8),
123 PRN_7(9), PRN_8(10), PRN_9(11), PRN_10(12), PRN_11(13), PRN_12(14),
124 PDOP(15), // PDOP (precision)
125 HDOP(16), // HDOP (horizontal precision)
126 VDOP(17), ; // VDOP (vertical precision)
127
128 public final int position;
129 GPGSA(int position) {
130 this.position = position;
131 }
132 }
133
134 public GpxData data;
135
136 private final SimpleDateFormat rmcTimeFmt = new SimpleDateFormat("ddMMyyHHmmss.SSS");
137 private final SimpleDateFormat rmcTimeFmtStd = new SimpleDateFormat("ddMMyyHHmmss");
138
139 private Date readTime(String p) {
140 Date d = rmcTimeFmt.parse(p, new ParsePosition(0));
141 if (d == null) {
142 d = rmcTimeFmtStd.parse(p, new ParsePosition(0));
143 }
144 if (d == null)
145 throw new RuntimeException("Date is malformed"); // malformed
146 return d;
147 }
148
149 // functons for reading the error stats
150 public NMEAParserState ps;
151
152 public int getParserUnknown() {
153 return ps.unknown;
154 }
155 public int getParserZeroCoordinates() {
156 return ps.zeroCoord;
157 }
158 public int getParserChecksumErrors() {
159 return ps.checksumErrors+ps.noChecksum;
160 }
161 public int getParserMalformed() {
162 return ps.malformed;
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 = 0; // number of successfully parsed sentences
216 protected int malformed = 0;
217 protected int checksumErrors = 0;
218 protected int noChecksum = 0;
219 protected int unknown = 0;
220 protected int zeroCoord = 0;
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
283 // better now.
284 ps.pTime=accu;
285 currentwp = new WayPoint(latLon);
286 }
287 if(!currentwp.attr.containsKey("time")) {
288 // As this sentence has no complete time only use it
289 // if there is no time so far
290 currentwp.put(GpxConstants.PT_TIME, DateUtils.fromDate(d));
291 }
292 // elevation
293 accu=e[GPGGA.HEIGHT_UNTIS.position];
294 if("M".equals(accu)) {
295 // Ignore heights that are not in meters for now
296 accu=e[GPGGA.HEIGHT.position];
297 if(!accu.isEmpty()) {
298 Double.parseDouble(accu);
299 // if it throws it's malformed; this should only happen if the
300 // device sends nonstandard data.
301 if(!accu.isEmpty()) { // FIX ? same check
302 currentwp.put(GpxConstants.PT_ELE, accu);
303 }
304 }
305 }
306 // number of sattelites
307 accu=e[GPGGA.SATELLITE_COUNT.position];
308 int sat = 0;
309 if(!accu.isEmpty()) {
310 sat = Integer.parseInt(accu);
311 currentwp.put(GpxConstants.PT_SAT, accu);
312 }
313 // h-dilution
314 accu=e[GPGGA.HDOP.position];
315 if(!accu.isEmpty()) {
316 currentwp.put(GpxConstants.PT_HDOP, Float.valueOf(accu));
317 }
318 // fix
319 accu=e[GPGGA.QUALITY.position];
320 if(!accu.isEmpty()) {
321 int fixtype = Integer.parseInt(accu);
322 switch(fixtype) {
323 case 0:
324 currentwp.put(GpxConstants.PT_FIX, "none");
325 break;
326 case 1:
327 if(sat < 4) {
328 currentwp.put(GpxConstants.PT_FIX, "2d");
329 } else {
330 currentwp.put(GpxConstants.PT_FIX, "3d");
331 }
332 break;
333 case 2:
334 currentwp.put(GpxConstants.PT_FIX, "dgps");
335 break;
336 default:
337 break;
338 }
339 }
340 } else if("$GPVTG".equals(e[0]) || "$GNVTG".equals(e[0])) {
341 // COURSE
342 accu = e[GPVTG.COURSE_REF.position];
343 if("T".equals(accu)) {
344 // other values than (T)rue are ignored
345 accu = e[GPVTG.COURSE.position];
346 if(!accu.isEmpty()) {
347 Double.parseDouble(accu);
348 currentwp.put("course", accu);
349 }
350 }
351 // SPEED
352 accu = e[GPVTG.SPEED_KMH_UNIT.position];
353 if(accu.startsWith("K")) {
354 accu = e[GPVTG.SPEED_KMH.position];
355 if(!accu.isEmpty()) {
356 double speed = Double.parseDouble(accu);
357 speed /= 3.6; // speed in m/s
358 currentwp.put("speed", Double.toString(speed));
359 }
360 }
361 } else if("$GPGSA".equals(e[0]) || "$GNGSA".equals(e[0])) {
362 // vdop
363 accu=e[GPGSA.VDOP.position];
364 if(!accu.isEmpty()) {
365 currentwp.put(GpxConstants.PT_VDOP, Float.valueOf(accu));
366 }
367 // hdop
368 accu=e[GPGSA.HDOP.position];
369 if(!accu.isEmpty()) {
370 currentwp.put(GpxConstants.PT_HDOP, Float.valueOf(accu));
371 }
372 // pdop
373 accu=e[GPGSA.PDOP.position];
374 if(!accu.isEmpty()) {
375 currentwp.put(GpxConstants.PT_PDOP, Float.valueOf(accu));
376 }
377 } else if("$GPRMC".equals(e[0]) || "$GNRMC".equals(e[0])) {
378 // coordinates
379 LatLon latLon = parseLatLon(
380 e[GPRMC.WIDTH_NORTH_NAME.position],
381 e[GPRMC.LENGTH_EAST_NAME.position],
382 e[GPRMC.WIDTH_NORTH.position],
383 e[GPRMC.LENGTH_EAST.position]
384 );
385 if (LatLon.ZERO.equals(latLon)) {
386 ps.zeroCoord++;
387 return false;
388 }
389 // time
390 currentDate = e[GPRMC.DATE.position];
391 String time = e[GPRMC.TIME.position];
392
393 Date d = readTime(currentDate+time);
394
395 if(ps.pTime==null || currentwp==null || !ps.pTime.equals(time)) {
396 // this node is newer than the previous, create a new waypoint.
397 ps.pTime=time;
398 currentwp = new WayPoint(latLon);
399 }
400 // time: this sentence has complete time so always use it.
401 currentwp.put(GpxConstants.PT_TIME, DateUtils.fromDate(d));
402 // speed
403 accu = e[GPRMC.SPEED.position];
404 if(!accu.isEmpty() && !currentwp.attr.containsKey("speed")) {
405 double speed = Double.parseDouble(accu);
406 speed *= 0.514444444; // to m/s
407 currentwp.put("speed", Double.toString(speed));
408 }
409 // course
410 accu = e[GPRMC.COURSE.position];
411 if(!accu.isEmpty() && !currentwp.attr.containsKey("course")) {
412 Double.parseDouble(accu);
413 currentwp.put("course", accu);
414 }
415
416 // TODO fix?
417 // * Mode (A = autonom; D = differential; E = estimated; N = not valid; S
418 // * = simulated)
419 // *
420 // * @since NMEA 2.3
421 //
422 //MODE(12);
423 } else {
424 ps.unknown++;
425 return false;
426 }
427 ps.pDate = currentDate;
428 if(ps.pWp != currentwp) {
429 if(ps.pWp!=null) {
430 ps.pWp.setTime();
431 }
432 ps.pWp = currentwp;
433 ps.waypoints.add(currentwp);
434 ps.success++;
435 return true;
436 }
437 return true;
438
439 } catch (RuntimeException x) {
440 // out of bounds and such
441 ps.malformed++;
442 ps.pWp=null;
443 return false;
444 }
445 }
446
447 private LatLon parseLatLon(String ns, String ew, String dlat, String dlon)
448 throws NumberFormatException {
449 String widthNorth = dlat.trim();
450 String lengthEast = dlon.trim();
451
452 // return a zero latlon instead of null so it is logged as zero coordinate
453 // instead of malformed sentence
454 if(widthNorth.isEmpty() && lengthEast.isEmpty()) return new LatLon(0.0,0.0);
455
456 // The format is xxDDLL.LLLL
457 // xx optional whitespace
458 // DD (int) degres
459 // LL.LLLL (double) latidude
460 int latdegsep = widthNorth.indexOf('.') - 2;
461 if (latdegsep < 0) return null;
462
463 int latdeg = Integer.parseInt(widthNorth.substring(0, latdegsep));
464 double latmin = Double.parseDouble(widthNorth.substring(latdegsep));
465 if(latdeg < 0) {
466 latmin *= -1.0;
467 }
468 double lat = latdeg + latmin / 60;
469 if ("S".equals(ns)) {
470 lat = -lat;
471 }
472
473 int londegsep = lengthEast.indexOf('.') - 2;
474 if (londegsep < 0) return null;
475
476 int londeg = Integer.parseInt(lengthEast.substring(0, londegsep));
477 double lonmin = Double.parseDouble(lengthEast.substring(londegsep));
478 if(londeg < 0) {
479 lonmin *= -1.0;
480 }
481 double lon = londeg + lonmin / 60;
482 if ("W".equals(ew)) {
483 lon = -lon;
484 }
485 return new LatLon(lat, lon);
486 }
487}
Note: See TracBrowser for help on using the repository browser.