minmea.c 18 KB

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