battery detection function addded
Browse files
+35 −4 src/bar/blocks/battery.rs
| @@ -1,6 +1,7 @@ | |||
| 1 | use super::Block; | 1 | use super::Block; |
| 2 | use crate::errors::BlockError; | 2 | use crate::errors::BlockError; |
| 3 | use std::fs; | 3 | use std::fs; |
| 4 | +use std::path::{Path, PathBuf}; | ||
| 4 | use std::time::Duration; | 5 | use std::time::Duration; |
| 5 | 6 | ||
| 6 | pub struct Battery { | 7 | pub struct Battery { |
| @@ -12,6 +13,35 @@ pub struct Battery { | |||
| 12 | battery_path: String, | 13 | battery_path: String, |
| 13 | } | 14 | } |
| 14 | 15 | ||
| 16 | +fn detect_battery_name() -> Option<String> { | ||
| 17 | + let base = Path::new("/sys/class/power_supply"); | ||
| 18 | + let entries = fs::read_dir(base).ok()?; | ||
| 19 | + | ||
| 20 | + for entry in entries.flatten() { | ||
| 21 | + let path: PathBuf = entry.path(); | ||
| 22 | + | ||
| 23 | + let type_path = path.join("type"); | ||
| 24 | + let present_path = path.join("present"); | ||
| 25 | + | ||
| 26 | + let is_battery = fs::read_to_string(&type_path) | ||
| 27 | + .map(|s| s.trim() == "Battery") | ||
| 28 | + .unwrap_or(false); | ||
| 29 | + | ||
| 30 | + // Some systems omit "present"; treat missing as present. | ||
| 31 | + let is_present = fs::read_to_string(&present_path) | ||
| 32 | + .map(|s| s.trim() == "1") | ||
| 33 | + .unwrap_or(true); | ||
| 34 | + | ||
| 35 | + if is_battery && is_present { | ||
| 36 | + if let Some(name) = path.file_name().and_then(|n| n.to_str()) { | ||
| 37 | + return Some(name.to_string()); | ||
| 38 | + } | ||
| 39 | + } | ||
| 40 | + } | ||
| 41 | + | ||
| 42 | + None | ||
| 43 | +} | ||
| 44 | + | ||
| 15 | impl Battery { | 45 | impl Battery { |
| 16 | pub fn new( | 46 | pub fn new( |
| 17 | format_charging: &str, | 47 | format_charging: &str, |
| @@ -21,16 +51,17 @@ impl Battery { | |||
| 21 | color: u32, | 51 | color: u32, |
| 22 | battery_name: Option<String>, | 52 | battery_name: Option<String>, |
| 23 | ) -> Self { | 53 | ) -> Self { |
| 54 | + let name = battery_name | ||
| 55 | + .or_else(detect_battery_name) | ||
| 56 | + .unwrap_or_else(|| "BAT0".to_string()); | ||
| 57 | + | ||
| 24 | Self { | 58 | Self { |
| 25 | format_charging: format_charging.to_string(), | 59 | format_charging: format_charging.to_string(), |
| 26 | format_discharging: format_discharging.to_string(), | 60 | format_discharging: format_discharging.to_string(), |
| 27 | format_full: format_full.to_string(), | 61 | format_full: format_full.to_string(), |
| 28 | interval: Duration::from_secs(interval_secs), | 62 | interval: Duration::from_secs(interval_secs), |
| 29 | color, | 63 | color, |
| 30 | - battery_path: format!( | 64 | + battery_path: format!("/sys/class/power_supply/{}", name), |
| 31 | - "/sys/class/power_supply/{}", | ||
| 32 | - battery_name.unwrap_or_else(|| "BAT0".to_string()) | ||
| 33 | - ), | ||
| 34 | } | 65 | } |
| 35 | } | 66 | } |
| 36 | 67 | ||