controller/emgauwa-controller/src/relay_loop.rs

57 lines
1.4 KiB
Rust
Raw Normal View History

use std::time::Duration;
2023-11-29 13:27:46 +00:00
2023-12-07 03:30:33 +00:00
use actix::Addr;
2023-11-29 13:27:46 +00:00
use chrono::Local;
2023-12-07 03:30:33 +00:00
use emgauwa_lib::constants::RELAYS_RETRY_TIMEOUT;
use emgauwa_lib::errors::EmgauwaError;
use futures::pin_mut;
use tokio::time;
2023-12-07 03:30:33 +00:00
use tokio::time::timeout;
use utils::app_state_get_notifier;
2023-11-25 23:54:03 +00:00
2023-12-07 03:30:33 +00:00
use crate::app_state::AppState;
use crate::utils;
2023-11-29 13:27:46 +00:00
2023-12-07 03:30:33 +00:00
pub async fn run_relays_loop(app_state: Addr<AppState>) {
log::debug!("Spawned relays loop");
loop {
2023-12-07 03:30:33 +00:00
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<AppState>) -> Result<(), EmgauwaError> {
let default_duration = Duration::new(10, 0);
let notifier = &*app_state_get_notifier(app_state).await?;
2024-04-23 23:29:07 +00:00
let mut this = utils::app_state_get_this(app_state).await?;
2023-12-07 03:30:33 +00:00
loop {
let notifier_future = notifier.notified();
pin_mut!(notifier_future);
let timeout_result = timeout(default_duration, &mut notifier_future).await;
let changed = timeout_result.is_ok();
2024-04-23 23:29:07 +00:00
if changed {
log::debug!("Reloading controller in relay loop");
this = utils::app_state_get_this(app_state).await?;
}
let mut relay_debug = String::new();
for relay in this.relays.iter() {
relay_debug.push_str(&format!(
"{}: {} |",
relay.r.name, relay.active_schedule.name
));
}
2023-12-07 03:30:33 +00:00
log::debug!(
2024-04-23 23:29:07 +00:00
"Relay loop at {}: {}",
2023-12-07 03:30:33 +00:00
Local::now().naive_local().time(),
2024-04-23 23:29:07 +00:00
relay_debug
2023-12-07 03:30:33 +00:00
);
}
2023-11-27 11:49:40 +00:00
}