diff --git a/src/tiles/battery.rs b/src/tiles/battery.rs index 86bc508..5d57a90 100644 --- a/src/tiles/battery.rs +++ b/src/tiles/battery.rs @@ -17,7 +17,7 @@ use num_traits::FromPrimitive; use std::convert::TryInto; use std::sync::Arc; use std::{convert::Infallible, time::Duration}; -use tokio::sync::watch; +use tokio::sync::mpsc; use tokio::try_join; #[derive(FromPrimitive, Debug, PartialEq, Eq)] @@ -60,7 +60,7 @@ pub async fn battery( dbus_conn.as_ref(), ); - let init_info = { + let mut info = { let (percentage, raw_state, time_to_empty, time_to_full) = try_join!( proxy.percentage(), proxy.state(), @@ -75,9 +75,7 @@ pub async fn battery( } }; - eprintln!("{:#?}", init_info); - - let (tx, mut rx) = watch::channel(init_info); + let (tx, mut rx) = mpsc::unbounded_channel(); let _reciever = dbus_conn .add_match(PropertiesPropertiesChanged::match_rule( @@ -85,40 +83,10 @@ pub async fn battery( Some(path), )) .await? - .cb(move |_, changed: PropertiesPropertiesChanged| { - tx.send_modify(|info| { - let props = changed.changed_properties; - props - .get("Percentage") - .and_then(Variant::as_f64) - .map(|val| info.percentage = val); - - props - .get("State") - .and_then(Variant::as_u64) - .and_then(DeviceState::from_u64) - .map(|val| info.state = val); - - props - .get("TimeToEmpty") - .and_then(Variant::as_i64) - .map(|val| val.clamp(0, i64::MAX).try_into().unwrap()) - .map(Duration::from_secs) - .map(|val| info.time_to_empty = val); - - props - .get("TimeToFull") - .and_then(Variant::as_i64) - .map(|val| val.clamp(0, i64::MAX).try_into().unwrap()) - .map(Duration::from_secs) - .map(|val| info.time_to_full = val); - }); - true - }); + .cb(move |_, changed: PropertiesPropertiesChanged| tx.send(changed).is_ok()); loop { let block = { - let info = rx.borrow(); let time_str = match info.state { DeviceState::Discharging => format_duration(info.time_to_empty), DeviceState::Charging => format_duration(info.time_to_full), @@ -151,6 +119,32 @@ pub async fn battery( }; output.send(block).await?; - rx.changed().await?; + let msg = rx.recv().await.ok_or_eyre("Battery stream closed")?; + let props = msg.changed_properties; + + props + .get("Percentage") + .and_then(Variant::as_f64) + .map(|val| info.percentage = val); + + props + .get("State") + .and_then(Variant::as_u64) + .and_then(DeviceState::from_u64) + .map(|val| info.state = val); + + props + .get("TimeToEmpty") + .and_then(Variant::as_i64) + .map(|val| val.clamp(0, i64::MAX).try_into().unwrap()) + .map(Duration::from_secs) + .map(|val| info.time_to_empty = val); + + props + .get("TimeToFull") + .and_then(Variant::as_i64) + .map(|val| val.clamp(0, i64::MAX).try_into().unwrap()) + .map(Duration::from_secs) + .map(|val| info.time_to_full = val); } }