Rename active_schedule to override_schedule and add EmgauwaNow
This commit is contained in:
parent
bf3192ec65
commit
8244a1d837
4 changed files with 228 additions and 151 deletions
|
@ -3,9 +3,10 @@ use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use actix::{Actor, Context, Handler, Message};
|
use actix::{Actor, Context, Handler, Message};
|
||||||
use emgauwa_common::constants;
|
use emgauwa_common::constants;
|
||||||
|
use emgauwa_common::db::DbSchedule;
|
||||||
use emgauwa_common::errors::EmgauwaError;
|
use emgauwa_common::errors::EmgauwaError;
|
||||||
use emgauwa_common::models::Controller;
|
use emgauwa_common::models::Controller;
|
||||||
use emgauwa_common::types::RelayStates;
|
use emgauwa_common::types::{RelayStates, Weekday};
|
||||||
use futures::executor::block_on;
|
use futures::executor::block_on;
|
||||||
use sqlx::{Pool, Sqlite};
|
use sqlx::{Pool, Sqlite};
|
||||||
use tokio::sync::Notify;
|
use tokio::sync::Notify;
|
||||||
|
@ -30,6 +31,14 @@ pub struct RelayPulse {
|
||||||
pub duration: Option<u32>,
|
pub duration: Option<u32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Message)]
|
||||||
|
#[rtype(result = "Result<(), EmgauwaError>")]
|
||||||
|
pub struct RelayOverrideSchedule {
|
||||||
|
pub relay_number: i64,
|
||||||
|
pub schedule: Option<DbSchedule>,
|
||||||
|
pub weekday: Weekday,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Message)]
|
#[derive(Message)]
|
||||||
#[rtype(result = "Controller")]
|
#[rtype(result = "Controller")]
|
||||||
pub struct GetThis {}
|
pub struct GetThis {}
|
||||||
|
@ -105,7 +114,7 @@ impl Handler<UpdateRelayStates> for AppState {
|
||||||
.iter_mut()
|
.iter_mut()
|
||||||
.zip(msg.relay_states.iter())
|
.zip(msg.relay_states.iter())
|
||||||
.for_each(|(driver, state)| {
|
.for_each(|(driver, state)| {
|
||||||
if let Err(e) = driver.set(state.unwrap_or(false)) {
|
if let Err(e) = driver.set(state.is_on.unwrap_or(false)) {
|
||||||
log::error!("Error setting relay: {}", e);
|
log::error!("Error setting relay: {}", e);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
@ -148,6 +157,35 @@ impl Handler<RelayPulse> for AppState {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Handler<RelayOverrideSchedule> for AppState {
|
||||||
|
type Result = Result<(), EmgauwaError>;
|
||||||
|
|
||||||
|
fn handle(&mut self, msg: RelayOverrideSchedule, _ctx: &mut Self::Context) -> Self::Result {
|
||||||
|
let relay_num = msg.relay_number;
|
||||||
|
let schedule = msg.schedule;
|
||||||
|
let weekday = msg.weekday;
|
||||||
|
|
||||||
|
let relay = self
|
||||||
|
.this
|
||||||
|
.relays
|
||||||
|
.iter_mut()
|
||||||
|
.find(|r| r.r.number == relay_num)
|
||||||
|
.ok_or(EmgauwaError::Other(String::from("Relay not found")))?;
|
||||||
|
|
||||||
|
log::debug!(
|
||||||
|
"Overriding schedule for relay {} to '{}' on day {}",
|
||||||
|
relay_num,
|
||||||
|
schedule.as_ref().map_or("NONE", |s| &s.name),
|
||||||
|
weekday
|
||||||
|
);
|
||||||
|
|
||||||
|
relay.override_schedule = Some(schedule);
|
||||||
|
relay.override_schedule_weekday = weekday;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Handler<GetThis> for AppState {
|
impl Handler<GetThis> for AppState {
|
||||||
type Result = Controller;
|
type Result = Controller;
|
||||||
|
|
||||||
|
|
|
@ -1,11 +1,11 @@
|
||||||
use std::time::{Duration, Instant};
|
use std::time::Duration;
|
||||||
|
|
||||||
use actix::Addr;
|
use actix::Addr;
|
||||||
use chrono::{Local, Timelike};
|
use chrono::Timelike;
|
||||||
use emgauwa_common::constants::RELAYS_RETRY_TIMEOUT;
|
use emgauwa_common::constants::RELAYS_RETRY_TIMEOUT;
|
||||||
use emgauwa_common::errors::EmgauwaError;
|
use emgauwa_common::errors::EmgauwaError;
|
||||||
use emgauwa_common::models::Controller;
|
use emgauwa_common::models::Controller;
|
||||||
use emgauwa_common::types::{RelayStates, Weekday};
|
use emgauwa_common::types::{EmgauwaNow, RelayState, RelayStates, Weekday};
|
||||||
use emgauwa_common::utils::printable_relay_states;
|
use emgauwa_common::utils::printable_relay_states;
|
||||||
use futures::pin_mut;
|
use futures::pin_mut;
|
||||||
use tokio::time;
|
use tokio::time;
|
||||||
|
@ -32,42 +32,44 @@ async fn run_relays(app_state: &Addr<AppState>) -> Result<(), EmgauwaError> {
|
||||||
let mut last_weekday = emgauwa_common::utils::get_weekday();
|
let mut last_weekday = emgauwa_common::utils::get_weekday();
|
||||||
let mut this = utils::app_state_get_this(app_state).await?;
|
let mut this = utils::app_state_get_this(app_state).await?;
|
||||||
let mut relay_states: RelayStates = Vec::new();
|
let mut relay_states: RelayStates = Vec::new();
|
||||||
|
let now = EmgauwaNow::now();
|
||||||
|
|
||||||
init_relay_states(&mut relay_states, &this);
|
init_relay_states(&mut relay_states, &this);
|
||||||
calc_relay_states(&mut relay_states, &mut this, app_state).await?;
|
calc_relay_states(&mut relay_states, &mut this, app_state, &now).await?;
|
||||||
|
|
||||||
let mut duration_override = None;
|
let mut duration_override = None;
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
|
let now = EmgauwaNow::now();
|
||||||
log::debug!(
|
log::debug!(
|
||||||
"Relay loop at {}: {}",
|
"Relay loop at {}: {}",
|
||||||
Local::now().naive_local().time(),
|
now.time,
|
||||||
printable_relay_states(&this.get_relay_states())
|
printable_relay_states(&this.get_relay_states())
|
||||||
);
|
);
|
||||||
|
|
||||||
let notifier_future = notifier.notified();
|
let notifier_future = notifier.notified();
|
||||||
pin_mut!(notifier_future);
|
pin_mut!(notifier_future);
|
||||||
let mut changed = timeout(
|
let mut changed = timeout(
|
||||||
get_next_duration(&this, &mut duration_override),
|
get_next_duration(&mut this, &mut duration_override, &now),
|
||||||
&mut notifier_future,
|
&mut notifier_future,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.is_ok();
|
.is_ok();
|
||||||
|
|
||||||
check_weekday(app_state, &mut last_weekday, &mut changed).await?;
|
check_weekday(app_state, &mut last_weekday, &mut changed, &now).await?;
|
||||||
|
|
||||||
if changed {
|
if changed {
|
||||||
log::debug!("Reloading controller in relay loop");
|
log::debug!("Reloading controller in relay loop");
|
||||||
this = utils::app_state_get_this(app_state).await?;
|
this = utils::app_state_get_this(app_state).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let now_pulse = Instant::now();
|
|
||||||
duration_override = this
|
duration_override = this
|
||||||
.relays
|
.relays
|
||||||
.iter_mut()
|
.iter_mut()
|
||||||
.filter_map(|relay| match relay.check_pulsing(&now_pulse) {
|
.filter_map(|relay| match relay.check_pulsing(&now.instant) {
|
||||||
None => None,
|
None => None,
|
||||||
Some(pulse) => {
|
Some(pulse) => {
|
||||||
let dur = pulse - now_pulse;
|
let dur = pulse - now.instant;
|
||||||
log::debug!(
|
log::debug!(
|
||||||
"Pulsing relay {} for {}s until {:?} ",
|
"Pulsing relay {} for {}s until {:?} ",
|
||||||
relay.r.number,
|
relay.r.number,
|
||||||
|
@ -79,50 +81,57 @@ async fn run_relays(app_state: &Addr<AppState>) -> Result<(), EmgauwaError> {
|
||||||
})
|
})
|
||||||
.min();
|
.min();
|
||||||
|
|
||||||
calc_relay_states(&mut relay_states, &mut this, app_state).await?;
|
calc_relay_states(&mut relay_states, &mut this, app_state, &now).await?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn init_relay_states(relay_states: &mut RelayStates, this: &Controller) {
|
fn init_relay_states(relay_states: &mut RelayStates, this: &Controller) {
|
||||||
relay_states.clear();
|
relay_states.clear();
|
||||||
for _ in 0..this.c.relay_count {
|
this.relays.iter().for_each(|r| {
|
||||||
relay_states.push(None);
|
relay_states.push(RelayState {
|
||||||
}
|
active_schedule: r.active_schedule.clone(),
|
||||||
|
is_on: None
|
||||||
|
});
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn calc_relay_states(
|
async fn calc_relay_states(
|
||||||
relay_states: &mut RelayStates,
|
relay_states: &mut RelayStates,
|
||||||
this: &mut Controller,
|
this: &mut Controller,
|
||||||
app_state: &Addr<AppState>,
|
app_state: &Addr<AppState>,
|
||||||
|
now: &EmgauwaNow,
|
||||||
) -> Result<(), EmgauwaError> {
|
) -> Result<(), EmgauwaError> {
|
||||||
let now = Local::now().time();
|
|
||||||
let now_pulse = Instant::now();
|
|
||||||
|
|
||||||
this.relays
|
this.relays
|
||||||
.iter_mut()
|
.iter_mut()
|
||||||
.zip(relay_states.iter_mut())
|
.zip(relay_states.iter_mut())
|
||||||
.for_each(|(relay, state)| {
|
.for_each(|(relay, state)| {
|
||||||
|
relay.reload_active_schedule(now.weekday);
|
||||||
relay.is_on = Some(
|
relay.is_on = Some(
|
||||||
relay.active_schedule.is_on(&now) || relay.check_pulsing(&now_pulse).is_some(),
|
relay.active_schedule.is_on(&now.time)
|
||||||
|
|| relay.check_pulsing(&now.instant).is_some(),
|
||||||
);
|
);
|
||||||
*state = relay.is_on;
|
|
||||||
|
state.is_on = relay.is_on;
|
||||||
|
state.active_schedule = relay.active_schedule.clone();
|
||||||
});
|
});
|
||||||
utils::app_state_update_relays_on(app_state, relay_states.clone()).await
|
utils::app_state_update_relays_on(app_state, relay_states.clone()).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_next_duration(this: &Controller, duration_override: &mut Option<Duration>) -> Duration {
|
fn get_next_duration(
|
||||||
|
this: &mut Controller,
|
||||||
|
duration_override: &mut Option<Duration>,
|
||||||
|
now: &EmgauwaNow,
|
||||||
|
) -> Duration {
|
||||||
if let Some(duration) = duration_override {
|
if let Some(duration) = duration_override {
|
||||||
log::debug!("Duration override. Waiting for {}s", duration.as_secs());
|
log::debug!("Duration override. Waiting for {}s", duration.as_secs());
|
||||||
return *duration;
|
return *duration;
|
||||||
}
|
}
|
||||||
|
|
||||||
let now = Local::now().time();
|
|
||||||
let now_in_s = now.num_seconds_from_midnight();
|
|
||||||
let next_timestamp = this
|
let next_timestamp = this
|
||||||
.get_next_time(&now)
|
.check_next_time(now)
|
||||||
.map_or(86400, |t| t.num_seconds_from_midnight());
|
.map_or(86400, |t| t.num_seconds_from_midnight());
|
||||||
|
|
||||||
let duration_to_next = Duration::from_secs((next_timestamp - now_in_s) as u64);
|
let duration_to_next = Duration::from_secs((next_timestamp - now.time_in_s()) as u64);
|
||||||
|
|
||||||
log::debug!(
|
log::debug!(
|
||||||
"Next timestamp: {}; Waiting for {}s",
|
"Next timestamp: {}; Waiting for {}s",
|
||||||
|
@ -137,8 +146,9 @@ async fn check_weekday(
|
||||||
app_state: &Addr<AppState>,
|
app_state: &Addr<AppState>,
|
||||||
last_weekday: &mut Weekday,
|
last_weekday: &mut Weekday,
|
||||||
changed: &mut bool,
|
changed: &mut bool,
|
||||||
|
now: &EmgauwaNow,
|
||||||
) -> Result<(), EmgauwaError> {
|
) -> Result<(), EmgauwaError> {
|
||||||
let current_weekday = emgauwa_common::utils::get_weekday();
|
let current_weekday = now.weekday;
|
||||||
if current_weekday.ne(last_weekday) {
|
if current_weekday.ne(last_weekday) {
|
||||||
log::debug!("Weekday changed");
|
log::debug!("Weekday changed");
|
||||||
*last_weekday = current_weekday;
|
*last_weekday = current_weekday;
|
||||||
|
|
19
src/utils.rs
19
src/utils.rs
|
@ -1,9 +1,10 @@
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use actix::Addr;
|
use actix::Addr;
|
||||||
|
use emgauwa_common::db::DbSchedule;
|
||||||
use emgauwa_common::errors::EmgauwaError;
|
use emgauwa_common::errors::EmgauwaError;
|
||||||
use emgauwa_common::models::Controller;
|
use emgauwa_common::models::Controller;
|
||||||
use emgauwa_common::types::RelayStates;
|
use emgauwa_common::types::{RelayStates, Weekday};
|
||||||
use tokio::sync::Notify;
|
use tokio::sync::Notify;
|
||||||
|
|
||||||
use crate::app_state;
|
use crate::app_state;
|
||||||
|
@ -64,3 +65,19 @@ pub async fn app_state_relay_pulse(
|
||||||
.await
|
.await
|
||||||
.map_err(EmgauwaError::from)?
|
.map_err(EmgauwaError::from)?
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn app_state_relay_override_schedule(
|
||||||
|
app_state: &Addr<AppState>,
|
||||||
|
relay_number: i64,
|
||||||
|
schedule: Option<DbSchedule>,
|
||||||
|
weekday: Weekday,
|
||||||
|
) -> Result<(), EmgauwaError> {
|
||||||
|
app_state
|
||||||
|
.send(app_state::RelayOverrideSchedule {
|
||||||
|
relay_number,
|
||||||
|
weekday,
|
||||||
|
schedule,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(EmgauwaError::from)?
|
||||||
|
}
|
||||||
|
|
|
@ -1,12 +1,13 @@
|
||||||
use actix::Addr;
|
use actix::Addr;
|
||||||
use sqlx::{Pool, Sqlite};
|
|
||||||
use sqlx::pool::PoolConnection;
|
|
||||||
use tokio_tungstenite::tungstenite;
|
|
||||||
use tokio_tungstenite::tungstenite::Message;
|
|
||||||
use emgauwa_common::db::{DbController, DbJunctionRelaySchedule, DbRelay, DbSchedule};
|
use emgauwa_common::db::{DbController, DbJunctionRelaySchedule, DbRelay, DbSchedule};
|
||||||
use emgauwa_common::errors::{DatabaseError, EmgauwaError};
|
use emgauwa_common::errors::{DatabaseError, EmgauwaError};
|
||||||
use emgauwa_common::models::{Controller, Relay};
|
use emgauwa_common::models::{Controller, Relay};
|
||||||
use emgauwa_common::types::{ControllerWsAction, ScheduleUid};
|
use emgauwa_common::types::{ControllerWsAction, ScheduleUid};
|
||||||
|
use sqlx::pool::PoolConnection;
|
||||||
|
use sqlx::{Pool, Sqlite};
|
||||||
|
use tokio_tungstenite::tungstenite;
|
||||||
|
use tokio_tungstenite::tungstenite::Message;
|
||||||
|
|
||||||
use crate::app_state::AppState;
|
use crate::app_state::AppState;
|
||||||
use crate::utils;
|
use crate::utils;
|
||||||
use crate::utils::app_state_get_this;
|
use crate::utils::app_state_get_this;
|
||||||
|
@ -57,7 +58,7 @@ pub async fn handle_action(
|
||||||
ControllerWsAction::Controller(controller) => {
|
ControllerWsAction::Controller(controller) => {
|
||||||
handle_controller(conn, &this, controller).await?
|
handle_controller(conn, &this, controller).await?
|
||||||
}
|
}
|
||||||
ControllerWsAction::Relays(relays) => handle_relays(conn, &this, relays).await?,
|
ControllerWsAction::Relays(relays) => handle_relays(conn, app_state, &this, relays).await?,
|
||||||
ControllerWsAction::Schedules(schedules) => handle_schedules(conn, schedules).await?,
|
ControllerWsAction::Schedules(schedules) => handle_schedules(conn, schedules).await?,
|
||||||
ControllerWsAction::RelayPulse((relay_num, duration)) => {
|
ControllerWsAction::RelayPulse((relay_num, duration)) => {
|
||||||
handle_relay_pulse(app_state, relay_num, duration).await?
|
handle_relay_pulse(app_state, relay_num, duration).await?
|
||||||
|
@ -125,6 +126,7 @@ async fn handle_schedules(
|
||||||
|
|
||||||
async fn handle_relays(
|
async fn handle_relays(
|
||||||
conn: &mut PoolConnection<Sqlite>,
|
conn: &mut PoolConnection<Sqlite>,
|
||||||
|
app_state: &Addr<AppState>,
|
||||||
this: &Controller,
|
this: &Controller,
|
||||||
relays: Vec<Relay>,
|
relays: Vec<Relay>,
|
||||||
) -> Result<(), EmgauwaError> {
|
) -> Result<(), EmgauwaError> {
|
||||||
|
@ -143,7 +145,7 @@ async fn handle_relays(
|
||||||
handle_schedules(conn, relay.schedules.clone()).await?;
|
handle_schedules(conn, relay.schedules.clone()).await?;
|
||||||
|
|
||||||
let mut schedules = Vec::new(); // We need to get the schedules from the database to have the right IDs
|
let mut schedules = Vec::new(); // We need to get the schedules from the database to have the right IDs
|
||||||
for schedule in relay.schedules {
|
for schedule in &relay.schedules {
|
||||||
schedules.push(
|
schedules.push(
|
||||||
DbSchedule::get_by_uid(conn, &schedule.uid)
|
DbSchedule::get_by_uid(conn, &schedule.uid)
|
||||||
.await?
|
.await?
|
||||||
|
@ -151,6 +153,16 @@ async fn handle_relays(
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some((override_schedule, weekday)) = relay.unwrap_override_schedule() {
|
||||||
|
utils::app_state_relay_override_schedule(
|
||||||
|
app_state,
|
||||||
|
relay.r.number,
|
||||||
|
override_schedule.clone(),
|
||||||
|
weekday,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
|
||||||
DbJunctionRelaySchedule::set_schedules(conn, &db_relay, schedules.iter().collect()).await?;
|
DbJunctionRelaySchedule::set_schedules(conn, &db_relay, schedules.iter().collect()).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue