fix(power): fix battery state / charge devices info

This commit is contained in:
Konstantinos 2024-10-22 18:46:53 +03:00 committed by GitHub
parent 5d948783fe
commit b8f0be58a7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,7 +1,7 @@
use chrono::{Duration, TimeDelta};
use futures::future::join_all;
use futures::FutureExt;
use upower_dbus::{BatteryType, DeviceProxy};
use futures::{future::join_all, TryFutureExt};
use upower_dbus::{BatteryState, BatteryType, DeviceProxy};
use zbus::Connection;
mod ppdaemon;
@ -230,7 +230,7 @@ pub struct Battery {
pub icon_name: String,
pub is_present: bool,
pub percent: f64,
pub on_battery: bool,
pub is_charging: bool,
pub remaining_duration: Duration,
}
@ -294,34 +294,21 @@ async fn enumerate_devices<'a>() -> Result<Vec<upower_dbus::DeviceProxy<'a>>, zb
.collect())
}
async fn get_on_battery_status() -> Result<bool, zbus::Error> {
let connection = match Connection::system().await {
Ok(c) => c,
Err(e) => {
tracing::error!("zbus connection failed. {e}");
return Err(e);
}
};
match upower_dbus::UPowerProxy::new(&connection).await {
Ok(p) => p.on_battery().await,
Err(e) => Err(e),
}
}
impl Battery {
pub async fn from_device(proxy: DeviceProxy<'_>) -> Self {
let mut remaining_duration: Duration = Duration::default();
let (is_present, percentage, on_battery) = futures::join!(
let (is_present, percentage, battery_state) = futures::join!(
proxy.is_present().map(Result::unwrap_or_default),
proxy.percentage().map(Result::unwrap_or_default),
get_on_battery_status().map(Result::unwrap_or_default)
proxy.state().map(|r| r.unwrap_or(BatteryState::Unknown)),
);
let percent = percentage.clamp(0.0, 100.0);
if on_battery {
let is_charging = matches!(battery_state, BatteryState::Charging);
if !is_charging {
if let Ok(time) = proxy.time_to_empty().await {
if let Ok(dur) = Duration::from_std(std::time::Duration::from_secs(time as u64)) {
remaining_duration = dur;
@ -352,7 +339,7 @@ impl Battery {
} else {
0
};
let charging = if on_battery { "" } else { "charging-" };
let charging = if is_charging { "charging-" } else { "" };
let icon_name =
format!("cosmic-applet-battery-level-{battery_percent}-{charging}symbolic",);
@ -361,7 +348,7 @@ impl Battery {
icon_name,
is_present,
percent,
on_battery,
is_charging,
remaining_duration,
}
}
@ -411,7 +398,7 @@ impl Battery {
"battery",
"remaining-time",
time = time,
action = if self.on_battery { "empty" } else { "full" }
action = if !self.is_charging { "empty" } else { "full" }
)
}
}
@ -436,7 +423,7 @@ mod tests {
let (actual, expected) = case;
let battery = Battery {
remaining_duration: Duration::new(actual, 0).unwrap(),
on_battery: true,
is_charging: false,
..Default::default()
};
assert_eq!(battery.remaining_time(), expected);