minmea.c 20 KB

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