gpx.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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 (informational logging only, points are not rejected because of these) */
  31. #define POS_JUMP_THRESHOLD 100.0 /* meters between consecutive raw fixes */
  32. #define ALT_JUMP_THRESHOLD 50.0 /* meters between consecutive raw fixes */
  33. struct prev_points_s {
  34. struct location_s data[PREV_POINTS_LENGTH];
  35. unsigned char start;
  36. unsigned char count;
  37. };
  38. struct avg_store_s {
  39. float lat;
  40. float lon;
  41. time_t time;
  42. };
  43. struct elevation_s {
  44. unsigned char initialized;
  45. float smoothed_alt;
  46. float baseline;
  47. time_t last_time;
  48. };
  49. static struct gpx_s {
  50. struct prev_points_s prev_points;
  51. unsigned char avg_count;
  52. unsigned char paused;
  53. unsigned char point_count;
  54. struct avg_store_s avg_store;
  55. struct location_s last_saved;
  56. struct location_s last_distance_point; /* Last accepted point for distance calculation */
  57. struct kalman_s kalman[2];
  58. struct elevation_s elevation;
  59. } gpx;
  60. float kalman_predict(struct kalman_s *k, float data);
  61. void kalman_init(struct kalman_s *k);
  62. float elevation_process(float alt, time_t time);
  63. void add_elevation_filtered(float amount, unsigned char is_gain);
  64. void prev_points_append(struct location_s *new){
  65. gpx.prev_points.data[(gpx.prev_points.start + gpx.prev_points.count)%PREV_POINTS_LENGTH] = *new;
  66. if(++gpx.prev_points.count > PREV_POINTS_LENGTH){
  67. gpx.prev_points.count--;
  68. gpx.prev_points.start++;
  69. gpx.prev_points.start %= PREV_POINTS_LENGTH;
  70. }
  71. }
  72. struct location_s *prev_points_get(unsigned char index){
  73. unsigned char i, addr = gpx.prev_points.start;
  74. for(i=0; i<index; i++){
  75. addr++;
  76. }
  77. addr %= PREV_POINTS_LENGTH;
  78. return &gpx.prev_points.data[addr];
  79. }
  80. unsigned char gpx_init(FIL *file) {
  81. unsigned int bw;
  82. kalman_init(&gpx.kalman[0]);
  83. kalman_init(&gpx.kalman[1]);
  84. gpx.prev_points.count = 0;
  85. gpx.avg_count = 0;
  86. gpx.last_saved.lon = 0;
  87. gpx.last_saved.lat = 0;
  88. gpx.last_saved.time = 0;
  89. gpx.last_distance_point.lon = 0;
  90. gpx.last_distance_point.lat = 0;
  91. gpx.last_distance_point.time = 0;
  92. gpx.elevation.initialized = 0;
  93. gpx.paused = 1; /* make it add a <trkseg> tag */
  94. strcpy_P(buf, xml_header);
  95. strcat_P(buf, xml_trk_start);
  96. return f_write(file, buf, strlen(buf), &bw);
  97. }
  98. void gpx_save_single_point(struct location_s *loc) {
  99. FIL gpx;
  100. UINT bw;
  101. unsigned char err = 0;
  102. char *time = get_iso_time(loc->time, 1);
  103. iso_time_to_filename(time);
  104. xsprintf(buf, PSTR("%s-POINT.GPX"), time);
  105. xprintf(PSTR("Writing single point in %s\r\n"), buf);
  106. if ((err = f_open(&gpx, buf, FA_WRITE | FA_OPEN_ALWAYS))) {
  107. f_close(&gpx);
  108. // System.status = STATUS_FILE_OPEN_ERROR;
  109. xputs_P(PSTR("File open error\r\n"));
  110. return; /* Failed to open file */
  111. }
  112. strcpy_P(buf, xml_header);
  113. err |= f_write(&gpx, buf, strlen(buf), &bw);
  114. xsprintf(buf, PSTR("\t<wpt lat=\"%.8f\" lon=\"%.8f\"></wpt>\n</gpx>\n"), loc->lat, loc->lon);
  115. err |= f_write(&gpx, buf, strlen(buf), &bw);
  116. err |= f_close(&gpx);
  117. if (err) {
  118. /* TODO */
  119. }
  120. }
  121. unsigned char is_paused(void) {
  122. return gpx.paused;
  123. }
  124. unsigned char gpx_write(struct location_s *loc, FIL *file) {
  125. unsigned int bw;
  126. const char *time;
  127. unsigned char paused = System.tracking_paused || System.tracking_auto_paused;
  128. if (paused) {
  129. if (!gpx.paused) {
  130. strcpy_P(buf, xml_trkseg_end);
  131. gpx.paused = 1;
  132. gpx.point_count = 0;
  133. System.current_pause_start = utc;
  134. } else {
  135. return 0; /* nothing to store */
  136. }
  137. } else {
  138. if (gpx.paused) {
  139. strcpy_P(buf, xml_trkseg_start);
  140. f_write(file, buf, strlen(buf), &bw);
  141. gpx.paused = 0;
  142. if (System.current_pause_start)
  143. System.pause_time += utc - System.current_pause_start;
  144. }
  145. time = get_iso_time(loc->time, 0);
  146. 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);
  147. strcat_P(buf, PSTR("\t\t\t</trkpt>\n"));
  148. }
  149. {
  150. unsigned char ret;
  151. unsigned long int t0 = get_uptime_ms();
  152. ret = f_write(file, buf, strlen(buf), &bw);
  153. io_mark(t0);
  154. return ret;
  155. }
  156. }
  157. unsigned char gpx_close(FIL *file) {
  158. unsigned int bw;
  159. buf[0] = '\0';
  160. if (!gpx.paused)
  161. strcpy_P(buf, xml_trkseg_end);
  162. strcat_P(buf, PSTR("\t</trk>\n</gpx>\n"));
  163. f_write(file, buf, strlen(buf), &bw);
  164. return f_close(file);
  165. }
  166. void gpx_process_point(struct location_s *loc, FIL *file){
  167. float lon_est, lon_err, lat_est, lat_err, dist;
  168. struct location_s *ptr;
  169. struct location_s nloc;
  170. struct location_s filtered_loc;
  171. if (gpx.point_count < System.conf.skip_points) { /* Skipping initial points */
  172. gpx.point_count++;
  173. return;
  174. }
  175. /* Always apply Kalman filtering for distance calculation */
  176. lat_est = kalman_predict(&gpx.kalman[0], loc->lat);
  177. lon_est = kalman_predict(&gpx.kalman[1], loc->lon);
  178. filtered_loc.lat = lat_est;
  179. filtered_loc.lon = lon_est;
  180. filtered_loc.time = loc->time;
  181. filtered_loc.alt = loc->alt;
  182. if (get_flag(CONFFLAG_DISABLE_FILTERS)) {
  183. /* Write unfiltered data to GPX, but always calculate distance/elevation from filtered data */
  184. if (get_flag(CONFFLAG_VERBOSE_LOG))
  185. xputs_P(PSTR("Write with filters disabled\r\n"));
  186. gpx_write(loc, file);
  187. System.points_written++;
  188. /* Calculate distance and elevation from filtered points */
  189. if (gpx.last_distance_point.lat != 0) {
  190. float ele_change;
  191. dist = distance(&gpx.last_distance_point, &filtered_loc);
  192. if (dist > POS_JUMP_THRESHOLD)
  193. log_jump(0, dist);
  194. add_distance(dist);
  195. ele_change = filtered_loc.alt - gpx.last_distance_point.alt;
  196. if (fabs(ele_change) > ALT_JUMP_THRESHOLD)
  197. log_jump(1, ele_change);
  198. add_elevation(ele_change);
  199. }
  200. elevation_process(filtered_loc.alt, filtered_loc.time);
  201. gpx.last_distance_point = filtered_loc;
  202. } else {
  203. /* Apply Kalman error check */
  204. lat_err = fabs(loc->lat - lat_est);
  205. lon_err = fabs(loc->lon - lon_est);
  206. // xprintf(PSTR("lat_err: %e, lon_err: %e, limit: %e\r\n"), lat_err, lon_err, (float)KALMAN_ERR_MAX);
  207. if(lat_err > KALMAN_ERR_MAX || lon_err > KALMAN_ERR_MAX){
  208. if (get_flag(CONFFLAG_VERBOSE_LOG))
  209. xputs_P(PSTR("KALMAN REJECT\r\n"));
  210. log_reject(REJECT_REASON_KALMAN);
  211. return;
  212. }
  213. prev_points_append(&filtered_loc);
  214. if(gpx.prev_points.count == PREV_POINTS_LENGTH){
  215. float dist12 = distance(prev_points_get(0), prev_points_get(1));
  216. float dist34 = distance(prev_points_get(2), prev_points_get(3));
  217. float dist32 = distance(prev_points_get(2), prev_points_get(1));
  218. if (get_flag(CONFFLAG_VERBOSE_LOG))
  219. xprintf(PSTR("New distance: %fm\r\n"), dist32);
  220. if(dist34 > dist12 && dist32 > dist12){
  221. if (get_flag(CONFFLAG_VERBOSE_LOG))
  222. xputs_P(PSTR("DISTANCE DIFF REJECT\r\n"));
  223. log_reject(REJECT_REASON_DISTDIFF);
  224. return;
  225. }
  226. if (dist32 > POS_JUMP_THRESHOLD)
  227. log_jump(0, dist32);
  228. ptr = prev_points_get(PREV_POINTS_LENGTH - 2);
  229. } else {
  230. if(gpx.prev_points.count >= PREV_POINTS_LENGTH-2){
  231. ptr = prev_points_get(gpx.prev_points.count - 2);
  232. if (get_flag(CONFFLAG_VERBOSE_LOG))
  233. xputs_P(PSTR("NEW\r\n"));
  234. } else {
  235. return;
  236. }
  237. }
  238. if(distance(&gpx.last_saved, ptr) < MIN_DIST_DELTA){
  239. if (get_flag(CONFFLAG_VERBOSE_LOG))
  240. xputs_P(PSTR("Too small position change REJECT\r\n"));
  241. log_reject(REJECT_REASON_MINDIST);
  242. return;
  243. }
  244. if (get_flag(CONFFLAG_VERBOSE_LOG))
  245. xputs_P(PSTR("ACCEPT\r\n"));
  246. log_reject_flush(); /* close out any pending reject burst now that good data has resumed */
  247. /* Calculate distance and elevation for accepted point */
  248. if (gpx.last_distance_point.lat != 0) {
  249. float ele_change;
  250. dist = distance(&gpx.last_distance_point, ptr);
  251. add_distance(dist);
  252. ele_change = ptr->alt - gpx.last_distance_point.alt;
  253. if (fabs(ele_change) > ALT_JUMP_THRESHOLD)
  254. log_jump(1, ele_change);
  255. add_elevation(ele_change);
  256. }
  257. elevation_process(ptr->alt, ptr->time);
  258. gpx.last_distance_point = *ptr;
  259. gpx.avg_store.lat += ptr->lat;
  260. gpx.avg_store.lon += ptr->lon;
  261. if(gpx.avg_count == AVG_COUNT/2)
  262. gpx.avg_store.time = ptr->time;
  263. if(++gpx.avg_count == AVG_COUNT){
  264. nloc.lat = gpx.avg_store.lat / AVG_COUNT;
  265. nloc.lon = gpx.avg_store.lon / AVG_COUNT;
  266. nloc.time = gpx.avg_store.time;
  267. nloc.alt = gpx.elevation.smoothed_alt; /* filtered (smoothed) altitude, for the filtered GPX write */
  268. gpx.avg_count = 0;
  269. gpx.avg_store.lat = 0;
  270. gpx.avg_store.lon = 0;
  271. gpx.avg_store.time = 0;
  272. gpx.last_saved = nloc;
  273. gpx_write(&nloc, file);
  274. System.points_written++;
  275. }
  276. }
  277. if (System.time_start == 0)
  278. System.time_start = utc;
  279. }
  280. void kalman_init(struct kalman_s *k){
  281. k->initialized = 0;
  282. k->P_last = 0;
  283. //the noise in the system
  284. k->Q = KALMAN_Q; // process variance
  285. k->R = KALMAN_R; // measurement variance
  286. k->K = 0;
  287. }
  288. float kalman_predict(struct kalman_s *k, float data){
  289. if(!k->initialized){
  290. //initial values for the kalman filter
  291. k->x_est_last = data;
  292. k->initialized = 1;
  293. return data;
  294. }
  295. //do a prediction
  296. float x_temp_est = k->x_est_last;
  297. float P_temp = k->P_last + k->Q;
  298. //calculate the Kalman gain
  299. k->K = P_temp * (1.0/(P_temp + k->R));
  300. //correct
  301. float x_est = x_temp_est + k->K * (data - x_temp_est);
  302. k->P_last = (1 - k->K) * P_temp;
  303. k->x_est_last = x_est;
  304. return x_est;
  305. }
  306. #define R_EARTH 6371e3 // m
  307. float distance(struct location_s *pos1, struct location_s *pos2){
  308. float lat1 = pos1->lat * M_PI / 180.0;
  309. float lat2 = pos2->lat * M_PI / 180.0;
  310. float dlat = (pos2->lat - pos1->lat) * M_PI / 180.0;
  311. float dlon = (pos2->lon - pos1->lon) * M_PI / 180.0;
  312. float a = sinf(dlat/2.0) * sinf(dlat/2.0) + cosf(lat1) * cosf(lat2) * sinf(dlon/2.0) * sinf(dlon/2.0);
  313. float c = 2 * atan2f(sqrtf(a), sqrtf(1-a));
  314. float ret = R_EARTH * c;
  315. return ret;
  316. }
  317. void add_distance(float dist) {
  318. unsigned char paused = System.tracking_paused || System.tracking_auto_paused;
  319. if (!paused)
  320. System.distance += (dist+0.005)*100.0;
  321. if (get_flag(CONFFLAG_VERBOSE_LOG))
  322. xprintf(PSTR("Distance: %.2f m; sum: %.2f m\r\n"), (double)dist, (double)System.distance/100.0);
  323. }
  324. /* Unfiltered (raw), per-point gain/loss - kept only for comparison against the
  325. * filtered (dead-band+smoothed) totals in the periodic status line/session summary. */
  326. void add_elevation(float ele_change) {
  327. unsigned char paused = System.tracking_paused || System.tracking_auto_paused;
  328. if (!paused) {
  329. if (ele_change > 0) {
  330. System.elevation_gain_raw += (ele_change+0.05)*10.0;
  331. } else if (ele_change < 0) {
  332. System.elevation_loss_raw += (-ele_change+0.05)*10.0;
  333. }
  334. }
  335. if (get_flag(CONFFLAG_VERBOSE_LOG))
  336. xprintf(PSTR("Elevation change: %.1f m; raw gain: %.1f m, raw loss: %.1f m\r\n"),
  337. (double)ele_change, (double)System.elevation_gain_raw/10.0, (double)System.elevation_loss_raw/10.0);
  338. }
  339. /* Filtered (dead-band + smoothed) gain/loss, used for display, GPX ascent stats
  340. * and the periodic status line/session summary. */
  341. void add_elevation_filtered(float amount, unsigned char is_gain) {
  342. unsigned long int dm = (unsigned long int)(amount*10.0 + 0.5);
  343. if (is_gain)
  344. System.elevation_gain += dm;
  345. else
  346. System.elevation_loss += dm;
  347. }
  348. /* Exponential smoothing (~30s time constant) followed by a 5m dead-band on the
  349. * result, so that a step in the smoothed altitude only counts once it clears
  350. * the dead-band, and only the amount past the dead-band edge is credited. */
  351. float elevation_process(float alt, time_t time) {
  352. unsigned char paused = System.tracking_paused || System.tracking_auto_paused;
  353. unsigned long int alt_dm;
  354. float delta;
  355. if (!gpx.elevation.initialized) {
  356. gpx.elevation.smoothed_alt = alt;
  357. gpx.elevation.baseline = alt;
  358. gpx.elevation.last_time = time;
  359. gpx.elevation.initialized = 1;
  360. } else {
  361. float dt = (float)(time - gpx.elevation.last_time);
  362. float alpha;
  363. if (dt <= 0)
  364. dt = 1.0;
  365. gpx.elevation.last_time = time;
  366. alpha = dt / (ELEV_SMOOTH_TAU + dt);
  367. gpx.elevation.smoothed_alt += alpha * (alt - gpx.elevation.smoothed_alt);
  368. }
  369. if (gpx.elevation.smoothed_alt > 0) {
  370. alt_dm = (unsigned long int)(gpx.elevation.smoothed_alt*10.0 + 0.5);
  371. if (alt_dm > System.alt_max)
  372. System.alt_max = alt_dm;
  373. }
  374. if (paused) {
  375. /* Discard the dead-band reference drift accumulated while paused,
  376. * the same way distance/raw elevation data is discarded when paused. */
  377. gpx.elevation.baseline = gpx.elevation.smoothed_alt;
  378. } else {
  379. delta = gpx.elevation.smoothed_alt - gpx.elevation.baseline;
  380. if (delta > ELEV_DEADBAND) {
  381. add_elevation_filtered(delta - ELEV_DEADBAND, 1);
  382. gpx.elevation.baseline = gpx.elevation.smoothed_alt - ELEV_DEADBAND;
  383. } else if (delta < -ELEV_DEADBAND) {
  384. add_elevation_filtered(-delta - ELEV_DEADBAND, 0);
  385. gpx.elevation.baseline = gpx.elevation.smoothed_alt + ELEV_DEADBAND;
  386. }
  387. }
  388. return gpx.elevation.smoothed_alt;
  389. }