Compare commits
20 Commits
2370faa718
...
0.3.1
| Author | SHA1 | Date | |
|---|---|---|---|
| c278e0f830 | |||
| 38f5dd1b71 | |||
|
714b31ea31
|
|||
|
9473d1139f
|
|||
|
d001ce4567
|
|||
|
f7ec98f8e3
|
|||
|
924a14cdcb
|
|||
|
d5a221e1a3
|
|||
|
b8e05e33a6
|
|||
|
362534384a
|
|||
|
fee9c7a171
|
|||
|
e458c69c80
|
|||
|
548e7d3240
|
|||
|
ac306eece4
|
|||
|
4cf6b628ee
|
|||
|
01a7576d7f
|
|||
|
1e55385645
|
|||
|
1ac0dbe210
|
|||
|
939e4d9785
|
|||
|
08bdeb693b
|
1169
Cargo.lock
generated
@ -1,6 +1,8 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = ["backend", "common", "frontend"]
|
members = ["backend", "common", "frontend"]
|
||||||
|
|
||||||
|
resolver = "2"
|
||||||
|
|
||||||
[profile.dev]
|
[profile.dev]
|
||||||
# Issue with const-generics
|
# Issue with const-generics
|
||||||
incremental = false
|
incremental = false
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
##################
|
##################
|
||||||
### BASE STAGE ###
|
### BASE STAGE ###
|
||||||
##################
|
##################
|
||||||
FROM rust:1.62.1 as base
|
FROM rust:1.72.1 as base
|
||||||
|
|
||||||
# Install build dependencies
|
# Install build dependencies
|
||||||
RUN cargo install --locked cargo-make trunk strip_cargo_version
|
RUN cargo install --locked cargo-make trunk strip_cargo_version
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "hemma"
|
name = "hemma"
|
||||||
version = "0.1.0"
|
version = "0.3.1"
|
||||||
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"
|
||||||
|
|||||||
@ -144,7 +144,7 @@ fn wind_speed_to_beaufort(mps: f64) -> BeaufortScale {
|
|||||||
let index = beaufort_wind_speeds
|
let index = beaufort_wind_speeds
|
||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.find_map(|(i, range)| range.contains(&mps).then(|| i))
|
.find_map(|(i, range)| range.contains(&mps).then_some(i))
|
||||||
.unwrap_or(beaufort_wind_speeds.len());
|
.unwrap_or(beaufort_wind_speeds.len());
|
||||||
|
|
||||||
BeaufortScale(index as u8)
|
BeaufortScale(index as u8)
|
||||||
|
|||||||
@ -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;
|
||||||
@ -32,7 +33,7 @@ struct Opt {
|
|||||||
#[clap(short, long)]
|
#[clap(short, long)]
|
||||||
quiet: bool,
|
quiet: bool,
|
||||||
|
|
||||||
#[clap(long, short, default_value = "127.0.0.0:8000")]
|
#[clap(long, short, default_value = "127.0.0.1:8000")]
|
||||||
bind: SocketAddr,
|
bind: SocketAddr,
|
||||||
|
|
||||||
#[clap(long, default_value = "./www")]
|
#[clap(long, default_value = "./www")]
|
||||||
|
|||||||
@ -1,22 +1,22 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use chrono::{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,37 +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.subscribe(),
|
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();
|
|
||||||
sleep(tokio::time::Duration::from_millis(1000 / 10)).await; // limit to 10 updates/second
|
|
||||||
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;
|
||||||
@ -74,59 +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 {
|
|
||||||
let handle = spawn(wake_task(
|
// TODO handle error
|
||||||
state.client_message.subscribe(),
|
lights_state.update(move |state| {
|
||||||
cmd.clone(),
|
state.script_prefs
|
||||||
id.clone(),
|
.entry(script).or_default()
|
||||||
day,
|
.entry(bulb).or_default()
|
||||||
time,
|
.kvs.insert(name, value);
|
||||||
));
|
}).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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
@ -134,79 +123,3 @@ pub async fn lights_task(state: &State) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn wake_task(
|
|
||||||
mut client_messages: broadcast::Receiver<ClientRequest>,
|
|
||||||
cmd: mpsc::Sender<BulbCommand>,
|
|
||||||
id: BulbId,
|
|
||||||
day: Weekday,
|
|
||||||
time: NaiveTime,
|
|
||||||
) {
|
|
||||||
let now = Local::now();
|
|
||||||
let day_num = day.num_days_from_monday();
|
|
||||||
let now_day = now.weekday();
|
|
||||||
let now_day_num = now_day.num_days_from_monday();
|
|
||||||
|
|
||||||
let mut alarm = now;
|
|
||||||
if day_num >= now_day_num {
|
|
||||||
// next alarm is this week
|
|
||||||
alarm += chrono::Duration::days((day_num - now_day_num).into());
|
|
||||||
alarm = alarm.date().and_time(time).unwrap();
|
|
||||||
} else {
|
|
||||||
// next alarm is next week
|
|
||||||
alarm += chrono::Duration::weeks(1);
|
|
||||||
alarm -= chrono::Duration::days((now_day_num - day_num).into());
|
|
||||||
alarm = alarm.date().and_time(time).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
loop {
|
|
||||||
info!("sleeping until {alarm}");
|
|
||||||
sleep((alarm - Local::now()).to_std().unwrap()).await;
|
|
||||||
alarm += chrono::Duration::weeks(1);
|
|
||||||
|
|
||||||
// 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, &mut client_messages) => 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;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wait until we receive a client request that mutates the given bulb
|
|
||||||
async fn wait_for_bulb_command(
|
|
||||||
bulb_id: &BulbId,
|
|
||||||
client_messages: &mut 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,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
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
@ -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
@ -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
@ -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.1.0"
|
version = "0.3.1"
|
||||||
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,20 +1,17 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "hemma_web"
|
name = "hemma_web"
|
||||||
version = "0.1.0"
|
version = "0.3.1"
|
||||||
authors = ["Joakim Hulthe <joakim@hulthe.net"]
|
authors = ["Joakim Hulthe <joakim@hulthe.net"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[lib]
|
|
||||||
crate-type = ["cdylib"]
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
seed = "0.9.1"
|
seed = "0.10.0"
|
||||||
wasm-bindgen = "=0.2.80" # 0.2.81 has a breaking change
|
wasm-bindgen = "=0.2.87" # must match Trunk.toml
|
||||||
serde = { version = "1", features = ['derive'] }
|
serde = { version = "1.0.0", features = ['derive'] }
|
||||||
serde_json = "1"
|
|
||||||
anyhow = "*"
|
|
||||||
ron = "0.7.1"
|
ron = "0.7.1"
|
||||||
chrono = { version = "0.4.20", features = ["serde"] }
|
chrono = { version = "0.4.20", features = ["serde"] }
|
||||||
|
gloo-net = { version = "0.4.0", default-features = false, features = ["websocket"] }
|
||||||
|
gloo-console = "0.3.0"
|
||||||
|
|
||||||
[dependencies.css_typegen]
|
[dependencies.css_typegen]
|
||||||
git = "https://github.com/hulthe/css_typegen.git"
|
git = "https://github.com/hulthe/css_typegen.git"
|
||||||
|
|||||||
@ -1,12 +1,13 @@
|
|||||||
[serve]
|
[serve]
|
||||||
address = "0.0.0.0"
|
address = "0.0.0.0"
|
||||||
|
|
||||||
|
[tools]
|
||||||
|
wasm_bindgen = "0.2.87"
|
||||||
|
|
||||||
[[proxy]]
|
[[proxy]]
|
||||||
# This WebSocket proxy example has a backend and ws field. This example will listen for
|
# This WebSocket proxy example has a backend and ws field. This example will listen for
|
||||||
# WebSocket connections at `/api/ws` and proxy them to `ws://localhost:9000/api/ws`.
|
# WebSocket connections at `/api/ws` and proxy them to `ws://localhost:9000/api/ws`.
|
||||||
backend = "ws://localhost:8000/api/ws"
|
backend = "ws://127.0.0.1:8000/api/ws"
|
||||||
ws = true
|
ws = true
|
||||||
|
|
||||||
#[[proxy]]
|
#[[proxy]]
|
||||||
|
|||||||
@ -12,10 +12,8 @@
|
|||||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu|Ubuntu+Mono&display=swap">
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu|Ubuntu+Mono&display=swap">
|
||||||
|
|
||||||
<!-- pwa manifest -->
|
<!-- pwa manifest -->
|
||||||
<!--
|
|
||||||
<link data-trunk rel="copy-file" href="/static/manifest.json">
|
<link data-trunk rel="copy-file" href="/static/manifest.json">
|
||||||
<link rel="manifest" href="/static/manifest.json">
|
<link rel="manifest" href="/manifest.json">
|
||||||
-->
|
|
||||||
|
|
||||||
<!-- copy image directory -->
|
<!-- copy image directory -->
|
||||||
<link data-trunk rel="copy-dir" href="/static/images">
|
<link data-trunk rel="copy-dir" href="/static/images">
|
||||||
@ -26,7 +24,7 @@
|
|||||||
<link rel="preload" href="/images/penguin3.svg" as="image">
|
<link rel="preload" href="/images/penguin3.svg" as="image">
|
||||||
|
|
||||||
<!-- icon -->
|
<!-- icon -->
|
||||||
<link rel="icon" type="image/png" href="/images/icon.png">
|
<link rel="icon" type="image/png" href="/images/penguin2.svg">
|
||||||
|
|
||||||
<title>hemma</title>
|
<title>hemma</title>
|
||||||
<meta name="description" content="Home automation and information">
|
<meta name="description" content="Home automation and information">
|
||||||
|
|||||||
4
frontend/rust-toolchain.toml
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
[toolchain]
|
||||||
|
channel = "stable"
|
||||||
|
components = ["rust-src", "rustfmt", "rust-src"]
|
||||||
|
targets = ["wasm32-unknown-unknown"]
|
||||||
@ -1,10 +1,20 @@
|
|||||||
use crate::page;
|
use crate::page;
|
||||||
use common::{ClientMessage, ServerMessage};
|
use common::{ClientMessage, ServerMessage};
|
||||||
|
use gloo_console::error;
|
||||||
|
use gloo_net::websocket;
|
||||||
|
use gloo_net::websocket::futures::WebSocket;
|
||||||
use seed::app::orders::OrdersContainer;
|
use seed::app::orders::OrdersContainer;
|
||||||
|
use seed::futures::channel::mpsc::channel;
|
||||||
|
use seed::futures::channel::mpsc::Sender;
|
||||||
|
use seed::futures::select_biased;
|
||||||
|
use seed::futures::SinkExt;
|
||||||
|
use seed::futures::StreamExt;
|
||||||
use seed::prelude::*;
|
use seed::prelude::*;
|
||||||
use seed::{log, window};
|
use seed::window;
|
||||||
|
use seed::FutureExt;
|
||||||
use seed_router::Router;
|
use seed_router::Router;
|
||||||
use std::collections::VecDeque;
|
use std::collections::VecDeque;
|
||||||
|
use std::error::Error;
|
||||||
|
|
||||||
pub type AppOrders = OrdersContainer<Msg, Model, Vec<Node<Msg>>>;
|
pub type AppOrders = OrdersContainer<Msg, Model, Vec<Node<Msg>>>;
|
||||||
|
|
||||||
@ -14,8 +24,16 @@ const TIMEOUT_CONNECT_DELAYS: &[u32] = &[2, 5, 10, 10, 10, 20, 30, 60, 120, 300]
|
|||||||
pub struct Model {
|
pub struct Model {
|
||||||
page: Pages,
|
page: Pages,
|
||||||
send_queue: VecDeque<ClientMessage>,
|
send_queue: VecDeque<ClientMessage>,
|
||||||
socket: WebSocket,
|
|
||||||
|
/// Websocket URL
|
||||||
ws_url: String,
|
ws_url: String,
|
||||||
|
|
||||||
|
/// Channel to send websocket messages.
|
||||||
|
socket: Option<Sender<websocket::Message>>,
|
||||||
|
|
||||||
|
/// Handle to the websocket task.
|
||||||
|
socket_task: Option<CmdHandle>,
|
||||||
|
|
||||||
timeout_count: usize,
|
timeout_count: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -47,14 +65,14 @@ pub enum Msg {
|
|||||||
|
|
||||||
// Global
|
// Global
|
||||||
Connect,
|
Connect,
|
||||||
SocketOpened(),
|
SocketOpened(Sender<websocket::Message>),
|
||||||
SocketClosed(CloseEvent),
|
SocketClosed,
|
||||||
SocketError(),
|
SocketMessage(websocket::Message),
|
||||||
SocketMessage(WebSocketMessage),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn init(url: Url, orders: &mut impl Orders<Msg>) -> Model {
|
pub fn init(url: Url, orders: &mut impl Orders<Msg>) -> Model {
|
||||||
orders.subscribe(Msg::SendMessage);
|
orders.subscribe(Msg::SendMessage);
|
||||||
|
orders.send_msg(Msg::Connect);
|
||||||
|
|
||||||
let location = window().location();
|
let location = window().location();
|
||||||
let host = location.host().expect("Failed to get hostname");
|
let host = location.host().expect("Failed to get hostname");
|
||||||
@ -69,73 +87,109 @@ pub fn init(url: Url, orders: &mut impl Orders<Msg>) -> Model {
|
|||||||
page: Pages::from_url(url, &mut orders.proxy(Msg::Page))
|
page: Pages::from_url(url, &mut orders.proxy(Msg::Page))
|
||||||
.unwrap_or(Pages::NotFound(Default::default())),
|
.unwrap_or(Pages::NotFound(Default::default())),
|
||||||
send_queue: Default::default(),
|
send_queue: Default::default(),
|
||||||
socket: open_socket(&ws_url, orders),
|
|
||||||
ws_url,
|
ws_url,
|
||||||
|
socket_task: None,
|
||||||
|
socket: None,
|
||||||
timeout_count: 0,
|
timeout_count: 0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn open_socket(url: &str, orders: &mut impl Orders<Msg>) -> WebSocket {
|
fn open_socket(url: String, orders: &mut impl Orders<Msg>) -> CmdHandle {
|
||||||
WebSocket::builder(url, orders)
|
let update_fn = orders.msg_sender();
|
||||||
.on_open(Msg::SocketOpened)
|
|
||||||
.on_close(Msg::SocketClosed)
|
orders.perform_cmd_with_handle(async move {
|
||||||
.on_error(Msg::SocketError)
|
let mut ws = WebSocket::open(&url).expect("Failed to open websocket");
|
||||||
.on_message(Msg::SocketMessage)
|
let (tx, mut rx) = channel(128);
|
||||||
.build_and_open()
|
update_fn(Some(Msg::SocketOpened(tx)));
|
||||||
.expect("failed to open websocket")
|
|
||||||
|
loop {
|
||||||
|
select_biased! {
|
||||||
|
message = rx.next().fuse() => {
|
||||||
|
let Some(message) = message else { return; };
|
||||||
|
if let Err(e) = ws.send(message).await {
|
||||||
|
error!(format!("websocket error: {e:?}"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
message = ws.next().fuse() => match message {
|
||||||
|
Some(Ok(message)) => update_fn(Some(Msg::SocketMessage(message))),
|
||||||
|
Some(Err(e)) => {
|
||||||
|
error!(format!("websocket error: {e:?}"));
|
||||||
|
update_fn(Some(Msg::SocketClosed));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
update_fn(Some(Msg::SocketClosed));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update(msg: Msg, model: &mut Model, orders: &mut AppOrders) {
|
pub fn update(msg: Msg, model: &mut Model, orders: &mut AppOrders) {
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
log!(format!("{msg:?}"));
|
gloo_console::debug!(format!("{msg:?}"));
|
||||||
|
|
||||||
match msg {
|
match msg {
|
||||||
Msg::Page(msg) => model.page.update(msg, &mut orders.proxy(Msg::Page)),
|
Msg::Page(msg) => model.page.update(msg, &mut orders.proxy(Msg::Page)),
|
||||||
Msg::FlushMessageQueue => {
|
Msg::FlushMessageQueue => {
|
||||||
while let Some(message) = model.send_queue.pop_front() {
|
if let Some(socket) = model.socket.as_mut() {
|
||||||
let serialized = ron::to_string(&message).unwrap();
|
while let Some(message) = model.send_queue.pop_front() {
|
||||||
|
let serialized = ron::to_string(&message).expect("failed to serialize ron");
|
||||||
|
|
||||||
if let Err(e) = model.socket.send_text(serialized) {
|
let ws_message = websocket::Message::Text(serialized);
|
||||||
model.send_queue.push_front(message);
|
if socket.try_send(ws_message).is_err() {
|
||||||
log!(e);
|
error!("websocket queue full");
|
||||||
return;
|
model.send_queue.push_front(message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Msg::Connect => {
|
Msg::Connect => {
|
||||||
model.socket = open_socket(&model.ws_url, orders);
|
model.socket_task = Some(open_socket(model.ws_url.clone(), orders));
|
||||||
}
|
}
|
||||||
Msg::SendMessage(message) => {
|
Msg::SendMessage(message) => {
|
||||||
model.send_queue.push_back(message);
|
model.send_queue.push_back(message);
|
||||||
orders.send_msg(Msg::FlushMessageQueue);
|
orders.send_msg(Msg::FlushMessageQueue);
|
||||||
}
|
}
|
||||||
Msg::SocketOpened() => {
|
Msg::SocketOpened(socket) => {
|
||||||
|
model.socket = Some(socket);
|
||||||
model.timeout_count = 0;
|
model.timeout_count = 0;
|
||||||
orders.send_msg(Msg::FlushMessageQueue);
|
orders.send_msg(Msg::FlushMessageQueue);
|
||||||
}
|
}
|
||||||
Msg::SocketClosed(_event) => {
|
Msg::SocketClosed => {
|
||||||
|
model.socket_task = None;
|
||||||
|
model.socket = None;
|
||||||
|
|
||||||
let timeout_sec = TIMEOUT_CONNECT_DELAYS[model.timeout_count];
|
let timeout_sec = TIMEOUT_CONNECT_DELAYS[model.timeout_count];
|
||||||
let timeout_ms = timeout_sec * 1000;
|
let timeout_ms = timeout_sec * 1000;
|
||||||
orders.perform_cmd(cmds::timeout(timeout_ms, || Msg::Connect));
|
orders.perform_cmd(cmds::timeout(timeout_ms, || Msg::Connect));
|
||||||
|
|
||||||
log!(format!(
|
error!(format!(
|
||||||
"Socket closed, trying to reconnect in {timeout_sec} seconds"
|
"Socket closed, trying to reconnect in {timeout_sec} seconds"
|
||||||
));
|
));
|
||||||
|
|
||||||
model.timeout_count = TIMEOUT_CONNECT_DELAYS.len().min(model.timeout_count + 1);
|
model.timeout_count = TIMEOUT_CONNECT_DELAYS.len().min(model.timeout_count + 1);
|
||||||
}
|
}
|
||||||
Msg::SocketError() => {}
|
|
||||||
Msg::SocketMessage(message) => {
|
Msg::SocketMessage(message) => {
|
||||||
if let Err(e) = handle_ws_msg(message, orders) {
|
if let Err(e) = handle_ws_msg(message, orders) {
|
||||||
log!(e);
|
error!(format!("{e:?}"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_ws_msg(message: WebSocketMessage, orders: &mut impl Orders<Msg>) -> anyhow::Result<()> {
|
fn handle_ws_msg(
|
||||||
let message = message.text().map_err(|e| anyhow::format_err!("{e:?}"))?;
|
message: websocket::Message,
|
||||||
let message: ServerMessage = ron::from_str(&message)?;
|
orders: &mut impl Orders<Msg>,
|
||||||
|
) -> Result<(), Box<dyn Error>> {
|
||||||
|
let websocket::Message::Text(text) = &message else {
|
||||||
|
return Err("Server is sending us raw bytes on the websocket! Argh!".into());
|
||||||
|
};
|
||||||
|
let message: ServerMessage = ron::from_str(text)?;
|
||||||
orders.notify(message);
|
orders.notify(message);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@ -143,9 +197,4 @@ fn handle_ws_msg(message: WebSocketMessage, orders: &mut impl Orders<Msg>) -> an
|
|||||||
|
|
||||||
pub fn view(model: &Model) -> Vec<Node<Msg>> {
|
pub fn view(model: &Model) -> Vec<Node<Msg>> {
|
||||||
vec![model.page.view().map_msg(Msg::Page)]
|
vec![model.page.view().map_msg(Msg::Page)]
|
||||||
//match &model.page {
|
|
||||||
// Pages::NotFound => vec![h1!["Not Found"]],
|
|
||||||
// Pages::InfoScreen => vec![div![C![C.info_box], raw![&model.info_page]]],
|
|
||||||
// Pages::Lights(page) => vec![],
|
|
||||||
//}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -19,7 +19,7 @@ pub struct ColorPicker {
|
|||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
enum ColorPickerSetting {
|
enum ColorPickerSetting {
|
||||||
#[default]
|
#[default]
|
||||||
HSB,
|
Hsb,
|
||||||
Kelvin,
|
Kelvin,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -55,14 +55,14 @@ impl ColorPicker {
|
|||||||
}
|
}
|
||||||
|
|
||||||
match self.dragging.take() {
|
match self.dragging.take() {
|
||||||
Some(ColorPickerAttr::HueSat) => self.mode = ColorPickerSetting::HSB,
|
Some(ColorPickerAttr::HueSat) => self.mode = ColorPickerSetting::Hsb,
|
||||||
Some(ColorPickerAttr::Brightness) => {}
|
Some(ColorPickerAttr::Brightness) => {}
|
||||||
Some(ColorPickerAttr::Temperature) => self.mode = ColorPickerSetting::Kelvin,
|
Some(ColorPickerAttr::Temperature) => self.mode = ColorPickerSetting::Kelvin,
|
||||||
None => return,
|
None => return,
|
||||||
}
|
}
|
||||||
|
|
||||||
let color = match self.mode {
|
let color = match self.mode {
|
||||||
ColorPickerSetting::HSB => {
|
ColorPickerSetting::Hsb => {
|
||||||
BulbColor::hsb(self.hue, self.saturation, self.brightness)
|
BulbColor::hsb(self.hue, self.saturation, self.brightness)
|
||||||
}
|
}
|
||||||
ColorPickerSetting::Kelvin => {
|
ColorPickerSetting::Kelvin => {
|
||||||
@ -130,10 +130,12 @@ impl ColorPicker {
|
|||||||
|
|
||||||
let (r, g, b) = hsb_to_rgb(self.hue, 1.0, 1.0);
|
let (r, g, b) = hsb_to_rgb(self.hue, 1.0, 1.0);
|
||||||
let saturation_gradient = match self.mode {
|
let saturation_gradient = match self.mode {
|
||||||
ColorPickerSetting::HSB => {
|
ColorPickerSetting::Hsb => {
|
||||||
format!("background: linear-gradient(0deg, #000, rgba({r},{g},{b},1));")
|
format!("background: linear-gradient(0deg, #000, rgba({r},{g},{b},1));")
|
||||||
}
|
}
|
||||||
ColorPickerSetting::Kelvin => format!("background: linear-gradient(0deg, #000, #fff);"),
|
ColorPickerSetting::Kelvin => {
|
||||||
|
"background: linear-gradient(0deg, #000, #fff);".to_string()
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
div![
|
div![
|
||||||
@ -186,7 +188,7 @@ impl ColorPicker {
|
|||||||
self.hue = h;
|
self.hue = h;
|
||||||
self.saturation = s;
|
self.saturation = s;
|
||||||
self.brightness = b;
|
self.brightness = b;
|
||||||
self.mode = ColorPickerSetting::HSB;
|
self.mode = ColorPickerSetting::Hsb;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_kelvin(&mut self, t: f32, b: f32) {
|
pub fn set_kelvin(&mut self, t: f32, b: f32) {
|
||||||
|
|||||||
@ -3,10 +3,8 @@ mod components;
|
|||||||
mod css;
|
mod css;
|
||||||
mod page;
|
mod page;
|
||||||
|
|
||||||
use seed::prelude::wasm_bindgen;
|
|
||||||
use seed::App;
|
use seed::App;
|
||||||
|
|
||||||
#[wasm_bindgen(start)]
|
pub fn main() {
|
||||||
pub fn start() {
|
|
||||||
App::start("app", app::init, app::update, app::view);
|
App::start("app", app::init, app::update, app::view);
|
||||||
}
|
}
|
||||||
@ -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::prelude::*;
|
use seed::{attrs, button, div, empty, h2, input, table, td, tr, C};
|
||||||
use seed::{attrs, button, div, input, C};
|
use seed::{prelude::*, IF};
|
||||||
use seed_router::Page;
|
use seed_router::Page;
|
||||||
use std::collections::{BTreeMap, HashSet, HashMap};
|
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)]
|
||||||
@ -23,13 +23,12 @@ pub struct Model {
|
|||||||
groups_interacted: bool,
|
groups_interacted: bool,
|
||||||
|
|
||||||
color_picker: ColorPicker,
|
color_picker: ColorPicker,
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[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)]
|
||||||
@ -40,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 {
|
||||||
@ -56,10 +61,14 @@ impl Page for Model {
|
|||||||
fn update(&mut self, msg: Self::Msg, orders: &mut impl Orders<Self::Msg>) {
|
fn update(&mut self, msg: Self::Msg, orders: &mut impl Orders<Self::Msg>) {
|
||||||
match msg {
|
match msg {
|
||||||
Msg::ServerMessage(msg) => match msg {
|
Msg::ServerMessage(msg) => match msg {
|
||||||
ServerMessage::BulbState { id, mode: new_mode, wake_schedule } => {
|
ServerMessage::BulbState {
|
||||||
|
id,
|
||||||
|
mode: new_mode,
|
||||||
|
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);
|
||||||
@ -109,7 +118,7 @@ impl Page for Model {
|
|||||||
}
|
}
|
||||||
Msg::ColorPicker(msg) => {
|
Msg::ColorPicker(msg) => {
|
||||||
self.color_picker
|
self.color_picker
|
||||||
.update(msg, &mut orders.proxy(|msg| Msg::ColorPicker(msg)));
|
.update(msg, &mut orders.proxy(Msg::ColorPicker));
|
||||||
}
|
}
|
||||||
Msg::SetBulbPower(power) => {
|
Msg::SetBulbPower(power) => {
|
||||||
self.groups_interacted = true;
|
self.groups_interacted = true;
|
||||||
@ -121,180 +130,212 @@ impl Page for Model {
|
|||||||
orders.notify(message);
|
orders.notify(message);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Msg::LightTime(time, day) => {
|
Msg::SetParam {
|
||||||
if time == "" {
|
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)
|
||||||
orders.notify(message);
|
.unwrap() //TOD
|
||||||
});
|
.kvs
|
||||||
}
|
.insert(name.clone(), value.clone());
|
||||||
else if let Ok(time) = NaiveTime::parse_from_str(&time, "%H:%M") {
|
let message = ClientMessage::SetBulbPref {
|
||||||
self.for_selected_bulbs(|id, _| {
|
bulb: id.clone(),
|
||||||
let message = ClientMessage::SetBulbWakeTime {
|
script: script.clone(),
|
||||||
id: id.clone(),
|
name: name.clone(),
|
||||||
day,
|
value: value.clone(),
|
||||||
time: Some(time),
|
};
|
||||||
};
|
orders.notify(message);
|
||||||
orders.notify(message);
|
});
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn view(&self) -> Node<Self::Msg> {
|
||||||
|
//let view_bulb = |(id, (mode, color_picker)): (&BulbId, &(BulbMode, ColorPicker))| {
|
||||||
|
// div![
|
||||||
|
// C![C.bulb_box],
|
||||||
|
// h1![id],
|
||||||
|
// div![
|
||||||
|
// C![C.bulb_controls],
|
||||||
|
// {
|
||||||
|
// let id = id.clone();
|
||||||
|
// color_picker.view().map_msg(|msg| Msg::ColorPicker(id, msg))
|
||||||
|
// },
|
||||||
|
// button![
|
||||||
|
// if mode.power {
|
||||||
|
// C![C.bulb_power_button, C.bulb_power_button_on]
|
||||||
|
// } else {
|
||||||
|
// C![C.bulb_power_button]
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// let id = id.clone();
|
||||||
|
// let power = !mode.power;
|
||||||
|
// ev(Ev::Click, move |_| Msg::SetBulbPower(id, power))
|
||||||
|
// },
|
||||||
|
// ],
|
||||||
|
// ],
|
||||||
|
// ]
|
||||||
|
//};
|
||||||
|
|
||||||
fn view(&self) -> Node<Self::Msg> {
|
let bulb_map_width = self
|
||||||
//let view_bulb = |(id, (mode, color_picker)): (&BulbId, &(BulbMode, ColorPicker))| {
|
.bulb_map
|
||||||
// div![
|
.groups
|
||||||
// C![C.bulb_box],
|
.iter()
|
||||||
// h1![id],
|
.map(|group| group.x + group.shape.width())
|
||||||
// div![
|
.max()
|
||||||
// C![C.bulb_controls],
|
.unwrap_or(0);
|
||||||
// {
|
|
||||||
// let id = id.clone();
|
|
||||||
// color_picker.view().map_msg(|msg| Msg::ColorPicker(id, msg))
|
|
||||||
// },
|
|
||||||
// button![
|
|
||||||
// if mode.power {
|
|
||||||
// C![C.bulb_power_button, C.bulb_power_button_on]
|
|
||||||
// } else {
|
|
||||||
// C![C.bulb_power_button]
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// let id = id.clone();
|
|
||||||
// let power = !mode.power;
|
|
||||||
// ev(Ev::Click, move |_| Msg::SetBulbPower(id, power))
|
|
||||||
// },
|
|
||||||
// ],
|
|
||||||
// ],
|
|
||||||
// ]
|
|
||||||
//};
|
|
||||||
|
|
||||||
let bulb_map_width = self
|
let bulb_map_height = self
|
||||||
.bulb_map
|
.bulb_map
|
||||||
.groups
|
.groups
|
||||||
.iter()
|
.iter()
|
||||||
.map(|group| group.x + group.shape.width())
|
.map(|group| group.y + group.shape.height())
|
||||||
.max()
|
.max()
|
||||||
.unwrap_or(0);
|
.unwrap_or(0);
|
||||||
|
|
||||||
let bulb_map_height = self
|
let view_bulb_group = |(i, group): (usize, &BulbGroup)| {
|
||||||
.bulb_map
|
let (w, h) = (group.shape.width(), group.shape.height());
|
||||||
.groups
|
let mut style = String::new();
|
||||||
.iter()
|
write!(
|
||||||
.map(|group| group.y + group.shape.height())
|
&mut style,
|
||||||
.max()
|
"margin-left: {}rem; margin-top: {}rem; width: {}rem; height: {}rem;",
|
||||||
.unwrap_or(0);
|
group.x, group.y, w, h
|
||||||
|
)
|
||||||
|
.ok();
|
||||||
|
|
||||||
let view_bulb_group = |(i, group): (usize, &BulbGroup)| {
|
if let BulbGroupShape::Circle { r } = group.shape {
|
||||||
let (w, h) = (group.shape.width(), group.shape.height());
|
write!(&mut style, " border-radius: {r}rem;").ok();
|
||||||
let mut style = String::new();
|
}
|
||||||
write!(
|
|
||||||
&mut style,
|
|
||||||
"margin-left: {}rem; margin-top: {}rem; width: {}rem; height: {}rem;",
|
|
||||||
group.x, group.y, w, h
|
|
||||||
)
|
|
||||||
.ok();
|
|
||||||
|
|
||||||
if let BulbGroupShape::Circle { r } = group.shape {
|
div![
|
||||||
write!(&mut style, " border-radius: {r}rem;").ok();
|
&group.name[..1],
|
||||||
}
|
if self.selected_groups.contains(&i) {
|
||||||
|
C![C.bulb_group, C.bulb_group_selected]
|
||||||
div![
|
|
||||||
&group.name[..1],
|
|
||||||
if self.selected_groups.contains(&i) {
|
|
||||||
C![C.bulb_group, C.bulb_group_selected]
|
|
||||||
} else {
|
|
||||||
C![C.bulb_group]
|
|
||||||
},
|
|
||||||
attrs! {
|
|
||||||
At::Style => style,
|
|
||||||
},
|
|
||||||
ev(Ev::Click, move |event| {
|
|
||||||
event.stop_propagation();
|
|
||||||
Msg::SelectGroup(i)
|
|
||||||
}),
|
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
let selected_bulb = self
|
|
||||||
.selected_groups
|
|
||||||
.iter()
|
|
||||||
.next()
|
|
||||||
.and_then(|&index| self.bulb_map.groups.get(index))
|
|
||||||
.and_then(|group| group.bulbs.first())
|
|
||||||
.and_then(|id| self.bulb_states.get(id))
|
|
||||||
.cloned() // TODO: remove clone
|
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
let calendar_day = |day: Weekday| {
|
|
||||||
let time = selected_bulb.wake_schedule.get(&day).map(|t| t.to_string()).unwrap_or_default();
|
|
||||||
div![
|
|
||||||
C![C.calendar_day],
|
|
||||||
day.to_string(),
|
|
||||||
input![
|
|
||||||
C![C.calendar_time_input],
|
|
||||||
attrs! {At::Placeholder => time},
|
|
||||||
input_ev(Ev::Input, move |input| Msg::LightTime(input, day))
|
|
||||||
],
|
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
div![
|
|
||||||
C![C.bulb_box],
|
|
||||||
div![
|
|
||||||
C![C.bulb_map],
|
|
||||||
attrs! {
|
|
||||||
At::Style => format!("width: {}rem; height: {}rem;", bulb_map_width, bulb_map_height),
|
|
||||||
},
|
|
||||||
ev(Ev::Click, |_| Msg::DeselectGroups),
|
|
||||||
self.bulb_map.groups.iter().enumerate().map(view_bulb_group),
|
|
||||||
],
|
|
||||||
div![
|
|
||||||
C![C.bulb_controls],
|
|
||||||
self.color_picker
|
|
||||||
.view()
|
|
||||||
.map_msg(|msg| Msg::ColorPicker(msg)),
|
|
||||||
button![
|
|
||||||
if selected_bulb.mode.power {
|
|
||||||
C![C.bulb_power_button, C.bulb_power_button_on]
|
|
||||||
} else {
|
} else {
|
||||||
C![C.bulb_power_button]
|
C![C.bulb_group]
|
||||||
},
|
},
|
||||||
ev(Ev::Click, move |_| Msg::SetBulbPower(!selected_bulb.mode.power)),
|
attrs! {
|
||||||
div![attrs! { At::Id => "switch_socket" }],
|
At::Style => style,
|
||||||
div![attrs! { At::Id => "off_label" }, "Off"],
|
},
|
||||||
div![attrs! { At::Id => "on_label" }, "On"],
|
ev(Ev::Click, move |event| {
|
||||||
div![attrs! { At::Id => "lever_stem" }],
|
event.stop_propagation();
|
||||||
div![attrs! { At::Id => "lever_face" }],
|
Msg::SelectGroup(i)
|
||||||
],
|
}),
|
||||||
],
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
let selected_bulb = self
|
||||||
|
.selected_groups
|
||||||
|
.iter()
|
||||||
|
.next()
|
||||||
|
.and_then(|&index| self.bulb_map.groups.get(index))
|
||||||
|
.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),
|
||||||
|
})
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
div![
|
div![
|
||||||
C![C.calendar_box],
|
C![C.bulb_box],
|
||||||
calendar_day(Weekday::Mon),
|
div![
|
||||||
calendar_day(Weekday::Tue),
|
C![C.bulb_map],
|
||||||
calendar_day(Weekday::Wed),
|
attrs! {
|
||||||
calendar_day(Weekday::Thu),
|
At::Style => format!("min-width: {}rem; height: {}rem;", bulb_map_width, bulb_map_height),
|
||||||
calendar_day(Weekday::Fri),
|
},
|
||||||
calendar_day(Weekday::Sat),
|
ev(Ev::Click, |_| Msg::DeselectGroups),
|
||||||
calendar_day(Weekday::Sun),
|
self.bulb_map.groups.iter().enumerate().map(view_bulb_group),
|
||||||
],
|
],
|
||||||
]
|
div![
|
||||||
}
|
C![C.bulb_controls],
|
||||||
|
IF!(selected_bulb.is_none() => C![C.cross_out]),
|
||||||
|
self.color_picker.view().map_msg(Msg::ColorPicker),
|
||||||
|
button![
|
||||||
|
if selected_bulb.map(|b| b.mode.power).unwrap_or(false) {
|
||||||
|
C![C.bulb_power_button, C.bulb_power_button_on]
|
||||||
|
} else {
|
||||||
|
C![C.bulb_power_button]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
let target_power = selected_bulb.map(|b| !b.mode.power);
|
||||||
|
ev(Ev::Click, move |_| target_power.map(Msg::SetBulbPower))
|
||||||
|
},
|
||||||
|
div![attrs! { At::Id => "switch_socket" }],
|
||||||
|
div![attrs! { At::Id => "off_label" }, "Off"],
|
||||||
|
div![attrs! { At::Id => "on_label" }, "On"],
|
||||||
|
div![attrs! { At::Id => "lever_stem" }],
|
||||||
|
div![attrs! { At::Id => "lever_face" }],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
div![
|
||||||
|
C![C.prefs_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![]
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
52
frontend/static/images/icon.svg
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||||
|
<svg
|
||||||
|
width="160"
|
||||||
|
height="160"
|
||||||
|
viewBox="0 0 42.333333 42.333333"
|
||||||
|
version="1.1"
|
||||||
|
id="svg8"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
xmlns:svg="http://www.w3.org/2000/svg"
|
||||||
|
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||||
|
xmlns:cc="http://creativecommons.org/ns#"
|
||||||
|
xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||||
|
<defs
|
||||||
|
id="defs2" />
|
||||||
|
<metadata
|
||||||
|
id="metadata5">
|
||||||
|
<rdf:RDF>
|
||||||
|
<cc:Work
|
||||||
|
rdf:about="">
|
||||||
|
<dc:format>image/svg+xml</dc:format>
|
||||||
|
<dc:type
|
||||||
|
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||||
|
</cc:Work>
|
||||||
|
</rdf:RDF>
|
||||||
|
</metadata>
|
||||||
|
<rect
|
||||||
|
style="fill:#302f3b;fill-opacity:1;stroke:none;stroke-width:13.5876;stroke-linecap:round"
|
||||||
|
id="rect1"
|
||||||
|
width="42.333332"
|
||||||
|
height="42.333332"
|
||||||
|
x="0"
|
||||||
|
y="0" />
|
||||||
|
<g
|
||||||
|
id="layer1"
|
||||||
|
style="display:inline;fill:#ffffff"
|
||||||
|
transform="translate(5.2916666,4.9872409)">
|
||||||
|
<path
|
||||||
|
style="fill:#ffffff;stroke-width:0.177246"
|
||||||
|
d="m 13.134179,31.651166 c -1.367874,-0.18043 -3.4872278,-0.85238 -4.780367,-1.51563 -1.871747,-0.96002 -4.179215,-3.22966 -5.0074297,-4.92534 -1.5914865,-3.25839 -1.6801158,-7.72336 -0.2278948,-11.48085 1.0247424,-2.65144 2.7098602,-4.5706201 5.4768881,-6.2376401 4.4640374,-2.6894 6.9208324,-4.59636 8.5218534,-6.61464 0.435944,-0.54955 0.851411,-0.9404 0.923263,-0.86855 0.34663,0.34663 0.709996,2.45556 0.596276,3.46071 l -0.118698,1.04918 0.543199,-0.3868 c 0.298763,-0.21273 0.754695,-0.66407 1.013185,-1.00297 0.258491,-0.3389 0.531184,-0.55268 0.605988,-0.47507 0.277608,0.28804 0.872923,2.3693 0.872923,3.05181 0,0.78189 -0.07309,0.70941 2.140938,2.12277 3.360595,2.14527 5.28622,5.2741001 5.845846,9.4985401 0.238089,1.79727 0.119928,4.12317 -0.289284,5.69424 -0.438918,1.68512 -1.295306,3.20011 -2.596637,4.59356 -2.715779,2.90803 -6.119638,4.1954 -10.928887,4.13338 -1.132683,-0.0146 -2.298705,-0.0581 -2.591161,-0.0967 z m 5.683631,-1.1265 c 5.074026,-0.89873 8.492767,-3.70496 9.49005,-7.7898 0.358508,-1.46844 0.317005,-5.28368 -0.07569,-6.95754 -0.594746,-2.53514 -2.005266,-4.78931 -3.64922,-5.8318801 -1.428352,-0.90583 -1.561881,-0.82384 -2.840659,1.7442101 -0.615739,1.23654 -1.777129,3.21756 -2.580868,4.40229 l -1.461342,2.15404 0.927607,0.3153 c 1.188141,0.40386 2.476979,1.20634 2.848748,1.77373 0.272049,0.4152 0.269021,0.4806 -0.04735,1.02231 -0.778356,1.33273 -2.272203,1.79512 -5.849412,1.81056 l -2.340153,0.0101 -2.489801,2.46697 c -2.6276133,2.60352 -2.8788341,3.03045 -2.0880964,3.54856 1.8126654,1.18771 7.0732674,1.8772 10.1561944,1.33115 z m 3.183004,-13.17071 c -0.205126,-0.14999 -0.329285,-0.4602 -0.329285,-0.8227 0,-0.96498 1.087198,-1.43355 1.715448,-0.73934 0.872429,0.96402 -0.338235,2.3283 -1.386163,1.56204 z m -3.186586,4.78402 c 1.133944,-0.30198 1.619925,-0.56299 1.85054,-0.9939 0.246861,-0.46126 -0.269147,-0.94676 -1.770094,-1.66543 -1.062457,-0.50872 -1.296906,-0.55176 -3.013183,-0.55311 -1.794444,-0.001 -1.910137,0.0225 -3.231141,0.66815 -1.860639,0.90936 -2.118197,1.48499 -0.948717,2.12031 1.182601,0.64245 5.357705,0.89133 7.112595,0.42398 z m -5.26747,-0.96936 c -1.113796,-0.13246 -1.303724,-0.23853 -1.149022,-0.64168 0.08921,-0.23246 0.582443,-0.27351 3.286452,-0.27351 1.749822,0 3.307658,0.0484 3.461858,0.10758 0.350902,0.13466 0.365077,0.53097 0.02367,0.66198 -0.432127,0.16582 -4.555272,0.2726 -5.622968,0.14563 z m -3.7845902,-3.81466 c 0.7343882,-0.537 0.2478022,-1.88618 -0.6802563,-1.88618 -0.5030742,0 -0.9992445,0.51278 -0.9992445,1.03268 0,0.90987 0.9453857,1.39029 1.6795008,0.8535 z"
|
||||||
|
id="path865" />
|
||||||
|
<path
|
||||||
|
style="fill:#ffffff;fill-opacity:1;stroke:#000000;stroke-width:0;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"
|
||||||
|
d="m 7.5967544,-6.2400058 c 0,0 -0.041418,0.1031026 -0.02862,0.2093299 0.012798,0.1062273 0.084435,0.1741091 0.084435,0.1741091 l -0.083147,0.088222 c 0,0 -0.1053512,-0.138166 -0.073877,-0.2774823 0.031474,-0.1393166 0.1012092,-0.1941783 0.101209,-0.1941787 z"
|
||||||
|
id="path1039" />
|
||||||
|
</g>
|
||||||
|
<g
|
||||||
|
id="layer2"
|
||||||
|
style="display:none" />
|
||||||
|
<g
|
||||||
|
id="layer3"
|
||||||
|
style="display:none" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 4.1 KiB |
BIN
frontend/static/images/icon_x128.png
Normal file
|
After Width: | Height: | Size: 4.7 KiB |
BIN
frontend/static/images/icon_x144.png
Normal file
|
After Width: | Height: | Size: 5.3 KiB |
BIN
frontend/static/images/icon_x192.png
Normal file
|
After Width: | Height: | Size: 7.2 KiB |
BIN
frontend/static/images/icon_x512.png
Normal file
|
After Width: | Height: | Size: 20 KiB |
BIN
frontend/static/images/icon_x72png
Normal file
|
After Width: | Height: | Size: 2.6 KiB |
76
frontend/static/images/light.svg
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||||
|
<svg
|
||||||
|
width="900px"
|
||||||
|
height="900px"
|
||||||
|
viewBox="0 0 900 900"
|
||||||
|
version="1.1"
|
||||||
|
xml:space="preserve"
|
||||||
|
id="SVGRoot"
|
||||||
|
inkscape:version="1.3.1 (91b66b0783, 2023-11-16, custom)"
|
||||||
|
sodipodi:docname="light.svg"
|
||||||
|
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||||
|
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
xmlns:svg="http://www.w3.org/2000/svg"><defs
|
||||||
|
id="defs2" />
|
||||||
|
<sodipodi:namedview
|
||||||
|
pagecolor="#302f3b"
|
||||||
|
bordercolor="#292929"
|
||||||
|
borderopacity="1"
|
||||||
|
inkscape:showpageshadow="2"
|
||||||
|
inkscape:pageopacity="0.0"
|
||||||
|
inkscape:pagecheckerboard="0"
|
||||||
|
inkscape:deskcolor="#232323"
|
||||||
|
id="namedview1"
|
||||||
|
inkscape:zoom="0.64016282"
|
||||||
|
inkscape:cx="414.73824"
|
||||||
|
inkscape:cy="449.88555"
|
||||||
|
inkscape:window-width="1684"
|
||||||
|
inkscape:window-height="1010"
|
||||||
|
inkscape:window-x="0"
|
||||||
|
inkscape:window-y="0"
|
||||||
|
inkscape:window-maximized="1"
|
||||||
|
inkscape:current-layer="SVGRoot" />
|
||||||
|
<style
|
||||||
|
type="text/css"
|
||||||
|
id="style1">
|
||||||
|
g.prefab path {
|
||||||
|
vector-effect:non-scaling-stroke;
|
||||||
|
-inkscape-stroke:hairline;
|
||||||
|
fill: none;
|
||||||
|
fill-opacity: 1;
|
||||||
|
stroke-opacity: 1;
|
||||||
|
stroke: #00349c;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<circle
|
||||||
|
style="fill:#000000;fill-opacity:0.00697072;stroke:#ffffff;stroke-opacity:1;stroke-width:48;stroke-dasharray:none"
|
||||||
|
id="path3"
|
||||||
|
cx="450"
|
||||||
|
cy="450"
|
||||||
|
r="120" /><path
|
||||||
|
style="fill:#000000;fill-opacity:0.00697069;stroke:#ffffff;stroke-width:51.2769;stroke-dasharray:none;stroke-opacity:1;stroke-linecap:round"
|
||||||
|
d="M 450,252 V 52"
|
||||||
|
id="path4" /><path
|
||||||
|
style="fill:#000000;fill-opacity:0.00697069;stroke:#ffffff;stroke-width:51.2769;stroke-dasharray:none;stroke-opacity:1;stroke-linecap:round"
|
||||||
|
d="m 450.00045,848.81135 v -200"
|
||||||
|
id="path4-6" /><path
|
||||||
|
style="fill:#000000;fill-opacity:0.00697069;stroke:#ffffff;stroke-width:51.2769;stroke-dasharray:none;stroke-opacity:1;stroke-linecap:round"
|
||||||
|
d="m 648.4059,450.40545 h 200"
|
||||||
|
id="path5" /><path
|
||||||
|
style="fill:#000000;fill-opacity:0.00697069;stroke:#ffffff;stroke-width:51.2769;stroke-dasharray:none;stroke-opacity:1;stroke-linecap:round"
|
||||||
|
d="m 51.59455,450.4059 h 200"
|
||||||
|
id="path6" /><path
|
||||||
|
style="fill:#000000;fill-opacity:0.00697069;stroke:#ffffff;stroke-width:51.2769;stroke-dasharray:none;stroke-opacity:1;stroke-linecap:round"
|
||||||
|
d="M 590.29406,310.11152 731.71542,168.69016"
|
||||||
|
id="path7" /><path
|
||||||
|
style="fill:#000000;fill-opacity:0.00697069;stroke:#ffffff;stroke-width:51.2769;stroke-dasharray:none;stroke-opacity:1;stroke-linecap:round"
|
||||||
|
d="M 168.28503,732.12119 309.70639,590.69983"
|
||||||
|
id="path8" /><path
|
||||||
|
style="fill:#000000;fill-opacity:0.00697069;stroke:#ffffff;stroke-width:51.2769;stroke-dasharray:none;stroke-opacity:1;stroke-linecap:round"
|
||||||
|
d="M 590.29438,590.69951 731.71574,732.12087"
|
||||||
|
id="path9" /><path
|
||||||
|
style="fill:#000000;fill-opacity:0.00697069;stroke:#ffffff;stroke-width:51.2769;stroke-dasharray:none;stroke-opacity:1;stroke-linecap:round"
|
||||||
|
d="M 168.28471,168.69048 309.70607,310.11184"
|
||||||
|
id="path10" /></svg>
|
||||||
|
After Width: | Height: | Size: 3.0 KiB |
17
frontend/static/manifest.json
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"name": "Hemma",
|
||||||
|
"short_name": "Hemma",
|
||||||
|
"start_url": "/lights",
|
||||||
|
"display": "standalone",
|
||||||
|
"background_color": "#302f3b",
|
||||||
|
"description": "Styr lampor",
|
||||||
|
"icons": [
|
||||||
|
{ "src": "/images/icon_x72.png", "sizes": "72x72", "type": "image/png", "purpose": "maskable" },
|
||||||
|
{ "src": "/images/icon_x128.png", "sizes": "128x128", "type": "image/png", "purpose": "maskable" },
|
||||||
|
{ "src": "/images/icon_x144.png", "sizes": "144x144", "type": "image/png", "purpose": "maskable" },
|
||||||
|
{ "src": "/images/icon_x192.png", "sizes": "192x192", "type": "image/png", "purpose": "maskable" },
|
||||||
|
{ "src": "/images/icon_x512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" },
|
||||||
|
{ "src": "/images/icon.svg", "sizes": "513x512", "purpose": "maskable" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
@ -19,6 +19,16 @@ body {
|
|||||||
font-size: x-large;
|
font-size: x-large;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* filthy hacks to make the page stop overflowing on mobile */
|
||||||
|
@media (width <= 430px) {
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
transform-origin: top left;
|
||||||
|
scale: 0.9;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (width <= 390px) { body { scale: 0.85; } }
|
||||||
|
|
||||||
.info_box {
|
.info_box {
|
||||||
margin: auto;
|
margin: auto;
|
||||||
max-width: 40em;
|
max-width: 40em;
|
||||||
@ -84,16 +94,12 @@ body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.bulb_box {
|
.bulb_box {
|
||||||
display: flex;
|
|
||||||
flex-direction: row;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: space-around;
|
|
||||||
width: fit-content;
|
width: fit-content;
|
||||||
|
margin: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.bulb_box > * {
|
.bulb_box > * {
|
||||||
margin: 0.5em;
|
margin-bottom: 1.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.bulb_controls {
|
.bulb_controls {
|
||||||
@ -101,24 +107,62 @@ body {
|
|||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
padding-right: 0.5em;
|
padding-right: 0.5em;
|
||||||
background: #56636e;
|
background: #00000000;
|
||||||
border: solid 0.25em #5b3f63;
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.cross_out {
|
||||||
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
|
opacity: 0.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cross_out:before {
|
||||||
|
position: absolute;
|
||||||
|
content: '';
|
||||||
|
display: block;
|
||||||
|
background: #00000000;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
top: 0;
|
||||||
|
bottom: 0;
|
||||||
|
margin: auto;
|
||||||
|
z-index: 90;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cross_out:after {
|
||||||
|
position: absolute;
|
||||||
|
content: '';
|
||||||
|
background: #56636e;
|
||||||
|
display: block;
|
||||||
|
width: 0;
|
||||||
|
height: 10px;
|
||||||
|
border-radius: 8px;
|
||||||
|
-webkit-transform: rotate(-30deg);
|
||||||
|
transform: rotate(-30deg);
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
top: 0;
|
||||||
|
bottom: 0;
|
||||||
|
margin: auto;
|
||||||
|
z-index: 91;
|
||||||
|
box-shadow: black 0.5rem 0.6rem 1rem 0.3rem;
|
||||||
|
animation: to_width_90 .2s ease-out 0s 1 forwards;
|
||||||
|
}
|
||||||
|
@keyframes to_width_90 { to { width: 90%; } }
|
||||||
|
|
||||||
.bulb_map {
|
.bulb_map {
|
||||||
background: url(images/blueprint_bg.png);
|
background: url(images/blueprint_bg.png);
|
||||||
background-size: auto;
|
background-size: auto;
|
||||||
background-size: 1em;
|
background-size: 1em;
|
||||||
padding: 2rem;
|
padding: 2rem;
|
||||||
border: solid 0.4rem #5b3f63;
|
border: solid 0.1rem;
|
||||||
|
border-radius: 0.2rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.bulb_map::after {
|
.bulb_map::after {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
content: #0003;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.bulb_group {
|
.bulb_group {
|
||||||
@ -130,6 +174,7 @@ body {
|
|||||||
font-size: 2em;
|
font-size: 2em;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
box-shadow: #0006 0.1em 0.1em 0.1em;
|
box-shadow: #0006 0.1em 0.1em 0.1em;
|
||||||
|
user-select: none;
|
||||||
transition: 0.3s ease-in-out;
|
transition: 0.3s ease-in-out;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -259,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;
|
||||||
@ -277,7 +324,50 @@ body {
|
|||||||
//margin-bottom: .7em;
|
//margin-bottom: .7em;
|
||||||
margin-left: .5em;
|
margin-left: .5em;
|
||||||
}
|
}
|
||||||
.calendar_box {
|
|
||||||
with: 10em;
|
.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;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.prefs_box > h2 {
|
||||||
|
writing-mode: sideways-lr;
|
||||||
|
margin-top: auto;
|
||||||
|
margin-bottom: auto;
|
||||||
|
}
|
||||||
|
.prefs_box > * {
|
||||||
|
flex-shrink: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||