Switch to ulog for logging and add few commandline params
[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
34 #include <string.h>
35 #include <termios.h>
36
37 #include <libubox/utils.h>
38
39 #include "log.h"
40 #include "nmea.h"
41
42 #define MAX_NMEA_PARAM  20
43 #define MAX_TIME_OFFSET 2
44 #define MAX_BAD_TIME    3
45
46 struct nmea_param {
47         char *str;
48         int num;
49 } nmea_params[MAX_NMEA_PARAM];
50
51 static int nmea_bad_time;
52 char longitude[32] = { 0 }, latitude[32] = { 0 }, course[16] = { 0 }, speed[16] = { 0 }, elivation[16] = { 0 };
53 int gps_valid = 0;
54
55 static void
56 nmea_txt_cb(void)
57 {
58         char *ids[] = { "ERROR", "WARNING", "NOTICE", };
59
60         if (nmea_params[3].num < 0 || nmea_params[3].num > 2)
61                 nmea_params[3].num = 0;
62
63         DEBUG(3, "%s: %s\n", ids[nmea_params[3].num], nmea_params[4].str);
64 }
65
66 static void
67 nmea_rmc_cb(void)
68 {
69         struct tm tm;
70         char tmp[256];
71
72         if (*nmea_params[2].str != 'A') {
73                 gps_valid = 0;
74                 DEBUG(4, "waiting for valid signal\n");
75                 return;
76         }
77
78         gps_valid = 1;
79         memset(&tm, 0, sizeof(tm));
80         tm.tm_isdst = 1;
81
82         if (!strptime(nmea_params[1].str, "%H%M%S", &tm))
83                 ERROR("failed to parse time\n");
84         else if (!strptime(nmea_params[9].str, "%d%m%y", &tm))
85                 ERROR("failed to parse date\n");
86         else {
87                 /* is there a libc api for the tz adjustment ? */
88                 struct timeval tv = { mktime(&tm), 0 };
89                 struct timeval cur;
90
91                 strftime(tmp, 256, "%D %02H:%02M:%02S", &tm);
92                 DEBUG(3, "date: %s UTC\n", tmp);
93
94                 tv.tv_sec -= timezone;
95                 if (daylight)
96                         tv.tv_sec += 3600;
97
98                 gettimeofday(&cur, NULL);
99
100                 if (abs(cur.tv_sec - tv.tv_sec) > MAX_TIME_OFFSET) {
101                         if (++nmea_bad_time > MAX_BAD_TIME) {
102                                 LOG("system time differs from GPS time by more than %d seconds. Using %s UTC as the new time\n", MAX_TIME_OFFSET, tmp);
103                                 settimeofday(&tv, NULL);
104                         }
105                 } else {
106                         nmea_bad_time = 0;
107                 }
108         }
109
110         if (strlen(nmea_params[3].str) != 9 || strlen(nmea_params[5].str) != 10) {
111                 ERROR("lat/lng have invalid string length\n");
112         } else {
113                 int latd, latm, lats;
114                 int lngd, lngm, lngs;
115                 float flats, flngs;
116                 DEBUG(4, "position: %s, %s\n",
117                         nmea_params[3].str, nmea_params[5].str);
118                 latm = atoi(&nmea_params[3].str[2]);
119                 nmea_params[3].str[2] = '\0';
120                 latd = atoi(nmea_params[3].str);
121                 lats = atoi(&nmea_params[3].str[5]);
122                 if (*nmea_params[4].str != 'N')
123                         latm *= -1;
124
125                 lngm = atoi(&nmea_params[5].str[3]);
126                 nmea_params[5].str[3] = '\0';
127                 lngd = atoi(nmea_params[5].str);
128                 lngs = atoi(&nmea_params[5].str[6]);
129                 if (*nmea_params[6].str != 'E')
130                         lngm *= -1;
131
132                 flats = lats;
133                 flats *= 60;
134                 flats /= 10000;
135
136                 flngs = lngs;
137                 flngs *= 60;
138                 flngs /= 10000;
139
140 #define ms_to_deg(x, y) (((x * 10000) + y) / 60)
141
142                 DEBUG(4, "position: %d°%d.%04d, %d°%d.%04d\n",
143                         latd, latm, lats, lngd, lngm, lngs);
144                 DEBUG(4, "position: %d°%d'%.1f\" %d°%d'%.1f\"\n",
145                         latd, latm, flats, lngd, lngm, flngs);
146
147                 snprintf(latitude, sizeof(latitude), "%d.%04d", latd, ms_to_deg(latm, lats));
148                 snprintf(longitude, sizeof(longitude), "%d.%04d", lngd, ms_to_deg(lngm, lngs));
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(elivation, nmea_params[9].str, sizeof(elivation));
160         DEBUG(4, "height: %s\n", elivation);
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[6].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 = strtok(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 = strtok(NULL, ",");
231         }
232
233         return cnt;
234 }
235
236 static void
237 nmea_process(char *a)
238 {
239         char *csum;
240         int cnt, i;
241
242         if (strncmp(a, "$GP", 3))
243                 return;
244
245         a++;
246         csum = strrchr(a, '*');
247         if (!csum)
248                 return;
249
250         if (nmea_verify_checksum(a)) {
251                 ERROR("nmea message has invlid checksum\n");
252                 return;
253         }
254
255         cnt = nmea_tokenize(&a[2]);
256         if (cnt < 0) {
257                 ERROR("failed to tokenize %s\n", a);\
258                 return;
259         }
260
261         for (i = 0; i < ARRAY_SIZE(nmea_msgs); i++) {
262                 if (strcmp(nmea_params[0].str, nmea_msgs[i].msg))
263                         continue;
264                 if (nmea_msgs[i].cnt <= cnt)
265                         nmea_msgs[i].handler();
266                 else
267                         ERROR("%s datagram has wrong parameter count got %d but expected %d\n", nmea_msgs[i].msg, cnt, nmea_msgs[i].cnt);
268                 return;
269         }
270 }
271
272 static int
273 nmea_consume(struct ustream *s, char **a)
274 {
275         char *eol = strstr(*a, "\n");
276
277         if (!eol)
278                 return -1;
279
280         *eol++ = '\0';
281
282         nmea_process(*a);
283
284         ustream_consume(s, eol - *a);
285         *a = eol;
286
287         return 0;
288 }
289
290 static void
291 nmea_msg_cb(struct ustream *s, int bytes)
292 {
293         int len;
294         char *a = ustream_get_read_buf(s, &len);
295
296         while (!nmea_consume(s, &a))
297                 ;
298 }
299
300 static void nmea_notify_cb(struct ustream *s)
301 {
302         if (!s->eof)
303                 return;
304
305         ERROR("tty error, shutting down\n");
306         exit(-1);
307 }
308
309 int
310 nmea_open(char *dev, struct ustream_fd *s, speed_t speed)
311 {
312         struct termios tio;
313         int tty;
314
315         tty = open(dev, O_RDWR | O_NOCTTY | O_NONBLOCK);
316         if (tty < 0) {
317                 ERROR("%s: device open failed\n", dev);
318                 return -1;
319         }
320
321         tcgetattr(tty, &tio);
322         tio.c_cflag |= CREAD;
323         tio.c_cflag |= CS8;
324         tio.c_iflag |= IGNPAR;
325         tio.c_lflag &= ~(ICANON);
326         tio.c_lflag &= ~(ECHO);
327         tio.c_lflag &= ~(ECHOE);
328         tio.c_lflag &= ~(ISIG);
329         tio.c_cc[VMIN] = 1;
330         tio.c_cc[VTIME] = 0;
331         cfsetispeed(&tio, speed);
332         cfsetospeed(&tio, speed);
333         tcsetattr(tty, TCSANOW, &tio);
334
335         s->stream.string_data = true;
336         s->stream.notify_read = nmea_msg_cb;
337         s->stream.notify_state = nmea_notify_cb;
338
339         ustream_fd_init(s, tty);
340
341         tcflush(tty, TCIFLUSH);
342
343         return 0;
344 }