nmea: parse $GPZDA sentences for date/time
[project/ugps.git] / nmea.c
1 /*
2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
15 *
16 * Copyright (C) 2014 John Crispin <blogic@openwrt.org>
17 */
18
19 #define _DEFAULT_SOURCE
20 #define _XOPEN_SOURCE
21 #define _BSD_SOURCE
22 #include <time.h>
23
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <sys/ioctl.h>
27 #include <sys/time.h>
28
29 #include <fcntl.h>
30 #include <time.h>
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <unistd.h>
34 #include <errno.h>
35 #include <math.h>
36
37 #include <string.h>
38 #include <termios.h>
39
40 #include <libubox/utils.h>
41
42 #include "log.h"
43 #include "nmea.h"
44
45 #define MAX_NMEA_PARAM 20
46 #define MAX_TIME_OFFSET 5
47 #define MAX_BAD_TIME 3
48
49 struct nmea_param {
50 char *str;
51 int num;
52 } nmea_params[MAX_NMEA_PARAM];
53
54 static int nmea_bad_time;
55 char longitude[33] = { 0 }, latitude[33] = { 0 }, course[17] = { 0 }, speed[17] = { 0 }, elevation[17] = { 0 };
56 int gps_valid = 0;
57
58 static void
59 nmea_txt_cb(void)
60 {
61 char *ids[] = { "ERROR", "WARNING", "NOTICE", };
62
63 if (nmea_params[3].num < 0 || nmea_params[3].num > 2)
64 nmea_params[3].num = 0;
65
66 DEBUG(3, "%s: %s\n", ids[nmea_params[3].num], nmea_params[4].str);
67 }
68
69 static void
70 do_adjust_clock(struct tm *tm)
71 {
72 char tmp[256];
73
74 strftime(tmp, 256, "%Y-%m-%dT%H:%M:%S", tm);
75 DEBUG(3, "date: %s UTC\n", tmp);
76
77 if (adjust_clock) {
78 time_t sec = timegm(tm);
79 struct timeval cur;
80
81 gettimeofday(&cur, NULL);
82
83 if ((sec < 0) || (llabs(cur.tv_sec - sec) > MAX_TIME_OFFSET)) {
84 struct timeval tv = { 0 };
85 tv.tv_sec = sec;
86 if (++nmea_bad_time > MAX_BAD_TIME) {
87 LOG("system time differs from GPS time by more than %d seconds. Using %s UTC as the new time\n", MAX_TIME_OFFSET, tmp);
88 /* only set datetime if specified by command line argument! */
89 settimeofday(&tv, NULL);
90 }
91 } else {
92 nmea_bad_time = 0;
93 }
94 }
95 }
96
97 static void
98 nmea_rmc_cb(void)
99 {
100 struct tm tm;
101
102 if (*nmea_params[2].str != 'A') {
103 gps_valid = 0;
104 DEBUG(4, "waiting for valid signal\n");
105 return;
106 }
107
108 gps_valid = 1;
109 memset(&tm, 0, sizeof(tm));
110 tm.tm_isdst = 1;
111
112 if (sscanf(nmea_params[1].str, "%02d%02d%02d",
113 &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 3) {
114 ERROR("failed to parse time '%s'\n", nmea_params[1].str);
115 }
116 else if (sscanf(nmea_params[9].str, "%02d%02d%02d",
117 &tm.tm_mday, &tm.tm_mon, &tm.tm_year) != 3) {
118 ERROR("failed to parse date '%s'\n", nmea_params[9].str);
119 }
120 else if (tm.tm_year == 0) {
121 DEBUG(4, "waiting for valid date\n");
122 return;
123 }
124 else {
125 tm.tm_year += 100; /* year starts with 1900 */
126 tm.tm_mon -= 1; /* month starts with 0 */
127
128 do_adjust_clock(&tm);
129 }
130
131 if (strlen(nmea_params[3].str) < 9 || strlen(nmea_params[5].str) < 10) {
132 ERROR("lat/lng have invalid string length %zu<9, %zu<10\n",
133 strlen(nmea_params[3].str), strlen(nmea_params[5].str));
134 } else {
135 float minutes;
136 float degrees;
137 float lat = strtof(nmea_params[3].str, NULL);
138 float lon = strtof(nmea_params[5].str, NULL);
139
140 degrees = floor(lat / 100.0);
141 minutes = lat - (degrees * 100.0);
142 lat = degrees + minutes / 60.0;
143
144 degrees = floor(lon / 100.0);
145 minutes = lon - (degrees * 100.0);
146 lon = degrees + minutes / 60.0;
147
148 if (*nmea_params[4].str == 'S')
149 lat *= -1.0;
150 if (*nmea_params[6].str == 'W')
151 lon *= -1.0;
152
153 snprintf(latitude, sizeof(latitude), "%f", lat);
154 snprintf(longitude, sizeof(longitude), "%f", lon);
155
156 DEBUG(3, "position: %s %s\n", latitude, longitude);
157 gps_timestamp();
158 }
159 }
160
161 static void
162 nmea_zda_cb(void)
163 {
164 struct tm tm;
165
166 gps_valid = 1;
167
168 memset(&tm, 0, sizeof(tm));
169 tm.tm_isdst = 1;
170
171 if (sscanf(nmea_params[1].str, "%02d%02d%02d",
172 &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 3) {
173 ERROR("failed to parse time '%s'\n", nmea_params[1].str);
174 return;
175 }
176
177 if ((sscanf(nmea_params[2].str, "%02d", &tm.tm_mday) != 1) ||
178 (sscanf(nmea_params[3].str, "%02d", &tm.tm_mon) != 1) ||
179 (sscanf(nmea_params[4].str, "%04d", &tm.tm_year) != 1)) {
180 ERROR("failed to parse time '%s,%s,%s'\n",
181 nmea_params[2].str, nmea_params[3].str, nmea_params[4].str);
182 return;
183 }
184
185 if (tm.tm_year == 0) {
186 DEBUG(4, "waiting for valid date\n");
187 return;
188 }
189
190 tm.tm_mon -= 1; /* month starts with 0 */
191 tm.tm_year -= 1900; /* full 4-digit year, tm expects years till 1900 */
192
193 do_adjust_clock(&tm);
194 }
195
196 static void
197 nmea_gga_cb(void)
198 {
199 if (!gps_valid)
200 return;
201 strncpy(elevation, nmea_params[9].str, sizeof(elevation));
202 DEBUG(4, "height: %s\n", elevation);
203 }
204
205 static void
206 nmea_vtg_cb(void)
207 {
208 if (!gps_valid)
209 return;
210 strncpy(course, nmea_params[1].str, sizeof(course));
211 strncpy(speed, nmea_params[7].str, sizeof(speed));
212 DEBUG(4, "course: %s\n", course);
213 DEBUG(4, "speed: %s\n", speed);
214 }
215
216 static struct nmea_msg {
217 char *msg;
218 int cnt;
219 void (*handler) (void);
220 } nmea_msgs[] = {
221 {
222 .msg = "TXT",
223 .cnt = 5,
224 .handler = nmea_txt_cb,
225 }, {
226 .msg = "RMC",
227 .cnt = 11,
228 .handler = nmea_rmc_cb,
229 }, {
230 .msg = "GGA",
231 .cnt = 14,
232 .handler = nmea_gga_cb,
233 }, {
234 .msg = "VTG",
235 .cnt = 9,
236 .handler = nmea_vtg_cb,
237 }, {
238 .msg = "ZDA",
239 .cnt = 5,
240 .handler = nmea_zda_cb,
241 },
242 };
243
244 static int
245 nmea_verify_checksum(char *s)
246 {
247 char *csum = strrchr(s, '*');
248 int isum, c = 0;
249
250 if (!csum)
251 return -1;
252
253 *csum = '\0';
254 csum++;
255 isum = strtol(csum, NULL, 16);
256
257 while(*s)
258 c ^= *s++;
259
260 if (isum != c)
261 return -1;
262
263 return 0;
264 }
265
266 static int
267 nmea_tokenize(char *msg)
268 {
269 int cnt = 0;
270 char *tok = strsep(&msg, ",");
271
272 while (tok && cnt < MAX_NMEA_PARAM) {
273 nmea_params[cnt].str = tok;
274 nmea_params[cnt].num = atoi(tok);
275 cnt++;
276 tok = strsep(&msg, ",");
277 }
278
279 return cnt;
280 }
281
282 static void
283 nmea_process(char *a)
284 {
285 char *csum;
286 int cnt;
287 unsigned int i;
288
289 if (strncmp(a, "$GP", 3))
290 return;
291
292 a++;
293 csum = strrchr(a, '*');
294 if (!csum)
295 return;
296
297 if (nmea_verify_checksum(a)) {
298 ERROR("nmea message has invalid checksum\n");
299 return;
300 }
301
302 cnt = nmea_tokenize(&a[2]);
303 if (cnt < 0) {
304 ERROR("failed to tokenize %s\n", a);\
305 return;
306 }
307
308 for (i = 0; i < ARRAY_SIZE(nmea_msgs); i++) {
309 if (strcmp(nmea_params[0].str, nmea_msgs[i].msg))
310 continue;
311 if (nmea_msgs[i].cnt <= cnt)
312 nmea_msgs[i].handler();
313 else
314 ERROR("%s datagram has wrong parameter count got %d but expected %d\n", nmea_msgs[i].msg, cnt, nmea_msgs[i].cnt);
315 return;
316 }
317 }
318
319 static int
320 nmea_consume(struct ustream *s, char **a)
321 {
322 char *eol = strstr(*a, "\n");
323
324 if (!eol)
325 return -1;
326
327 *eol++ = '\0';
328
329 nmea_process(*a);
330
331 ustream_consume(s, eol - *a);
332 *a = eol;
333
334 return 0;
335 }
336
337 static void
338 nmea_msg_cb(struct ustream *s, int bytes)
339 {
340 int len;
341 char *a = ustream_get_read_buf(s, &len);
342
343 while (!nmea_consume(s, &a))
344 ;
345 }
346
347 static void nmea_notify_cb(struct ustream *s)
348 {
349 if (!s->eof)
350 return;
351
352 ERROR("tty error, shutting down\n");
353 exit(-1);
354 }
355
356 int
357 nmea_open(char *dev, struct ustream_fd *s, speed_t speed)
358 {
359 struct termios tio;
360 int tty;
361
362 tty = open(dev, O_RDWR | O_NOCTTY | O_NONBLOCK);
363 if (tty < 0) {
364 ERROR("%s: device open failed: %s\n", dev, strerror(errno));
365 return -1;
366 }
367
368 tcgetattr(tty, &tio);
369 tio.c_cflag |= CREAD;
370 tio.c_cflag |= CS8;
371 tio.c_iflag |= IGNPAR;
372 tio.c_lflag &= ~(ICANON);
373 tio.c_lflag &= ~(ECHO);
374 tio.c_lflag &= ~(ECHOE);
375 tio.c_lflag &= ~(ISIG);
376 tio.c_cc[VMIN] = 1;
377 tio.c_cc[VTIME] = 0;
378 cfsetispeed(&tio, speed);
379 cfsetospeed(&tio, speed);
380 tcsetattr(tty, TCSANOW, &tio);
381
382 s->stream.string_data = true;
383 s->stream.notify_read = nmea_msg_cb;
384 s->stream.notify_state = nmea_notify_cb;
385
386 ustream_fd_init(s, tty);
387
388 tcflush(tty, TCIFLUSH);
389
390 return 0;
391 }