Compare commits
1 Commits
0.3.1
...
589d8edf80
| Author | SHA1 | Date | |
|---|---|---|---|
|
589d8edf80
|
598
Cargo.lock
generated
598
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.3.1"
|
version = "0.2.3"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
@ -19,7 +19,6 @@ 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,7 +1,6 @@
|
|||||||
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 common::{BulbPrefs, ClientMessage, ScriptId, ServerMessage};
|
use chrono::{DateTime, Datelike, Local, NaiveTime, Weekday};
|
||||||
use lighter_lib::BulbId;
|
use common::{ClientMessage, ServerMessage};
|
||||||
|
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::State;
|
use crate::{ClientRequest, 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 {
|
||||||
script_prefs: HashMap<ScriptId, HashMap<BulbId, BulbPrefs>>,
|
wake_schedule: HashMap<BulbId, HashMap<Weekday, NaiveTime>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn lights_task(state: &State) {
|
pub async fn lights_task(state: &State) {
|
||||||
@ -29,43 +29,36 @@ pub async fn lights_task(state: &State) {
|
|||||||
.await
|
.await
|
||||||
.expect("Failed to open lights config");
|
.expect("Failed to open lights config");
|
||||||
|
|
||||||
let provider = BulbsMqtt::new(config.bulbs.clone(), config.mqtt.clone());
|
let (cmd, bulb_states) = BulbManager::launch(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 scripts: HashMap<ScriptId, Box<dyn LightScript + Send>> = Default::default();
|
let mut wake_tasks: HashMap<(BulbId, Weekday), JoinHandle<()>> = lights_state
|
||||||
scripts.insert(
|
.get()
|
||||||
"waker".to_string(),
|
.wake_schedule
|
||||||
Box::new(Waker::create(manager.clone())),
|
.iter()
|
||||||
);
|
.flat_map(|(bulb, schedule)| schedule.iter().map(move |(day, time)| (bulb, day, time)))
|
||||||
scripts.insert(
|
.map(|(bulb, day, time)| {
|
||||||
"party".to_string(),
|
let handle = spawn(wake_task(
|
||||||
Box::new(Party::create(manager.clone())),
|
state.client_message.clone(),
|
||||||
);
|
cmd.clone(),
|
||||||
|
bulb.clone(),
|
||||||
|
*day,
|
||||||
|
*time,
|
||||||
|
));
|
||||||
|
|
||||||
for (script, prefs) in &lights_state.get().script_prefs {
|
((bulb.clone(), *day), handle)
|
||||||
let Some(script) = scripts.get_mut(script) else {
|
})
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
for (bulb, prefs) in prefs {
|
|
||||||
for (name, value) in &prefs.kvs {
|
|
||||||
script.set_param(bulb, name, value.clone())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
loop {
|
|
||||||
select! {
|
|
||||||
_ = manager.notify_on_change() => {
|
|
||||||
for (id, mode) in manager.bulbs().await.clone().into_iter() {
|
|
||||||
let prefs = scripts.iter_mut()
|
|
||||||
.map(|(script, prefs)|
|
|
||||||
(script.clone(), prefs.get_params(&id)))
|
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let msg = ServerMessage::BulbState { id, mode, prefs };
|
loop {
|
||||||
|
let notify = bulb_states.notify_on_change();
|
||||||
|
select! {
|
||||||
|
_ = notify => {
|
||||||
|
let lights_state = lights_state.get();
|
||||||
|
for (id, mode) in bulb_states.bulbs().await.clone().into_iter() {
|
||||||
|
let wake_schedule = lights_state.wake_schedule.get(&id).cloned().unwrap_or_default();
|
||||||
|
let msg = ServerMessage::BulbState { id, mode, wake_schedule };
|
||||||
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;
|
||||||
@ -80,42 +73,58 @@ pub async fn lights_task(state: &State) {
|
|||||||
|
|
||||||
match request.message {
|
match request.message {
|
||||||
ClientMessage::SetBulbColor { id, color } => {
|
ClientMessage::SetBulbColor { id, color } => {
|
||||||
manager.send_command(BulbCommand::SetColor(BulbSelector::Id(id), color)).await;
|
if let Err(e) = cmd.send(BulbCommand::SetColor(BulbSelector::Id(id), color)).await {
|
||||||
|
error!("bulb manager error: {e}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
ClientMessage::SetBulbPower { id, power } => {
|
ClientMessage::SetBulbPower { id, power } => {
|
||||||
manager.send_command(BulbCommand::SetPower(BulbSelector::Id(id), power)).await;
|
if let Err(e) = cmd.send(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;
|
||||||
}
|
}
|
||||||
for (id, mode) in manager.bulbs().await.clone().into_iter() {
|
let lights_state = lights_state.get();
|
||||||
let prefs = scripts.iter_mut()
|
for (id, mode) in bulb_states.bulbs().await.clone().into_iter() {
|
||||||
.map(|(script, prefs)|
|
let wake_schedule = lights_state.wake_schedule.get(&id).cloned().unwrap_or_default();
|
||||||
(script.clone(), prefs.get_params(&id)))
|
let msg = ServerMessage::BulbState { id, mode, wake_schedule };
|
||||||
.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::SetBulbPref { bulb, script, name, value } => {
|
ClientMessage::SetBulbWakeTime { id, day, time } => {
|
||||||
let Some(s) = scripts.get_mut(&script) else {
|
if let Err(e) = lights_state.update(|lights_state| {
|
||||||
continue;
|
let schedule = lights_state.wake_schedule.entry(id.clone()).or_default();
|
||||||
|
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());
|
|
||||||
|
|
||||||
// TODO handle error
|
if let Some(time) = time {
|
||||||
lights_state.update(move |state| {
|
let handle = spawn(wake_task(
|
||||||
state.script_prefs
|
state.client_message.clone(),
|
||||||
.entry(script).or_default()
|
cmd.clone(),
|
||||||
.entry(bulb).or_default()
|
id.clone(),
|
||||||
.kvs.insert(name, value);
|
day,
|
||||||
}).await.expect("failed to persist lights state");
|
time,
|
||||||
|
));
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
@ -123,3 +132,112 @@ 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
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -1,12 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
@ -1,79 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
@ -1,188 +0,0 @@
|
|||||||
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
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,15 +0,0 @@
|
|||||||
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.3.1"
|
version = "0.2.3"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
|||||||
@ -1,5 +1,6 @@
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use chrono::{NaiveTime, Weekday};
|
||||||
use lighter_lib::{BulbColor, BulbId, BulbMode};
|
use lighter_lib::{BulbColor, BulbId, BulbMode};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
@ -14,7 +15,7 @@ pub enum ServerMessage {
|
|||||||
BulbState {
|
BulbState {
|
||||||
id: BulbId,
|
id: BulbId,
|
||||||
mode: BulbMode,
|
mode: BulbMode,
|
||||||
prefs: BTreeMap<ScriptId, BulbPrefs>,
|
wake_schedule: HashMap<Weekday, NaiveTime>,
|
||||||
},
|
},
|
||||||
|
|
||||||
BulbMap(BulbMap),
|
BulbMap(BulbMap),
|
||||||
@ -34,11 +35,10 @@ pub enum ClientMessage {
|
|||||||
id: BulbId,
|
id: BulbId,
|
||||||
power: bool,
|
power: bool,
|
||||||
},
|
},
|
||||||
SetBulbPref {
|
SetBulbWakeTime {
|
||||||
bulb: BulbId,
|
id: BulbId,
|
||||||
script: ScriptId,
|
day: Weekday,
|
||||||
name: String,
|
time: Option<NaiveTime>,
|
||||||
value: Param,
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -78,16 +78,3 @@ 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.3.1"
|
version = "0.2.3"
|
||||||
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 common::{BulbGroup, BulbGroupShape, BulbMap, BulbPrefs, ClientMessage, Param, ServerMessage};
|
use chrono::{NaiveTime, Weekday};
|
||||||
|
use common::{BulbGroup, BulbGroupShape, BulbMap, ClientMessage, ServerMessage};
|
||||||
use lighter_lib::{BulbId, BulbMode};
|
use lighter_lib::{BulbId, BulbMode};
|
||||||
use seed::{attrs, button, div, empty, h2, input, table, td, tr, C};
|
use seed::{attrs, button, div, 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, HashSet};
|
use std::collections::{BTreeMap, HashMap, 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,
|
||||||
prefs: BTreeMap<String, BulbPrefs>,
|
wake_schedule: HashMap<Weekday, NaiveTime>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@ -39,13 +39,7 @@ 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 {
|
||||||
@ -64,11 +58,11 @@ impl Page for Model {
|
|||||||
ServerMessage::BulbState {
|
ServerMessage::BulbState {
|
||||||
id,
|
id,
|
||||||
mode: new_mode,
|
mode: new_mode,
|
||||||
prefs,
|
wake_schedule,
|
||||||
} => {
|
} => {
|
||||||
*self.bulb_states.entry(id).or_default() = BulbState {
|
*self.bulb_states.entry(id).or_default() = BulbState {
|
||||||
mode: new_mode,
|
mode: new_mode,
|
||||||
prefs,
|
wake_schedule,
|
||||||
};
|
};
|
||||||
|
|
||||||
//color_picker.set_color(mode.color);
|
//color_picker.set_color(mode.color);
|
||||||
@ -130,25 +124,26 @@ impl Page for Model {
|
|||||||
orders.notify(message);
|
orders.notify(message);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Msg::SetParam {
|
Msg::LightTime(time, day) => {
|
||||||
script,
|
if time.is_empty() {
|
||||||
name,
|
self.for_selected_bulbs(|id, _| {
|
||||||
value,
|
let message = ClientMessage::SetBulbWakeTime {
|
||||||
} => {
|
id: id.clone(),
|
||||||
self.for_selected_bulbs(|id, bulb| {
|
day,
|
||||||
bulb.prefs
|
time: None,
|
||||||
.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);
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -235,44 +230,20 @@ 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 script_param = |script: &str, name: &str, value: &Param| {
|
let calendar_day = |day: Weekday| {
|
||||||
let name = name.to_string();
|
let time = selected_bulb
|
||||||
let script = script.to_string();
|
.and_then(|b| b.wake_schedule.get(&day))
|
||||||
|
.map(|t| t.to_string())
|
||||||
match value {
|
.unwrap_or_default();
|
||||||
Param::String(value) => tr![
|
|
||||||
C![C.pref_line],
|
|
||||||
td![&name],
|
|
||||||
td![input![
|
|
||||||
C![C.pref_input],
|
|
||||||
attrs! {At::Placeholder => &script},
|
|
||||||
attrs! {At::Value => value},
|
|
||||||
input_ev(Ev::Input, move |input| Msg::SetParam {
|
|
||||||
script,
|
|
||||||
name,
|
|
||||||
value: Param::String(input),
|
|
||||||
})
|
|
||||||
]]
|
|
||||||
],
|
|
||||||
&Param::Toggle(value) => {
|
|
||||||
tr![
|
tr![
|
||||||
C![C.pref_line],
|
C![C.calendar_day],
|
||||||
button![
|
td![day.to_string()],
|
||||||
if value {
|
td![input![
|
||||||
C![C.pref_button_enabled]
|
C![C.calendar_time_input],
|
||||||
} else {
|
attrs! {At::Placeholder => time},
|
||||||
C![C.pref_button]
|
input_ev(Ev::Input, move |input| Msg::LightTime(input, day))
|
||||||
},
|
]],
|
||||||
&name,
|
|
||||||
input_ev(Ev::Click, move |_| Msg::SetParam {
|
|
||||||
script,
|
|
||||||
name,
|
|
||||||
value: Param::Toggle(!value),
|
|
||||||
})
|
|
||||||
]
|
]
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
div![
|
div![
|
||||||
@ -307,35 +278,30 @@ impl Page for Model {
|
|||||||
],
|
],
|
||||||
],
|
],
|
||||||
div![
|
div![
|
||||||
C![C.prefs_box],
|
C![C.calendar_box],
|
||||||
IF!(selected_bulb.is_none() => C![C.cross_out]),
|
IF!(selected_bulb.is_none() => C![C.cross_out]),
|
||||||
h2!["Settings"],
|
h2!["Wake Schedule"],
|
||||||
if let Some(selected_bulb) = selected_bulb {
|
table![
|
||||||
table![selected_bulb
|
calendar_day(Weekday::Mon),
|
||||||
.prefs
|
calendar_day(Weekday::Tue),
|
||||||
.iter()
|
calendar_day(Weekday::Wed),
|
||||||
.flat_map(|(script, prefs)| repeat(script).zip(prefs.kvs.iter()))
|
calendar_day(Weekday::Thu),
|
||||||
.map(|(script, (name, value))| script_param(script, name, value))]
|
calendar_day(Weekday::Fri),
|
||||||
} else {
|
calendar_day(Weekday::Sat),
|
||||||
empty![]
|
calendar_day(Weekday::Sun),
|
||||||
},
|
],
|
||||||
],
|
],
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Model {
|
impl Model {
|
||||||
fn for_selected_bulbs(&mut self, mut f: impl FnMut(&BulbId, &mut BulbState)) {
|
fn for_selected_bulbs(&self, mut f: impl FnMut(&BulbId, &BulbState)) {
|
||||||
for &index in &self.selected_groups {
|
self.selected_groups
|
||||||
let Some(group) = self.bulb_map.groups.get(index) else {
|
.iter()
|
||||||
continue;
|
.filter_map(|&index| self.bulb_map.groups.get(index))
|
||||||
};
|
.flat_map(|group| group.bulbs.iter())
|
||||||
|
.filter_map(|id| self.bulb_states.get(id).map(|bulb| (id, bulb)))
|
||||||
for id in group.bulbs.iter() {
|
.for_each(|(id, bulb)| f(id, bulb));
|
||||||
if let Some(bulb) = self.bulb_states.get_mut(id) {
|
|
||||||
f(id, bulb);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -304,16 +304,14 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
.pref_input {
|
.calendar_time_input {
|
||||||
background: #453f4b;
|
background: #453f4b;
|
||||||
border: solid 0.35em #5b3f63;
|
border: solid 0.35em #5b3f63;
|
||||||
border-radius: .3em;
|
border-radius: .3em;
|
||||||
@ -325,49 +323,17 @@ body {
|
|||||||
margin-left: .5em;
|
margin-left: .5em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.pref_button {}
|
.calendar_box {
|
||||||
.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;
|
||||||
}
|
}
|
||||||
|
|
||||||
.prefs_box > h2 {
|
.calendar_box > h2 {
|
||||||
writing-mode: sideways-lr;
|
writing-mode: sideways-lr;
|
||||||
margin-top: auto;
|
margin-top: auto;
|
||||||
margin-bottom: auto;
|
margin-bottom: auto;
|
||||||
}
|
}
|
||||||
.prefs_box > * {
|
.calendar_box > * {
|
||||||
flex-shrink: 1;
|
flex-shrink: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user