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