gpx.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. #ifdef PC_BUILD
  2. #include "../gps-test-tool/main.h"
  3. #else
  4. #include "main.h"
  5. #endif
  6. #define KALMAN_Q 8.5e-6
  7. #define KALMAN_R 4e-5
  8. #define KALMAN_ERR_MAX 6e-4
  9. __flash const char xml_header[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
  10. "<gpx xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.topografix.com/GPX/1/1\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\" version=\"1.1\" creator=\"k4be\">\n";
  11. __flash const char xml_trk_start[] = "\t<trk>\n";
  12. __flash const char xml_trkseg_end[] = "\t\t</trkseg>\n";
  13. __flash const char xml_trkseg_start[] = "\t\t<trkseg>\n";
  14. FIL gpx_file;
  15. static char buf[sizeof(xml_header)+sizeof(xml_trk_start)+2];
  16. struct kalman_s {
  17. unsigned char initialized;
  18. float x_est_last;
  19. float P_last;
  20. float Q;
  21. float R;
  22. float K;
  23. };
  24. #define PREV_POINTS_LENGTH 4
  25. #define AVG_COUNT 3
  26. #define MIN_DIST_DELTA 2.0
  27. /* Elevation dead-band + smoothing, applied to the filtered ascent/descent totals */
  28. #define ELEV_SMOOTH_TAU 30.0 /* seconds */
  29. #define ELEV_DEADBAND 5.0 /* meters */
  30. /* Large-jump detection thresholds. POS_JUMP_THRESHOLD is informational
  31. * logging only - the distance-diff spike check above already rejects
  32. * inconsistent position jumps regardless of size. ALT_JUMP_THRESHOLD both
  33. * logs and (combined with the same spike shape) rejects an inconsistent
  34. * altitude jump - unlike position there was previously no altitude
  35. * consistency check at all, letting a poor-geometry fix's bogus altitude
  36. * (right sats/HDOP, wrong solution - e.g. just after reacquiring signal)
  37. * straight into the accepted track. */
  38. #define POS_JUMP_THRESHOLD 100.0 /* meters between consecutive raw fixes */
  39. #define ALT_JUMP_THRESHOLD 50.0 /* meters between consecutive raw fixes */
  40. struct prev_points_s {
  41. struct location_s data[PREV_POINTS_LENGTH];
  42. unsigned char start;
  43. unsigned char count;
  44. };
  45. struct avg_store_s {
  46. float lat;
  47. float lon;
  48. time_t time;
  49. };
  50. struct elevation_s {
  51. unsigned char initialized;
  52. float smoothed_alt;
  53. float baseline;
  54. time_t last_time;
  55. };
  56. static struct gpx_s {
  57. struct prev_points_s prev_points;
  58. unsigned char avg_count;
  59. unsigned char paused;
  60. unsigned char point_count;
  61. time_t last_point_time; /* time of the last point seen by gpx_process_point(), to detect a fix gap */
  62. struct avg_store_s avg_store;
  63. struct location_s last_saved;
  64. struct location_s last_distance_point; /* Last accepted point for distance calculation */
  65. struct kalman_s kalman[2];
  66. struct elevation_s elevation;
  67. } gpx;
  68. float kalman_predict(struct kalman_s *k, float data);
  69. void kalman_init(struct kalman_s *k);
  70. float elevation_process(float alt, time_t time);
  71. void add_elevation_filtered(float amount, unsigned char is_gain);
  72. void prev_points_append(struct location_s *new){
  73. gpx.prev_points.data[(gpx.prev_points.start + gpx.prev_points.count)%PREV_POINTS_LENGTH] = *new;
  74. if(++gpx.prev_points.count > PREV_POINTS_LENGTH){
  75. gpx.prev_points.count--;
  76. gpx.prev_points.start++;
  77. gpx.prev_points.start %= PREV_POINTS_LENGTH;
  78. }
  79. }
  80. struct location_s *prev_points_get(unsigned char index){
  81. unsigned char i, addr = gpx.prev_points.start;
  82. for(i=0; i<index; i++){
  83. addr++;
  84. }
  85. addr %= PREV_POINTS_LENGTH;
  86. return &gpx.prev_points.data[addr];
  87. }
  88. unsigned char gpx_init(FIL *file) {
  89. unsigned int bw;
  90. kalman_init(&gpx.kalman[0]);
  91. kalman_init(&gpx.kalman[1]);
  92. gpx.prev_points.count = 0;
  93. gpx.avg_count = 0;
  94. gpx.last_saved.lon = 0;
  95. gpx.last_saved.lat = 0;
  96. gpx.last_saved.time = 0;
  97. gpx.last_distance_point.lon = 0;
  98. gpx.last_distance_point.lat = 0;
  99. gpx.last_distance_point.time = 0;
  100. gpx.elevation.initialized = 0;
  101. gpx.last_point_time = 0;
  102. gpx.point_count = 0;
  103. gpx.paused = 1; /* make it add a <trkseg> tag */
  104. strcpy_P(buf, xml_header);
  105. strcat_P(buf, xml_trk_start);
  106. return f_write(file, buf, strlen(buf), &bw);
  107. }
  108. void gpx_save_single_point(struct location_s *loc) {
  109. FIL gpx;
  110. UINT bw;
  111. unsigned char err = 0;
  112. char *time = get_iso_time(loc->time, 1);
  113. iso_time_to_filename(time);
  114. xsprintf(buf, PSTR("%s-POINT.GPX"), time);
  115. xprintf(PSTR("Writing single point in %s\r\n"), buf);
  116. if ((err = f_open(&gpx, buf, FA_WRITE | FA_OPEN_ALWAYS))) {
  117. f_close(&gpx);
  118. // System.status = STATUS_FILE_OPEN_ERROR;
  119. xputs_P(PSTR("File open error\r\n"));
  120. return; /* Failed to open file */
  121. }
  122. strcpy_P(buf, xml_header);
  123. err |= f_write(&gpx, buf, strlen(buf), &bw);
  124. xsprintf(buf, PSTR("\t<wpt lat=\"%.8f\" lon=\"%.8f\"></wpt>\n</gpx>\n"), loc->lat, loc->lon);
  125. err |= f_write(&gpx, buf, strlen(buf), &bw);
  126. err |= f_close(&gpx);
  127. if (err) {
  128. /* TODO */
  129. }
  130. }
  131. unsigned char is_paused(void) {
  132. return tracking_is_paused();
  133. }
  134. unsigned char gpx_write(struct location_s *loc, FIL *file) {
  135. unsigned int bw;
  136. const char *time;
  137. unsigned char paused = tracking_is_paused();
  138. if (paused) {
  139. if (!gpx.paused) {
  140. strcpy_P(buf, xml_trkseg_end);
  141. gpx.paused = 1;
  142. gpx.point_count = 0;
  143. } else {
  144. return 0; /* nothing to store */
  145. }
  146. } else {
  147. if (gpx.paused) {
  148. strcpy_P(buf, xml_trkseg_start);
  149. f_write(file, buf, strlen(buf), &bw);
  150. gpx.paused = 0;
  151. }
  152. time = get_iso_time(loc->time, 0);
  153. xsprintf(buf, PSTR("\t\t\t<trkpt lat=\"%.8f\" lon=\"%.8f\">\n\t\t\t\t<ele>%.2f</ele>\n\t\t\t\t<time>%s</time>\n"), loc->lat, loc->lon, loc->alt, time);
  154. strcat_P(buf, PSTR("\t\t\t</trkpt>\n"));
  155. }
  156. {
  157. unsigned char ret;
  158. unsigned long int t0 = get_uptime_ms();
  159. ret = f_write(file, buf, strlen(buf), &bw);
  160. io_mark(t0);
  161. return ret;
  162. }
  163. }
  164. unsigned char gpx_close(FIL *file) {
  165. unsigned int bw;
  166. buf[0] = '\0';
  167. if (!gpx.paused)
  168. strcpy_P(buf, xml_trkseg_end);
  169. strcat_P(buf, PSTR("\t</trk>\n</gpx>\n"));
  170. f_write(file, buf, strlen(buf), &bw);
  171. return f_close(file);
  172. }
  173. /* A fix normally arrives about once a second; treat a longer gap between
  174. * accepted points as a fix having been lost and reacquired (regardless of
  175. * why the epochs in between were rejected/absent - fix loss, a 2D fix, poor
  176. * HDOP, or the receiver simply not producing lines), even without an
  177. * explicit auto-pause. A freshly reacquired fix can take a few seconds to
  178. * converge (seen after a real signal loss: a nominally-3D, in-range-HDOP fix
  179. * still a couple hundred meters off in altitude until more satellites come
  180. * in), the same way a fix has never been trusted right after power-on -
  181. * so re-run the existing skip_points warm-up, and reset the Kalman/window
  182. * state that would otherwise splice the old and new fixes together. */
  183. #define FIX_GAP_SECONDS 3
  184. void gpx_process_point(struct location_s *loc, FIL *file){
  185. float lon_est, lon_err, lat_est, lat_err, dist;
  186. struct location_s *ptr;
  187. static struct location_s nloc;
  188. static struct location_s filtered_loc;
  189. if (tracking_is_paused())
  190. System.points_paused++;
  191. if (gpx.last_point_time && loc->time - gpx.last_point_time > FIX_GAP_SECONDS) {
  192. if (get_flag(CONFFLAG_VERBOSE_LOG))
  193. xputs_P(PSTR("FIX GAP: resetting warm-up/filter state\r\n"));
  194. kalman_init(&gpx.kalman[0]);
  195. kalman_init(&gpx.kalman[1]);
  196. gpx.prev_points.count = 0;
  197. gpx.avg_count = 0;
  198. gpx.avg_store.lat = 0;
  199. gpx.avg_store.lon = 0;
  200. gpx.avg_store.time = 0;
  201. gpx.point_count = 0;
  202. }
  203. gpx.last_point_time = loc->time;
  204. if (gpx.point_count < System.conf.skip_points) { /* Skipping initial points */
  205. gpx.point_count++;
  206. System.points_skipped++;
  207. return;
  208. }
  209. /* Always apply Kalman filtering for distance calculation */
  210. lat_est = kalman_predict(&gpx.kalman[0], loc->lat);
  211. lon_est = kalman_predict(&gpx.kalman[1], loc->lon);
  212. filtered_loc.lat = lat_est;
  213. filtered_loc.lon = lon_est;
  214. filtered_loc.time = loc->time;
  215. filtered_loc.alt = loc->alt;
  216. if (get_flag(CONFFLAG_DISABLE_FILTERS)) {
  217. /* Write unfiltered data to GPX, but always calculate distance/elevation from filtered data */
  218. if (get_flag(CONFFLAG_VERBOSE_LOG))
  219. xputs_P(PSTR("Write with filters disabled\r\n"));
  220. gpx_write(loc, file);
  221. System.points_written++;
  222. System.points_accepted++;
  223. /* Calculate distance and elevation from filtered points */
  224. if (gpx.last_distance_point.lat != 0) {
  225. float ele_change;
  226. dist = distance(&gpx.last_distance_point, &filtered_loc);
  227. if (dist > POS_JUMP_THRESHOLD)
  228. log_jump(0, dist);
  229. add_distance(dist);
  230. ele_change = filtered_loc.alt - gpx.last_distance_point.alt;
  231. if (fabs(ele_change) > ALT_JUMP_THRESHOLD)
  232. log_jump(1, ele_change);
  233. add_elevation(ele_change);
  234. }
  235. elevation_process(filtered_loc.alt, filtered_loc.time);
  236. gpx.last_distance_point = filtered_loc;
  237. } else {
  238. /* Apply Kalman error check */
  239. lat_err = fabs(loc->lat - lat_est);
  240. lon_err = fabs(loc->lon - lon_est);
  241. // xprintf(PSTR("lat_err: %e, lon_err: %e, limit: %e\r\n"), lat_err, lon_err, (float)KALMAN_ERR_MAX);
  242. if(lat_err > KALMAN_ERR_MAX || lon_err > KALMAN_ERR_MAX){
  243. if (get_flag(CONFFLAG_VERBOSE_LOG))
  244. xputs_P(PSTR("KALMAN REJECT\r\n"));
  245. log_reject(REJECT_REASON_KALMAN);
  246. return;
  247. }
  248. prev_points_append(&filtered_loc);
  249. if(gpx.prev_points.count == PREV_POINTS_LENGTH){
  250. float dist12 = distance(prev_points_get(0), prev_points_get(1));
  251. float dist34 = distance(prev_points_get(2), prev_points_get(3));
  252. float dist32 = distance(prev_points_get(2), prev_points_get(1));
  253. /* Same spike test as the distance check below, applied to altitude:
  254. * a poor-geometry fix (e.g. right after reacquiring signal) can pass
  255. * the satellite-count/HDOP gate in nmea.c yet still carry a wildly
  256. * wrong altitude, so catch it here the same way a position spike is
  257. * caught - a jump surrounded by two much smaller ones on both sides.
  258. * TODO: GSA's VDOP would be a more direct altitude-quality gate than
  259. * this shape heuristic, but VDOP is only in GSA, which is parsed
  260. * after GGA within the epoch (see nmea.c's gp_gga_parse HDOP
  261. * comment) - using it here would need buffering a point across the
  262. * epoch boundary until VDOP arrives. Left as a future refinement. */
  263. float alt12 = fabs(prev_points_get(0)->alt - prev_points_get(1)->alt);
  264. float alt34 = fabs(prev_points_get(2)->alt - prev_points_get(3)->alt);
  265. float alt32 = fabs(prev_points_get(2)->alt - prev_points_get(1)->alt);
  266. if (get_flag(CONFFLAG_VERBOSE_LOG))
  267. xprintf(PSTR("New distance: %fm\r\n"), dist32);
  268. if(dist34 > dist12 && dist32 > dist12){
  269. if (get_flag(CONFFLAG_VERBOSE_LOG))
  270. xputs_P(PSTR("DISTANCE DIFF REJECT\r\n"));
  271. log_reject(REJECT_REASON_DISTDIFF);
  272. return;
  273. }
  274. if(alt32 > ALT_JUMP_THRESHOLD && alt34 > alt12 && alt32 > alt12){
  275. if (get_flag(CONFFLAG_VERBOSE_LOG))
  276. xputs_P(PSTR("ALTITUDE DIFF REJECT\r\n"));
  277. log_reject(REJECT_REASON_ALTDIFF);
  278. return;
  279. }
  280. if (dist32 > POS_JUMP_THRESHOLD)
  281. log_jump(0, dist32);
  282. ptr = prev_points_get(PREV_POINTS_LENGTH - 2);
  283. } else {
  284. if(gpx.prev_points.count >= PREV_POINTS_LENGTH-2){
  285. ptr = prev_points_get(gpx.prev_points.count - 2);
  286. if (get_flag(CONFFLAG_VERBOSE_LOG))
  287. xputs_P(PSTR("NEW\r\n"));
  288. } else {
  289. return;
  290. }
  291. }
  292. if(distance(&gpx.last_saved, ptr) < MIN_DIST_DELTA){
  293. if (get_flag(CONFFLAG_VERBOSE_LOG))
  294. xputs_P(PSTR("Too small position change REJECT\r\n"));
  295. log_reject(REJECT_REASON_MINDIST);
  296. return;
  297. }
  298. if (get_flag(CONFFLAG_VERBOSE_LOG))
  299. xputs_P(PSTR("ACCEPT\r\n"));
  300. log_reject_flush(); /* close out any pending reject burst now that good data has resumed */
  301. System.points_accepted++;
  302. /* Calculate distance and elevation for accepted point */
  303. if (gpx.last_distance_point.lat != 0) {
  304. float ele_change;
  305. dist = distance(&gpx.last_distance_point, ptr);
  306. add_distance(dist);
  307. ele_change = ptr->alt - gpx.last_distance_point.alt;
  308. if (fabs(ele_change) > ALT_JUMP_THRESHOLD)
  309. log_jump(1, ele_change);
  310. add_elevation(ele_change);
  311. }
  312. elevation_process(ptr->alt, ptr->time);
  313. gpx.last_distance_point = *ptr;
  314. gpx.avg_store.lat += ptr->lat;
  315. gpx.avg_store.lon += ptr->lon;
  316. if(gpx.avg_count == AVG_COUNT/2)
  317. gpx.avg_store.time = ptr->time;
  318. if(++gpx.avg_count == AVG_COUNT){
  319. nloc.lat = gpx.avg_store.lat / AVG_COUNT;
  320. nloc.lon = gpx.avg_store.lon / AVG_COUNT;
  321. nloc.time = gpx.avg_store.time;
  322. nloc.alt = gpx.elevation.smoothed_alt; /* filtered (smoothed) altitude, for the filtered GPX write */
  323. gpx.avg_count = 0;
  324. gpx.avg_store.lat = 0;
  325. gpx.avg_store.lon = 0;
  326. gpx.avg_store.time = 0;
  327. gpx.last_saved = nloc;
  328. gpx_write(&nloc, file);
  329. System.points_written++;
  330. }
  331. }
  332. if (System.time_start == 0)
  333. System.time_start = utc;
  334. }
  335. void kalman_init(struct kalman_s *k){
  336. k->initialized = 0;
  337. k->P_last = 0;
  338. //the noise in the system
  339. k->Q = KALMAN_Q; // process variance
  340. k->R = KALMAN_R; // measurement variance
  341. k->K = 0;
  342. }
  343. float kalman_predict(struct kalman_s *k, float data){
  344. if(!k->initialized){
  345. //initial values for the kalman filter
  346. k->x_est_last = data;
  347. k->initialized = 1;
  348. return data;
  349. }
  350. //do a prediction
  351. float x_temp_est = k->x_est_last;
  352. float P_temp = k->P_last + k->Q;
  353. //calculate the Kalman gain
  354. k->K = P_temp * (1.0/(P_temp + k->R));
  355. //correct
  356. float x_est = x_temp_est + k->K * (data - x_temp_est);
  357. k->P_last = (1 - k->K) * P_temp;
  358. k->x_est_last = x_est;
  359. return x_est;
  360. }
  361. #define R_EARTH 6371e3 // m
  362. float distance(struct location_s *pos1, struct location_s *pos2){
  363. float lat1 = pos1->lat * M_PI / 180.0;
  364. float lat2 = pos2->lat * M_PI / 180.0;
  365. float dlat = (pos2->lat - pos1->lat) * M_PI / 180.0;
  366. float dlon = (pos2->lon - pos1->lon) * M_PI / 180.0;
  367. float a = sinf(dlat/2.0) * sinf(dlat/2.0) + cosf(lat1) * cosf(lat2) * sinf(dlon/2.0) * sinf(dlon/2.0);
  368. float c = 2 * atan2f(sqrtf(a), sqrtf(1-a));
  369. float ret = R_EARTH * c;
  370. return ret;
  371. }
  372. void add_distance(float dist) {
  373. unsigned char paused = tracking_is_paused();
  374. if (!paused)
  375. System.distance += (dist+0.005)*100.0;
  376. if (get_flag(CONFFLAG_VERBOSE_LOG))
  377. xprintf(PSTR("Distance: %.2f m; sum: %.2f m\r\n"), (double)dist, (double)System.distance/100.0);
  378. }
  379. /* Unfiltered (raw), per-point gain/loss - kept only for comparison against the
  380. * filtered (dead-band+smoothed) totals in the periodic status line/session summary. */
  381. void add_elevation(float ele_change) {
  382. unsigned char paused = tracking_is_paused();
  383. if (!paused) {
  384. if (ele_change > 0) {
  385. System.elevation_gain_raw += (ele_change+0.05)*10.0;
  386. } else if (ele_change < 0) {
  387. System.elevation_loss_raw += (-ele_change+0.05)*10.0;
  388. }
  389. }
  390. if (get_flag(CONFFLAG_VERBOSE_LOG))
  391. xprintf(PSTR("Elevation change: %.1f m; raw gain: %.1f m, raw loss: %.1f m\r\n"),
  392. (double)ele_change, (double)System.elevation_gain_raw/10.0, (double)System.elevation_loss_raw/10.0);
  393. }
  394. /* Filtered (dead-band + smoothed) gain/loss, used for display, GPX ascent stats
  395. * and the periodic status line/session summary. */
  396. void add_elevation_filtered(float amount, unsigned char is_gain) {
  397. unsigned long int dm = (unsigned long int)(amount*10.0 + 0.5);
  398. if (is_gain)
  399. System.elevation_gain += dm;
  400. else
  401. System.elevation_loss += dm;
  402. }
  403. /* Exponential smoothing (~30s time constant) followed by a 5m dead-band on the
  404. * result, so that a step in the smoothed altitude only counts once it clears
  405. * the dead-band, and only the amount past the dead-band edge is credited. */
  406. float elevation_process(float alt, time_t time) {
  407. unsigned char paused = tracking_is_paused();
  408. unsigned long int alt_dm;
  409. float delta;
  410. if (!gpx.elevation.initialized) {
  411. gpx.elevation.smoothed_alt = alt;
  412. gpx.elevation.baseline = alt;
  413. gpx.elevation.last_time = time;
  414. gpx.elevation.initialized = 1;
  415. } else {
  416. float dt = (float)(time - gpx.elevation.last_time);
  417. float alpha;
  418. if (dt <= 0)
  419. dt = 1.0;
  420. gpx.elevation.last_time = time;
  421. alpha = dt / (ELEV_SMOOTH_TAU + dt);
  422. gpx.elevation.smoothed_alt += alpha * (alt - gpx.elevation.smoothed_alt);
  423. }
  424. if (gpx.elevation.smoothed_alt > 0) {
  425. alt_dm = (unsigned long int)(gpx.elevation.smoothed_alt*10.0 + 0.5);
  426. if (alt_dm > System.alt_max)
  427. System.alt_max = alt_dm;
  428. }
  429. if (paused) {
  430. /* Discard the dead-band reference drift accumulated while paused,
  431. * the same way distance/raw elevation data is discarded when paused. */
  432. gpx.elevation.baseline = gpx.elevation.smoothed_alt;
  433. } else {
  434. delta = gpx.elevation.smoothed_alt - gpx.elevation.baseline;
  435. if (delta > ELEV_DEADBAND) {
  436. add_elevation_filtered(delta - ELEV_DEADBAND, 1);
  437. gpx.elevation.baseline = gpx.elevation.smoothed_alt - ELEV_DEADBAND;
  438. } else if (delta < -ELEV_DEADBAND) {
  439. add_elevation_filtered(-delta - ELEV_DEADBAND, 0);
  440. gpx.elevation.baseline = gpx.elevation.smoothed_alt + ELEV_DEADBAND;
  441. }
  442. }
  443. return gpx.elevation.smoothed_alt;
  444. }