Add waiting for next period

This commit is contained in:
Tobias Reisinger 2024-04-26 00:00:42 +02:00
parent 6f2deb38e1
commit 0b0350da0e
Signed by: serguzim
GPG key ID: 13AD60C237A28DFE
5 changed files with 105 additions and 37 deletions

View file

@ -54,6 +54,25 @@ impl Period {
pub fn is_on(&self, now: &NaiveTime) -> bool {
self.start.eq(&self.end) || (self.start.le(now) && self.end.gt(now))
}
pub fn get_next_time(&self, now: &NaiveTime) -> Option<NaiveTime> {
if self.start.eq(&self.end) {
// this period is always on
return None;
}
let start_after_now = self.start.gt(now);
let end_after_now = self.end.gt(now);
let start_before_end = self.start.lt(&self.end);
return match (start_after_now, end_after_now, start_before_end) {
(false, false, _) => None, // both before now
(true, false, _) => Some(self.start), // only start after now
(false, true, _) => Some(self.end), // only end after now
(true, true, true) => Some(self.start), // both after now but start first
(true, true, false) => Some(self.end), // both after now but end first
};
}
}
impl Type<Sqlite> for DbPeriods {

View file

@ -198,4 +198,12 @@ impl DbSchedule {
pub fn is_on(&self, now: &NaiveTime) -> bool {
self.periods.0.iter().any(|period| period.is_on(now))
}
pub fn get_next_time(&self, now: &NaiveTime) -> Option<NaiveTime> {
self.periods
.0
.iter()
.filter_map(|period| period.get_next_time(now))
.min()
}
}

View file

@ -1,4 +1,5 @@
use actix::MessageResponse;
use chrono::NaiveTime;
use futures::executor::block_on;
use serde_derive::{Deserialize, Serialize};
use sqlx::pool::PoolConnection;
@ -62,4 +63,11 @@ impl Controller {
pub fn get_relay_states(&self) -> RelayStates {
self.relays.iter().map(|r| r.is_on).collect()
}
pub fn get_next_time(&self, now: &NaiveTime) -> Option<NaiveTime> {
self.relays
.iter()
.filter_map(|r| r.active_schedule.get_next_time(now))
.min()
}
}

View file

@ -79,4 +79,8 @@ impl Relay {
pub fn is_on(&self, now: &NaiveTime) -> bool {
self.active_schedule.is_on(now)
}
pub fn get_next_time(&self, now: &NaiveTime) -> Option<NaiveTime> {
self.active_schedule.get_next_time(now)
}
}