nmea.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. p = gp_col(str, 1); /* Get h:m:s */
  142. if (!p)
  143. return 0;
  144. tmc.tm_hour = gp_val(p, 2);
  145. tmc.tm_min = gp_val(p+2, 2);
  146. tmc.tm_sec = gp_val(p+4, 2);
  147. p = gp_col(str, 9); /* Get y:m:d */
  148. if (!p)
  149. return 0;
  150. tmc.tm_mday = gp_val(p, 2);
  151. tmc.tm_mon = gp_val(p+2, 2) - 1;
  152. tmc.tm_year = gp_val(p+4, 2) + 100;
  153. utc = mktime(&tmc); /* Check time validity */
  154. if (utc == -1)
  155. return 0;
  156. p = gp_col(str, 2); /* Get status */
  157. if (!p || *p != 'A') {
  158. System.location_valid = LOC_INVALID;
  159. FLAGS &= ~F_GPSOK;
  160. return 0; /* Return 0 even is time is valid (comes from module's internal RTC) */
  161. }
  162. FLAGS |= F_GPSOK;
  163. /* Speed over ground, from this same sentence (and the same epoch whose
  164. * status field was just checked above), in knots - converted to km/h.
  165. * Not VTG: some receivers omit VTG or send a shorter form of it, and RMC
  166. * is the one sentence essentially every NMEA GNSS module emits. */
  167. p = gp_col(str, 7);
  168. if (p && *p) {
  169. xatof(&p, &speed_knots);
  170. speed_sample_process(speed_knots * 1.852);
  171. }
  172. return utc;
  173. }
  174. static void gp_gga_parse(const char *str) {
  175. const char *p;
  176. double tmp;
  177. p = gp_col(str, 7); /* satellites used */
  178. System.satellites_used = atoi(p);
  179. if (System.satellites_used >= System.conf.min_sats) {
  180. System.sat_count_low = 0;
  181. } else {
  182. System.sat_count_low = 1;
  183. }
  184. /* check validity */
  185. p = gp_col(str, 6);
  186. if (*p == '0') {
  187. System.location_valid = LOC_INVALID;
  188. return;
  189. }
  190. if (!System.sat_count_low)
  191. System.location_valid = LOC_VALID_NEW; /* don't accept the coordinates otherwise, even if reported valid */
  192. /* parse location */
  193. p = gp_col(str, 2); /* latitude */
  194. location.lat = gp_val(p, 2); /* degrees */
  195. p += 2;
  196. xatof(&p, &tmp); /* minutes */
  197. tmp /= 60; /* convert minutes to degrees */
  198. location.lat += tmp;
  199. p = gp_col(str, 3); /* N/S */
  200. if (*p != 'N')
  201. location.lat = -location.lat;
  202. p = gp_col(str, 4); /* longitude */
  203. location.lon = gp_val(p, 3); /* degrees */
  204. p += 3;
  205. xatof(&p, &tmp); /* minutes */
  206. tmp /= 60; /* convert minutes to degrees */
  207. location.lon += tmp;
  208. p = gp_col(str, 5); /* E/W */
  209. if (*p != 'E')
  210. location.lon = -location.lon;
  211. p = gp_col(str, 6); /* fix type */
  212. if (*p == '2')
  213. System.sbas = 1;
  214. else
  215. System.sbas = 0;
  216. p = gp_col(str, 9); /* MSL altitude */
  217. xatof(&p, &tmp);
  218. location.alt = tmp;
  219. location.time = utc; /* parsed from RMC */
  220. }
  221. /* A fix is only trusted (for the speed average, and for the auto-pause
  222. * speed-based unpause check below) when it is valid, of a known type, and
  223. * reasonably accurate: a single sample from a poor fix (e.g. HDOP 16 with
  224. * only a few satellites) would otherwise distort the whole-session average,
  225. * or - worse - talk the auto-pause logic into resuming a stationary logger. */
  226. #define FIX_QUALITY_HDOP_MAX_X100 500 /* a fix is untrustworthy once HDOP > 5.00 */
  227. unsigned char gps_fix_trustworthy(void) {
  228. return (FLAGS & F_GPSOK) && System.fix_type != FIX_TYPE_UNKNOWN
  229. && System.hdop_x100 <= FIX_QUALITY_HDOP_MAX_X100;
  230. }
  231. static void gp_gsa_parse(const char *str) {
  232. const char *p;
  233. double hdop;
  234. p = gp_col(str, 2); /* fix type: 1 no fix, 2 2D, 3 3D */
  235. if (p && *p == '2')
  236. System.fix_type = FIX_TYPE_2D;
  237. else if (p && *p == '3')
  238. System.fix_type = FIX_TYPE_3D;
  239. else
  240. System.fix_type = FIX_TYPE_UNKNOWN;
  241. p = gp_col(str, 16); /* HDOP */
  242. if (p && *p) {
  243. xatof(&p, &hdop);
  244. System.hdop_x100 = (unsigned int)(hdop*100.0 + 0.5);
  245. }
  246. }
  247. /*$PMTK355*31<CR><LF>
  248. Return $PMTK001,355,3,1,0,0*2E “$PMTK001,355,3,GLON_Enable,BEIDOU_Enable,GALILEO_Enable”
  249. The GLONASS search mode is enabled. */
  250. static void pmtk001_parse(const char *str) {
  251. const char *p;
  252. /* check validity */
  253. p = gp_col(str, 1);
  254. if (strcmp_P(p, PSTR("355"))) /* not the PMTK355 reply */
  255. return;
  256. p = gp_col(str, 2);
  257. if (*p == '0' || *p == '1') { /* invalid / unsupported */
  258. System.gps_only = 1;
  259. xputs_P(PSTR("GPS only\r\n"));
  260. } else {
  261. System.gps_only = 0;
  262. xputs_P(PSTR("Multi GNSS\r\n"));
  263. }
  264. gps_initialize();
  265. }
  266. unsigned char nmea_checksum(const char *str) {
  267. unsigned char cs = 0;
  268. while (*str && *str != '*') {
  269. cs ^= *str++; /* NMEA checksum is quite primitive, but still should catch simple bitstream errors or truncated lines */
  270. }
  271. return cs;
  272. }
  273. time_t gps_parse(const char *str) { /* Get all required data from NMEA sentences */
  274. signed int len = strlen(str)-2; /* remove final \r\n */
  275. const char *checksum;
  276. unsigned char calc_checksum, inc_checksum;
  277. signed int i;
  278. char c;
  279. if (len < 4)
  280. return 0; /* each message must contain $.*xx where . is one or more actual data characters and xx is the checksum */
  281. for (i = len-1; i && i >= (len-2); i--) { /* find checksum */
  282. if (str[i] == '*')
  283. break;
  284. }
  285. checksum = str+i+1; /* skip * character */
  286. inc_checksum = 0; /* parse hex string */
  287. while (*checksum && isalnum(*checksum)) {
  288. inc_checksum *= 16;
  289. c = *checksum++;
  290. if (c >= '0' && c <= '9') {
  291. inc_checksum += c - '0';
  292. } else if (c >= 'a' && c <= 'f') {
  293. inc_checksum += c - 'a' + 10;
  294. } else if (c >= 'A' && c <= 'F') {
  295. inc_checksum += c - 'A' + 10;
  296. } else {
  297. xputs_P(PSTR("Invalid NMEA: malformed checksum\r\n"));
  298. return 0; /* invalid checksum character */
  299. }
  300. }
  301. str++; /* drop initial $ */
  302. calc_checksum = nmea_checksum(str);
  303. if (inc_checksum != calc_checksum) {
  304. xputs_P(PSTR("Invalid NMEA checksum received\r\n"));
  305. return 0;
  306. }
  307. if (!gp_comp(str, PSTR("GPRMC")) || !gp_comp(str, PSTR("GNRMC")) || !gp_comp(str, PSTR("BDRMC")) || !gp_comp(str, PSTR("GARMC"))) {
  308. return gp_rmc_parse(str);
  309. }
  310. if (!gp_comp(str, PSTR("GPGGA")) || !gp_comp(str, PSTR("GNGGA")) || !gp_comp(str, PSTR("BDGGA")) || !gp_comp(str, PSTR("GAGGA"))) {
  311. gp_gga_parse(str);
  312. return 0;
  313. }
  314. if (!gp_comp(str, PSTR("GPGSA")) || !gp_comp(str, PSTR("GNGSA")) || !gp_comp(str, PSTR("BDGSA")) || !gp_comp(str, PSTR("GAGSA"))) {
  315. gp_gsa_parse(str);
  316. return 0;
  317. }
  318. if (!System.gps_initialized && !gp_comp(str, PSTR("PMTK011"))) {
  319. gps_initialize();
  320. return 0;
  321. }
  322. if (!gp_comp(str, PSTR("PMTK001"))) {
  323. pmtk001_parse(str);
  324. return 0;
  325. }
  326. if (!gp_comp(str, PSTR("PMTK"))) {
  327. /* Any other PMTK reply (e.g. PMTK705, the firmware release query
  328. * response) - log it verbatim, no need for a dedicated parser. */
  329. log_prefix();
  330. xputs_P(PSTR("RX "));
  331. xputs(str);
  332. return 0;
  333. }
  334. return 0;
  335. }
  336. void uart0_put_wrap(int c) {
  337. uart0_put((char)c);
  338. }
  339. void gps_initialize(void) {
  340. /*
  341. * PMTK355: query gnss search mode (will fail if only GPS is supported)
  342. * PMTK353: set gnss search mode (GPS/Galileo/Glonass/Beidou)
  343. * PMTK313: enable SBAS
  344. * PMTK605: query firmware release; the reply (PMTK705) is logged
  345. * verbatim by the generic PMTK passthrough in gps_parse()
  346. */
  347. switch (System.gps_initialized) {
  348. case GPS_INIT_NOT_INITIALIZED:
  349. xfprintf(uart0_put_wrap, PSTR("$PMTK355*31\r\n"));
  350. xputs_P(PSTR("GNSS mode query sent\r\n"));
  351. xfprintf(uart0_put_wrap, PSTR("$PMTK605*31\r\n"));
  352. System.gps_initialized = GPS_INIT_QUERY_SENT;
  353. break;
  354. case GPS_INIT_QUERY_SENT:
  355. if (get_flag(CONFFLAG_ENABLE_SBAS)) {
  356. xfprintf(uart0_put_wrap, PSTR("$PMTK313,1*2E\r\n"));
  357. xputs_P(PSTR("SBAS enable sent\r\n"));
  358. } else {
  359. xfprintf(uart0_put_wrap, PSTR("$PMTK313,0*2F\r\n"));
  360. xputs_P(PSTR("SBAS disable sent\r\n"));
  361. }
  362. if (!System.gps_only) {
  363. switch (System.conf.gnss_mode) {
  364. default:
  365. case GNSS_MODE_GPS_GLONASS_GALILEO:
  366. xfprintf(uart0_put_wrap, PSTR("$PMTK353,1,1,1,0,0*2A\r\n"));
  367. break;
  368. case GNSS_MODE_GPS:
  369. xfprintf(uart0_put_wrap, PSTR("$PMTK353,1,0,0,0,0*2A\r\n"));
  370. break;
  371. case GNSS_MODE_GPS_GALILEO:
  372. xfprintf(uart0_put_wrap, PSTR("$PMTK353,1,0,1,0,0*2B\r\n"));
  373. break;
  374. case GNSS_MODE_GALILEO:
  375. xfprintf(uart0_put_wrap, PSTR("$PMTK353,0,0,1,0,0*2A\r\n"));
  376. break;
  377. case GNSS_MODE_GPS_BEIDOU:
  378. xfprintf(uart0_put_wrap, PSTR("$PMTK353,1,0,0,0,1*2B\r\n"));
  379. break;
  380. case GNSS_MODE_BEIDOU:
  381. xfprintf(uart0_put_wrap, PSTR("$PMTK353,0,0,0,0,1*2A\r\n"));
  382. break;
  383. }
  384. xputs_P(PSTR("GNSS mode setting sent\r\n"));
  385. } else {
  386. System.conf.gnss_mode = GNSS_MODE_GPS;
  387. }
  388. break;
  389. default:
  390. break;
  391. }
  392. }
  393. void check_min_sat_limit(void) {
  394. 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)) {
  395. /* by geometry, max visible number is 6..12 */
  396. System.conf.min_sats = 6;
  397. }
  398. }