tony / oxwm

Branch: 661f3e4
Switch branches/tags
master
Daniel Azevedo battery detection function addded 661f3e4 2026-01-06
103 lines · 2.7 KB Raw Blame History
1 use super::Block;
2 use crate::errors::BlockError;
3 use std::fs;
4 use std::path::{Path, PathBuf};
5 use std::time::Duration;
6
7 pub struct Battery {
8 format_charging: String,
9 format_discharging: String,
10 format_full: String,
11 interval: Duration,
12 color: u32,
13 battery_path: String,
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
45 impl Battery {
46 pub fn new(
47 format_charging: &str,
48 format_discharging: &str,
49 format_full: &str,
50 interval_secs: u64,
51 color: u32,
52 battery_name: Option<String>,
53 ) -> Self {
54 let name = battery_name
55 .or_else(detect_battery_name)
56 .unwrap_or_else(|| "BAT0".to_string());
57
58 Self {
59 format_charging: format_charging.to_string(),
60 format_discharging: format_discharging.to_string(),
61 format_full: format_full.to_string(),
62 interval: Duration::from_secs(interval_secs),
63 color,
64 battery_path: format!("/sys/class/power_supply/{}", name),
65 }
66 }
67
68 fn read_file(&self, filename: &str) -> Result<String, BlockError> {
69 let path = format!("{}/{}", self.battery_path, filename);
70 Ok(fs::read_to_string(path)?.trim().to_string())
71 }
72
73 fn get_capacity(&self) -> Result<u32, BlockError> {
74 Ok(self.read_file("capacity")?.parse()?)
75 }
76
77 fn get_status(&self) -> Result<String, BlockError> {
78 self.read_file("status")
79 }
80 }
81
82 impl Block for Battery {
83 fn content(&mut self) -> Result<String, BlockError> {
84 let capacity = self.get_capacity()?;
85 let status = self.get_status()?;
86
87 let format = match status.as_str() {
88 "Charging" => &self.format_charging,
89 "Full" => &self.format_full,
90 _ => &self.format_discharging,
91 };
92
93 Ok(format.replace("{}", &capacity.to_string()))
94 }
95
96 fn interval(&self) -> Duration {
97 self.interval
98 }
99
100 fn color(&self) -> u32 {
101 self.color
102 }
103 }