minmea.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. /*
  2. * Copyright © 2014 Kosma Moczek <kosma@cloudyourcar.com>
  3. * This program is free software. It comes without any warranty, to the extent
  4. * permitted by applicable law. You can redistribute it and/or modify it under
  5. * the terms of the Do What The Fuck You Want To Public License, Version 2, as
  6. * published by Sam Hocevar. See the COPYING file for more details.
  7. */
  8. #include "minmea.h"
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <ctype.h>
  12. #include <stdarg.h>
  13. #define boolstr(s) ((s) ? "true" : "false")
  14. static int hex2int(char c)
  15. {
  16. if (c >= '0' && c <= '9')
  17. return c - '0';
  18. if (c >= 'A' && c <= 'F')
  19. return c - 'A' + 10;
  20. if (c >= 'a' && c <= 'f')
  21. return c - 'a' + 10;
  22. return -1;
  23. }
  24. bool minmea_check(const char *sentence, bool strict)
  25. {
  26. uint8_t checksum = 0x00;
  27. // Sequence length is limited.
  28. if (strlen(sentence) > MINMEA_MAX_LENGTH + 3)
  29. return false;
  30. // A valid sentence starts with "$".
  31. if (*sentence++ != '$')
  32. return false;
  33. // The optional checksum is an XOR of all bytes between "$" and "*".
  34. while (*sentence && *sentence != '*' && isprint((unsigned char) *sentence))
  35. checksum ^= *sentence++;
  36. // If checksum is present...
  37. if (*sentence == '*') {
  38. // Extract checksum.
  39. sentence++;
  40. int upper = hex2int(*sentence++);
  41. if (upper == -1)
  42. return false;
  43. int lower = hex2int(*sentence++);
  44. if (lower == -1)
  45. return false;
  46. int expected = upper << 4 | lower;
  47. // Check for checksum mismatch.
  48. if (checksum != expected)
  49. return false;
  50. } else if (strict) {
  51. // Discard non-checksummed frames in strict mode.
  52. return false;
  53. }
  54. // The only stuff allowed at this point is a newline.
  55. if (*sentence && strcmp(sentence, "\n") && strcmp(sentence, "\r\n"))
  56. return false;
  57. return true;
  58. }
  59. static inline bool minmea_isfield(char c) {
  60. return isprint((unsigned char) c) && c != ',' && c != '*';
  61. }
  62. bool minmea_scan(const char *sentence, const char *format, ...)
  63. {
  64. bool result = false;
  65. bool optional = false;
  66. va_list ap;
  67. va_start(ap, format);
  68. const char *field = sentence;
  69. #define next_field() \
  70. do { \
  71. /* Progress to the next field. */ \
  72. while (minmea_isfield(*sentence)) \
  73. sentence++; \
  74. /* Make sure there is a field there. */ \
  75. if (*sentence == ',') { \
  76. sentence++; \
  77. field = sentence; \
  78. } else { \
  79. field = NULL; \
  80. } \
  81. } while (0)
  82. while (*format) {
  83. char type = *format++;
  84. if (type == ';') {
  85. // All further fields are optional.
  86. optional = true;
  87. continue;
  88. }
  89. if (!field && !optional) {
  90. // Field requested but we ran out if input. Bail out.
  91. goto parse_error;
  92. }
  93. switch (type) {
  94. case 'c': { // Single character field (char).
  95. char value = '\0';
  96. if (field && minmea_isfield(*field))
  97. value = *field;
  98. *va_arg(ap, char *) = value;
  99. } break;
  100. case 'd': { // Single character direction field (int).
  101. int value = 0;
  102. if (field && minmea_isfield(*field)) {
  103. switch (*field) {
  104. case 'N':
  105. case 'E':
  106. value = 1;
  107. break;
  108. case 'S':
  109. case 'W':
  110. value = -1;
  111. break;
  112. default:
  113. goto parse_error;
  114. }
  115. }
  116. *va_arg(ap, int *) = value;
  117. } break;
  118. case 'f': { // Fractional value with scale (struct minmea_float).
  119. int sign = 0;
  120. int_least32_t value = -1;
  121. int_least32_t scale = 0;
  122. if (field) {
  123. while (minmea_isfield(*field)) {
  124. if (*field == '+' && !sign && value == -1) {
  125. sign = 1;
  126. } else if (*field == '-' && !sign && value == -1) {
  127. sign = -1;
  128. } else if (isdigit((unsigned char) *field)) {
  129. int digit = *field - '0';
  130. if (value == -1)
  131. value = 0;
  132. if (value > (INT_LEAST32_MAX-digit) / 10) {
  133. /* we ran out of bits, what do we do? */
  134. if (scale) {
  135. /* truncate extra precision */
  136. break;
  137. } else {
  138. /* integer overflow. bail out. */
  139. goto parse_error;
  140. }
  141. }
  142. value = (10 * value) + digit;
  143. if (scale)
  144. scale *= 10;
  145. } else if (*field == '.' && scale == 0) {
  146. scale = 1;
  147. } else if (*field == ' ') {
  148. /* Allow spaces at the start of the field. Not NMEA
  149. * conformant, but some modules do this. */
  150. if (sign != 0 || value != -1 || scale != 0)
  151. goto parse_error;
  152. } else {
  153. goto parse_error;
  154. }
  155. field++;
  156. }
  157. }
  158. if ((sign || scale) && value == -1)
  159. goto parse_error;
  160. if (value == -1) {
  161. /* No digits were scanned. */
  162. value = 0;
  163. scale = 0;
  164. } else if (scale == 0) {
  165. /* No decimal point. */
  166. scale = 1;
  167. }
  168. if (sign)
  169. value *= sign;
  170. *va_arg(ap, struct minmea_float *) = (struct minmea_float) {value, scale};
  171. } break;
  172. case 'i': { // Integer value, default 0 (int).
  173. int value = 0;
  174. if (field) {
  175. char *endptr;
  176. value = strtol(field, &endptr, 10);
  177. if (minmea_isfield(*endptr))
  178. goto parse_error;
  179. }
  180. *va_arg(ap, int *) = value;
  181. } break;
  182. case 's': { // String value (char *).
  183. char *buf = va_arg(ap, char *);
  184. if (field) {
  185. while (minmea_isfield(*field))
  186. *buf++ = *field++;
  187. }
  188. *buf = '\0';
  189. } break;
  190. case 't': { // NMEA talker+sentence identifier (char *).
  191. // This field is always mandatory.
  192. if (!field)
  193. goto parse_error;
  194. if (field[0] != '$')
  195. goto parse_error;
  196. for (int f=0; f<5; f++)
  197. if (!minmea_isfield(field[1+f]))
  198. goto parse_error;
  199. char *buf = va_arg(ap, char *);
  200. memcpy(buf, field+1, 5);
  201. buf[5] = '\0';
  202. } break;
  203. case 'D': { // Date (int, int, int), -1 if empty.
  204. struct minmea_date *date = va_arg(ap, struct minmea_date *);
  205. int d = -1, m = -1, y = -1;
  206. if (field && minmea_isfield(*field)) {
  207. // Always six digits.
  208. for (int f=0; f<6; f++)
  209. if (!isdigit((unsigned char) field[f]))
  210. goto parse_error;
  211. d = strtol((char[]) {field[0], field[1], '\0'}, NULL, 10);
  212. m = strtol((char[]) {field[2], field[3], '\0'}, NULL, 10);
  213. y = strtol((char[]) {field[4], field[5], '\0'}, NULL, 10);
  214. }
  215. date->day = d;
  216. date->month = m;
  217. date->year = y;
  218. } break;
  219. case 'T': { // Time (int, int, int, int), -1 if empty.
  220. struct minmea_time *time_ = va_arg(ap, struct minmea_time *);
  221. int h = -1, i = -1, s = -1, u = -1;
  222. if (field && minmea_isfield(*field)) {
  223. // Minimum required: integer time.
  224. for (int f=0; f<6; f++)
  225. if (!isdigit((unsigned char) field[f]))
  226. goto parse_error;
  227. h = strtol((char[]) {field[0], field[1], '\0'}, NULL, 10);
  228. i = strtol((char[]) {field[2], field[3], '\0'}, NULL, 10);
  229. s = strtol((char[]) {field[4], field[5], '\0'}, NULL, 10);
  230. field += 6;
  231. // Extra: fractional time. Saved as microseconds.
  232. if (*field++ == '.') {
  233. int value = 0;
  234. int scale = 1000000;
  235. while (isdigit((unsigned char) *field) && scale > 1) {
  236. value = (value * 10) + (*field++ - '0');
  237. scale /= 10;
  238. }
  239. u = value * scale;
  240. } else {
  241. u = 0;
  242. }
  243. }
  244. time_->hours = h;
  245. time_->minutes = i;
  246. time_->seconds = s;
  247. time_->microseconds = u;
  248. } break;
  249. case '_': { // Ignore the field.
  250. } break;
  251. default: { // Unknown.
  252. goto parse_error;
  253. } break;
  254. }
  255. next_field();
  256. }
  257. result = true;
  258. parse_error:
  259. va_end(ap);
  260. return result;
  261. }
  262. bool minmea_talker_id(char talker[3], const char *sentence)
  263. {
  264. char type[6];
  265. if (!minmea_scan(sentence, "t", type))
  266. return false;
  267. talker[0] = type[0];
  268. talker[1] = type[1];
  269. talker[2] = '\0';
  270. return true;
  271. }
  272. enum minmea_sentence_id minmea_sentence_id(const char *sentence, bool strict)
  273. {
  274. if (!minmea_check(sentence, strict))
  275. return MINMEA_INVALID;
  276. char type[6];
  277. if (!minmea_scan(sentence, "t", type))
  278. return MINMEA_INVALID;
  279. if (!strcmp(type+2, "RMC"))
  280. return MINMEA_SENTENCE_RMC;
  281. if (!strcmp(type+2, "GGA"))
  282. return MINMEA_SENTENCE_GGA;
  283. if (!strcmp(type+2, "GSA"))
  284. return MINMEA_SENTENCE_GSA;
  285. if (!strcmp(type+2, "GLL"))
  286. return MINMEA_SENTENCE_GLL;
  287. if (!strcmp(type+2, "GST"))
  288. return MINMEA_SENTENCE_GST;
  289. if (!strcmp(type+2, "GSV"))
  290. return MINMEA_SENTENCE_GSV;
  291. return MINMEA_UNKNOWN;
  292. }
  293. bool minmea_parse_rmc(struct minmea_sentence_rmc *frame, const char *sentence)
  294. {
  295. // $GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62
  296. char type[6];
  297. char validity;
  298. int latitude_direction;
  299. int longitude_direction;
  300. int variation_direction;
  301. if (!minmea_scan(sentence, "tTcfdfdffDfd",
  302. type,
  303. &frame->time,
  304. &validity,
  305. &frame->latitude, &latitude_direction,
  306. &frame->longitude, &longitude_direction,
  307. &frame->speed,
  308. &frame->course,
  309. &frame->date,
  310. &frame->variation, &variation_direction))
  311. return false;
  312. if (strcmp(type+2, "RMC"))
  313. return false;
  314. frame->valid = (validity == 'A');
  315. frame->latitude.value *= latitude_direction;
  316. frame->longitude.value *= longitude_direction;
  317. frame->variation.value *= variation_direction;
  318. return true;
  319. }
  320. bool minmea_parse_gga(struct minmea_sentence_gga *frame, const char *sentence)
  321. {
  322. // $GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47
  323. char type[6];
  324. int latitude_direction;
  325. int longitude_direction;
  326. if (!minmea_scan(sentence, "tTfdfdiiffcfci_",
  327. type,
  328. &frame->time,
  329. &frame->latitude, &latitude_direction,
  330. &frame->longitude, &longitude_direction,
  331. &frame->fix_quality,
  332. &frame->satellites_tracked,
  333. &frame->hdop,
  334. &frame->altitude, &frame->altitude_units,
  335. &frame->height, &frame->height_units,
  336. &frame->dgps_age))
  337. return false;
  338. if (strcmp(type+2, "GGA"))
  339. return false;
  340. frame->latitude.value *= latitude_direction;
  341. frame->longitude.value *= longitude_direction;
  342. return true;
  343. }
  344. bool minmea_parse_gsa(struct minmea_sentence_gsa *frame, const char *sentence)
  345. {
  346. // $GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39
  347. char type[6];
  348. if (!minmea_scan(sentence, "tciiiiiiiiiiiiifff",
  349. type,
  350. &frame->mode,
  351. &frame->fix_type,
  352. &frame->sats[0],
  353. &frame->sats[1],
  354. &frame->sats[2],
  355. &frame->sats[3],
  356. &frame->sats[4],
  357. &frame->sats[5],
  358. &frame->sats[6],
  359. &frame->sats[7],
  360. &frame->sats[8],
  361. &frame->sats[9],
  362. &frame->sats[10],
  363. &frame->sats[11],
  364. &frame->pdop,
  365. &frame->hdop,
  366. &frame->vdop))
  367. return false;
  368. if (strcmp(type+2, "GSA"))
  369. return false;
  370. return true;
  371. }
  372. bool minmea_parse_gll(struct minmea_sentence_gll *frame, const char *sentence)
  373. {
  374. // $GPGLL,3723.2475,N,12158.3416,W,161229.487,A,A*41$;
  375. char type[6];
  376. int latitude_direction;
  377. int longitude_direction;
  378. if (!minmea_scan(sentence, "tfdfdTc;c",
  379. type,
  380. &frame->latitude, &latitude_direction,
  381. &frame->longitude, &longitude_direction,
  382. &frame->time,
  383. &frame->status,
  384. &frame->mode))
  385. return false;
  386. if (strcmp(type+2, "GLL"))
  387. return false;
  388. frame->latitude.value *= latitude_direction;
  389. frame->longitude.value *= longitude_direction;
  390. return true;
  391. }
  392. bool minmea_parse_gst(struct minmea_sentence_gst *frame, const char *sentence)
  393. {
  394. // $GPGST,024603.00,3.2,6.6,4.7,47.3,5.8,5.6,22.0*58
  395. char type[6];
  396. if (!minmea_scan(sentence, "tTfffffff",
  397. type,
  398. &frame->time,
  399. &frame->rms_deviation,
  400. &frame->semi_major_deviation,
  401. &frame->semi_minor_deviation,
  402. &frame->semi_major_orientation,
  403. &frame->latitude_error_deviation,
  404. &frame->longitude_error_deviation,
  405. &frame->altitude_error_deviation))
  406. return false;
  407. if (strcmp(type+2, "GST"))
  408. return false;
  409. return true;
  410. }
  411. bool minmea_parse_gsv(struct minmea_sentence_gsv *frame, const char *sentence)
  412. {
  413. // $GPGSV,3,1,11,03,03,111,00,04,15,270,00,06,01,010,00,13,06,292,00*74
  414. // $GPGSV,3,3,11,22,42,067,42,24,14,311,43,27,05,244,00,,,,*4D
  415. // $GPGSV,4,2,11,08,51,203,30,09,45,215,28*75
  416. // $GPGSV,4,4,13,39,31,170,27*40
  417. // $GPGSV,4,4,13*7B
  418. char type[6];
  419. if (!minmea_scan(sentence, "tiii;iiiiiiiiiiiiiiii",
  420. type,
  421. &frame->total_msgs,
  422. &frame->msg_nr,
  423. &frame->total_sats,
  424. &frame->sats[0].nr,
  425. &frame->sats[0].elevation,
  426. &frame->sats[0].azimuth,
  427. &frame->sats[0].snr,
  428. &frame->sats[1].nr,
  429. &frame->sats[1].elevation,
  430. &frame->sats[1].azimuth,
  431. &frame->sats[1].snr,
  432. &frame->sats[2].nr,
  433. &frame->sats[2].elevation,
  434. &frame->sats[2].azimuth,
  435. &frame->sats[2].snr,
  436. &frame->sats[3].nr,
  437. &frame->sats[3].elevation,
  438. &frame->sats[3].azimuth,
  439. &frame->sats[3].snr
  440. )) {
  441. return false;
  442. }
  443. if (strcmp(type+2, "GSV"))
  444. return false;
  445. return true;
  446. }
  447. int minmea_gettime(struct timespec *ts, const struct minmea_date *date, const struct minmea_time *time_)
  448. {
  449. if (date->year == -1 || time_->hours == -1)
  450. return -1;
  451. struct tm tm;
  452. memset(&tm, 0, sizeof(tm));
  453. tm.tm_year = 2000 + date->year - 1900;
  454. tm.tm_mon = date->month - 1;
  455. tm.tm_mday = date->day;
  456. tm.tm_hour = time_->hours;
  457. tm.tm_min = time_->minutes;
  458. tm.tm_sec = time_->seconds;
  459. time_t timestamp = timegm(&tm); /* See README.md if your system lacks timegm(). */
  460. if (timestamp != -1) {
  461. ts->tv_sec = timestamp;
  462. ts->tv_nsec = time_->microseconds * 1000;
  463. return 0;
  464. } else {
  465. return -1;
  466. }
  467. }
  468. /* vim: set ts=4 sw=4 et: */