minmea.c 20 KB

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