Implement catchup hours logic

This commit is contained in:
2024-09-19 21:26:57 +02:00
parent 09c25a67c5
commit fe0bc03c03
6 changed files with 62 additions and 6 deletions

View File

@ -6,8 +6,9 @@ use prettytable::{row, Table};
use crate::constants;
use crate::devices::device::{Device, DeviceId, DeviceRelay, DeviceRelayID};
use crate::energy::consumption::EnergyConsumption;
use crate::energy::relay_state_history;
use crate::energy::relay_state_history::RelayStateHistory;
use crate::utils::time_utils::time_secs;
use crate::utils::time_utils::{curr_hour, time_secs, time_start_of_day};
#[derive(Default)]
pub struct DeviceState {
@ -168,7 +169,11 @@ impl EnergyEngine {
curr_consumption - sum_relays_consumption(&self.relays_state, devices) as i32
}
pub fn refresh(&mut self, curr_consumption: EnergyConsumption, devices: &[Device]) {
pub fn refresh(
&mut self,
curr_consumption: EnergyConsumption,
devices: &[Device],
) -> anyhow::Result<()> {
let base_production = self.estimated_consumption_without_relays(curr_consumption, devices);
log::info!("Estimated base production: {base_production}");
@ -254,7 +259,39 @@ impl EnergyEngine {
}
}
// TODO Turn on relays with running constraints (only ENABLED)
// Turn on relays with running constraints (only ENABLED)
for d in devices {
for r in &d.relays {
if !r.enabled || !d.enabled || !self.device_state(&d.id).is_online() {
continue;
}
if new_relays_state.get(&r.id).unwrap().is_on() {
continue;
}
let Some(constraints) = &r.daily_runtime else {
continue;
};
if !constraints.catch_up_hours.contains(&curr_hour()) {
continue;
}
let time_start_day = time_start_of_day()?;
let start_time = time_start_day + constraints.reset_time as u64;
let end_time = time_start_day + 3600 * 24 + constraints.reset_time as u64;
let total_runtime =
relay_state_history::relay_total_runtime(r.id, start_time, end_time)?;
if total_runtime > constraints.min_runtime {
continue;
}
log::info!("Forcefully turn on relay {} to catch up running constraints (only {}s this day)", r.name, total_runtime);
new_relays_state.get_mut(&r.id).unwrap().on = true;
}
}
// Order relays
let mut ordered_relays = devices
@ -320,6 +357,8 @@ impl EnergyEngine {
}
self.print_summary(curr_consumption, devices);
Ok(())
}
/// Save relays state to disk