minmea.c 20 KB

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