From 1d11c3a968ec0bb7a4a703db718ff275f55cf0dd Mon Sep 17 00:00:00 2001 From: Pierre HUBERT Date: Thu, 12 Sep 2024 21:45:58 +0200 Subject: [PATCH] WIP energy engine update --- central_backend/src/energy/engine.rs | 47 +++++++++++++++++++++++++--- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/central_backend/src/energy/engine.rs b/central_backend/src/energy/engine.rs index f186210..6e3e3f8 100644 --- a/central_backend/src/energy/engine.rs +++ b/central_backend/src/energy/engine.rs @@ -58,13 +58,52 @@ impl EnergyEngine { } pub fn refresh(&mut self, curr_consumption: EnergyConsumption, devices: &[Device]) { - // TODO : force creation of missing relays state + // Force creation of missing relays state + for d in devices { + for r in &d.relays { + // Requesting relay state is enough to trigger relay creation + self.relay_state(r.id); + } + } - let new_relays_state = self.relays_state.clone(); + let mut new_relays_state = self.relays_state.clone(); - // TODO Forcefully turn off relays that belongs to offline devices + // Forcefully turn off relays that belongs to offline devices + for d in devices { + if !self.device_state(&d.id).is_online() { + for r in &d.relays { + new_relays_state.get_mut(&r.id).unwrap().on = false; + } + } + } - // TODO Forcefully turn off relays with dependency conflicts + // Forcefully turn off relays with missing dependency + loop { + let mut changed = false; + + for d in devices { + if !self.device_state(&d.id).is_online() { + for r in &d.relays { + if !new_relays_state.get(&r.id).unwrap().on { + continue; + } + + // Check if any dependency of relay is off + if r.depends_on + .iter() + .any(|d| !new_relays_state.get(d).unwrap().on) + { + new_relays_state.get_mut(&r.id).unwrap().on = false; + changed = true; + } + } + } + } + + if !changed { + break; + } + } // TODO Virtually turn off all relays that can be stopped