battery: refactor to do less in callback

This commit is contained in:
Artemis Tosini 2023-12-24 22:25:31 +00:00
parent fb76f49325
commit 4893221973
Signed by: artemist
GPG key ID: ADFFE553DCBB831E

View file

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