Custom consumption widget is operational

This commit is contained in:
Pierre HUBERT 2024-06-30 23:04:04 +02:00
parent 1f14cf8212
commit 8918547375
6 changed files with 33 additions and 0 deletions

View File

@ -929,6 +929,7 @@ dependencies = [
"egui", "egui",
"env_logger", "env_logger",
"lazy_static", "lazy_static",
"log",
] ]
[[package]] [[package]]

View File

@ -5,6 +5,7 @@ edition = "2021"
[dependencies] [dependencies]
env_logger = "0.11.3" env_logger = "0.11.3"
log = "0.4.22"
clap = { version = "4.5.8", features = ["derive", "env"] } clap = { version = "4.5.8", features = ["derive", "env"] }
egui = "0.27.2" egui = "0.27.2"
eframe = "0.27.2" eframe = "0.27.2"

View File

@ -16,6 +16,10 @@ pub struct AppConfig {
/// Maximal value /// Maximal value
#[clap(long, default_value_t = 5000)] #[clap(long, default_value_t = 5000)]
pub max: i64, pub max: i64,
/// Minimum interval between two persistence (milliseconds)
#[clap(long, default_value_t = 500)]
pub min_save_interval: u128,
} }
lazy_static::lazy_static! { lazy_static::lazy_static! {

View File

@ -1 +1,2 @@
pub mod app_config; pub mod app_config;
pub mod utils;

View File

@ -1,4 +1,5 @@
use custom_consumption::app_config::AppConfig; use custom_consumption::app_config::AppConfig;
use custom_consumption::utils::time_millis;
fn main() { fn main() {
env_logger::init(); env_logger::init();
@ -17,6 +18,8 @@ fn main() {
struct MyApp { struct MyApp {
consumption: i64, consumption: i64,
last_saved_consumption: i64,
last_save_time: u128,
} }
impl Default for MyApp { impl Default for MyApp {
@ -32,12 +35,25 @@ impl Default for MyApp {
Self { Self {
consumption: prev_consumption, consumption: prev_consumption,
last_saved_consumption: prev_consumption,
last_save_time: time_millis(),
} }
} }
} }
impl eframe::App for MyApp { impl eframe::App for MyApp {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { 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| { egui::CentralPanel::default().show(ctx, |ui| {
ui.heading("Custom consumption"); ui.heading("Custom consumption");
ui.add( ui.add(

View File

@ -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()
}