use std::time::Duration; use actix::Addr; use chrono::Local; use emgauwa_lib::constants::RELAYS_RETRY_TIMEOUT; use emgauwa_lib::errors::EmgauwaError; use futures::pin_mut; use tokio::time; use tokio::time::timeout; use utils::app_state_get_notifier; use crate::app_state::AppState; use crate::utils; pub async fn run_relays_loop(app_state: Addr) { log::debug!("Spawned relays loop"); loop { let run_result = run_relays(&app_state).await; if let Err(err) = run_result { log::error!("Error running relays: {}", err); } time::sleep(RELAYS_RETRY_TIMEOUT).await; } } async fn run_relays(app_state: &Addr) -> Result<(), EmgauwaError> { let default_duration = Duration::new(10, 0); let notifier = &*app_state_get_notifier(app_state).await?; let mut last_weekday = emgauwa_lib::utils::get_weekday(); let mut this = utils::app_state_get_this(app_state).await?; loop { let notifier_future = notifier.notified(); pin_mut!(notifier_future); let timeout_result = timeout(default_duration, &mut notifier_future).await; let mut changed = timeout_result.is_ok(); let current_weekday = emgauwa_lib::utils::get_weekday(); if current_weekday != last_weekday { log::debug!("Weekday changed"); last_weekday = current_weekday; utils::app_state_reload(app_state).await?; changed = true; } if changed { log::debug!("Reloading controller in relay loop"); this = utils::app_state_get_this(app_state).await?; } let mut relay_debug = String::new(); let now = Local::now().time(); for relay in this.relays.iter() { relay_debug.push_str(&format!( "{}{}: {} ; ", if relay.active_schedule.is_on(&now) { "+" } else { "-" }, relay.r.name, relay.active_schedule.name )); } log::debug!( "Relay loop at {}: {}", Local::now().naive_local().time(), relay_debug ); } }