minmea.c 20 KB

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