minmea.c 19 KB

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