diff --git a/custom_consumption/Cargo.lock b/custom_consumption/Cargo.lock index 5e51b8b..266dcc9 100644 --- a/custom_consumption/Cargo.lock +++ b/custom_consumption/Cargo.lock @@ -929,6 +929,7 @@ dependencies = [ "egui", "env_logger", "lazy_static", + "log", ] [[package]] diff --git a/custom_consumption/Cargo.toml b/custom_consumption/Cargo.toml index 621b490..3eaf2e8 100644 --- a/custom_consumption/Cargo.toml +++ b/custom_consumption/Cargo.toml @@ -5,6 +5,7 @@ edition = "2021" [dependencies] env_logger = "0.11.3" +log = "0.4.22" clap = { version = "4.5.8", features = ["derive", "env"] } egui = "0.27.2" eframe = "0.27.2" diff --git a/custom_consumption/src/app_config.rs b/custom_consumption/src/app_config.rs index 8b6a8cd..88fc45a 100644 --- a/custom_consumption/src/app_config.rs +++ b/custom_consumption/src/app_config.rs @@ -16,6 +16,10 @@ pub struct AppConfig { /// Maximal value #[clap(long, default_value_t = 5000)] pub max: i64, + + /// Minimum interval between two persistence (milliseconds) + #[clap(long, default_value_t = 500)] + pub min_save_interval: u128, } lazy_static::lazy_static! { diff --git a/custom_consumption/src/lib.rs b/custom_consumption/src/lib.rs index 62a6f82..9ef3282 100644 --- a/custom_consumption/src/lib.rs +++ b/custom_consumption/src/lib.rs @@ -1 +1,2 @@ pub mod app_config; +pub mod utils; diff --git a/custom_consumption/src/main.rs b/custom_consumption/src/main.rs index 988f194..33d6471 100644 --- a/custom_consumption/src/main.rs +++ b/custom_consumption/src/main.rs @@ -1,4 +1,5 @@ use custom_consumption::app_config::AppConfig; +use custom_consumption::utils::time_millis; fn main() { env_logger::init(); @@ -17,6 +18,8 @@ fn main() { struct MyApp { consumption: i64, + last_saved_consumption: i64, + last_save_time: u128, } impl Default for MyApp { @@ -32,12 +35,25 @@ impl Default for MyApp { Self { consumption: prev_consumption, + last_saved_consumption: prev_consumption, + last_save_time: time_millis(), } } } impl eframe::App for MyApp { fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { + if self.consumption != self.last_saved_consumption + && self.last_save_time + AppConfig::get().min_save_interval < time_millis() + { + log::info!("Persist {}", self.consumption); + self.last_saved_consumption = self.consumption; + self.last_save_time = time_millis(); + + std::fs::write(AppConfig::get().file_path(), self.consumption.to_string()) + .expect("Failed to save value!"); + } + egui::CentralPanel::default().show(ctx, |ui| { ui.heading("Custom consumption"); ui.add( diff --git a/custom_consumption/src/utils.rs b/custom_consumption/src/utils.rs new file mode 100644 index 0000000..4c73ed9 --- /dev/null +++ b/custom_consumption/src/utils.rs @@ -0,0 +1,10 @@ +use std::time::{SystemTime, UNIX_EPOCH}; + +/// Get the current time since epoch + +pub fn time_millis() -> u128 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() +}