Add relay pulse functionality

This commit is contained in:
Tobias Reisinger 2024-04-26 16:15:24 +02:00
parent e2f3d7b82a
commit 61a3c6093b
Signed by: serguzim
GPG key ID: 13AD60C237A28DFE
14 changed files with 201 additions and 13 deletions

View file

@ -1,6 +1,8 @@
use std::sync::Arc;
use std::time::{Duration, Instant};
use actix::{Actor, Context, Handler, Message};
use emgauwa_lib::constants;
use emgauwa_lib::errors::EmgauwaError;
use emgauwa_lib::models::Controller;
use emgauwa_lib::types::RelayStates;
@ -8,6 +10,8 @@ use futures::executor::block_on;
use sqlx::{Pool, Sqlite};
use tokio::sync::Notify;
use crate::settings::Settings;
#[derive(Message)]
#[rtype(result = "Result<(), EmgauwaError>")]
pub struct Reload {}
@ -18,6 +22,13 @@ pub struct UpdateRelayStates {
pub relay_states: RelayStates,
}
#[derive(Message)]
#[rtype(result = "Result<(), EmgauwaError>")]
pub struct RelayPulse {
pub relay_number: i64,
pub duration: Option<u32>,
}
#[derive(Message)]
#[rtype(result = "Controller")]
pub struct GetThis {}
@ -33,15 +44,17 @@ pub struct GetRelayNotifier {}
pub struct AppState {
pub pool: Pool<Sqlite>,
pub this: Controller,
pub settings: Settings,
pub controller_notifier: Arc<Notify>,
pub relay_notifier: Arc<Notify>,
}
impl AppState {
pub fn new(pool: Pool<Sqlite>, this: Controller) -> AppState {
pub fn new(pool: Pool<Sqlite>, this: Controller, settings: Settings) -> AppState {
AppState {
pool,
this,
settings,
controller_notifier: Arc::new(Notify::new()),
relay_notifier: Arc::new(Notify::new()),
}
@ -85,6 +98,40 @@ impl Handler<UpdateRelayStates> for AppState {
}
}
impl Handler<RelayPulse> for AppState {
type Result = Result<(), EmgauwaError>;
fn handle(&mut self, msg: RelayPulse, _ctx: &mut Self::Context) -> Self::Result {
let relay_num = msg.relay_number;
let duration = Duration::from_secs(
match msg.duration {
None => {
self.settings
.get_relay(relay_num)
.ok_or(EmgauwaError::Other(String::from(
"Relay not found in settings",
)))?
.pulse
}
Some(dur) => Some(dur as u64),
}
.unwrap_or(constants::RELAY_PULSE_DURATION),
);
let now = Instant::now();
let until = now + duration;
self.this.relay_pulse(relay_num, until)?;
log::debug!(
"Pulsing relay {} for {} seconds until {:?}",
relay_num,
duration.as_secs(),
until
);
Ok(())
}
}
impl Handler<GetThis> for AppState {
type Result = Controller;

View file

@ -104,13 +104,12 @@ async fn main() -> Result<(), std::io::Error> {
let this = Controller::from_db_model(&mut conn, db_controller).map_err(EmgauwaError::from)?;
let app_state = app_state::AppState::new(pool.clone(), this).start();
let url = format!(
"ws://{}:{}/api/v1/ws/controllers",
settings.server.host, settings.server.port
);
let app_state = app_state::AppState::new(pool.clone(), this, settings).start();
let _ = tokio::join!(
tokio::spawn(run_relays_loop(app_state.clone())),

View file

@ -1,4 +1,4 @@
use std::time::Duration;
use std::time::{Duration, Instant};
use actix::Addr;
use chrono::{Local, Timelike};
@ -35,6 +35,8 @@ async fn run_relays(app_state: &Addr<AppState>) -> Result<(), EmgauwaError> {
init_relay_states(&mut relay_states, &this);
calc_relay_states(&mut relay_states, &mut this, app_state).await?;
let mut duration_override = None;
loop {
log::debug!(
"Relay loop at {}: {}",
@ -44,9 +46,12 @@ async fn run_relays(app_state: &Addr<AppState>) -> Result<(), EmgauwaError> {
let notifier_future = notifier.notified();
pin_mut!(notifier_future);
let mut changed = timeout(get_next_duration(&this), &mut notifier_future)
.await
.is_ok();
let mut changed = timeout(
get_next_duration(&this, &mut duration_override),
&mut notifier_future,
)
.await
.is_ok();
check_weekday(app_state, &mut last_weekday, &mut changed).await?;
@ -55,6 +60,25 @@ async fn run_relays(app_state: &Addr<AppState>) -> Result<(), EmgauwaError> {
this = utils::app_state_get_this(app_state).await?;
}
let now_pulse = Instant::now();
duration_override = this
.relays
.iter_mut()
.filter_map(|relay| match relay.check_pulsing(&now_pulse) {
None => None,
Some(pulse) => {
let dur = pulse - now_pulse;
log::debug!(
"Pulsing relay {} for {}s until {:?} ",
relay.r.number,
dur.as_secs(),
pulse
);
Some(dur)
}
})
.min();
calc_relay_states(&mut relay_states, &mut this, app_state).await?;
}
}
@ -72,18 +96,26 @@ async fn calc_relay_states(
app_state: &Addr<AppState>,
) -> Result<(), EmgauwaError> {
let now = Local::now().time();
let now_pulse = Instant::now();
this.relays
.iter_mut()
.zip(relay_states.iter_mut())
.for_each(|(relay, state)| {
relay.is_on = Some(relay.active_schedule.is_on(&now));
relay.is_on = Some(
relay.active_schedule.is_on(&now) || relay.check_pulsing(&now_pulse).is_some(),
);
*state = relay.is_on;
});
utils::app_state_update_relays_on(app_state, relay_states.clone()).await
}
fn get_next_duration(this: &Controller) -> Duration {
fn get_next_duration(this: &Controller, duration_override: &mut Option<Duration>) -> Duration {
if let Some(duration) = duration_override {
log::debug!("Duration override. Waiting for {}s", duration.as_secs());
return *duration;
}
let now = Local::now().time();
let now_in_s = now.num_seconds_from_midnight();
let next_timestamp = this

View file

@ -13,6 +13,7 @@ pub struct Relay {
pub number: Option<i64>,
pub pin: u8,
pub inverted: bool,
pub pulse: Option<u64>,
}
#[derive(Clone, Debug, Deserialize)]
@ -50,6 +51,7 @@ impl Default for Relay {
name: String::from("Relay"),
pin: 0,
inverted: false,
pulse: None,
}
}
}
@ -65,3 +67,9 @@ pub fn init() -> Result<Settings, EmgauwaError> {
Ok(settings)
}
impl Settings {
pub fn get_relay(&self, number: i64) -> Option<&Relay> {
self.relays.iter().find(|r| r.number == Some(number))
}
}

View file

@ -50,3 +50,17 @@ pub async fn app_state_update_relays_on(
.await
.map_err(EmgauwaError::from)
}
pub async fn app_state_relay_pulse(
app_state: &Addr<AppState>,
relay_number: i64,
duration: Option<u32>,
) -> Result<(), EmgauwaError> {
app_state
.send(app_state::RelayPulse {
relay_number,
duration,
})
.await
.map_err(EmgauwaError::from)?
}

View file

@ -140,6 +140,9 @@ pub async fn handle_action(
}
ControllerWsAction::Relays(relays) => handle_relays(conn, &this, relays).await?,
ControllerWsAction::Schedules(schedules) => handle_schedules(conn, schedules).await?,
ControllerWsAction::RelayPulse((relay_num, duration)) => {
handle_relay_pulse(app_state, relay_num, duration).await?
}
_ => return Ok(()),
};
@ -234,3 +237,11 @@ async fn handle_relays(
Ok(())
}
async fn handle_relay_pulse(
app_state: &Addr<AppState>,
relay_num: i64,
duration: Option<u32>,
) -> Result<(), EmgauwaError> {
utils::app_state_relay_pulse(app_state, relay_num, duration).await
}