nmea.c 12 KB

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