Show more useful error message if we can't open GPS device
[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 _BSD_SOURCE
20 #define _XOPEN_SOURCE
21 #include <time.h>
22
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/ioctl.h>
26 #include <sys/time.h>
27
28 #include <fcntl.h>
29 #include <time.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <unistd.h>
33 #include <errno.h>
34
35 #include <string.h>
36 #include <termios.h>
37
38 #include <libubox/utils.h>
39
40 #include "log.h"
41 #include "nmea.h"
42
43 #define MAX_NMEA_PARAM  20
44 #define MAX_TIME_OFFSET 2
45 #define MAX_BAD_TIME    3
46
47 struct nmea_param {
48         char *str;
49         int num;
50 } nmea_params[MAX_NMEA_PARAM];
51
52 static int nmea_bad_time;
53 char longitude[32] = { 0 }, latitude[32] = { 0 }, course[16] = { 0 }, speed[16] = { 0 }, elivation[16] = { 0 };
54 int gps_valid = 0;
55
56 static void
57 nmea_txt_cb(void)
58 {
59         char *ids[] = { "ERROR", "WARNING", "NOTICE", };
60
61         if (nmea_params[3].num < 0 || nmea_params[3].num > 2)
62                 nmea_params[3].num = 0;
63
64         DEBUG(3, "%s: %s\n", ids[nmea_params[3].num], nmea_params[4].str);
65 }
66
67 static void
68 nmea_rmc_cb(void)
69 {
70         struct tm tm;
71         char tmp[256];
72
73         if (*nmea_params[2].str != 'A') {
74                 gps_valid = 0;
75                 DEBUG(4, "waiting for valid signal\n");
76                 return;
77         }
78
79         gps_valid = 1;
80         memset(&tm, 0, sizeof(tm));
81         tm.tm_isdst = 1;
82
83         if (!strptime(nmea_params[1].str, "%H%M%S", &tm))
84                 ERROR("failed to parse time\n");
85         else if (!strptime(nmea_params[9].str, "%d%m%y", &tm))
86                 ERROR("failed to parse date\n");
87         else {
88                 /* is there a libc api for the tz adjustment ? */
89                 struct timeval tv = { mktime(&tm), 0 };
90                 struct timeval cur;
91
92                 strftime(tmp, 256, "%D %02H:%02M:%02S", &tm);
93                 DEBUG(3, "date: %s UTC\n", tmp);
94
95                 tv.tv_sec -= timezone;
96                 if (daylight)
97                         tv.tv_sec += 3600;
98
99                 gettimeofday(&cur, NULL);
100
101                 if (abs(cur.tv_sec - tv.tv_sec) > MAX_TIME_OFFSET) {
102                         if (++nmea_bad_time > MAX_BAD_TIME) {
103                                 LOG("system time differs from GPS time by more than %d seconds. Using %s UTC as the new time\n", MAX_TIME_OFFSET, tmp);
104                                 settimeofday(&tv, NULL);
105                         }
106                 } else {
107                         nmea_bad_time = 0;
108                 }
109         }
110
111         if (strlen(nmea_params[3].str) != 9 || strlen(nmea_params[5].str) != 10) {
112                 ERROR("lat/lng have invalid string length\n");
113         } else {
114                 int latd, latm, lats;
115                 int lngd, lngm, lngs;
116                 float flats, flngs;
117                 DEBUG(4, "position: %s, %s\n",
118                         nmea_params[3].str, nmea_params[5].str);
119                 latm = atoi(&nmea_params[3].str[2]);
120                 nmea_params[3].str[2] = '\0';
121                 latd = atoi(nmea_params[3].str);
122                 lats = atoi(&nmea_params[3].str[5]);
123                 if (*nmea_params[4].str != 'N')
124                         latm *= -1;
125
126                 lngm = atoi(&nmea_params[5].str[3]);
127                 nmea_params[5].str[3] = '\0';
128                 lngd = atoi(nmea_params[5].str);
129                 lngs = atoi(&nmea_params[5].str[6]);
130                 if (*nmea_params[6].str != 'E')
131                         lngm *= -1;
132
133                 flats = lats;
134                 flats *= 60;
135                 flats /= 10000;
136
137                 flngs = lngs;
138                 flngs *= 60;
139                 flngs /= 10000;
140
141 #define ms_to_deg(x, y) (((x * 10000) + y) / 60)
142
143                 DEBUG(4, "position: %d°%d.%04d, %d°%d.%04d\n",
144                         latd, latm, lats, lngd, lngm, lngs);
145                 DEBUG(4, "position: %d°%d'%.1f\" %d°%d'%.1f\"\n",
146                         latd, latm, flats, lngd, lngm, flngs);
147
148                 snprintf(latitude, sizeof(latitude), "%d.%04d", latd, ms_to_deg(latm, lats));
149                 snprintf(longitude, sizeof(longitude), "%d.%04d", lngd, ms_to_deg(lngm, lngs));
150                 DEBUG(3, "position: %s %s\n", latitude, longitude);
151                 gps_timestamp();
152         }
153 }
154
155 static void
156 nmea_gga_cb(void)
157 {
158         if (!gps_valid)
159                 return;
160         strncpy(elivation, nmea_params[9].str, sizeof(elivation));
161         DEBUG(4, "height: %s\n", elivation);
162 }
163
164 static void
165 nmea_vtg_cb(void)
166 {
167         if (!gps_valid)
168                 return;
169         strncpy(course, nmea_params[1].str, sizeof(course));
170         strncpy(speed, nmea_params[6].str, sizeof(speed));
171         DEBUG(4, "course: %s\n", course);
172         DEBUG(4, "speed: %s\n", speed);
173 }
174
175 static struct nmea_msg {
176         char *msg;
177         int cnt;
178         void (*handler) (void);
179 } nmea_msgs[] = {
180         {
181                 .msg = "TXT",
182                 .cnt = 5,
183                 .handler = nmea_txt_cb,
184         }, {
185                 .msg = "RMC",
186                 .cnt = 11,
187                 .handler = nmea_rmc_cb,
188         }, {
189                 .msg = "GGA",
190                 .cnt = 14,
191                 .handler = nmea_gga_cb,
192         }, {
193                 .msg = "VTG",
194                 .cnt = 9,
195                 .handler = nmea_vtg_cb,
196         },
197 };
198
199 static int
200 nmea_verify_checksum(char *s)
201 {
202         char *csum = strrchr(s, '*');
203         int isum, c = 0;
204
205         if (!csum)
206                 return -1;
207
208         *csum = '\0';
209         csum++;
210         isum = strtol(csum, NULL, 16);
211
212         while(*s)
213                 c ^= *s++;
214
215         if (isum != c)
216                 return -1;
217
218         return 0;
219 }
220
221 static int
222 nmea_tokenize(char *msg)
223 {
224         int cnt = 0;
225         char *tok = strsep(&msg, ",");
226
227         while (tok && cnt < MAX_NMEA_PARAM) {
228                 nmea_params[cnt].str = tok;
229                 nmea_params[cnt].num = atoi(tok);
230                 cnt++;
231                 tok = strsep(&msg, ",");
232         }
233
234         return cnt;
235 }
236
237 static void
238 nmea_process(char *a)
239 {
240         char *csum;
241         int cnt, 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 }