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

Last change on this file since 1388 was 1388, checked in by stoecker, 15 years ago

fix NMEA parsing: #1853

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