Compare commits
3 Commits
589d8edf80
...
0.3.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
714b31ea31
|
|||
|
9473d1139f
|
|||
|
d001ce4567
|
411
Cargo.lock
generated
411
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "hemma"
|
name = "hemma"
|
||||||
version = "0.2.3"
|
version = "0.3.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
@ -19,6 +19,7 @@ toml = "0.5.9"
|
|||||||
serde = { version = "1.0.138", features = ["derive"] }
|
serde = { version = "1.0.138", features = ["derive"] }
|
||||||
futures = "0.3.21"
|
futures = "0.3.21"
|
||||||
chrono = { version = "0.4.20", features = ["serde"] }
|
chrono = { version = "0.4.20", features = ["serde"] }
|
||||||
|
rand = "0.8.5"
|
||||||
|
|
||||||
[dependencies.common]
|
[dependencies.common]
|
||||||
path = "../common"
|
path = "../common"
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
mod collector;
|
mod collector;
|
||||||
mod persistence;
|
mod persistence;
|
||||||
mod tasks;
|
mod tasks;
|
||||||
|
mod util;
|
||||||
|
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use collector::CollectorConfig;
|
use collector::CollectorConfig;
|
||||||
|
|||||||
@ -1,22 +1,22 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use chrono::{DateTime, Datelike, Local, NaiveTime, Weekday};
|
use common::{BulbPrefs, ClientMessage, ScriptId, ServerMessage};
|
||||||
use common::{ClientMessage, ServerMessage};
|
use lighter_lib::BulbId;
|
||||||
use lighter_lib::{BulbColor, BulbId};
|
|
||||||
use lighter_manager::manager::{BulbCommand, BulbManager, BulbSelector};
|
use lighter_manager::manager::{BulbCommand, BulbManager, BulbSelector};
|
||||||
|
use lighter_manager::provider::mqtt::BulbsMqtt;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::time::Duration;
|
|
||||||
use tokio::select;
|
use tokio::select;
|
||||||
use tokio::sync::{broadcast, mpsc};
|
|
||||||
use tokio::task::{spawn, JoinHandle};
|
|
||||||
use tokio::time::sleep;
|
|
||||||
|
|
||||||
use crate::persistence::PersistenceFile;
|
use crate::persistence::PersistenceFile;
|
||||||
use crate::{ClientRequest, State};
|
use crate::State;
|
||||||
|
|
||||||
|
use self::scripts::{LightScript, Party, Waker};
|
||||||
|
|
||||||
|
pub mod scripts;
|
||||||
|
|
||||||
#[derive(Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
struct LightsState {
|
struct LightsState {
|
||||||
wake_schedule: HashMap<BulbId, HashMap<Weekday, NaiveTime>>,
|
script_prefs: HashMap<ScriptId, HashMap<BulbId, BulbPrefs>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn lights_task(state: &State) {
|
pub async fn lights_task(state: &State) {
|
||||||
@ -29,36 +29,43 @@ pub async fn lights_task(state: &State) {
|
|||||||
.await
|
.await
|
||||||
.expect("Failed to open lights config");
|
.expect("Failed to open lights config");
|
||||||
|
|
||||||
let (cmd, bulb_states) = BulbManager::launch(config.bulbs.clone(), config.mqtt.clone())
|
let provider = BulbsMqtt::new(config.bulbs.clone(), config.mqtt.clone());
|
||||||
|
let manager = BulbManager::launch(config.bulbs.clone(), provider)
|
||||||
.await
|
.await
|
||||||
.expect("Failed to launch bulb manager");
|
.expect("Failed to launch bulb manager");
|
||||||
|
|
||||||
let mut wake_tasks: HashMap<(BulbId, Weekday), JoinHandle<()>> = lights_state
|
let mut scripts: HashMap<ScriptId, Box<dyn LightScript + Send>> = Default::default();
|
||||||
.get()
|
scripts.insert(
|
||||||
.wake_schedule
|
"waker".to_string(),
|
||||||
.iter()
|
Box::new(Waker::create(manager.clone())),
|
||||||
.flat_map(|(bulb, schedule)| schedule.iter().map(move |(day, time)| (bulb, day, time)))
|
);
|
||||||
.map(|(bulb, day, time)| {
|
scripts.insert(
|
||||||
let handle = spawn(wake_task(
|
"party".to_string(),
|
||||||
state.client_message.clone(),
|
Box::new(Party::create(manager.clone())),
|
||||||
cmd.clone(),
|
);
|
||||||
bulb.clone(),
|
|
||||||
*day,
|
|
||||||
*time,
|
|
||||||
));
|
|
||||||
|
|
||||||
((bulb.clone(), *day), handle)
|
for (script, prefs) in &lights_state.get().script_prefs {
|
||||||
})
|
let Some(script) = scripts.get_mut(script) else {
|
||||||
.collect();
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
for (bulb, prefs) in prefs {
|
||||||
|
for (name, value) in &prefs.kvs {
|
||||||
|
script.set_param(bulb, name, value.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let notify = bulb_states.notify_on_change();
|
|
||||||
select! {
|
select! {
|
||||||
_ = notify => {
|
_ = manager.notify_on_change() => {
|
||||||
let lights_state = lights_state.get();
|
for (id, mode) in manager.bulbs().await.clone().into_iter() {
|
||||||
for (id, mode) in bulb_states.bulbs().await.clone().into_iter() {
|
let prefs = scripts.iter_mut()
|
||||||
let wake_schedule = lights_state.wake_schedule.get(&id).cloned().unwrap_or_default();
|
.map(|(script, prefs)|
|
||||||
let msg = ServerMessage::BulbState { id, mode, wake_schedule };
|
(script.clone(), prefs.get_params(&id)))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let msg = ServerMessage::BulbState { id, mode, prefs };
|
||||||
if let Err(e) = server_message.send(msg) {
|
if let Err(e) = server_message.send(msg) {
|
||||||
error!("broadcast channel error: {e}");
|
error!("broadcast channel error: {e}");
|
||||||
return;
|
return;
|
||||||
@ -73,58 +80,42 @@ pub async fn lights_task(state: &State) {
|
|||||||
|
|
||||||
match request.message {
|
match request.message {
|
||||||
ClientMessage::SetBulbColor { id, color } => {
|
ClientMessage::SetBulbColor { id, color } => {
|
||||||
if let Err(e) = cmd.send(BulbCommand::SetColor(BulbSelector::Id(id), color)).await {
|
manager.send_command(BulbCommand::SetColor(BulbSelector::Id(id), color)).await;
|
||||||
error!("bulb manager error: {e}");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
ClientMessage::SetBulbPower { id, power } => {
|
ClientMessage::SetBulbPower { id, power } => {
|
||||||
if let Err(e) = cmd.send(BulbCommand::SetPower(BulbSelector::Id(id), power)).await {
|
manager.send_command(BulbCommand::SetPower(BulbSelector::Id(id), power)).await;
|
||||||
error!("bulb manager error: {e}");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
ClientMessage::GetBulbs => {
|
ClientMessage::GetBulbs => {
|
||||||
if let Err(e) = request.response.send(ServerMessage::BulbMap(config.bulb_map.clone())).await {
|
if let Err(e) = request.response.send(ServerMessage::BulbMap(config.bulb_map.clone())).await {
|
||||||
error!("GetBulbs response channel error: {e}");
|
error!("GetBulbs response channel error: {e}");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let lights_state = lights_state.get();
|
for (id, mode) in manager.bulbs().await.clone().into_iter() {
|
||||||
for (id, mode) in bulb_states.bulbs().await.clone().into_iter() {
|
let prefs = scripts.iter_mut()
|
||||||
let wake_schedule = lights_state.wake_schedule.get(&id).cloned().unwrap_or_default();
|
.map(|(script, prefs)|
|
||||||
let msg = ServerMessage::BulbState { id, mode, wake_schedule };
|
(script.clone(), prefs.get_params(&id)))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let msg = ServerMessage::BulbState { id, mode, prefs };
|
||||||
if let Err(e) = request.response.send(msg).await {
|
if let Err(e) = request.response.send(msg).await {
|
||||||
error!("GetBulbs response channel error: {e}");
|
error!("GetBulbs response channel error: {e}");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ClientMessage::SetBulbWakeTime { id, day, time } => {
|
ClientMessage::SetBulbPref { bulb, script, name, value } => {
|
||||||
if let Err(e) = lights_state.update(|lights_state| {
|
let Some(s) = scripts.get_mut(&script) else {
|
||||||
let schedule = lights_state.wake_schedule.entry(id.clone()).or_default();
|
continue;
|
||||||
if let Some(time) = time {
|
|
||||||
schedule.insert(day, time);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
schedule.remove(&day);
|
|
||||||
}
|
|
||||||
}).await {
|
|
||||||
error!("Failed to save wake schedule: {e}");
|
|
||||||
};
|
};
|
||||||
|
s.set_param(&bulb, &name, value.clone());
|
||||||
|
|
||||||
if let Some(time) = time {
|
// TODO handle error
|
||||||
let handle = spawn(wake_task(
|
lights_state.update(move |state| {
|
||||||
state.client_message.clone(),
|
state.script_prefs
|
||||||
cmd.clone(),
|
.entry(script).or_default()
|
||||||
id.clone(),
|
.entry(bulb).or_default()
|
||||||
day,
|
.kvs.insert(name, value);
|
||||||
time,
|
}).await.expect("failed to persist lights state");
|
||||||
));
|
|
||||||
|
|
||||||
if let Some(old_handle) = wake_tasks.insert((id, day), handle) {
|
|
||||||
old_handle.abort();
|
|
||||||
}
|
|
||||||
} else if let Some(old_handle) = wake_tasks.remove(&(id, day)) {
|
|
||||||
old_handle.abort();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
@ -132,112 +123,3 @@ pub async fn lights_task(state: &State) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn wake_task(
|
|
||||||
client_messages: broadcast::Sender<ClientRequest>,
|
|
||||||
cmd: mpsc::Sender<BulbCommand>,
|
|
||||||
id: BulbId,
|
|
||||||
day: Weekday,
|
|
||||||
time: NaiveTime,
|
|
||||||
) {
|
|
||||||
let mut alarm = next_alarm(Local::now(), day, time);
|
|
||||||
|
|
||||||
loop {
|
|
||||||
info!("sleeping until {alarm}");
|
|
||||||
sleep((alarm - Local::now()).to_std().unwrap()).await;
|
|
||||||
|
|
||||||
// slowly turn up brightness of bulb
|
|
||||||
for brightness in (1..=75).map(|i| (i as f32) * 0.01) {
|
|
||||||
select! {
|
|
||||||
// abort if the client pokes the bulb
|
|
||||||
_ = wait_for_bulb_command(&id, client_messages.subscribe()) => break,
|
|
||||||
_ = sleep(Duration::from_secs(12)) => {}
|
|
||||||
};
|
|
||||||
|
|
||||||
if cmd
|
|
||||||
.send(BulbCommand::SetColor(
|
|
||||||
BulbSelector::Id(id.clone()),
|
|
||||||
BulbColor::Kelvin {
|
|
||||||
t: 0.0,
|
|
||||||
b: brightness,
|
|
||||||
},
|
|
||||||
))
|
|
||||||
.await
|
|
||||||
.is_err()
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
alarm = next_alarm(Local::now(), day, time);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the next alarm, from a weekday+time schedule.
|
|
||||||
fn next_alarm(now: DateTime<Local>, day: Weekday, time: NaiveTime) -> DateTime<Local> {
|
|
||||||
let day_of_alarm = day.num_days_from_monday() as i64;
|
|
||||||
let day_now = now.weekday().num_days_from_monday() as i64;
|
|
||||||
|
|
||||||
let alarm = now + chrono::Duration::days(day_of_alarm - day_now);
|
|
||||||
let mut alarm = alarm
|
|
||||||
.date_naive()
|
|
||||||
.and_time(time)
|
|
||||||
.and_local_timezone(Local)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
if alarm <= now {
|
|
||||||
alarm += chrono::Duration::weeks(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
alarm
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wait until we receive a client request that mutates the given bulb
|
|
||||||
async fn wait_for_bulb_command(
|
|
||||||
bulb_id: &BulbId,
|
|
||||||
mut client_messages: broadcast::Receiver<ClientRequest>,
|
|
||||||
) {
|
|
||||||
loop {
|
|
||||||
match client_messages.recv().await {
|
|
||||||
Err(_) => return,
|
|
||||||
Ok(request) => match request.message {
|
|
||||||
ClientMessage::SetBulbColor { id, .. }
|
|
||||||
| ClientMessage::SetBulbPower { id, .. }
|
|
||||||
| ClientMessage::SetBulbWakeTime { id, .. }
|
|
||||||
if &id == bulb_id =>
|
|
||||||
{
|
|
||||||
break
|
|
||||||
}
|
|
||||||
_ => continue,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod test {
|
|
||||||
use chrono::{offset::TimeZone, Local, NaiveTime, Weekday};
|
|
||||||
|
|
||||||
use super::next_alarm;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_alarm_date() {
|
|
||||||
const FMT: &str = "%Y-%m-%d %H:%M";
|
|
||||||
let now = Local.datetime_from_str("2022-10-18 15:30", FMT).unwrap();
|
|
||||||
let test_values = [
|
|
||||||
(Weekday::Tue, (16, 30), "2022-10-18 16:30"),
|
|
||||||
(Weekday::Tue, (14, 30), "2022-10-25 14:30"),
|
|
||||||
(Weekday::Wed, (15, 30), "2022-10-19 15:30"),
|
|
||||||
(Weekday::Mon, (15, 30), "2022-10-24 15:30"),
|
|
||||||
];
|
|
||||||
|
|
||||||
for (day, (hour, min), expected) in test_values {
|
|
||||||
let expected = Local.datetime_from_str(expected, FMT).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
next_alarm(now, day, NaiveTime::from_hms(hour, min, 0)),
|
|
||||||
expected
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
12
backend/src/tasks/lights/scripts/mod.rs
Normal file
12
backend/src/tasks/lights/scripts/mod.rs
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
use common::{BulbPrefs, Param};
|
||||||
|
use lighter_lib::BulbId;
|
||||||
|
|
||||||
|
mod party;
|
||||||
|
mod waker;
|
||||||
|
pub use party::Party;
|
||||||
|
pub use waker::Waker;
|
||||||
|
|
||||||
|
pub trait LightScript {
|
||||||
|
fn get_params(&mut self, bulb: &BulbId) -> BulbPrefs;
|
||||||
|
fn set_param(&mut self, bulb: &BulbId, name: &str, value: Param);
|
||||||
|
}
|
||||||
79
backend/src/tasks/lights/scripts/party.rs
Normal file
79
backend/src/tasks/lights/scripts/party.rs
Normal file
@ -0,0 +1,79 @@
|
|||||||
|
use std::{collections::HashMap, time::Duration};
|
||||||
|
|
||||||
|
use common::{BulbPrefs, Param};
|
||||||
|
use lighter_lib::{BulbColor, BulbId};
|
||||||
|
use lighter_manager::manager::{BulbCommand, BulbManager, BulbSelector};
|
||||||
|
use rand::random;
|
||||||
|
use tokio::{spawn, time::sleep};
|
||||||
|
|
||||||
|
use crate::util::DeadMansHandle;
|
||||||
|
|
||||||
|
use super::LightScript;
|
||||||
|
|
||||||
|
pub struct Party {
|
||||||
|
manager: BulbManager,
|
||||||
|
party_tasks: HashMap<BulbId, DeadMansHandle>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Party {
|
||||||
|
pub fn create(manager: BulbManager) -> Self {
|
||||||
|
Party {
|
||||||
|
manager,
|
||||||
|
party_tasks: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LightScript for Party {
|
||||||
|
fn get_params(&mut self, bulb: &BulbId) -> BulbPrefs {
|
||||||
|
let enabled = self.party_tasks.get(bulb).is_some();
|
||||||
|
|
||||||
|
BulbPrefs {
|
||||||
|
kvs: [("Party".to_string(), Param::Toggle(enabled))]
|
||||||
|
.into_iter()
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_param(&mut self, bulb: &BulbId, name: &str, param: Param) {
|
||||||
|
if name != "Party" {
|
||||||
|
error!("invalit param name");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: should be toggle
|
||||||
|
let Param::Toggle(enabled) = param else {
|
||||||
|
error!("invalit param kind");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
if !enabled {
|
||||||
|
self.party_tasks.remove(bulb);
|
||||||
|
} else {
|
||||||
|
let task = spawn(party_task(self.manager.clone(), bulb.clone()));
|
||||||
|
self.party_tasks
|
||||||
|
.insert(bulb.clone(), DeadMansHandle(task.abort_handle()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn party_task(manager: BulbManager, id: BulbId) {
|
||||||
|
manager
|
||||||
|
.until_interrupted(id.clone(), async {
|
||||||
|
let mut h: f32 = random();
|
||||||
|
loop {
|
||||||
|
sleep(Duration::from_millis(50)).await;
|
||||||
|
|
||||||
|
h += 0.01;
|
||||||
|
if h > 1.0 {
|
||||||
|
h = 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let color = BulbColor::HSB { h, s: 1.0, b: 1.0 };
|
||||||
|
manager
|
||||||
|
.send_command(BulbCommand::SetColor(BulbSelector::Id(id.clone()), color))
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
188
backend/src/tasks/lights/scripts/waker.rs
Normal file
188
backend/src/tasks/lights/scripts/waker.rs
Normal file
@ -0,0 +1,188 @@
|
|||||||
|
use std::{collections::HashMap, time::Duration};
|
||||||
|
|
||||||
|
use chrono::{DateTime, Datelike, Local, NaiveTime, Weekday};
|
||||||
|
use common::{BulbPrefs, Param};
|
||||||
|
use lighter_lib::{BulbColor, BulbId};
|
||||||
|
use lighter_manager::manager::{BulbCommand, BulbManager, BulbSelector};
|
||||||
|
use tokio::{spawn, time::sleep};
|
||||||
|
|
||||||
|
use crate::util::DeadMansHandle;
|
||||||
|
|
||||||
|
use super::LightScript;
|
||||||
|
|
||||||
|
pub struct Waker {
|
||||||
|
manager: BulbManager,
|
||||||
|
wake_times: HashMap<BulbId, HashMap<Weekday, NaiveTime>>,
|
||||||
|
wake_tasks: HashMap<(BulbId, Weekday), DeadMansHandle>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Waker {
|
||||||
|
pub fn create(manager: BulbManager) -> Self {
|
||||||
|
Waker {
|
||||||
|
manager,
|
||||||
|
wake_times: Default::default(),
|
||||||
|
wake_tasks: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const TIME_FMT: &str = "%H:%M";
|
||||||
|
|
||||||
|
impl LightScript for Waker {
|
||||||
|
fn get_params(&mut self, bulb: &BulbId) -> BulbPrefs {
|
||||||
|
let settings = self.wake_times.entry(bulb.clone()).or_default();
|
||||||
|
|
||||||
|
let kvs = DAYS_OF_WEEK
|
||||||
|
.iter()
|
||||||
|
.map(|day| {
|
||||||
|
let time = match settings.get(day) {
|
||||||
|
Some(time) => time.format(TIME_FMT).to_string(),
|
||||||
|
None => String::new(),
|
||||||
|
};
|
||||||
|
(format!("{day:?}"), Param::String(time))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
BulbPrefs { kvs }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_param(&mut self, bulb: &BulbId, name: &str, time: super::Param) {
|
||||||
|
let settings = self.wake_times.entry(bulb.clone()).or_default();
|
||||||
|
|
||||||
|
let Param::String(time) = time else {
|
||||||
|
error!("invalit param kind");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let time = NaiveTime::parse_from_str(&time, TIME_FMT)
|
||||||
|
.map(Some)
|
||||||
|
.unwrap_or(None);
|
||||||
|
|
||||||
|
let weekday = match name {
|
||||||
|
"Mon" => Weekday::Mon,
|
||||||
|
"Tue" => Weekday::Tue,
|
||||||
|
"Wed" => Weekday::Wed,
|
||||||
|
"Thu" => Weekday::Thu,
|
||||||
|
"Fri" => Weekday::Fri,
|
||||||
|
"Sat" => Weekday::Sat,
|
||||||
|
"Sun" => Weekday::Sun,
|
||||||
|
_ => {
|
||||||
|
error!("invalit param name");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let Some(time) = time else {
|
||||||
|
settings.remove(&weekday);
|
||||||
|
self.wake_tasks.remove(&(bulb.clone(), weekday));
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
settings.insert(weekday, time);
|
||||||
|
let task = spawn(wake_task(self.manager.clone(), bulb.clone(), weekday, time));
|
||||||
|
self.wake_tasks
|
||||||
|
.insert((bulb.clone(), weekday), DeadMansHandle(task.abort_handle()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const DAYS_OF_WEEK: &[Weekday] = &[
|
||||||
|
Weekday::Mon,
|
||||||
|
Weekday::Tue,
|
||||||
|
Weekday::Wed,
|
||||||
|
Weekday::Thu,
|
||||||
|
Weekday::Fri,
|
||||||
|
Weekday::Sat,
|
||||||
|
Weekday::Sun,
|
||||||
|
];
|
||||||
|
|
||||||
|
async fn wake_task(manager: BulbManager, id: BulbId, day: Weekday, time: NaiveTime) {
|
||||||
|
let mut alarm = next_alarm(Local::now(), day, time);
|
||||||
|
|
||||||
|
loop {
|
||||||
|
info!("waking lamp {id:?} at {alarm}");
|
||||||
|
sleep((alarm - Local::now()).to_std().unwrap()).await;
|
||||||
|
|
||||||
|
if let Some(bulb) = manager.bulbs().await.get(&id) {
|
||||||
|
// don't wake the bulb if it's already turned on
|
||||||
|
if bulb.power {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
warn!("bulb {id:?} does not exist");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
info!("waking lamp {id:?}");
|
||||||
|
let r = manager
|
||||||
|
.until_interrupted(id.clone(), async {
|
||||||
|
// slowly turn up brightness of bulb
|
||||||
|
for brightness in (1..=75).map(|i| (i as f32) * 0.01) {
|
||||||
|
//sleep(Duration::from_secs(12)).await;
|
||||||
|
sleep(Duration::from_millis(500)).await;
|
||||||
|
|
||||||
|
manager
|
||||||
|
.send_command(BulbCommand::SetColor(
|
||||||
|
BulbSelector::Id(id.clone()),
|
||||||
|
BulbColor::Kelvin {
|
||||||
|
t: 0.0,
|
||||||
|
b: brightness,
|
||||||
|
},
|
||||||
|
))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
|
if r.is_none() {
|
||||||
|
info!("interrupted waking lamp {id:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
alarm = next_alarm(Local::now(), day, time);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the next alarm, from a weekday+time schedule.
|
||||||
|
fn next_alarm(now: DateTime<Local>, day: Weekday, time: NaiveTime) -> DateTime<Local> {
|
||||||
|
let day_of_alarm = day.num_days_from_monday() as i64;
|
||||||
|
let day_now = now.weekday().num_days_from_monday() as i64;
|
||||||
|
|
||||||
|
let alarm = now + chrono::Duration::days(day_of_alarm - day_now);
|
||||||
|
let mut alarm = alarm
|
||||||
|
.date_naive()
|
||||||
|
.and_time(time)
|
||||||
|
.and_local_timezone(Local)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
if alarm <= now {
|
||||||
|
alarm += chrono::Duration::weeks(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
alarm
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use super::next_alarm;
|
||||||
|
use chrono::{offset::TimeZone, Local, NaiveTime, Weekday};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_alarm_date() {
|
||||||
|
const FMT: &str = "%Y-%m-%d %H:%M";
|
||||||
|
let now = Local.datetime_from_str("2022-10-18 15:30", FMT).unwrap();
|
||||||
|
let test_values = [
|
||||||
|
(Weekday::Tue, (16, 30), "2022-10-18 16:30"),
|
||||||
|
(Weekday::Tue, (14, 30), "2022-10-25 14:30"),
|
||||||
|
(Weekday::Wed, (15, 30), "2022-10-19 15:30"),
|
||||||
|
(Weekday::Mon, (15, 30), "2022-10-24 15:30"),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (day, (hour, min), expected) in test_values {
|
||||||
|
let expected = Local.datetime_from_str(expected, FMT).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
next_alarm(now, day, NaiveTime::from_hms(hour, min, 0)),
|
||||||
|
expected
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
15
backend/src/util.rs
Normal file
15
backend/src/util.rs
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
use tokio::task::AbortHandle;
|
||||||
|
|
||||||
|
pub struct DeadMansHandle(pub AbortHandle);
|
||||||
|
|
||||||
|
impl From<AbortHandle> for DeadMansHandle {
|
||||||
|
fn from(abort: AbortHandle) -> Self {
|
||||||
|
DeadMansHandle(abort)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for DeadMansHandle {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.0.abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "common"
|
name = "common"
|
||||||
version = "0.2.3"
|
version = "0.3.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
|||||||
@ -1,6 +1,5 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use chrono::{NaiveTime, Weekday};
|
|
||||||
use lighter_lib::{BulbColor, BulbId, BulbMode};
|
use lighter_lib::{BulbColor, BulbId, BulbMode};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
@ -15,7 +14,7 @@ pub enum ServerMessage {
|
|||||||
BulbState {
|
BulbState {
|
||||||
id: BulbId,
|
id: BulbId,
|
||||||
mode: BulbMode,
|
mode: BulbMode,
|
||||||
wake_schedule: HashMap<Weekday, NaiveTime>,
|
prefs: BTreeMap<ScriptId, BulbPrefs>,
|
||||||
},
|
},
|
||||||
|
|
||||||
BulbMap(BulbMap),
|
BulbMap(BulbMap),
|
||||||
@ -35,10 +34,11 @@ pub enum ClientMessage {
|
|||||||
id: BulbId,
|
id: BulbId,
|
||||||
power: bool,
|
power: bool,
|
||||||
},
|
},
|
||||||
SetBulbWakeTime {
|
SetBulbPref {
|
||||||
id: BulbId,
|
bulb: BulbId,
|
||||||
day: Weekday,
|
script: ScriptId,
|
||||||
time: Option<NaiveTime>,
|
name: String,
|
||||||
|
value: Param,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -78,3 +78,16 @@ impl BulbGroupShape {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub type ScriptId = String;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub enum Param {
|
||||||
|
String(String),
|
||||||
|
Toggle(bool),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct BulbPrefs {
|
||||||
|
pub kvs: BTreeMap<String, Param>,
|
||||||
|
}
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "hemma_web"
|
name = "hemma_web"
|
||||||
version = "0.2.3"
|
version = "0.3.0"
|
||||||
authors = ["Joakim Hulthe <joakim@hulthe.net"]
|
authors = ["Joakim Hulthe <joakim@hulthe.net"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
|
|||||||
@ -1,13 +1,13 @@
|
|||||||
use crate::components::color_picker::{ColorPicker, ColorPickerMsg};
|
use crate::components::color_picker::{ColorPicker, ColorPickerMsg};
|
||||||
use crate::css::C;
|
use crate::css::C;
|
||||||
use chrono::{NaiveTime, Weekday};
|
use common::{BulbGroup, BulbGroupShape, BulbMap, BulbPrefs, ClientMessage, Param, ServerMessage};
|
||||||
use common::{BulbGroup, BulbGroupShape, BulbMap, ClientMessage, ServerMessage};
|
|
||||||
use lighter_lib::{BulbId, BulbMode};
|
use lighter_lib::{BulbId, BulbMode};
|
||||||
use seed::{attrs, button, div, h2, input, table, td, tr, C};
|
use seed::{attrs, button, div, empty, h2, input, table, td, tr, C};
|
||||||
use seed::{prelude::*, IF};
|
use seed::{prelude::*, IF};
|
||||||
use seed_router::Page;
|
use seed_router::Page;
|
||||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
use std::collections::{BTreeMap, HashSet};
|
||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
|
use std::iter::repeat;
|
||||||
|
|
||||||
/// /lights page
|
/// /lights page
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
@ -28,7 +28,7 @@ pub struct Model {
|
|||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
struct BulbState {
|
struct BulbState {
|
||||||
mode: BulbMode,
|
mode: BulbMode,
|
||||||
wake_schedule: HashMap<Weekday, NaiveTime>,
|
prefs: BTreeMap<String, BulbPrefs>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@ -39,7 +39,13 @@ pub enum Msg {
|
|||||||
DeselectGroups,
|
DeselectGroups,
|
||||||
ColorPicker(ColorPickerMsg),
|
ColorPicker(ColorPickerMsg),
|
||||||
SetBulbPower(bool),
|
SetBulbPower(bool),
|
||||||
LightTime(String, Weekday),
|
|
||||||
|
/// Set a script parameter value for all selected bulbs.
|
||||||
|
SetParam {
|
||||||
|
script: String,
|
||||||
|
name: String,
|
||||||
|
value: Param,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Page for Model {
|
impl Page for Model {
|
||||||
@ -58,11 +64,11 @@ impl Page for Model {
|
|||||||
ServerMessage::BulbState {
|
ServerMessage::BulbState {
|
||||||
id,
|
id,
|
||||||
mode: new_mode,
|
mode: new_mode,
|
||||||
wake_schedule,
|
prefs,
|
||||||
} => {
|
} => {
|
||||||
*self.bulb_states.entry(id).or_default() = BulbState {
|
*self.bulb_states.entry(id).or_default() = BulbState {
|
||||||
mode: new_mode,
|
mode: new_mode,
|
||||||
wake_schedule,
|
prefs,
|
||||||
};
|
};
|
||||||
|
|
||||||
//color_picker.set_color(mode.color);
|
//color_picker.set_color(mode.color);
|
||||||
@ -124,26 +130,25 @@ impl Page for Model {
|
|||||||
orders.notify(message);
|
orders.notify(message);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Msg::LightTime(time, day) => {
|
Msg::SetParam {
|
||||||
if time.is_empty() {
|
script,
|
||||||
self.for_selected_bulbs(|id, _| {
|
name,
|
||||||
let message = ClientMessage::SetBulbWakeTime {
|
value,
|
||||||
id: id.clone(),
|
} => {
|
||||||
day,
|
self.for_selected_bulbs(|id, bulb| {
|
||||||
time: None,
|
bulb.prefs
|
||||||
|
.get_mut(&script)
|
||||||
|
.unwrap() //TOD
|
||||||
|
.kvs
|
||||||
|
.insert(name.clone(), value.clone());
|
||||||
|
let message = ClientMessage::SetBulbPref {
|
||||||
|
bulb: id.clone(),
|
||||||
|
script: script.clone(),
|
||||||
|
name: name.clone(),
|
||||||
|
value: value.clone(),
|
||||||
};
|
};
|
||||||
orders.notify(message);
|
orders.notify(message);
|
||||||
});
|
});
|
||||||
} else if let Ok(time) = NaiveTime::parse_from_str(&time, "%H:%M") {
|
|
||||||
self.for_selected_bulbs(|id, _| {
|
|
||||||
let message = ClientMessage::SetBulbWakeTime {
|
|
||||||
id: id.clone(),
|
|
||||||
day,
|
|
||||||
time: Some(time),
|
|
||||||
};
|
|
||||||
orders.notify(message);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -230,20 +235,44 @@ impl Page for Model {
|
|||||||
.and_then(|group| group.bulbs.first())
|
.and_then(|group| group.bulbs.first())
|
||||||
.and_then(|id| self.bulb_states.get(id));
|
.and_then(|id| self.bulb_states.get(id));
|
||||||
|
|
||||||
let calendar_day = |day: Weekday| {
|
let script_param = |script: &str, name: &str, value: &Param| {
|
||||||
let time = selected_bulb
|
let name = name.to_string();
|
||||||
.and_then(|b| b.wake_schedule.get(&day))
|
let script = script.to_string();
|
||||||
.map(|t| t.to_string())
|
|
||||||
.unwrap_or_default();
|
match value {
|
||||||
tr![
|
Param::String(value) => tr![
|
||||||
C![C.calendar_day],
|
C![C.pref_line],
|
||||||
td![day.to_string()],
|
td![&name],
|
||||||
td![input![
|
td![input![
|
||||||
C![C.calendar_time_input],
|
C![C.pref_input],
|
||||||
attrs! {At::Placeholder => time},
|
attrs! {At::Placeholder => &script},
|
||||||
input_ev(Ev::Input, move |input| Msg::LightTime(input, day))
|
attrs! {At::Value => value},
|
||||||
]],
|
input_ev(Ev::Input, move |input| Msg::SetParam {
|
||||||
|
script,
|
||||||
|
name,
|
||||||
|
value: Param::String(input),
|
||||||
|
})
|
||||||
|
]]
|
||||||
|
],
|
||||||
|
&Param::Toggle(value) => {
|
||||||
|
tr![
|
||||||
|
C![C.pref_line],
|
||||||
|
button![
|
||||||
|
if value {
|
||||||
|
C![C.pref_button_enabled]
|
||||||
|
} else {
|
||||||
|
C![C.pref_button]
|
||||||
|
},
|
||||||
|
&name,
|
||||||
|
input_ev(Ev::Click, move |_| Msg::SetParam {
|
||||||
|
script,
|
||||||
|
name,
|
||||||
|
value: Param::Toggle(!value),
|
||||||
|
})
|
||||||
]
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
div![
|
div![
|
||||||
@ -278,30 +307,35 @@ impl Page for Model {
|
|||||||
],
|
],
|
||||||
],
|
],
|
||||||
div![
|
div![
|
||||||
C![C.calendar_box],
|
C![C.prefs_box],
|
||||||
IF!(selected_bulb.is_none() => C![C.cross_out]),
|
IF!(selected_bulb.is_none() => C![C.cross_out]),
|
||||||
h2!["Wake Schedule"],
|
h2!["Settings"],
|
||||||
table![
|
if let Some(selected_bulb) = selected_bulb {
|
||||||
calendar_day(Weekday::Mon),
|
table![selected_bulb
|
||||||
calendar_day(Weekday::Tue),
|
.prefs
|
||||||
calendar_day(Weekday::Wed),
|
.iter()
|
||||||
calendar_day(Weekday::Thu),
|
.flat_map(|(script, prefs)| repeat(script).zip(prefs.kvs.iter()))
|
||||||
calendar_day(Weekday::Fri),
|
.map(|(script, (name, value))| script_param(script, name, value))]
|
||||||
calendar_day(Weekday::Sat),
|
} else {
|
||||||
calendar_day(Weekday::Sun),
|
empty![]
|
||||||
],
|
},
|
||||||
],
|
],
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Model {
|
impl Model {
|
||||||
fn for_selected_bulbs(&self, mut f: impl FnMut(&BulbId, &BulbState)) {
|
fn for_selected_bulbs(&mut self, mut f: impl FnMut(&BulbId, &mut BulbState)) {
|
||||||
self.selected_groups
|
for &index in &self.selected_groups {
|
||||||
.iter()
|
let Some(group) = self.bulb_map.groups.get(index) else {
|
||||||
.filter_map(|&index| self.bulb_map.groups.get(index))
|
continue;
|
||||||
.flat_map(|group| group.bulbs.iter())
|
};
|
||||||
.filter_map(|id| self.bulb_states.get(id).map(|bulb| (id, bulb)))
|
|
||||||
.for_each(|(id, bulb)| f(id, bulb));
|
for id in group.bulbs.iter() {
|
||||||
|
if let Some(bulb) = self.bulb_states.get_mut(id) {
|
||||||
|
f(id, bulb);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -304,14 +304,16 @@ body {
|
|||||||
|
|
||||||
transition: margin 0.1s ease-out;
|
transition: margin 0.1s ease-out;
|
||||||
}
|
}
|
||||||
.calendar_day {
|
|
||||||
|
|
||||||
|
.pref_line {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
margin-top: .3em;
|
margin-top: .3em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.calendar_time_input {
|
.pref_input {
|
||||||
background: #453f4b;
|
background: #453f4b;
|
||||||
border: solid 0.35em #5b3f63;
|
border: solid 0.35em #5b3f63;
|
||||||
border-radius: .3em;
|
border-radius: .3em;
|
||||||
@ -323,17 +325,49 @@ body {
|
|||||||
margin-left: .5em;
|
margin-left: .5em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.calendar_box {
|
.pref_button {}
|
||||||
|
.pref_button, .pref_button_enabled {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
|
||||||
|
font-size: large;
|
||||||
|
font-weight: bold;
|
||||||
|
color: white;
|
||||||
|
text-shadow: 0.1rem 0.1rem 0.3rem black;
|
||||||
|
|
||||||
|
padding: 1rem;
|
||||||
|
border: solid 0.35em #5b3f63;
|
||||||
|
border-radius: 0.3em;
|
||||||
|
background: transparent;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.pref_button_enabled::before {
|
||||||
|
content: "";
|
||||||
|
z-index: -1;
|
||||||
|
width: 20rem;
|
||||||
|
height: 20rem;
|
||||||
|
background-size: 100% 100%;
|
||||||
|
background-image: url(/images/hsb.png);
|
||||||
|
position: absolute;
|
||||||
|
transform: translate(-8.5rem, -2.5rem);
|
||||||
|
animation: infinite linear 3s button_rainbow;
|
||||||
|
}
|
||||||
|
@keyframes button_rainbow {
|
||||||
|
from { transform: translate(-8.5rem, -2.5rem) rotate( 0deg); }
|
||||||
|
to { transform: translate(-8.5rem, -2.5rem) rotate(360deg); }
|
||||||
|
}
|
||||||
|
|
||||||
|
.prefs_box {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.calendar_box > h2 {
|
.prefs_box > h2 {
|
||||||
writing-mode: sideways-lr;
|
writing-mode: sideways-lr;
|
||||||
margin-top: auto;
|
margin-top: auto;
|
||||||
margin-bottom: auto;
|
margin-bottom: auto;
|
||||||
}
|
}
|
||||||
.calendar_box > * {
|
.prefs_box > * {
|
||||||
flex-shrink: 1;
|
flex-shrink: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user