gpx.c 13 KB

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