Fix battery detection

This commit is contained in:
Moritz Ruth 2023-03-09 23:35:49 +01:00
parent 9143d30de3
commit a6e721009e
Signed by: moritzruth
GPG key ID: C9BBAB79405EE56D
4 changed files with 47 additions and 31 deletions

1
.gitignore vendored
View file

@ -1 +1,2 @@
/target/ /target/
.idea/

View file

@ -142,4 +142,4 @@ When a notification is dismissed, `closed` is sent into the topic.
## License ## License
Hassliebe is licensed under the [Blue Oak Model License 1.0.0](/LICENSE.md). Hassliebe is licensed under the [Blue Oak Model License 1.0.0](./LICENSE.md).

View file

@ -1,10 +1,11 @@
use std::fs; use std::fs::ReadDir;
use std::time::Duration; use std::time::Duration;
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use rumqttc::QoS; use rumqttc::QoS;
use serde::Deserialize; use serde::Deserialize;
use sysinfo::{CpuExt, System, SystemExt}; use sysinfo::{CpuExt, System, SystemExt};
use tokio::task::spawn_blocking;
use tokio::time::MissedTickBehavior; use tokio::time::MissedTickBehavior;
use validator::Validate; use validator::Validate;
@ -77,12 +78,26 @@ pub async fn init(context: &mut InitializationContext) -> Result<()> {
} }
if config.battery != 0 { if config.battery != 0 {
let battery_dirs = fs::read_dir("/sys/class/power_supply")?.filter_map(|d| d.ok()).collect::<Vec<_>>(); let battery_dirs = spawn_blocking(|| {
std::fs::read_dir("/sys/class/power_supply")
// TODO: Filter battery_dirs by the existence of "capacity" .map(|dirs| {
dirs.filter_map(|d| d.ok())
.filter(|d| std::fs::read_to_string(d.path().join("capacity")).is_ok())
.collect::<Vec<_>>()
})
.unwrap_or_default()
})
.await
.unwrap();
if let Some(dir) = battery_dirs.first() { if let Some(dir) = battery_dirs.first() {
log::debug!("Found {} batteries, using {}", battery_dirs.len(), dir.file_name().to_string_lossy()); log::debug!(
"Found {} {}, using {}",
battery_dirs.len(),
if battery_dirs.len() == 1 { "battery" } else { "batteries" },
dir.file_name().to_string_lossy()
);
let path = dir.path(); let path = dir.path();
let capacity_path = path.clone().join("capacity"); let capacity_path = path.clone().join("capacity");
let status_path = path.clone().join("status"); let status_path = path.clone().join("status");
@ -97,7 +112,7 @@ pub async fn init(context: &mut InitializationContext) -> Result<()> {
}, },
context, context,
config.battery, config.battery,
move || Ok(fs::read_to_string(&capacity_path)?), move || Ok(std::fs::read_to_string(&capacity_path)?),
) )
.await?; .await?;
@ -111,7 +126,7 @@ pub async fn init(context: &mut InitializationContext) -> Result<()> {
}, },
context, context,
config.battery, config.battery,
move || Ok(fs::read_to_string(&status_path)?), move || Ok(std::fs::read_to_string(&status_path)?),
) )
.await?; .await?;
} else { } else {