Improve relay initialization

This commit is contained in:
Tobias Reisinger 2024-05-10 16:47:28 +02:00
parent 5e7d5466e8
commit ca6988b01f
Signed by: serguzim
GPG key ID: 13AD60C237A28DFE
3 changed files with 19 additions and 8 deletions

BIN
Cargo.lock generated

Binary file not shown.

View file

@ -64,9 +64,6 @@ async fn main() -> Result<(), std::io::Error> {
init_logging(&settings.logging.level)?;
let mut pfd: Option<PiFaceDigital> = None;
let drivers = settings.relays_make_drivers(&mut pfd)?;
let pool = db::init(&settings.database)
.await
.map_err(EmgauwaError::from)?;
@ -105,6 +102,12 @@ async fn main() -> Result<(), std::io::Error> {
let this = Controller::from_db_model(&mut conn, db_controller).map_err(EmgauwaError::from)?;
let now = chrono::Local::now().time();
let initial_states: Vec<bool> = this.relays.iter().map(|r| r.active_schedule.is_on(&now)).collect();
let mut pfd: Option<PiFaceDigital> = None;
let drivers = settings.relays_make_drivers(&mut pfd, initial_states)?;
let url = format!(
"ws://{}:{}/api/v1/ws/controllers",
settings.server.host, settings.server.port
@ -112,6 +115,8 @@ async fn main() -> Result<(), std::io::Error> {
let app_state = app_state::AppState::new(pool.clone(), this, settings, drivers).start();
log::info!("Starting main loops");
let _ = tokio::join!(
tokio::spawn(run_relays_loop(app_state.clone())),
tokio::spawn(run_ws_loop(pool.clone(), app_state.clone(), url)),

View file

@ -68,11 +68,15 @@ impl Settings {
pub fn relays_make_drivers(
&self,
pfd: &mut Option<PiFaceDigital>,
) -> Result<Vec<Box<dyn drivers::RelayDriver>>, EmgauwaError> {
initial_states: Vec<bool>,
) -> Result<Vec<Box<dyn drivers::RelayDriver>>, EmgauwaError> {
let mut drivers = Vec::new();
for relay in &self.relays {
drivers.push(relay.make_driver(pfd)?);
}
let result: Result<(), EmgauwaError> = self.relays.iter().zip(initial_states.into_iter()).try_for_each(|(relay, state)| {
let driver = relay.make_driver(pfd, state)?;
drivers.push(driver);
Ok(())
});
result?;
Ok(drivers)
}
}
@ -81,8 +85,9 @@ impl Relay {
pub fn make_driver(
&self,
pfd: &mut Option<PiFaceDigital>,
state: bool,
) -> Result<Box<dyn drivers::RelayDriver>, EmgauwaError> {
let driver: Box<dyn drivers::RelayDriver> = match self.driver {
let mut driver: Box<dyn drivers::RelayDriver> = match self.driver {
drivers::Driver::Null => Box::new(drivers::NullDriver::new(self.pin)),
drivers::Driver::Gpio => Box::new(drivers::GpioDriver::new(self.pin, self.inverted)?),
drivers::Driver::PiFace => {
@ -92,6 +97,7 @@ impl Relay {
Box::new(drivers::PiFaceDriver::new(self.pin, pfd)?)
}
};
driver.set(state)?;
Ok(driver)
}
}