Skip to content

Commit

Permalink
Merge pull request #276 from nokyan/battery-fixes
Browse files Browse the repository at this point in the history
Only show laptop batteries
  • Loading branch information
nokyan authored Jul 6, 2024
2 parents 90d7131 + b028dc5 commit 0e66f41
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 11 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ plotters = { version = "0.3.6", default-features = false, features = [
"area_series",
] }
plotters-cairo = "0.6.0"
serde = { version = "1.0.203", features = ["serde_derive"] }
rmp-serde = "1.3.0"
rust-ini = "0.21.0"
gtk-macros = "0.3.0"
Expand Down
2 changes: 0 additions & 2 deletions data/resources/ui/widgets/double_graph_box.ui
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
</style>
<property name="hexpand">true</property>
<property name="halign">start</property>
<property name="selectable">true</property>
<property name="ellipsize">2</property>
</object>
</child>
Expand Down Expand Up @@ -76,7 +75,6 @@
</style>
<property name="hexpand">true</property>
<property name="halign">start</property>
<property name="selectable">true</property>
<property name="ellipsize">2</property>
</object>
</child>
Expand Down
1 change: 0 additions & 1 deletion data/resources/ui/widgets/graph_box.ui
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
</style>
<property name="hexpand">true</property>
<property name="halign">start</property>
<property name="selectable">true</property>
<property name="ellipsize">2</property>
</object>
</child>
Expand Down
79 changes: 73 additions & 6 deletions src/utils/battery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,17 @@ use std::{
};

use anyhow::{bail, Context, Result};
use once_cell::sync::Lazy;
use regex::Regex;

use crate::i18n::{i18n, i18n_f};

use super::units::convert_energy;

// For (at least) Lenovo Yoga 6 13ALC7
static HEX_ENCODED_REGEX: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^(0x[0-9a-fA-F]{2}\s*)*$").unwrap());

pub struct BatteryData {
pub inner: Battery,
pub charge: Result<f64>,
Expand Down Expand Up @@ -156,14 +162,16 @@ impl Battery {
let mut entries = std::fs::read_dir("/sys/class/power_supply")?;
while let Some(entry) = entries.next() {
let entry = entry?;
if std::fs::read_to_string(entry.path().join("type"))

if !entry
.path()
.file_name()
.map(|name| name.to_string_lossy().starts_with("BAT"))
.unwrap_or_default()
.to_ascii_lowercase()
.trim()
!= "battery"
{
continue;
}

list.push(entry.path());
}
Ok(list)
Expand All @@ -173,11 +181,11 @@ impl Battery {
let sysfs_path = sysfs_path.as_ref().to_path_buf();

let manufacturer = std::fs::read_to_string(sysfs_path.join("manufacturer"))
.map(|s| s.replace('\n', ""))
.map(|s| Self::untangle_weird_encoding(s.replace('\n', "")))
.ok();

let model_name = std::fs::read_to_string(sysfs_path.join("model_name"))
.map(|s| s.replace('\n', ""))
.map(|s| Self::untangle_weird_encoding(s.replace('\n', "")))
.ok();

let technology = Technology::from_str(
Expand Down Expand Up @@ -207,6 +215,24 @@ impl Battery {
}
}

// apparently some manufacturers like to for whatever reason reencode the manufacturer and model name in hex or
// similar, this function will try to untangle it
fn untangle_weird_encoding<S: AsRef<str>>(s: S) -> String {
if HEX_ENCODED_REGEX.is_match(s.as_ref()) {
String::from_utf8_lossy(
&s.as_ref()
.split_whitespace()
.map(|hex| u8::from_str_radix(&hex.replace("0x", ""), 16))
.flatten()
.map(|byte| if byte == 0x0 { ' ' as u8 } else { byte }) // gtk will crash when encountering NUL
.collect::<Vec<u8>>(),
)
.to_string()
} else {
s.as_ref().to_string()
}
}

pub fn display_name(&self) -> String {
if let Some(design_capacity) = self.design_capacity {
let converted_energy = convert_energy(design_capacity, true);
Expand Down Expand Up @@ -292,3 +318,44 @@ impl Battery {
.context("unable to parse power_now sysfs file")
}
}

#[cfg(test)]
mod test {
use super::Battery;

#[test]
fn dont_untangle_untangled_string() {
let untangled_string = String::from("This is a normal string");
assert_eq!(
Battery::untangle_weird_encoding(untangled_string),
String::from("This is a normal string")
)
}

#[test]
fn dont_untangle_non_hex_bytes() {
let non_hex_bytes = String::from("0xxy 0x4g");
assert_eq!(
Battery::untangle_weird_encoding(non_hex_bytes),
String::from("0xxy 0x4g")
)
}

#[test]
fn untangle_tangled_string() {
let tangled_string = String::from("0x41 0x42 0x43 0x58 0x59 0x5A");
assert_eq!(
Battery::untangle_weird_encoding(tangled_string),
String::from("ABCXYZ")
);
}

#[test]
fn untangle_tangled_string_with_nul() {
let tangled_string = String::from("0x41 0x42 0x43 0x00 0x44");
assert_eq!(
Battery::untangle_weird_encoding(tangled_string),
String::from("ABC D")
);
}
}

0 comments on commit 0e66f41

Please sign in to comment.