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

Last change on this file since 3965 was 3083, checked in by bastiK, 14 years ago

added svn:eol-style=native to source files

  • Property svn:eol-style set to native
File size: 17.4 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.Collection;
14import java.util.Collections;
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.ImmutableGpxTrack;
20import org.openstreetmap.josm.data.gpx.WayPoint;
21import org.openstreetmap.josm.tools.DateUtils;
22
23/**
24 * Read a nmea file. Based on information from
25 * http://www.kowoma.de/gps/zusatzerklaerungen/NMEA.htm
26 *
27 * @author cbrill
28 */
29public class NmeaReader {
30
31 /** Handler for the different types that NMEA speaks. */
32 public static enum NMEA_TYPE {
33
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");
42
43 private final String type;
44
45 NMEA_TYPE(String type) {
46 this.type = type;
47 }
48
49 public String getType() {
50 return this.type;
51 }
52
53 public boolean equals(String type) {
54 return this.type.equals(type);
55 }
56 }
57
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
65
66 public final int position;
67
68 GPVTG(int position) {
69 this.position = position;
70 }
71 }
72
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);
89
90 public final int position;
91
92 GPRMC(int position) {
93 this.position = position;
94 }
95 }
96
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
110
111 public final int position;
112 GPGGA(int position) {
113 this.position = position;
114 }
115 }
116
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)
126
127 public final int position;
128 GPGSA(int position) {
129 this.position = position;
130 }
131 }
132
133 public GpxData data;
134
135 // private final static SimpleDateFormat GGATIMEFMT =
136 // new SimpleDateFormat("HHmmss.SSS");
137 private final static SimpleDateFormat RMCTIMEFMT =
138 new SimpleDateFormat("ddMMyyHHmmss.SSS");
139 private final static SimpleDateFormat RMCTIMEFMTSTD =
140 new SimpleDateFormat("ddMMyyHHmmss");
141
142 private Date readTime(String p)
143 {
144 Date d = RMCTIMEFMT.parse(p, new ParsePosition(0));
145 if (d == null) {
146 d = RMCTIMEFMTSTD.parse(p, new ParsePosition(0));
147 }
148 if (d == null)
149 throw new RuntimeException("Date is malformed"); // malformed
150 return d;
151 }
152
153 // functons for reading the error stats
154 public NMEAParserState ps;
155
156 public int getParserUnknown() {
157 return ps.unknown;
158 }
159 public int getParserZeroCoordinates() {
160 return ps.zero_coord;
161 }
162 public int getParserChecksumErrors() {
163 return ps.checksum_errors+ps.no_checksum;
164 }
165 public int getParserMalformed() {
166 return ps.malformed;
167 }
168 public int getNumberOfCoordinates() {
169 return ps.success;
170 }
171
172 public NmeaReader(InputStream source, File relativeMarkerPath) {
173
174 // create the data tree
175 data = new GpxData();
176 Collection<Collection<WayPoint>> currentTrack = new ArrayList<Collection<WayPoint>>();
177
178 try {
179 BufferedReader rd =
180 new BufferedReader(new InputStreamReader(source));
181
182 StringBuffer sb = new StringBuffer(1024);
183 int loopstart_char = rd.read();
184 ps = new NMEAParserState();
185 if(loopstart_char == -1)
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
192 if(sb.length()>=1020) {
193 sb.delete(0, sb.length()-1);
194 }
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;
204 } else {
205 sb.append((char)c);
206 }
207 }
208 rd.close();
209 currentTrack.add(ps.waypoints);
210 data.tracks.add(new ImmutableGpxTrack(currentTrack, Collections.<String, Object>emptyMap()));
211 data.recalculateBounds();
212
213 } catch (final IOException e) {
214 // TODO tell user about the problem?
215 }
216 }
217 private static class NMEAParserState {
218 protected Collection<WayPoint> waypoints = new ArrayList<WayPoint>();
219 protected String p_Time;
220 protected String p_Date;
221 protected WayPoint p_Wp;
222
223 protected int success = 0; // number of successfully parsend sentences
224 protected int malformed = 0;
225 protected int checksum_errors = 0;
226 protected int no_checksum = 0;
227 protected int unknown = 0;
228 protected int zero_coord = 0;
229 }
230
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 {
236 if (s.equals(""))
237 throw new NullPointerException();
238
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("\\*");
244 if(chkstrings.length > 1)
245 {
246 byte[] chb = chkstrings[0].getBytes();
247 int chk=0;
248 for(int i = 1; i < chb.length; i++) {
249 chk ^= chb[i];
250 }
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 }
257 } else {
258 ps.no_checksum++;
259 }
260 // now for the content
261 String[] e = chkstrings[0].split(",");
262 String accu;
263
264 WayPoint currentwp = ps.p_Wp;
265 String currentDate = ps.p_Date;
266
267 // handle the packet content
268 if(e[0].equals("$GPGGA")) {
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]
275 );
276 if(latLon==null)
277 throw new NullPointerException(); // malformed
278
279 if((latLon.lat()==0.0) && (latLon.lon()==0.0)) {
280 ps.zero_coord++;
281 return false;
282 }
283
284 // time
285 accu = e[GPGGA.TIME.position];
286 Date d = readTime(currentDate+accu);
287
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
298 currentwp.attr.put("time", DateUtils.fromDate(d));
299 }
300 // elevation
301 accu=e[GPGGA.HEIGHT_UNTIS.position];
302 if(accu.equals("M")) {
303 // Ignore heights that are not in meters for now
304 accu=e[GPGGA.HEIGHT.position];
305 if(!accu.equals("")) {
306 Double.parseDouble(accu);
307 // if it throws it's malformed; this should only happen if the
308 // device sends nonstandard data.
309 if(!accu.equals("")) {
310 currentwp.attr.put("ele", accu);
311 }
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];
323 if(!accu.equals("")) {
324 currentwp.attr.put("hdop", Float.parseFloat(accu));
325 }
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:
335 if(sat < 4) {
336 currentwp.attr.put("fix", "2d");
337 } else {
338 currentwp.attr.put("fix", "3d");
339 }
340 break;
341 case 2:
342 currentwp.attr.put("fix", "dgps");
343 break;
344 default:
345 break;
346 }
347 }
348 } else if(e[0].equals("$GPVTG")) {
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 }
369 } else if(e[0].equals("$GPGSA")) {
370 // vdop
371 accu=e[GPGSA.VDOP.position];
372 if(!accu.equals("")) {
373 currentwp.attr.put("vdop", Float.parseFloat(accu));
374 }
375 // hdop
376 accu=e[GPGSA.HDOP.position];
377 if(!accu.equals("")) {
378 currentwp.attr.put("hdop", Float.parseFloat(accu));
379 }
380 // pdop
381 accu=e[GPGSA.PDOP.position];
382 if(!accu.equals("")) {
383 currentwp.attr.put("pdop", Float.parseFloat(accu));
384 }
385 }
386 else if(e[0].equals("$GPRMC")) {
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]
393 );
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];
401
402 Date d = readTime(currentDate+time);
403
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.
410 currentwp.attr.put("time", DateUtils.fromDate(d));
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 }
424
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;
447
448 } catch(RuntimeException x) {
449 // out of bounds and such
450 // x.printStackTrace();
451 // System.out.println("Malformed line: "+s.toString().trim());
452 ps.malformed++;
453 ps.p_Wp=null;
454 return false;
455 }
456 }
457
458 private LatLon parseLatLon(String ns, String ew, String dlat, String dlon)
459 throws NumberFormatException {
460 String widthNorth = dlat.trim();
461 String lengthEast = dlon.trim();
462
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);
466
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;
473
474 int latdeg = Integer.parseInt(widthNorth.substring(0, latdegsep));
475 double latmin = Double.parseDouble(widthNorth.substring(latdegsep));
476 if(latdeg < 0) {
477 latmin *= -1.0;
478 }
479 double lat = latdeg + latmin / 60;
480 if ("S".equals(ns)) {
481 lat = -lat;
482 }
483
484 int londegsep = lengthEast.indexOf('.') - 2;
485 if (londegsep < 0) return null;
486
487 int londeg = Integer.parseInt(lengthEast.substring(0, londegsep));
488 double lonmin = Double.parseDouble(lengthEast.substring(londegsep));
489 if(londeg < 0) {
490 lonmin *= -1.0;
491 }
492 double lon = londeg + lonmin / 60;
493 if ("W".equals(ew)) {
494 lon = -lon;
495 }
496 return new LatLon(lat, lon);
497 }
498}
Note: See TracBrowser for help on using the repository browser.