nmea.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. #ifdef PC_BUILD
  2. #include "../gps-test-tool/main.h"
  3. #else
  4. #include "main.h"
  5. #endif
  6. /*----------------------------------------------------*/
  7. /* Get a line received from GPS module */
  8. /*----------------------------------------------------*/
  9. uint16_t get_line ( /* 0:line incomplete or timed out, >0: Number of bytes received. */
  10. char *buff,
  11. uint16_t sz_buf
  12. )
  13. {
  14. char c;
  15. static uint16_t i = 0;
  16. uint16_t ret_len;
  17. set_timer(recv_timeout, 1000);
  18. for (;;) {
  19. wdt_reset();
  20. if (FLAGS & (F_LVD | F_POWEROFF))
  21. return 0; /* A brownout is detected */
  22. if (timer_expired(recv_timeout))
  23. return 0; /* timeout; continue the main loop */
  24. if (System.keypress) /* process user keypress */
  25. return 0;
  26. if (!uart0_test()) {
  27. sleep();
  28. continue;
  29. }
  30. c = (char)uart0_get();
  31. if (i == 0 && c != '$' )
  32. continue; /* Find start of line */
  33. if (c == '\n' || c == '\r') {
  34. buff[i++] = '\r';
  35. buff[i++] = '\n';
  36. buff[i++] = '\0'; /* add null termination for string */
  37. break; /* EOL */
  38. }
  39. buff[i++] = c;
  40. if (System.conf.uart_log_mode != UART_LOG_MODE_SYSTEM)
  41. uart1_put(c);
  42. if (i >= sz_buf - 3) /* keep 3 bytes for terminating character */
  43. i = 0; /* Buffer overflow (abort this line) */
  44. }
  45. ret_len = i;
  46. i = 0;
  47. if (ret_len > 0 && System.conf.uart_log_mode != UART_LOG_MODE_SYSTEM) {
  48. uart1_put('\r');
  49. uart1_put('\n');
  50. }
  51. return ret_len;
  52. }
  53. /* Compare sentence header string */
  54. BYTE gp_comp (const char *str1, __flash const char *str2)
  55. {
  56. char c;
  57. do {
  58. c = pgm_read_byte(str2++);
  59. } while (c && c == *str1++);
  60. return c;
  61. }
  62. #define FIELD_BUF_LEN 32
  63. /* Get a column item */
  64. static
  65. const char* gp_col ( /* Returns pointer to the item (returns a NULL when not found) */
  66. const char* buf, /* Pointer to the sentence */
  67. BYTE col /* Column number (0 is the 1st item) */
  68. ) {
  69. BYTE c;
  70. static char field_buf[FIELD_BUF_LEN];
  71. unsigned char length = 0;
  72. while (col) {
  73. do {
  74. c = *buf++;
  75. if (c <= ' ') return NULL;
  76. } while (c != ',');
  77. col--;
  78. }
  79. while (*buf && *buf != ',' && length < FIELD_BUF_LEN-1) {
  80. field_buf[length++] = *buf++;
  81. }
  82. field_buf[length] = '\0';
  83. return field_buf;
  84. }
  85. unsigned int gp_val(const char *db, unsigned char count) {
  86. unsigned int out = 0;
  87. while (count--) {
  88. unsigned char n;
  89. n = *db - '0';
  90. if (n >= 10)
  91. return 0;
  92. out *= 10;
  93. out += n;
  94. db++;
  95. }
  96. return out;
  97. }
  98. #define SPEED_SAMPLE_CAP_MULT 3 /* cap any single sample at this multiple of the running average... */
  99. #define SPEED_SAMPLE_CAP_MIN_SAMPLES 60 /* ...but only once the average actually means something, ... */
  100. #define SPEED_SAMPLE_CAP_FLOOR_X100 2000 /* ...and never cap below this (20 km/h): the cap is a backstop against
  101. * a single wild outlier, not a speed limit - persistence (below) is what
  102. * lets a genuinely sustained fast segment (car/train) through. */
  103. #define SPEED_SAMPLE_HIGH_HISTORY_LEN 7 /* consider this many of the most recent samples... */
  104. #define SPEED_SAMPLE_HIGH_HISTORY_MASK ((1U << SPEED_SAMPLE_HIGH_HISTORY_LEN) - 1)
  105. #define SPEED_SAMPLE_HIGH_MIN_COUNT 5 /* ...and once this many of them were above the cap, stop clamping:
  106. * a single spike (e.g. the 200 km/h one-second glitch seen on a real
  107. * hike) never reaches this, but a sustained fast segment does within a
  108. * few seconds. */
  109. /* Bit history of "was this raw sample above the cap" for the last
  110. * SPEED_SAMPLE_HIGH_HISTORY_LEN samples (bit 0: most recent). Static file
  111. * scope, not part of System - it's working state for the cap logic only,
  112. * nothing else needs it. */
  113. static unsigned char speed_sample_high_history;
  114. static void speed_sample_process(double speed_kmh) {
  115. unsigned char paused = System.tracking_paused || System.tracking_auto_paused;
  116. unsigned char fix_trustworthy = gps_fix_trustworthy();
  117. System.speed = speed_kmh+0.5;
  118. /* Average speed: fixed-point accumulation of instantaneous samples,
  119. * excluding time spent paused, instead of dividing distance by time. */
  120. if (!paused && fix_trustworthy) {
  121. unsigned long int sample_x100 = (unsigned long int)(speed_kmh*100.0 + 0.5);
  122. if (System.speed_sample_count >= SPEED_SAMPLE_CAP_MIN_SAMPLES) {
  123. unsigned long int avg_x100 = System.speed_accum_x100 / System.speed_sample_count;
  124. unsigned long int cap_x100 = avg_x100 * SPEED_SAMPLE_CAP_MULT;
  125. unsigned char is_high;
  126. if (cap_x100 < SPEED_SAMPLE_CAP_FLOOR_X100)
  127. cap_x100 = SPEED_SAMPLE_CAP_FLOOR_X100;
  128. is_high = sample_x100 > cap_x100;
  129. speed_sample_high_history = (speed_sample_high_history << 1) | is_high;
  130. if (is_high && __builtin_popcount(speed_sample_high_history & SPEED_SAMPLE_HIGH_HISTORY_MASK) < SPEED_SAMPLE_HIGH_MIN_COUNT)
  131. sample_x100 = cap_x100; /* not (yet) persistent: clamp as a backstop against a lone spike */
  132. }
  133. System.speed_accum_x100 += sample_x100;
  134. System.speed_sample_count++;
  135. }
  136. }
  137. static time_t gp_rmc_parse(const char *str) {
  138. const char *p;
  139. struct tm tmc;
  140. double speed_knots;
  141. System.epoch_gga_ok = 0;
  142. System.epoch_gsa_ok = 0;
  143. System.epoch_logged = 0;
  144. p = gp_col(str, 1); /* Get h:m:s */
  145. if (!p)
  146. return 0;
  147. tmc.tm_hour = gp_val(p, 2);
  148. tmc.tm_min = gp_val(p+2, 2);
  149. tmc.tm_sec = gp_val(p+4, 2);
  150. p = gp_col(str, 9); /* Get y:m:d */
  151. if (!p)
  152. return 0;
  153. tmc.tm_mday = gp_val(p, 2);
  154. tmc.tm_mon = gp_val(p+2, 2) - 1;
  155. tmc.tm_year = gp_val(p+4, 2) + 100;
  156. utc = mktime(&tmc); /* Check time validity */
  157. if (utc == -1)
  158. return 0;
  159. p = gp_col(str, 2); /* Get status */
  160. if (!p || *p != 'A') {
  161. System.location_valid = LOC_INVALID;
  162. FLAGS &= ~F_GPSOK;
  163. return 0; /* Return 0 even is time is valid (comes from module's internal RTC) */
  164. }
  165. FLAGS |= F_GPSOK;
  166. /* Speed over ground, from this same sentence (and the same epoch whose
  167. * status field was just checked above), in knots - converted to km/h.
  168. * Not VTG: some receivers omit VTG or send a shorter form of it, and RMC
  169. * is the one sentence essentially every NMEA GNSS module emits. */
  170. p = gp_col(str, 7);
  171. if (p && *p) {
  172. xatof(&p, &speed_knots);
  173. speed_sample_process(speed_knots * 1.852);
  174. }
  175. return utc;
  176. }
  177. static void gp_gga_parse(const char *str) {
  178. const char *p;
  179. double tmp;
  180. p = gp_col(str, 7); /* satellites used */
  181. System.satellites_used = atoi(p);
  182. System.epoch_gga_ok = 1;
  183. if (System.satellites_used >= System.conf.min_sats) {
  184. System.sat_count_low = 0;
  185. } else {
  186. System.sat_count_low = 1;
  187. }
  188. /* check validity */
  189. p = gp_col(str, 6);
  190. if (*p == '0') {
  191. System.location_valid = LOC_INVALID;
  192. return;
  193. }
  194. if (!System.sat_count_low)
  195. System.location_valid = LOC_VALID_NEW; /* don't accept the coordinates otherwise, even if reported valid */
  196. /* parse location */
  197. p = gp_col(str, 2); /* latitude */
  198. location.lat = gp_val(p, 2); /* degrees */
  199. p += 2;
  200. xatof(&p, &tmp); /* minutes */
  201. tmp /= 60; /* convert minutes to degrees */
  202. location.lat += tmp;
  203. p = gp_col(str, 3); /* N/S */
  204. if (*p != 'N')
  205. location.lat = -location.lat;
  206. p = gp_col(str, 4); /* longitude */
  207. location.lon = gp_val(p, 3); /* degrees */
  208. p += 3;
  209. xatof(&p, &tmp); /* minutes */
  210. tmp /= 60; /* convert minutes to degrees */
  211. location.lon += tmp;
  212. p = gp_col(str, 5); /* E/W */
  213. if (*p != 'E')
  214. location.lon = -location.lon;
  215. p = gp_col(str, 6); /* fix type */
  216. if (*p == '2')
  217. System.sbas = 1;
  218. else
  219. System.sbas = 0;
  220. p = gp_col(str, 9); /* MSL altitude */
  221. xatof(&p, &tmp);
  222. location.alt = tmp;
  223. location.time = utc; /* parsed from RMC */
  224. }
  225. /* A fix is only trusted (for the speed average, and for the auto-pause
  226. * speed-based unpause check below) when it is valid, of a known type, and
  227. * reasonably accurate: a single sample from a poor fix (e.g. HDOP 16 with
  228. * only a few satellites) would otherwise distort the whole-session average,
  229. * or - worse - talk the auto-pause logic into resuming a stationary logger. */
  230. #define FIX_QUALITY_HDOP_MAX_X100 500 /* a fix is untrustworthy once HDOP > 5.00 */
  231. unsigned char gps_fix_trustworthy(void) {
  232. return (FLAGS & F_GPSOK) && System.fix_type != FIX_TYPE_UNKNOWN
  233. && System.hdop_x100 <= FIX_QUALITY_HDOP_MAX_X100;
  234. }
  235. static void gp_gsa_parse(const char *str) {
  236. const char *p;
  237. double hdop;
  238. p = gp_col(str, 2); /* fix type: 1 no fix, 2 2D, 3 3D */
  239. if (p && *p == '2')
  240. System.fix_type = FIX_TYPE_2D;
  241. else if (p && *p == '3')
  242. System.fix_type = FIX_TYPE_3D;
  243. else
  244. System.fix_type = FIX_TYPE_UNKNOWN;
  245. p = gp_col(str, 16); /* HDOP */
  246. if (p && *p) {
  247. xatof(&p, &hdop);
  248. System.hdop_x100 = (unsigned int)(hdop*100.0 + 0.5);
  249. }
  250. System.epoch_gsa_ok = 1;
  251. }
  252. /* Returns 1 exactly once per epoch (the moment both GGA and GSA have been
  253. * parsed for it, whichever arrives second), so callers that need this
  254. * epoch's satellite count and HDOP together (e.g. logging a fix event) never
  255. * see a stale value left over from a previous epoch or an earlier line -
  256. * regardless of which order the receiver sends GGA/GSA in. */
  257. unsigned char nmea_epoch_complete(void) {
  258. if (System.epoch_gga_ok && System.epoch_gsa_ok && !System.epoch_logged) {
  259. System.epoch_logged = 1;
  260. return 1;
  261. }
  262. return 0;
  263. }
  264. /*$PMTK355*31<CR><LF>
  265. Return $PMTK001,355,3,1,0,0*2E “$PMTK001,355,3,GLON_Enable,BEIDOU_Enable,GALILEO_Enable”
  266. The GLONASS search mode is enabled. */
  267. static void pmtk001_parse(const char *str) {
  268. const char *p;
  269. /* check validity */
  270. p = gp_col(str, 1);
  271. if (strcmp_P(p, PSTR("355"))) /* not the PMTK355 reply */
  272. return;
  273. p = gp_col(str, 2);
  274. if (*p == '0' || *p == '1') { /* invalid / unsupported */
  275. System.gps_only = 1;
  276. xputs_P(PSTR("GPS only\r\n"));
  277. } else {
  278. System.gps_only = 0;
  279. xputs_P(PSTR("Multi GNSS\r\n"));
  280. }
  281. gps_initialize();
  282. }
  283. unsigned char nmea_checksum(const char *str) {
  284. unsigned char cs = 0;
  285. while (*str && *str != '*') {
  286. cs ^= *str++; /* NMEA checksum is quite primitive, but still should catch simple bitstream errors or truncated lines */
  287. }
  288. return cs;
  289. }
  290. time_t gps_parse(const char *str) { /* Get all required data from NMEA sentences */
  291. signed int len = strlen(str)-2; /* remove final \r\n */
  292. const char *checksum;
  293. unsigned char calc_checksum, inc_checksum;
  294. signed int i;
  295. char c;
  296. if (len < 4)
  297. return 0; /* each message must contain $.*xx where . is one or more actual data characters and xx is the checksum */
  298. for (i = len-1; i && i >= (len-2); i--) { /* find checksum */
  299. if (str[i] == '*')
  300. break;
  301. }
  302. checksum = str+i+1; /* skip * character */
  303. inc_checksum = 0; /* parse hex string */
  304. while (*checksum && isalnum(*checksum)) {
  305. inc_checksum *= 16;
  306. c = *checksum++;
  307. if (c >= '0' && c <= '9') {
  308. inc_checksum += c - '0';
  309. } else if (c >= 'a' && c <= 'f') {
  310. inc_checksum += c - 'a' + 10;
  311. } else if (c >= 'A' && c <= 'F') {
  312. inc_checksum += c - 'A' + 10;
  313. } else {
  314. xputs_P(PSTR("Invalid NMEA: malformed checksum\r\n"));
  315. return 0; /* invalid checksum character */
  316. }
  317. }
  318. str++; /* drop initial $ */
  319. calc_checksum = nmea_checksum(str);
  320. if (inc_checksum != calc_checksum) {
  321. xputs_P(PSTR("Invalid NMEA checksum received\r\n"));
  322. return 0;
  323. }
  324. if (!gp_comp(str, PSTR("GPRMC")) || !gp_comp(str, PSTR("GNRMC")) || !gp_comp(str, PSTR("BDRMC")) || !gp_comp(str, PSTR("GARMC"))) {
  325. return gp_rmc_parse(str);
  326. }
  327. if (!gp_comp(str, PSTR("GPGGA")) || !gp_comp(str, PSTR("GNGGA")) || !gp_comp(str, PSTR("BDGGA")) || !gp_comp(str, PSTR("GAGGA"))) {
  328. gp_gga_parse(str);
  329. return 0;
  330. }
  331. if (!gp_comp(str, PSTR("GPGSA")) || !gp_comp(str, PSTR("GNGSA")) || !gp_comp(str, PSTR("BDGSA")) || !gp_comp(str, PSTR("GAGSA"))) {
  332. gp_gsa_parse(str);
  333. return 0;
  334. }
  335. if (!System.gps_initialized && !gp_comp(str, PSTR("PMTK011"))) {
  336. gps_initialize();
  337. return 0;
  338. }
  339. if (!gp_comp(str, PSTR("PMTK001"))) {
  340. pmtk001_parse(str);
  341. return 0;
  342. }
  343. if (!gp_comp(str, PSTR("PMTK"))) {
  344. /* Any other PMTK reply (e.g. PMTK705, the firmware release query
  345. * response) - log it verbatim, no need for a dedicated parser. */
  346. log_prefix();
  347. xputs_P(PSTR("RX "));
  348. xputs(str);
  349. return 0;
  350. }
  351. return 0;
  352. }
  353. void uart0_put_wrap(int c) {
  354. uart0_put((char)c);
  355. }
  356. void gps_initialize(void) {
  357. /*
  358. * PMTK355: query gnss search mode (will fail if only GPS is supported)
  359. * PMTK353: set gnss search mode (GPS/Galileo/Glonass/Beidou)
  360. * PMTK313: enable SBAS
  361. * PMTK605: query firmware release; the reply (PMTK705) is logged
  362. * verbatim by the generic PMTK passthrough in gps_parse()
  363. */
  364. switch (System.gps_initialized) {
  365. case GPS_INIT_NOT_INITIALIZED:
  366. xfprintf(uart0_put_wrap, PSTR("$PMTK355*31\r\n"));
  367. xputs_P(PSTR("GNSS mode query sent\r\n"));
  368. xfprintf(uart0_put_wrap, PSTR("$PMTK605*31\r\n"));
  369. System.gps_initialized = GPS_INIT_QUERY_SENT;
  370. break;
  371. case GPS_INIT_QUERY_SENT:
  372. if (get_flag(CONFFLAG_ENABLE_SBAS)) {
  373. xfprintf(uart0_put_wrap, PSTR("$PMTK313,1*2E\r\n"));
  374. xputs_P(PSTR("SBAS enable sent\r\n"));
  375. } else {
  376. xfprintf(uart0_put_wrap, PSTR("$PMTK313,0*2F\r\n"));
  377. xputs_P(PSTR("SBAS disable sent\r\n"));
  378. }
  379. if (!System.gps_only) {
  380. switch (System.conf.gnss_mode) {
  381. default:
  382. case GNSS_MODE_GPS_GLONASS_GALILEO:
  383. xfprintf(uart0_put_wrap, PSTR("$PMTK353,1,1,1,0,0*2A\r\n"));
  384. break;
  385. case GNSS_MODE_GPS:
  386. xfprintf(uart0_put_wrap, PSTR("$PMTK353,1,0,0,0,0*2A\r\n"));
  387. break;
  388. case GNSS_MODE_GPS_GALILEO:
  389. xfprintf(uart0_put_wrap, PSTR("$PMTK353,1,0,1,0,0*2B\r\n"));
  390. break;
  391. case GNSS_MODE_GALILEO:
  392. xfprintf(uart0_put_wrap, PSTR("$PMTK353,0,0,1,0,0*2A\r\n"));
  393. break;
  394. case GNSS_MODE_GPS_BEIDOU:
  395. xfprintf(uart0_put_wrap, PSTR("$PMTK353,1,0,0,0,1*2B\r\n"));
  396. break;
  397. case GNSS_MODE_BEIDOU:
  398. xfprintf(uart0_put_wrap, PSTR("$PMTK353,0,0,0,0,1*2A\r\n"));
  399. break;
  400. }
  401. xputs_P(PSTR("GNSS mode setting sent\r\n"));
  402. } else {
  403. System.conf.gnss_mode = GNSS_MODE_GPS;
  404. }
  405. break;
  406. default:
  407. break;
  408. }
  409. }
  410. void check_min_sat_limit(void) {
  411. if (System.conf.min_sats > 6 && (System.conf.gnss_mode == GNSS_MODE_GPS || System.conf.gnss_mode == GNSS_MODE_GALILEO || System.conf.gnss_mode == GNSS_MODE_BEIDOU)) {
  412. /* by geometry, max visible number is 6..12 */
  413. System.conf.min_sats = 6;
  414. }
  415. }