SolarEnergy/central_backend/src/energy/consumption.rs

43 lines
1.3 KiB
Rust
Raw Normal View History

use crate::app_config::{AppConfig, ConsumptionBackend};
use rand::{thread_rng, Rng};
2024-06-30 18:14:23 +00:00
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;
/// Get current electrical energy consumption
pub async fn get_curr_consumption() -> anyhow::Result<EnergyConsumption> {
let backend = AppConfig::get()
.consumption_backend
.as_ref()
.unwrap_or(&ConsumptionBackend::Constant { value: 300 });
match backend {
ConsumptionBackend::Constant { value } => Ok(*value),
ConsumptionBackend::Random { min, max } => Ok(thread_rng().gen_range(*min..*max)),
2024-06-30 18:14:23 +00:00
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)?)
}
}
}