diff --git a/central_backend/src/app_config.rs b/central_backend/src/app_config.rs index 802a9ab..fc42366 100644 --- a/central_backend/src/app_config.rs +++ b/central_backend/src/app_config.rs @@ -6,7 +6,7 @@ use std::path::{Path, PathBuf}; pub enum ConsumptionBackend { /// Constant consumption value Constant { - #[clap(long, default_value_t = 500)] + #[clap(short, long, default_value_t = 500)] value: i32, }, @@ -17,6 +17,12 @@ pub enum ConsumptionBackend { #[clap(long, default_value_t = 20000)] max: i32, }, + + /// Read consumption value in a file, on the filesystem + File { + #[clap(short, long, default_value = "/dev/shm/consumption.txt")] + path: String, + }, } /// Solar system central backend diff --git a/central_backend/src/energy/consumption.rs b/central_backend/src/energy/consumption.rs index 7f09a98..b0173b0 100644 --- a/central_backend/src/energy/consumption.rs +++ b/central_backend/src/energy/consumption.rs @@ -1,5 +1,15 @@ use crate::app_config::{AppConfig, ConsumptionBackend}; use rand::{thread_rng, Rng}; +use std::num::ParseIntError; +use std::path::Path; + +#[derive(thiserror::Error, Debug)] +pub enum ConsumptionError { + #[error("The file that should contain the consumption does not exists!")] + NonExistentFile, + #[error("The file that should contain the consumption has an invalid content!")] + FileInvalidContent(#[source] ParseIntError), +} pub type EnergyConsumption = i32; @@ -14,5 +24,19 @@ pub async fn get_curr_consumption() -> anyhow::Result { ConsumptionBackend::Constant { value } => Ok(*value), ConsumptionBackend::Random { min, max } => Ok(thread_rng().gen_range(*min..*max)), + + ConsumptionBackend::File { path } => { + let path = Path::new(path); + if !path.is_file() { + return Err(ConsumptionError::NonExistentFile.into()); + } + + let content = std::fs::read_to_string(path)?; + + Ok(content + .trim() + .parse() + .map_err(ConsumptionError::FileInvalidContent)?) + } } }