minmea.c 19 KB

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