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

Last change on this file since 4243 was 4243, checked in by stoecker, 14 years ago

fix track coloring and NMEA import

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