minmea.c 20 KB

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