Merge pull request #11198 from SteveCEvans/sce_rc2
[betaflight.git] / src / main / fc / stats.c
blob8ba13a8b38a0b128187196535c8f63e7bb8abae6
1 /*
2 * This file is part of Cleanflight and Betaflight.
4 * Cleanflight and Betaflight are free software. You can redistribute
5 * this software and/or modify this software under the terms of the
6 * GNU General Public License as published by the Free Software
7 * Foundation, either version 3 of the License, or (at your option)
8 * any later version.
10 * Cleanflight and Betaflight are distributed in the hope that they
11 * will be useful, but WITHOUT ANY WARRANTY; without even the implied
12 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this software.
18 * If not, see <http://www.gnu.org/licenses/>.
21 #include "platform.h"
23 #ifdef USE_PERSISTENT_STATS
25 #include "drivers/time.h"
27 #include "config/config.h"
28 #include "fc/dispatch.h"
29 #include "fc/runtime_config.h"
30 #include "fc/stats.h"
32 #include "io/beeper.h"
33 #include "io/gps.h"
35 #include "pg/stats.h"
38 #define STATS_SAVE_DELAY_US 500000 // Let disarming complete and save stats after this time
40 static timeMs_t arm_millis;
41 static uint32_t arm_distance_cm;
43 static bool saveRequired = false;
45 #ifdef USE_GPS
46 #define DISTANCE_FLOWN_CM (GPS_distanceFlownInCm)
47 #else
48 #define DISTANCE_FLOWN_CM (0)
49 #endif
51 void statsInit(void)
53 dispatchEnable();
56 void writeStats(struct dispatchEntry_s* self)
58 UNUSED(self);
60 if (!ARMING_FLAG(ARMED)) {
61 // Don't save if the user made config changes that have not yet been saved.
62 if (!isConfigDirty()) {
63 writeEEPROM();
65 // Repeat disarming beep indicating the stats save is complete
66 beeper(BEEPER_DISARMING);
69 saveRequired = false;
73 dispatchEntry_t writeStatsEntry =
75 writeStats, 0, NULL, false
79 void statsOnArm(void)
81 arm_millis = millis();
82 arm_distance_cm = DISTANCE_FLOWN_CM;
85 void statsOnDisarm(void)
87 int8_t minArmedTimeS = statsConfig()->stats_min_armed_time_s;
88 if (minArmedTimeS >= 0) {
89 uint32_t dtS = (millis() - arm_millis) / 1000;
90 if (dtS >= (uint8_t)minArmedTimeS) {
91 statsConfigMutable()->stats_total_flights += 1; // arm / flight counter
92 statsConfigMutable()->stats_total_time_s += dtS;
93 statsConfigMutable()->stats_total_dist_m += (DISTANCE_FLOWN_CM - arm_distance_cm) / 100;
95 saveRequired = true;
98 if (saveRequired) {
99 /* signal that stats need to be saved but don't execute time consuming flash operation
100 now - let the disarming process complete and then execute the actual save */
101 dispatchAdd(&writeStatsEntry, STATS_SAVE_DELAY_US);
105 #endif