minmea.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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, "GBS"))
  298. return MINMEA_SENTENCE_GBS;
  299. if (!strcmp(type+2, "GGA"))
  300. return MINMEA_SENTENCE_GGA;
  301. if (!strcmp(type+2, "GLL"))
  302. return MINMEA_SENTENCE_GLL;
  303. if (!strcmp(type+2, "GSA"))
  304. return MINMEA_SENTENCE_GSA;
  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, "RMC"))
  310. return MINMEA_SENTENCE_RMC;
  311. if (!strcmp(type+2, "VTG"))
  312. return MINMEA_SENTENCE_VTG;
  313. if (!strcmp(type+2, "ZDA"))
  314. return MINMEA_SENTENCE_ZDA;
  315. return MINMEA_UNKNOWN;
  316. }
  317. bool minmea_parse_gbs(struct minmea_sentence_gbs *frame, const char *sentence)
  318. {
  319. // $GNGBS,170556.00,3.0,2.9,8.3,,,,*5C
  320. char type[6];
  321. if (!minmea_scan(sentence, "tTfffdfff",
  322. type,
  323. &frame->time,
  324. &frame->err_latitude,
  325. &frame->err_longitude,
  326. &frame->err_altitude,
  327. &frame->svid,
  328. &frame->prob,
  329. &frame->bias,
  330. &frame->stddev
  331. ))
  332. return false;
  333. if (strcmp(type+2, "GBS"))
  334. return false;
  335. return true;
  336. }
  337. bool minmea_parse_rmc(struct minmea_sentence_rmc *frame, const char *sentence)
  338. {
  339. // $GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62
  340. char type[6];
  341. char validity;
  342. int latitude_direction;
  343. int longitude_direction;
  344. int variation_direction;
  345. if (!minmea_scan(sentence, "tTcfdfdffDfd",
  346. type,
  347. &frame->time,
  348. &validity,
  349. &frame->latitude, &latitude_direction,
  350. &frame->longitude, &longitude_direction,
  351. &frame->speed,
  352. &frame->course,
  353. &frame->date,
  354. &frame->variation, &variation_direction))
  355. return false;
  356. if (strcmp(type+2, "RMC"))
  357. return false;
  358. frame->valid = (validity == 'A');
  359. frame->latitude.value *= latitude_direction;
  360. frame->longitude.value *= longitude_direction;
  361. frame->variation.value *= variation_direction;
  362. return true;
  363. }
  364. bool minmea_parse_gga(struct minmea_sentence_gga *frame, const char *sentence)
  365. {
  366. // $GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47
  367. char type[6];
  368. int latitude_direction;
  369. int longitude_direction;
  370. if (!minmea_scan(sentence, "tTfdfdiiffcfcf_",
  371. type,
  372. &frame->time,
  373. &frame->latitude, &latitude_direction,
  374. &frame->longitude, &longitude_direction,
  375. &frame->fix_quality,
  376. &frame->satellites_tracked,
  377. &frame->hdop,
  378. &frame->altitude, &frame->altitude_units,
  379. &frame->height, &frame->height_units,
  380. &frame->dgps_age))
  381. return false;
  382. if (strcmp(type+2, "GGA"))
  383. return false;
  384. frame->latitude.value *= latitude_direction;
  385. frame->longitude.value *= longitude_direction;
  386. return true;
  387. }
  388. bool minmea_parse_gsa(struct minmea_sentence_gsa *frame, const char *sentence)
  389. {
  390. // $GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39
  391. char type[6];
  392. if (!minmea_scan(sentence, "tciiiiiiiiiiiiifff",
  393. type,
  394. &frame->mode,
  395. &frame->fix_type,
  396. &frame->sats[0],
  397. &frame->sats[1],
  398. &frame->sats[2],
  399. &frame->sats[3],
  400. &frame->sats[4],
  401. &frame->sats[5],
  402. &frame->sats[6],
  403. &frame->sats[7],
  404. &frame->sats[8],
  405. &frame->sats[9],
  406. &frame->sats[10],
  407. &frame->sats[11],
  408. &frame->pdop,
  409. &frame->hdop,
  410. &frame->vdop))
  411. return false;
  412. if (strcmp(type+2, "GSA"))
  413. return false;
  414. return true;
  415. }
  416. bool minmea_parse_gll(struct minmea_sentence_gll *frame, const char *sentence)
  417. {
  418. // $GPGLL,3723.2475,N,12158.3416,W,161229.487,A,A*41$;
  419. char type[6];
  420. int latitude_direction;
  421. int longitude_direction;
  422. if (!minmea_scan(sentence, "tfdfdTc;c",
  423. type,
  424. &frame->latitude, &latitude_direction,
  425. &frame->longitude, &longitude_direction,
  426. &frame->time,
  427. &frame->status,
  428. &frame->mode))
  429. return false;
  430. if (strcmp(type+2, "GLL"))
  431. return false;
  432. frame->latitude.value *= latitude_direction;
  433. frame->longitude.value *= longitude_direction;
  434. return true;
  435. }
  436. bool minmea_parse_gst(struct minmea_sentence_gst *frame, const char *sentence)
  437. {
  438. // $GPGST,024603.00,3.2,6.6,4.7,47.3,5.8,5.6,22.0*58
  439. char type[6];
  440. if (!minmea_scan(sentence, "tTfffffff",
  441. type,
  442. &frame->time,
  443. &frame->rms_deviation,
  444. &frame->semi_major_deviation,
  445. &frame->semi_minor_deviation,
  446. &frame->semi_major_orientation,
  447. &frame->latitude_error_deviation,
  448. &frame->longitude_error_deviation,
  449. &frame->altitude_error_deviation))
  450. return false;
  451. if (strcmp(type+2, "GST"))
  452. return false;
  453. return true;
  454. }
  455. bool minmea_parse_gsv(struct minmea_sentence_gsv *frame, const char *sentence)
  456. {
  457. // $GPGSV,3,1,11,03,03,111,00,04,15,270,00,06,01,010,00,13,06,292,00*74
  458. // $GPGSV,3,3,11,22,42,067,42,24,14,311,43,27,05,244,00,,,,*4D
  459. // $GPGSV,4,2,11,08,51,203,30,09,45,215,28*75
  460. // $GPGSV,4,4,13,39,31,170,27*40
  461. // $GPGSV,4,4,13*7B
  462. char type[6];
  463. if (!minmea_scan(sentence, "tiii;iiiiiiiiiiiiiiii",
  464. type,
  465. &frame->total_msgs,
  466. &frame->msg_nr,
  467. &frame->total_sats,
  468. &frame->sats[0].nr,
  469. &frame->sats[0].elevation,
  470. &frame->sats[0].azimuth,
  471. &frame->sats[0].snr,
  472. &frame->sats[1].nr,
  473. &frame->sats[1].elevation,
  474. &frame->sats[1].azimuth,
  475. &frame->sats[1].snr,
  476. &frame->sats[2].nr,
  477. &frame->sats[2].elevation,
  478. &frame->sats[2].azimuth,
  479. &frame->sats[2].snr,
  480. &frame->sats[3].nr,
  481. &frame->sats[3].elevation,
  482. &frame->sats[3].azimuth,
  483. &frame->sats[3].snr
  484. )) {
  485. return false;
  486. }
  487. if (strcmp(type+2, "GSV"))
  488. return false;
  489. return true;
  490. }
  491. bool minmea_parse_vtg(struct minmea_sentence_vtg *frame, const char *sentence)
  492. {
  493. // $GPVTG,054.7,T,034.4,M,005.5,N,010.2,K*48
  494. // $GPVTG,156.1,T,140.9,M,0.0,N,0.0,K*41
  495. // $GPVTG,096.5,T,083.5,M,0.0,N,0.0,K,D*22
  496. // $GPVTG,188.36,T,,M,0.820,N,1.519,K,A*3F
  497. char type[6];
  498. char c_true, c_magnetic, c_knots, c_kph, c_faa_mode;
  499. if (!minmea_scan(sentence, "tfcfcfcfc;c",
  500. type,
  501. &frame->true_track_degrees,
  502. &c_true,
  503. &frame->magnetic_track_degrees,
  504. &c_magnetic,
  505. &frame->speed_knots,
  506. &c_knots,
  507. &frame->speed_kph,
  508. &c_kph,
  509. &c_faa_mode))
  510. return false;
  511. if (strcmp(type+2, "VTG"))
  512. return false;
  513. // check chars
  514. if (c_true != 'T' ||
  515. c_magnetic != 'M' ||
  516. c_knots != 'N' ||
  517. c_kph != 'K')
  518. return false;
  519. frame->faa_mode = (enum minmea_faa_mode)c_faa_mode;
  520. return true;
  521. }
  522. bool minmea_parse_zda(struct minmea_sentence_zda *frame, const char *sentence)
  523. {
  524. // $GPZDA,201530.00,04,07,2002,00,00*60
  525. char type[6];
  526. if(!minmea_scan(sentence, "tTiiiii",
  527. type,
  528. &frame->time,
  529. &frame->date.day,
  530. &frame->date.month,
  531. &frame->date.year,
  532. &frame->hour_offset,
  533. &frame->minute_offset))
  534. return false;
  535. if (strcmp(type+2, "ZDA"))
  536. return false;
  537. // check offsets
  538. if (abs(frame->hour_offset) > 13 ||
  539. frame->minute_offset > 59 ||
  540. frame->minute_offset < 0)
  541. return false;
  542. return true;
  543. }
  544. int minmea_gettime(struct timespec *ts, const struct minmea_date *date, const struct minmea_time *time_)
  545. {
  546. if (date->year == -1 || time_->hours == -1)
  547. return -1;
  548. struct tm tm;
  549. memset(&tm, 0, sizeof(tm));
  550. if (date->year < 80) {
  551. tm.tm_year = 2000 + date->year - 1900; // 2000-2079
  552. } else if (date->year >= 1900) {
  553. tm.tm_year = date->year - 1900; // 4 digit year, use directly
  554. } else {
  555. tm.tm_year = date->year; // 1980-1999
  556. }
  557. tm.tm_mon = date->month - 1;
  558. tm.tm_mday = date->day;
  559. tm.tm_hour = time_->hours;
  560. tm.tm_min = time_->minutes;
  561. tm.tm_sec = time_->seconds;
  562. time_t timestamp = timegm(&tm); /* See README.md if your system lacks timegm(). */
  563. if (timestamp != (time_t)-1) {
  564. ts->tv_sec = timestamp;
  565. ts->tv_nsec = time_->microseconds * 1000;
  566. return 0;
  567. } else {
  568. return -1;
  569. }
  570. }
  571. /* vim: set ts=4 sw=4 et: */