nmea: make sure date is valid
[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 nmea_rmc_cb(void)
71 {
72 struct tm tm;
73 char tmp[256];
74
75 if (*nmea_params[2].str != 'A') {
76 gps_valid = 0;
77 DEBUG(4, "waiting for valid signal\n");
78 return;
79 }
80
81 gps_valid = 1;
82 memset(&tm, 0, sizeof(tm));
83 tm.tm_isdst = 1;
84
85 if (sscanf(nmea_params[1].str, "%02d%02d%02d",
86 &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 3) {
87 ERROR("failed to parse time '%s'\n", nmea_params[1].str);
88 }
89 else if (sscanf(nmea_params[9].str, "%02d%02d%02d",
90 &tm.tm_mday, &tm.tm_mon, &tm.tm_year) != 3) {
91 ERROR("failed to parse date '%s'\n", nmea_params[9].str);
92 }
93 else if (tm.tm_year == 0) {
94 DEBUG(4, "waiting for valid date\n");
95 return;
96 }
97 else {
98 tm.tm_year += 100; /* year starts with 1900 */
99 tm.tm_mon -= 1; /* month starts with 0 */
100
101 strftime(tmp, 256, "%Y-%m-%dT%H:%M:%S", &tm);
102 DEBUG(3, "date: %s UTC\n", tmp);
103
104 if (adjust_clock) {
105 time_t sec = timegm(&tm);
106 struct timeval cur;
107
108 gettimeofday(&cur, NULL);
109
110 if ((sec < 0) || (abs(cur.tv_sec - sec) > MAX_TIME_OFFSET)) {
111 struct timeval tv = { 0 };
112 tv.tv_sec = sec;
113 if (++nmea_bad_time > MAX_BAD_TIME) {
114 LOG("system time differs from GPS time by more than %d seconds. Using %s UTC as the new time\n", MAX_TIME_OFFSET, tmp);
115 /* only set datetime if specified by command line argument! */
116 settimeofday(&tv, NULL);
117 }
118 } else {
119 nmea_bad_time = 0;
120 }
121 }
122 }
123
124 if (strlen(nmea_params[3].str) < 9 || strlen(nmea_params[5].str) < 10) {
125 ERROR("lat/lng have invalid string length %zu<9, %zu<10\n",
126 strlen(nmea_params[3].str), strlen(nmea_params[5].str));
127 } else {
128 float minutes;
129 float degrees;
130 float lat = strtof(nmea_params[3].str, NULL);
131 float lon = strtof(nmea_params[5].str, NULL);
132
133 degrees = floor(lat / 100.0);
134 minutes = lat - (degrees * 100.0);
135 lat = degrees + minutes / 60.0;
136
137 degrees = floor(lon / 100.0);
138 minutes = lon - (degrees * 100.0);
139 lon = degrees + minutes / 60.0;
140
141 if (*nmea_params[4].str == 'S')
142 lat *= -1.0;
143 if (*nmea_params[6].str == 'W')
144 lon *= -1.0;
145
146 snprintf(latitude, sizeof(latitude), "%f", lat);
147 snprintf(longitude, sizeof(longitude), "%f", lon);
148
149 DEBUG(3, "position: %s %s\n", latitude, longitude);
150 gps_timestamp();
151 }
152 }
153
154 static void
155 nmea_gga_cb(void)
156 {
157 if (!gps_valid)
158 return;
159 strncpy(elevation, nmea_params[9].str, sizeof(elevation));
160 DEBUG(4, "height: %s\n", elevation);
161 }
162
163 static void
164 nmea_vtg_cb(void)
165 {
166 if (!gps_valid)
167 return;
168 strncpy(course, nmea_params[1].str, sizeof(course));
169 strncpy(speed, nmea_params[7].str, sizeof(speed));
170 DEBUG(4, "course: %s\n", course);
171 DEBUG(4, "speed: %s\n", speed);
172 }
173
174 static struct nmea_msg {
175 char *msg;
176 int cnt;
177 void (*handler) (void);
178 } nmea_msgs[] = {
179 {
180 .msg = "TXT",
181 .cnt = 5,
182 .handler = nmea_txt_cb,
183 }, {
184 .msg = "RMC",
185 .cnt = 11,
186 .handler = nmea_rmc_cb,
187 }, {
188 .msg = "GGA",
189 .cnt = 14,
190 .handler = nmea_gga_cb,
191 }, {
192 .msg = "VTG",
193 .cnt = 9,
194 .handler = nmea_vtg_cb,
195 },
196 };
197
198 static int
199 nmea_verify_checksum(char *s)
200 {
201 char *csum = strrchr(s, '*');
202 int isum, c = 0;
203
204 if (!csum)
205 return -1;
206
207 *csum = '\0';
208 csum++;
209 isum = strtol(csum, NULL, 16);
210
211 while(*s)
212 c ^= *s++;
213
214 if (isum != c)
215 return -1;
216
217 return 0;
218 }
219
220 static int
221 nmea_tokenize(char *msg)
222 {
223 int cnt = 0;
224 char *tok = strsep(&msg, ",");
225
226 while (tok && cnt < MAX_NMEA_PARAM) {
227 nmea_params[cnt].str = tok;
228 nmea_params[cnt].num = atoi(tok);
229 cnt++;
230 tok = strsep(&msg, ",");
231 }
232
233 return cnt;
234 }
235
236 static void
237 nmea_process(char *a)
238 {
239 char *csum;
240 int cnt;
241 unsigned int i;
242
243 if (strncmp(a, "$GP", 3))
244 return;
245
246 a++;
247 csum = strrchr(a, '*');
248 if (!csum)
249 return;
250
251 if (nmea_verify_checksum(a)) {
252 ERROR("nmea message has invalid checksum\n");
253 return;
254 }
255
256 cnt = nmea_tokenize(&a[2]);
257 if (cnt < 0) {
258 ERROR("failed to tokenize %s\n", a);\
259 return;
260 }
261
262 for (i = 0; i < ARRAY_SIZE(nmea_msgs); i++) {
263 if (strcmp(nmea_params[0].str, nmea_msgs[i].msg))
264 continue;
265 if (nmea_msgs[i].cnt <= cnt)
266 nmea_msgs[i].handler();
267 else
268 ERROR("%s datagram has wrong parameter count got %d but expected %d\n", nmea_msgs[i].msg, cnt, nmea_msgs[i].cnt);
269 return;
270 }
271 }
272
273 static int
274 nmea_consume(struct ustream *s, char **a)
275 {
276 char *eol = strstr(*a, "\n");
277
278 if (!eol)
279 return -1;
280
281 *eol++ = '\0';
282
283 nmea_process(*a);
284
285 ustream_consume(s, eol - *a);
286 *a = eol;
287
288 return 0;
289 }
290
291 static void
292 nmea_msg_cb(struct ustream *s, int bytes)
293 {
294 int len;
295 char *a = ustream_get_read_buf(s, &len);
296
297 while (!nmea_consume(s, &a))
298 ;
299 }
300
301 static void nmea_notify_cb(struct ustream *s)
302 {
303 if (!s->eof)
304 return;
305
306 ERROR("tty error, shutting down\n");
307 exit(-1);
308 }
309
310 int
311 nmea_open(char *dev, struct ustream_fd *s, speed_t speed)
312 {
313 struct termios tio;
314 int tty;
315
316 tty = open(dev, O_RDWR | O_NOCTTY | O_NONBLOCK);
317 if (tty < 0) {
318 ERROR("%s: device open failed: %s\n", dev, strerror(errno));
319 return -1;
320 }
321
322 tcgetattr(tty, &tio);
323 tio.c_cflag |= CREAD;
324 tio.c_cflag |= CS8;
325 tio.c_iflag |= IGNPAR;
326 tio.c_lflag &= ~(ICANON);
327 tio.c_lflag &= ~(ECHO);
328 tio.c_lflag &= ~(ECHOE);
329 tio.c_lflag &= ~(ISIG);
330 tio.c_cc[VMIN] = 1;
331 tio.c_cc[VTIME] = 0;
332 cfsetispeed(&tio, speed);
333 cfsetospeed(&tio, speed);
334 tcsetattr(tty, TCSANOW, &tio);
335
336 s->stream.string_data = true;
337 s->stream.notify_read = nmea_msg_cb;
338 s->stream.notify_state = nmea_notify_cb;
339
340 ustream_fd_init(s, tty);
341
342 tcflush(tty, TCIFLUSH);
343
344 return 0;
345 }