11 Commits

16 changed files with 889 additions and 741 deletions

1015
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -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

View File

@ -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

View File

@ -1,6 +1,6 @@
[package] [package]
name = "hemma" name = "hemma"
version = "0.1.0" version = "0.2.1"
edition = "2021" edition = "2021"
[dependencies] [dependencies]

View File

@ -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)

View File

@ -32,7 +32,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")]

View File

@ -1,6 +1,6 @@
use std::collections::HashMap; use std::collections::HashMap;
use chrono::{Datelike, Local, NaiveTime, Weekday}; use chrono::{DateTime, Datelike, Local, NaiveTime, Weekday};
use common::{ClientMessage, ServerMessage}; use common::{ClientMessage, ServerMessage};
use lighter_lib::{BulbColor, BulbId}; use lighter_lib::{BulbColor, BulbId};
use lighter_manager::manager::{BulbCommand, BulbManager, BulbSelector}; use lighter_manager::manager::{BulbCommand, BulbManager, BulbSelector};
@ -40,7 +40,7 @@ pub async fn lights_task(state: &State) {
.flat_map(|(bulb, schedule)| schedule.iter().map(move |(day, time)| (bulb, day, time))) .flat_map(|(bulb, schedule)| schedule.iter().map(move |(day, time)| (bulb, day, time)))
.map(|(bulb, day, time)| { .map(|(bulb, day, time)| {
let handle = spawn(wake_task( let handle = spawn(wake_task(
state.client_message.subscribe(), state.client_message.clone(),
cmd.clone(), cmd.clone(),
bulb.clone(), bulb.clone(),
*day, *day,
@ -112,20 +112,19 @@ pub async fn lights_task(state: &State) {
}; };
if let Some(time) = time { if let Some(time) = time {
let handle = spawn(wake_task( let handle = spawn(wake_task(
state.client_message.subscribe(), state.client_message.clone(),
cmd.clone(), cmd.clone(),
id.clone(), id.clone(),
day, day,
time, time,
)); ));
if let Some(old_handle) = wake_tasks.insert((id, day), handle) { 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(); old_handle.abort();
} }
} else if let Some(old_handle) = wake_tasks.remove(&(id, day)) {
old_handle.abort();
} }
} }
_ => {} _ => {}
@ -136,39 +135,23 @@ pub async fn lights_task(state: &State) {
} }
async fn wake_task( async fn wake_task(
mut client_messages: broadcast::Receiver<ClientRequest>, client_messages: broadcast::Sender<ClientRequest>,
cmd: mpsc::Sender<BulbCommand>, cmd: mpsc::Sender<BulbCommand>,
id: BulbId, id: BulbId,
day: Weekday, day: Weekday,
time: NaiveTime, time: NaiveTime,
) { ) {
let now = Local::now(); let mut alarm = next_alarm(Local::now(), day, time);
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 { loop {
info!("sleeping until {alarm}"); info!("sleeping until {alarm}");
sleep((alarm - Local::now()).to_std().unwrap()).await; sleep((alarm - Local::now()).to_std().unwrap()).await;
alarm += chrono::Duration::weeks(1);
// slowly turn up brightness of bulb // slowly turn up brightness of bulb
for brightness in (1..=75).map(|i| (i as f32) * 0.01) { for brightness in (1..=75).map(|i| (i as f32) * 0.01) {
select! { select! {
// abort if the client pokes the bulb // abort if the client pokes the bulb
_ = wait_for_bulb_command(&id, &mut client_messages) => break, _ = wait_for_bulb_command(&id, client_messages.subscribe()) => break,
_ = sleep(Duration::from_secs(12)) => {} _ = sleep(Duration::from_secs(12)) => {}
}; };
@ -186,13 +169,34 @@ async fn wake_task(
return; 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 /// Wait until we receive a client request that mutates the given bulb
async fn wait_for_bulb_command( async fn wait_for_bulb_command(
bulb_id: &BulbId, bulb_id: &BulbId,
client_messages: &mut broadcast::Receiver<ClientRequest>, mut client_messages: broadcast::Receiver<ClientRequest>,
) { ) {
loop { loop {
match client_messages.recv().await { match client_messages.recv().await {
@ -210,3 +214,31 @@ async fn wait_for_bulb_command(
} }
} }
} }
#[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
);
}
}
}

View File

@ -1,6 +1,6 @@
[package] [package]
name = "common" name = "common"
version = "0.1.0" version = "0.2.1"
edition = "2021" edition = "2021"
[dependencies] [dependencies]

View File

@ -1,20 +1,17 @@
[package] [package]
name = "hemma_web" name = "hemma_web"
version = "0.1.0" version = "0.2.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"

View File

@ -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]]

View File

@ -0,0 +1,4 @@
[toolchain]
channel = "stable"
components = ["rust-src", "rustfmt", "rust-src"]
targets = ["wasm32-unknown-unknown"]

View File

@ -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![],
//}
} }

View File

@ -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) {

View File

@ -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);
} }

View File

@ -3,10 +3,10 @@ use crate::css::C;
use chrono::{NaiveTime, Weekday}; use chrono::{NaiveTime, Weekday};
use common::{BulbGroup, BulbGroupShape, BulbMap, ClientMessage, 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, input, 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, HashMap, HashSet};
use std::fmt::Write; use std::fmt::Write;
/// /lights page /// /lights page
@ -23,7 +23,6 @@ pub struct Model {
groups_interacted: bool, groups_interacted: bool,
color_picker: ColorPicker, color_picker: ColorPicker,
} }
#[derive(Default, Clone)] #[derive(Default, Clone)]
@ -56,7 +55,11 @@ 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,
wake_schedule,
} => {
*self.bulb_states.entry(id).or_default() = BulbState { *self.bulb_states.entry(id).or_default() = BulbState {
mode: new_mode, mode: new_mode,
wake_schedule, wake_schedule,
@ -109,7 +112,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;
@ -122,7 +125,7 @@ impl Page for Model {
}); });
} }
Msg::LightTime(time, day) => { Msg::LightTime(time, day) => {
if time == "" { if time.is_empty() {
self.for_selected_bulbs(|id, _| { self.for_selected_bulbs(|id, _| {
let message = ClientMessage::SetBulbWakeTime { let message = ClientMessage::SetBulbWakeTime {
id: id.clone(), id: id.clone(),
@ -131,8 +134,7 @@ impl Page for Model {
}; };
orders.notify(message); orders.notify(message);
}); });
} } else if let Ok(time) = NaiveTime::parse_from_str(&time, "%H:%M") {
else if let Ok(time) = NaiveTime::parse_from_str(&time, "%H:%M") {
self.for_selected_bulbs(|id, _| { self.for_selected_bulbs(|id, _| {
let message = ClientMessage::SetBulbWakeTime { let message = ClientMessage::SetBulbWakeTime {
id: id.clone(), id: id.clone(),
@ -146,146 +148,147 @@ impl Page for Model {
} }
} }
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 calendar_day = |day: Weekday| {
let time = selected_bulb
.and_then(|b| b.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![ 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!("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.bulb_controls_disable]),
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.calendar_box],
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 { impl Model {

View File

@ -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;
@ -93,7 +103,8 @@ body {
} }
.bulb_box > * { .bulb_box > * {
margin: 0.5em; margin-bottom: 1em;
margin-right: 1em;
} }
.bulb_controls { .bulb_controls {
@ -103,9 +114,47 @@ body {
padding-right: 0.5em; padding-right: 0.5em;
background: #56636e; background: #56636e;
border: solid 0.25em #5b3f63; border: solid 0.25em #5b3f63;
} }
.bulb_controls_disable {
position: relative;
overflow: hidden;
}
.bulb_controls_disable:before {
position: absolute;
content: '';
display: block;
background: #000000;
opacity: 0.5;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
z-index: 90;
}
.bulb_controls_disable: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;
animation: to_full_width .2s ease-out 0s 1 forwards;
}
@keyframes to_full_width { to { width: 100%; } }
.bulb_map { .bulb_map {
background: url(images/blueprint_bg.png); background: url(images/blueprint_bg.png);
background-size: auto; background-size: auto;