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
emgauwa-controller/src

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;