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

Last change on this file since 2667 was 2655, checked in by jttt, 14 years ago

Fixed #4161 Major slowdown in recent versions, used correct pattern for listeners realized using CopyOnWriteArrayList

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.Collection;
14import java.util.Date;
15
16import org.openstreetmap.josm.data.coor.LatLon;
17import org.openstreetmap.josm.data.gpx.GpxData;
18import org.openstreetmap.josm.data.gpx.GpxTrack;
19import org.openstreetmap.josm.data.gpx.WayPoint;
20import org.openstreetmap.josm.tools.DateUtils;
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 }
147 if (d == null)
148 throw new RuntimeException("Date is malformed"); // malformed
149 return d;
150 }
151
152 // functons for reading the error stats
153 public NMEAParserState ps;
154
155 public int getParserUnknown() {
156 return ps.unknown;
157 }
158 public int getParserZeroCoordinates() {
159 return ps.zero_coord;
160 }
161 public int getParserChecksumErrors() {
162 return ps.checksum_errors+ps.no_checksum;
163 }
164 public int getParserMalformed() {
165 return ps.malformed;
166 }
167 public int getNumberOfCoordinates() {
168 return ps.success;
169 }
170
171 public NmeaReader(InputStream source, File relativeMarkerPath) {
172
173 // create the data tree
174 data = new GpxData();
175 GpxTrack currentTrack = new GpxTrack();
176 data.tracks.add(currentTrack);
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.trackSegs.add(ps.waypoints);
210 data.recalculateBounds();
211
212 } catch (final IOException e) {
213 // TODO tell user about the problem?
214 }
215 }
216 private static class NMEAParserState {
217 protected Collection<WayPoint> waypoints = new ArrayList<WayPoint>();
218 protected String p_Time;
219 protected String p_Date;
220 protected WayPoint p_Wp;
221
222 protected int success = 0; // number of successfully parsend sentences
223 protected int malformed = 0;
224 protected int checksum_errors = 0;
225 protected int no_checksum = 0;
226 protected int unknown = 0;
227 protected int zero_coord = 0;
228 }
229
230 // Parses split up sentences into WayPoints which are stored
231 // in the collection in the NMEAParserState object.
232 // Returns true if the input made sence, false otherwise.
233 private boolean ParseNMEASentence(String s, NMEAParserState ps) {
234 try {
235 if(s.equals("")) throw(null);
236
237 // checksum check:
238 // the bytes between the $ and the * are xored;
239 // if there is no * or other meanities it will throw
240 // and result in a malformed packet.
241 String[] chkstrings = s.split("\\*");
242 if(chkstrings.length > 1)
243 {
244 byte[] chb = chkstrings[0].getBytes();
245 int chk=0;
246 for(int i = 1; i < chb.length; i++) {
247 chk ^= chb[i];
248 }
249 if(Integer.parseInt(chkstrings[1].substring(0,2),16) != chk) {
250 //System.out.println("Checksum error");
251 ps.checksum_errors++;
252 ps.p_Wp=null;
253 return false;
254 }
255 } else {
256 ps.no_checksum++;
257 }
258 // now for the content
259 String[] e = chkstrings[0].split(",");
260 String accu;
261
262 WayPoint currentwp = ps.p_Wp;
263 String currentDate = ps.p_Date;
264
265 // handle the packet content
266 if(e[0].equals("$GPGGA")) {
267 // Position
268 LatLon latLon = parseLatLon(
269 e[GPGGA.LATITUDE_NAME.position],
270 e[GPGGA.LONGITUDE_NAME.position],
271 e[GPGGA.LATITUDE.position],
272 e[GPGGA.LONGITUDE.position]
273 );
274 if(latLon==null)
275 throw new NullPointerException(); // malformed
276
277 if((latLon.lat()==0.0) && (latLon.lon()==0.0)) {
278 ps.zero_coord++;
279 return false;
280 }
281
282 // time
283 accu = e[GPGGA.TIME.position];
284 Date d = readTime(currentDate+accu);
285
286 if((ps.p_Time==null) || (currentwp==null) || !ps.p_Time.equals(accu)) {
287 // this node is newer than the previous, create a new waypoint.
288 // no matter if previous WayPoint was null, we got something
289 // better now.
290 ps.p_Time=accu;
291 currentwp = new WayPoint(latLon);
292 }
293 if(!currentwp.attr.containsKey("time")) {
294 // As this sentence has no complete time only use it
295 // if there is no time so far
296 currentwp.attr.put("time", DateUtils.fromDate(d));
297 }
298 // elevation
299 accu=e[GPGGA.HEIGHT_UNTIS.position];
300 if(accu.equals("M")) {
301 // Ignore heights that are not in meters for now
302 accu=e[GPGGA.HEIGHT.position];
303 if(!accu.equals("")) {
304 Double.parseDouble(accu);
305 // if it throws it's malformed; this should only happen if the
306 // device sends nonstandard data.
307 if(!accu.equals("")) {
308 currentwp.attr.put("ele", accu);
309 }
310 }
311 }
312 // number of sattelites
313 accu=e[GPGGA.SATELLITE_COUNT.position];
314 int sat = 0;
315 if(!accu.equals("")) {
316 sat = Integer.parseInt(accu);
317 currentwp.attr.put("sat", accu);
318 }
319 // h-dilution
320 accu=e[GPGGA.HDOP.position];
321 if(!accu.equals("")) {
322 currentwp.attr.put("hdop", Float.parseFloat(accu));
323 }
324 // fix
325 accu=e[GPGGA.QUALITY.position];
326 if(!accu.equals("")) {
327 int fixtype = Integer.parseInt(accu);
328 switch(fixtype) {
329 case 0:
330 currentwp.attr.put("fix", "none");
331 break;
332 case 1:
333 if(sat < 4) {
334 currentwp.attr.put("fix", "2d");
335 } else {
336 currentwp.attr.put("fix", "3d");
337 }
338 break;
339 case 2:
340 currentwp.attr.put("fix", "dgps");
341 break;
342 default:
343 break;
344 }
345 }
346 } else if(e[0].equals("$GPVTG")) {
347 // COURSE
348 accu = e[GPVTG.COURSE_REF.position];
349 if(accu.equals("T")) {
350 // other values than (T)rue are ignored
351 accu = e[GPVTG.COURSE.position];
352 if(!accu.equals("")) {
353 Double.parseDouble(accu);
354 currentwp.attr.put("course", accu);
355 }
356 }
357 // SPEED
358 accu = e[GPVTG.SPEED_KMH_UNIT.position];
359 if(accu.startsWith("K")) {
360 accu = e[GPVTG.SPEED_KMH.position];
361 if(!accu.equals("")) {
362 double speed = Double.parseDouble(accu);
363 speed /= 3.6; // speed in m/s
364 currentwp.attr.put("speed", Double.toString(speed));
365 }
366 }
367 } else if(e[0].equals("$GPGSA")) {
368 // vdop
369 accu=e[GPGSA.VDOP.position];
370 if(!accu.equals("")) {
371 currentwp.attr.put("vdop", Float.parseFloat(accu));
372 }
373 // hdop
374 accu=e[GPGSA.HDOP.position];
375 if(!accu.equals("")) {
376 currentwp.attr.put("hdop", Float.parseFloat(accu));
377 }
378 // pdop
379 accu=e[GPGSA.PDOP.position];
380 if(!accu.equals("")) {
381 currentwp.attr.put("pdop", Float.parseFloat(accu));
382 }
383 }
384 else if(e[0].equals("$GPRMC")) {
385 // coordinates
386 LatLon latLon = parseLatLon(
387 e[GPRMC.WIDTH_NORTH_NAME.position],
388 e[GPRMC.LENGTH_EAST_NAME.position],
389 e[GPRMC.WIDTH_NORTH.position],
390 e[GPRMC.LENGTH_EAST.position]
391 );
392 if((latLon.lat()==0.0) && (latLon.lon()==0.0)) {
393 ps.zero_coord++;
394 return false;
395 }
396 // time
397 currentDate = e[GPRMC.DATE.position];
398 String time = e[GPRMC.TIME.position];
399
400 Date d = readTime(currentDate+time);
401
402 if((ps.p_Time==null) || (currentwp==null) || !ps.p_Time.equals(time)) {
403 // this node is newer than the previous, create a new waypoint.
404 ps.p_Time=time;
405 currentwp = new WayPoint(latLon);
406 }
407 // time: this sentence has complete time so always use it.
408 currentwp.attr.put("time", DateUtils.fromDate(d));
409 // speed
410 accu = e[GPRMC.SPEED.position];
411 if(!accu.equals("") && !currentwp.attr.containsKey("speed")) {
412 double speed = Double.parseDouble(accu);
413 speed *= 0.514444444; // to m/s
414 currentwp.attr.put("speed", Double.toString(speed));
415 }
416 // course
417 accu = e[GPRMC.COURSE.position];
418 if(!accu.equals("") && !currentwp.attr.containsKey("course")) {
419 Double.parseDouble(accu);
420 currentwp.attr.put("course", accu);
421 }
422
423 // TODO fix?
424 // * Mode (A = autonom; D = differential; E = estimated; N = not valid; S
425 // * = simulated)
426 // *
427 // * @since NMEA 2.3
428 //
429 //MODE(12);
430 } else {
431 ps.unknown++;
432 return false;
433 }
434 ps.p_Date = currentDate;
435 if(ps.p_Wp != currentwp) {
436 if(ps.p_Wp!=null) {
437 ps.p_Wp.setTime();
438 }
439 ps.p_Wp = currentwp;
440 ps.waypoints.add(currentwp);
441 ps.success++;
442 return true;
443 }
444 return true;
445
446 } catch(Exception x) {
447 // out of bounds and such
448 // x.printStackTrace();
449 // System.out.println("Malformed line: "+s.toString().trim());
450 ps.malformed++;
451 ps.p_Wp=null;
452 return false;
453 }
454 }
455
456 private LatLon parseLatLon(String ns, String ew, String dlat, String dlon)
457 throws NumberFormatException {
458 String widthNorth = dlat.trim();
459 String lengthEast = dlon.trim();
460
461 // return a zero latlon instead of null so it is logged as zero coordinate
462 // instead of malformed sentence
463 if(widthNorth.equals("")&&lengthEast.equals("")) return new LatLon(0.0,0.0);
464
465 // The format is xxDDLL.LLLL
466 // xx optional whitespace
467 // DD (int) degres
468 // LL.LLLL (double) latidude
469 int latdegsep = widthNorth.indexOf('.') - 2;
470 if (latdegsep < 0) return null;
471
472 int latdeg = Integer.parseInt(widthNorth.substring(0, latdegsep));
473 double latmin = Double.parseDouble(widthNorth.substring(latdegsep));
474 if(latdeg < 0) {
475 latmin *= -1.0;
476 }
477 double lat = latdeg + latmin / 60;
478 if ("S".equals(ns)) {
479 lat = -lat;
480 }
481
482 int londegsep = lengthEast.indexOf('.') - 2;
483 if (londegsep < 0) return null;
484
485 int londeg = Integer.parseInt(lengthEast.substring(0, londegsep));
486 double lonmin = Double.parseDouble(lengthEast.substring(londegsep));
487 if(londeg < 0) {
488 lonmin *= -1.0;
489 }
490 double lon = londeg + lonmin / 60;
491 if ("W".equals(ew)) {
492 lon = -lon;
493 }
494 return new LatLon(lat, lon);
495 }
496}
Note: See TracBrowser for help on using the repository browser.