Compare commits
1 Commits
0.3.0
...
589d8edf80
| Author | SHA1 | Date | |
|---|---|---|---|
|
589d8edf80
|
407
Cargo.lock
generated
407
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "hemma"
|
||||
version = "0.3.0"
|
||||
version = "0.2.3"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
@ -19,7 +19,6 @@ toml = "0.5.9"
|
||||
serde = { version = "1.0.138", features = ["derive"] }
|
||||
futures = "0.3.21"
|
||||
chrono = { version = "0.4.20", features = ["serde"] }
|
||||
rand = "0.8.5"
|
||||
|
||||
[dependencies.common]
|
||||
path = "../common"
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
mod collector;
|
||||
mod persistence;
|
||||
mod tasks;
|
||||
mod util;
|
||||
|
||||
use clap::Parser;
|
||||
use collector::CollectorConfig;
|
||||
|
||||
@ -1,22 +1,22 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use common::{BulbPrefs, ClientMessage, ScriptId, ServerMessage};
|
||||
use lighter_lib::BulbId;
|
||||
use chrono::{DateTime, Datelike, Local, NaiveTime, Weekday};
|
||||
use common::{ClientMessage, ServerMessage};
|
||||
use lighter_lib::{BulbColor, BulbId};
|
||||
use lighter_manager::manager::{BulbCommand, BulbManager, BulbSelector};
|
||||
use lighter_manager::provider::mqtt::BulbsMqtt;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::Duration;
|
||||
use tokio::select;
|
||||
use tokio::sync::{broadcast, mpsc};
|
||||
use tokio::task::{spawn, JoinHandle};
|
||||
use tokio::time::sleep;
|
||||
|
||||
use crate::persistence::PersistenceFile;
|
||||
use crate::State;
|
||||
|
||||
use self::scripts::{LightScript, Party, Waker};
|
||||
|
||||
pub mod scripts;
|
||||
use crate::{ClientRequest, State};
|
||||
|
||||
#[derive(Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct LightsState {
|
||||
script_prefs: HashMap<ScriptId, HashMap<BulbId, BulbPrefs>>,
|
||||
wake_schedule: HashMap<BulbId, HashMap<Weekday, NaiveTime>>,
|
||||
}
|
||||
|
||||
pub async fn lights_task(state: &State) {
|
||||
@ -29,43 +29,36 @@ pub async fn lights_task(state: &State) {
|
||||
.await
|
||||
.expect("Failed to open lights config");
|
||||
|
||||
let provider = BulbsMqtt::new(config.bulbs.clone(), config.mqtt.clone());
|
||||
let manager = BulbManager::launch(config.bulbs.clone(), provider)
|
||||
let (cmd, bulb_states) = BulbManager::launch(config.bulbs.clone(), config.mqtt.clone())
|
||||
.await
|
||||
.expect("Failed to launch bulb manager");
|
||||
|
||||
let mut scripts: HashMap<ScriptId, Box<dyn LightScript + Send>> = Default::default();
|
||||
scripts.insert(
|
||||
"waker".to_string(),
|
||||
Box::new(Waker::create(manager.clone())),
|
||||
);
|
||||
scripts.insert(
|
||||
"party".to_string(),
|
||||
Box::new(Party::create(manager.clone())),
|
||||
);
|
||||
let mut wake_tasks: HashMap<(BulbId, Weekday), JoinHandle<()>> = lights_state
|
||||
.get()
|
||||
.wake_schedule
|
||||
.iter()
|
||||
.flat_map(|(bulb, schedule)| schedule.iter().map(move |(day, time)| (bulb, day, time)))
|
||||
.map(|(bulb, day, time)| {
|
||||
let handle = spawn(wake_task(
|
||||
state.client_message.clone(),
|
||||
cmd.clone(),
|
||||
bulb.clone(),
|
||||
*day,
|
||||
*time,
|
||||
));
|
||||
|
||||
for (script, prefs) in &lights_state.get().script_prefs {
|
||||
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())
|
||||
}
|
||||
}
|
||||
}
|
||||
((bulb.clone(), *day), handle)
|
||||
})
|
||||
.collect();
|
||||
|
||||
loop {
|
||||
let notify = bulb_states.notify_on_change();
|
||||
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();
|
||||
|
||||
let msg = ServerMessage::BulbState { id, mode, prefs };
|
||||
_ = 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) {
|
||||
error!("broadcast channel error: {e}");
|
||||
return;
|
||||
@ -80,42 +73,58 @@ pub async fn lights_task(state: &State) {
|
||||
|
||||
match request.message {
|
||||
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 } => {
|
||||
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 => {
|
||||
if let Err(e) = request.response.send(ServerMessage::BulbMap(config.bulb_map.clone())).await {
|
||||
error!("GetBulbs response channel error: {e}");
|
||||
return;
|
||||
}
|
||||
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();
|
||||
|
||||
let msg = ServerMessage::BulbState { id, mode, prefs };
|
||||
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) = request.response.send(msg).await {
|
||||
error!("GetBulbs response channel error: {e}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
ClientMessage::SetBulbPref { bulb, script, name, value } => {
|
||||
let Some(s) = scripts.get_mut(&script) else {
|
||||
continue;
|
||||
ClientMessage::SetBulbWakeTime { id, day, time } => {
|
||||
if let Err(e) = lights_state.update(|lights_state| {
|
||||
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
|
||||
lights_state.update(move |state| {
|
||||
state.script_prefs
|
||||
.entry(script).or_default()
|
||||
.entry(bulb).or_default()
|
||||
.kvs.insert(name, value);
|
||||
}).await.expect("failed to persist lights state");
|
||||
if let Some(time) = time {
|
||||
let handle = spawn(wake_task(
|
||||
state.client_message.clone(),
|
||||
cmd.clone(),
|
||||
id.clone(),
|
||||
day,
|
||||
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]
|
||||
name = "common"
|
||||
version = "0.3.0"
|
||||
version = "0.2.3"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use chrono::{NaiveTime, Weekday};
|
||||
use lighter_lib::{BulbColor, BulbId, BulbMode};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@ -14,7 +15,7 @@ pub enum ServerMessage {
|
||||
BulbState {
|
||||
id: BulbId,
|
||||
mode: BulbMode,
|
||||
prefs: BTreeMap<ScriptId, BulbPrefs>,
|
||||
wake_schedule: HashMap<Weekday, NaiveTime>,
|
||||
},
|
||||
|
||||
BulbMap(BulbMap),
|
||||
@ -34,11 +35,10 @@ pub enum ClientMessage {
|
||||
id: BulbId,
|
||||
power: bool,
|
||||
},
|
||||
SetBulbPref {
|
||||
bulb: BulbId,
|
||||
script: ScriptId,
|
||||
name: String,
|
||||
value: Param,
|
||||
SetBulbWakeTime {
|
||||
id: BulbId,
|
||||
day: Weekday,
|
||||
time: Option<NaiveTime>,
|
||||
},
|
||||
}
|
||||
|
||||
@ -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]
|
||||
name = "hemma_web"
|
||||
version = "0.3.0"
|
||||
version = "0.2.3"
|
||||
authors = ["Joakim Hulthe <joakim@hulthe.net"]
|
||||
edition = "2021"
|
||||
|
||||
|
||||
@ -1,13 +1,13 @@
|
||||
use crate::components::color_picker::{ColorPicker, ColorPickerMsg};
|
||||
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 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_router::Page;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::fmt::Write;
|
||||
use std::iter::repeat;
|
||||
|
||||
/// /lights page
|
||||
#[derive(Default)]
|
||||
@ -28,7 +28,7 @@ pub struct Model {
|
||||
#[derive(Default, Clone)]
|
||||
struct BulbState {
|
||||
mode: BulbMode,
|
||||
prefs: BTreeMap<String, BulbPrefs>,
|
||||
wake_schedule: HashMap<Weekday, NaiveTime>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@ -39,13 +39,7 @@ pub enum Msg {
|
||||
DeselectGroups,
|
||||
ColorPicker(ColorPickerMsg),
|
||||
SetBulbPower(bool),
|
||||
|
||||
/// Set a script parameter value for all selected bulbs.
|
||||
SetParam {
|
||||
script: String,
|
||||
name: String,
|
||||
value: Param,
|
||||
},
|
||||
LightTime(String, Weekday),
|
||||
}
|
||||
|
||||
impl Page for Model {
|
||||
@ -64,11 +58,11 @@ impl Page for Model {
|
||||
ServerMessage::BulbState {
|
||||
id,
|
||||
mode: new_mode,
|
||||
prefs,
|
||||
wake_schedule,
|
||||
} => {
|
||||
*self.bulb_states.entry(id).or_default() = BulbState {
|
||||
mode: new_mode,
|
||||
prefs,
|
||||
wake_schedule,
|
||||
};
|
||||
|
||||
//color_picker.set_color(mode.color);
|
||||
@ -130,25 +124,26 @@ impl Page for Model {
|
||||
orders.notify(message);
|
||||
});
|
||||
}
|
||||
Msg::SetParam {
|
||||
script,
|
||||
name,
|
||||
value,
|
||||
} => {
|
||||
self.for_selected_bulbs(|id, bulb| {
|
||||
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);
|
||||
});
|
||||
Msg::LightTime(time, day) => {
|
||||
if time.is_empty() {
|
||||
self.for_selected_bulbs(|id, _| {
|
||||
let message = ClientMessage::SetBulbWakeTime {
|
||||
id: id.clone(),
|
||||
day,
|
||||
time: None,
|
||||
};
|
||||
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(|id| self.bulb_states.get(id));
|
||||
|
||||
let script_param = |script: &str, name: &str, value: &Param| {
|
||||
let name = name.to_string();
|
||||
let script = script.to_string();
|
||||
|
||||
match value {
|
||||
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![
|
||||
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),
|
||||
})
|
||||
]
|
||||
]
|
||||
}
|
||||
}
|
||||
let calendar_day = |day: Weekday| {
|
||||
let time = selected_bulb
|
||||
.and_then(|b| b.wake_schedule.get(&day))
|
||||
.map(|t| t.to_string())
|
||||
.unwrap_or_default();
|
||||
tr![
|
||||
C![C.calendar_day],
|
||||
td![day.to_string()],
|
||||
td![input![
|
||||
C![C.calendar_time_input],
|
||||
attrs! {At::Placeholder => time},
|
||||
input_ev(Ev::Input, move |input| Msg::LightTime(input, day))
|
||||
]],
|
||||
]
|
||||
};
|
||||
|
||||
div![
|
||||
@ -307,35 +278,30 @@ impl Page for Model {
|
||||
],
|
||||
],
|
||||
div![
|
||||
C![C.prefs_box],
|
||||
C![C.calendar_box],
|
||||
IF!(selected_bulb.is_none() => C![C.cross_out]),
|
||||
h2!["Settings"],
|
||||
if let Some(selected_bulb) = selected_bulb {
|
||||
table![selected_bulb
|
||||
.prefs
|
||||
.iter()
|
||||
.flat_map(|(script, prefs)| repeat(script).zip(prefs.kvs.iter()))
|
||||
.map(|(script, (name, value))| script_param(script, name, value))]
|
||||
} else {
|
||||
empty![]
|
||||
},
|
||||
h2!["Wake Schedule"],
|
||||
table![
|
||||
calendar_day(Weekday::Mon),
|
||||
calendar_day(Weekday::Tue),
|
||||
calendar_day(Weekday::Wed),
|
||||
calendar_day(Weekday::Thu),
|
||||
calendar_day(Weekday::Fri),
|
||||
calendar_day(Weekday::Sat),
|
||||
calendar_day(Weekday::Sun),
|
||||
],
|
||||
],
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
impl Model {
|
||||
fn for_selected_bulbs(&mut self, mut f: impl FnMut(&BulbId, &mut BulbState)) {
|
||||
for &index in &self.selected_groups {
|
||||
let Some(group) = self.bulb_map.groups.get(index) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
for id in group.bulbs.iter() {
|
||||
if let Some(bulb) = self.bulb_states.get_mut(id) {
|
||||
f(id, bulb);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn for_selected_bulbs(&self, mut f: impl FnMut(&BulbId, &BulbState)) {
|
||||
self.selected_groups
|
||||
.iter()
|
||||
.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_each(|(id, bulb)| f(id, bulb));
|
||||
}
|
||||
}
|
||||
|
||||
@ -304,16 +304,14 @@ body {
|
||||
|
||||
transition: margin 0.1s ease-out;
|
||||
}
|
||||
|
||||
|
||||
.pref_line {
|
||||
.calendar_day {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: space-between;
|
||||
margin-top: .3em;
|
||||
}
|
||||
|
||||
.pref_input {
|
||||
.calendar_time_input {
|
||||
background: #453f4b;
|
||||
border: solid 0.35em #5b3f63;
|
||||
border-radius: .3em;
|
||||
@ -325,49 +323,17 @@ body {
|
||||
margin-left: .5em;
|
||||
}
|
||||
|
||||
.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 {
|
||||
.calendar_box {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.prefs_box > h2 {
|
||||
.calendar_box > h2 {
|
||||
writing-mode: sideways-lr;
|
||||
margin-top: auto;
|
||||
margin-bottom: auto;
|
||||
}
|
||||
.prefs_box > * {
|
||||
.calendar_box > * {
|
||||
flex-shrink: 1;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user