Update deps
This commit is contained in:
1011
Cargo.lock
generated
1011
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -5,13 +5,13 @@ authors = ["Joakim Hulthe <joakim@hulthe.net"]
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
seed = "0.9.1"
|
||||
wasm-bindgen = "=0.2.80" # 0.2.81 has a breaking change
|
||||
serde = { version = "1", features = ['derive'] }
|
||||
serde_json = "1"
|
||||
anyhow = "*"
|
||||
seed = "0.10.0"
|
||||
wasm-bindgen = "=0.2.87" # must match Trunk.toml
|
||||
serde = { version = "1.0.0", features = ['derive'] }
|
||||
ron = "0.7.1"
|
||||
chrono = { version = "0.4.20", features = ["serde"] }
|
||||
gloo-net = "0.4.0"
|
||||
gloo-console = "0.3.0"
|
||||
|
||||
[dependencies.css_typegen]
|
||||
git = "https://github.com/hulthe/css_typegen.git"
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
[serve]
|
||||
address = "0.0.0.0"
|
||||
|
||||
|
||||
[tools]
|
||||
wasm_bindgen = "0.2.87"
|
||||
|
||||
[[proxy]]
|
||||
# This WebSocket proxy example has a backend and ws field. This example will listen for
|
||||
|
||||
@ -1,10 +1,20 @@
|
||||
use crate::page;
|
||||
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::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::{log, window};
|
||||
use seed::window;
|
||||
use seed::FutureExt;
|
||||
use seed_router::Router;
|
||||
use std::collections::VecDeque;
|
||||
use std::error::Error;
|
||||
|
||||
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 {
|
||||
page: Pages,
|
||||
send_queue: VecDeque<ClientMessage>,
|
||||
socket: WebSocket,
|
||||
|
||||
/// Websocket URL
|
||||
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,
|
||||
}
|
||||
|
||||
@ -47,14 +65,14 @@ pub enum Msg {
|
||||
|
||||
// Global
|
||||
Connect,
|
||||
SocketOpened(),
|
||||
SocketClosed(CloseEvent),
|
||||
SocketError(),
|
||||
SocketMessage(WebSocketMessage),
|
||||
SocketOpened(Sender<websocket::Message>),
|
||||
SocketClosed,
|
||||
SocketMessage(websocket::Message),
|
||||
}
|
||||
|
||||
pub fn init(url: Url, orders: &mut impl Orders<Msg>) -> Model {
|
||||
orders.subscribe(Msg::SendMessage);
|
||||
orders.send_msg(Msg::Connect);
|
||||
|
||||
let location = window().location();
|
||||
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))
|
||||
.unwrap_or(Pages::NotFound(Default::default())),
|
||||
send_queue: Default::default(),
|
||||
socket: open_socket(&ws_url, orders),
|
||||
ws_url,
|
||||
socket_task: None,
|
||||
socket: None,
|
||||
timeout_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn open_socket(url: &str, orders: &mut impl Orders<Msg>) -> WebSocket {
|
||||
WebSocket::builder(url, orders)
|
||||
.on_open(Msg::SocketOpened)
|
||||
.on_close(Msg::SocketClosed)
|
||||
.on_error(Msg::SocketError)
|
||||
.on_message(Msg::SocketMessage)
|
||||
.build_and_open()
|
||||
.expect("failed to open websocket")
|
||||
fn open_socket(url: String, orders: &mut impl Orders<Msg>) -> CmdHandle {
|
||||
let update_fn = orders.msg_sender();
|
||||
|
||||
orders.perform_cmd_with_handle(async move {
|
||||
let mut ws = WebSocket::open(&url).expect("Failed to open websocket");
|
||||
let (tx, mut rx) = channel(128);
|
||||
update_fn(Some(Msg::SocketOpened(tx)));
|
||||
|
||||
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) {
|
||||
#[cfg(debug_assertions)]
|
||||
log!(format!("{msg:?}"));
|
||||
gloo_console::debug!(format!("{msg:?}"));
|
||||
|
||||
match msg {
|
||||
Msg::Page(msg) => model.page.update(msg, &mut orders.proxy(Msg::Page)),
|
||||
Msg::FlushMessageQueue => {
|
||||
while let Some(message) = model.send_queue.pop_front() {
|
||||
let serialized = ron::to_string(&message).unwrap();
|
||||
if let Some(socket) = model.socket.as_mut() {
|
||||
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) {
|
||||
model.send_queue.push_front(message);
|
||||
log!(e);
|
||||
return;
|
||||
let ws_message = websocket::Message::Text(serialized);
|
||||
if socket.try_send(ws_message).is_err() {
|
||||
error!("websocket queue full");
|
||||
model.send_queue.push_front(message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Msg::Connect => {
|
||||
model.socket = open_socket(&model.ws_url, orders);
|
||||
model.socket_task = Some(open_socket(model.ws_url.clone(), orders));
|
||||
}
|
||||
Msg::SendMessage(message) => {
|
||||
model.send_queue.push_back(message);
|
||||
orders.send_msg(Msg::FlushMessageQueue);
|
||||
}
|
||||
Msg::SocketOpened() => {
|
||||
Msg::SocketOpened(socket) => {
|
||||
model.socket = Some(socket);
|
||||
model.timeout_count = 0;
|
||||
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_ms = timeout_sec * 1000;
|
||||
orders.perform_cmd(cmds::timeout(timeout_ms, || Msg::Connect));
|
||||
|
||||
log!(format!(
|
||||
error!(format!(
|
||||
"Socket closed, trying to reconnect in {timeout_sec} seconds"
|
||||
));
|
||||
|
||||
model.timeout_count = TIMEOUT_CONNECT_DELAYS.len().min(model.timeout_count + 1);
|
||||
}
|
||||
Msg::SocketError() => {}
|
||||
Msg::SocketMessage(message) => {
|
||||
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<()> {
|
||||
let message = message.text().map_err(|e| anyhow::format_err!("{e:?}"))?;
|
||||
let message: ServerMessage = ron::from_str(&message)?;
|
||||
fn handle_ws_msg(
|
||||
message: websocket::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);
|
||||
|
||||
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>> {
|
||||
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![],
|
||||
//}
|
||||
}
|
||||
|
||||
@ -6,7 +6,7 @@ use lighter_lib::{BulbId, BulbMode};
|
||||
use seed::prelude::*;
|
||||
use seed::{attrs, button, div, input, C};
|
||||
use seed_router::Page;
|
||||
use std::collections::{BTreeMap, HashSet, HashMap};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::fmt::Write;
|
||||
|
||||
/// /lights page
|
||||
@ -23,7 +23,6 @@ pub struct Model {
|
||||
groups_interacted: bool,
|
||||
|
||||
color_picker: ColorPicker,
|
||||
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
@ -56,7 +55,11 @@ impl Page for Model {
|
||||
fn update(&mut self, msg: Self::Msg, orders: &mut impl Orders<Self::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 {
|
||||
mode: new_mode,
|
||||
wake_schedule,
|
||||
@ -131,8 +134,7 @@ impl Page for Model {
|
||||
};
|
||||
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, _| {
|
||||
let message = ClientMessage::SetBulbWakeTime {
|
||||
id: id.clone(),
|
||||
@ -146,146 +148,150 @@ 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 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))
|
||||
// },
|
||||
// ],
|
||||
// ],
|
||||
// ]
|
||||
//};
|
||||
let bulb_map_width = self
|
||||
.bulb_map
|
||||
.groups
|
||||
.iter()
|
||||
.map(|group| group.x + group.shape.width())
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
|
||||
let bulb_map_width = self
|
||||
.bulb_map
|
||||
.groups
|
||||
.iter()
|
||||
.map(|group| group.x + group.shape.width())
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
let bulb_map_height = self
|
||||
.bulb_map
|
||||
.groups
|
||||
.iter()
|
||||
.map(|group| group.y + group.shape.height())
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
|
||||
let bulb_map_height = self
|
||||
.bulb_map
|
||||
.groups
|
||||
.iter()
|
||||
.map(|group| group.y + group.shape.height())
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
let view_bulb_group = |(i, group): (usize, &BulbGroup)| {
|
||||
let (w, h) = (group.shape.width(), group.shape.height());
|
||||
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();
|
||||
|
||||
let view_bulb_group = |(i, group): (usize, &BulbGroup)| {
|
||||
let (w, h) = (group.shape.width(), group.shape.height());
|
||||
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 {
|
||||
write!(&mut style, " border-radius: {r}rem;").ok();
|
||||
}
|
||||
|
||||
if let BulbGroupShape::Circle { r } = group.shape {
|
||||
write!(&mut style, " border-radius: {r}rem;").ok();
|
||||
}
|
||||
|
||||
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]
|
||||
div![
|
||||
&group.name[..1],
|
||||
if self.selected_groups.contains(&i) {
|
||||
C![C.bulb_group, C.bulb_group_selected]
|
||||
} else {
|
||||
C![C.bulb_power_button]
|
||||
C![C.bulb_group]
|
||||
},
|
||||
ev(Ev::Click, move |_| Msg::SetBulbPower(!selected_bulb.mode.power)),
|
||||
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" }],
|
||||
],
|
||||
],
|
||||
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.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),
|
||||
],
|
||||
]
|
||||
}
|
||||
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 {
|
||||
C![C.bulb_power_button]
|
||||
},
|
||||
ev(Ev::Click, move |_| Msg::SetBulbPower(
|
||||
!selected_bulb.mode.power
|
||||
)),
|
||||
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 {
|
||||
|
||||
Reference in New Issue
Block a user