Skip to main content

retch_sysinfo/
battery.rs

1// SPDX-FileCopyrightText: 2026 Ken Tobias
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4#[cfg(target_os = "linux")]
5use std::fs;
6#[cfg(target_os = "linux")]
7use std::path::Path;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum BatteryState {
11    Charging,
12    Discharging,
13    Full,
14    Unknown,
15}
16
17#[derive(Debug, Clone)]
18pub struct BatteryInfo {
19    pub percentage: f32,
20    pub health: Option<f32>,
21    pub state: BatteryState,
22    pub time_remaining: Option<std::time::Duration>,
23    pub vendor: Option<String>,
24    pub model: Option<String>,
25}
26
27#[cfg(target_os = "linux")]
28pub fn get_battery_info() -> Option<BatteryInfo> {
29    let power_supply = Path::new("/sys/class/power_supply");
30    if !power_supply.exists() {
31        return None;
32    }
33
34    let entries = fs::read_dir(power_supply).ok()?;
35    for entry in entries.flatten() {
36        let path = entry.path();
37        let name = path.file_name()?.to_string_lossy();
38        if name.starts_with("BAT") || name.starts_with("sb-") {
39            // Read type to confirm it's a battery
40            if let Some(supply_type) = read_file_to_string(path.join("type")) {
41                if supply_type != "Battery" {
42                    continue;
43                }
44            }
45
46            // Read capacity
47            let percentage = read_file_to_num::<f32, _>(path.join("capacity"))?;
48
49            // Read status
50            let state_str = read_file_to_string(path.join("status")).unwrap_or_default();
51            let state = match state_str.as_str() {
52                "Charging" => BatteryState::Charging,
53                "Discharging" => BatteryState::Discharging,
54                "Full" => BatteryState::Full,
55                _ => BatteryState::Unknown,
56            };
57
58            // Read vendor & model
59            let vendor = read_file_to_string(path.join("manufacturer"))
60                .or_else(|| read_file_to_string(path.join("vendor")));
61            let model = read_file_to_string(path.join("model_name"))
62                .or_else(|| read_file_to_string(path.join("model")));
63
64            // Compute health
65            let mut health = None;
66            if let (Some(full), Some(design)) = (
67                read_file_to_num::<f32, _>(path.join("energy_full")),
68                read_file_to_num::<f32, _>(path.join("energy_full_design")),
69            ) {
70                if design > 0.0 {
71                    health = Some((full / design) * 100.0);
72                }
73            } else if let (Some(full), Some(design)) = (
74                read_file_to_num::<f32, _>(path.join("charge_full")),
75                read_file_to_num::<f32, _>(path.join("charge_full_design")),
76            ) {
77                if design > 0.0 {
78                    health = Some((full / design) * 100.0);
79                }
80            }
81
82            // Compute time remaining
83            let mut time_remaining = None;
84            if state == BatteryState::Charging || state == BatteryState::Discharging {
85                if let (Some(power), Some(energy_now)) = (
86                    read_file_to_num::<f64, _>(path.join("power_now")),
87                    read_file_to_num::<f64, _>(path.join("energy_now")),
88                ) {
89                    if power > 0.0 {
90                        let hours = match state {
91                            BatteryState::Discharging => energy_now / power,
92                            BatteryState::Charging => {
93                                let energy_full =
94                                    read_file_to_num::<f64, _>(path.join("energy_full"))
95                                        .unwrap_or(energy_now);
96                                (energy_full - energy_now).max(0.0) / power
97                            }
98                            _ => 0.0,
99                        };
100                        time_remaining = Some(std::time::Duration::from_secs_f64(hours * 3600.0));
101                    }
102                } else if let (Some(current), Some(charge_now)) = (
103                    read_file_to_num::<f64, _>(path.join("current_now")),
104                    read_file_to_num::<f64, _>(path.join("charge_now")),
105                ) {
106                    if current > 0.0 {
107                        let hours = match state {
108                            BatteryState::Discharging => charge_now / current,
109                            BatteryState::Charging => {
110                                let charge_full =
111                                    read_file_to_num::<f64, _>(path.join("charge_full"))
112                                        .unwrap_or(charge_now);
113                                (charge_full - charge_now).max(0.0) / current
114                            }
115                            _ => 0.0,
116                        };
117                        time_remaining = Some(std::time::Duration::from_secs_f64(hours * 3600.0));
118                    }
119                }
120            }
121
122            return Some(BatteryInfo {
123                percentage,
124                health,
125                state,
126                time_remaining,
127                vendor,
128                model,
129            });
130        }
131    }
132
133    None
134}
135
136#[cfg(target_os = "macos")]
137pub fn get_battery_info() -> Option<BatteryInfo> {
138    let raw = crate::macos_ffi::get_battery_raw()?;
139
140    let max_cap = raw.max_mah? as f32;
141    let cur_cap = raw.current_mah? as f32;
142
143    let percentage = if max_cap > 0.0 {
144        (cur_cap / max_cap) * 100.0
145    } else {
146        0.0
147    };
148
149    let health = raw.design_mah.and_then(|design| {
150        if design == 0 {
151            return None;
152        }
153        let h_max = raw.raw_max_mah.or(raw.max_mah)? as f32;
154        Some((h_max / design as f32) * 100.0)
155    });
156
157    let state = if raw.fully_charged {
158        BatteryState::Full
159    } else if raw.is_charging {
160        BatteryState::Charging
161    } else {
162        BatteryState::Discharging
163    };
164
165    let time_remaining = raw
166        .time_remaining_mins
167        .map(|m| std::time::Duration::from_secs(m * 60));
168
169    Some(BatteryInfo {
170        percentage,
171        health,
172        state,
173        time_remaining,
174        vendor: raw.vendor,
175        model: raw.model,
176    })
177}
178
179#[cfg(target_os = "windows")]
180mod win32 {
181    #[repr(C)]
182    pub struct SYSTEM_POWER_STATUS {
183        pub ac_line_status: u8,
184        pub battery_flag: u8,
185        pub battery_life_percent: u8,
186        pub system_status: u8,
187        pub battery_life_time: u32,
188        pub battery_full_life_time: u32,
189    }
190
191    #[link(name = "kernel32")]
192    extern "system" {
193        pub fn GetSystemPowerStatus(lpSystemPowerStatus: *mut SYSTEM_POWER_STATUS) -> i32;
194    }
195}
196
197#[cfg(target_os = "windows")]
198pub fn get_battery_info() -> Option<BatteryInfo> {
199    let mut status = win32::SYSTEM_POWER_STATUS {
200        ac_line_status: 255,
201        battery_flag: 255,
202        battery_life_percent: 255,
203        system_status: 0,
204        battery_life_time: 0xffffffff,
205        battery_full_life_time: 0xffffffff,
206    };
207
208    let res = unsafe { win32::GetSystemPowerStatus(&mut status) };
209    if res == 0 || status.battery_life_percent == 255 {
210        return None;
211    }
212
213    let percentage = status.battery_life_percent as f32;
214    let state = match status.ac_line_status {
215        1 => {
216            if percentage >= 100.0 {
217                BatteryState::Full
218            } else {
219                BatteryState::Charging
220            }
221        }
222        0 => BatteryState::Discharging,
223        _ => BatteryState::Unknown,
224    };
225
226    let time_remaining = if status.battery_life_time != 0xffffffff {
227        Some(std::time::Duration::from_secs(
228            status.battery_life_time as u64,
229        ))
230    } else {
231        None
232    };
233
234    let mut info = BatteryInfo {
235        percentage,
236        health: None,
237        state,
238        time_remaining,
239        vendor: None,
240        model: None,
241    };
242
243    if let Ok(output) = std::process::Command::new("powershell")
244        .args([
245            "-Command",
246            "Get-CimInstance Win32_Battery | Select-Object DesignCapacity,FullChargeCapacity,Manufacturer,Name | Format-List",
247        ])
248        .output()
249    {
250        if let Ok(stdout) = String::from_utf8(output.stdout) {
251            let mut design_capacity: Option<f32> = None;
252            let mut full_charge_capacity: Option<f32> = None;
253
254            for line in stdout.lines() {
255                let line = line.trim();
256                if let Some(pos) = line.find(':') {
257                    let key = line[..pos].trim();
258                    let val = line[pos + 1..].trim();
259                    if !val.is_empty() {
260                        match key {
261                            "DesignCapacity" => design_capacity = val.parse().ok(),
262                            "FullChargeCapacity" => full_charge_capacity = val.parse().ok(),
263                            "Manufacturer" => info.vendor = Some(val.to_string()),
264                            "Name" => info.model = Some(val.to_string()),
265                            _ => {}
266                        }
267                    }
268                }
269            }
270
271            if let (Some(full), Some(design)) = (full_charge_capacity, design_capacity) {
272                if design > 0.0 {
273                    info.health = Some((full / design) * 100.0);
274                }
275            }
276        }
277    }
278
279    Some(info)
280}
281
282#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
283pub fn get_battery_info() -> Option<BatteryInfo> {
284    None
285}
286
287// Helpers
288#[cfg(target_os = "linux")]
289fn read_file_to_string<P: AsRef<Path>>(path: P) -> Option<String> {
290    fs::read_to_string(path).ok().map(|s| s.trim().to_string())
291}
292
293#[cfg(target_os = "linux")]
294fn read_file_to_num<T: std::str::FromStr, P: AsRef<Path>>(path: P) -> Option<T> {
295    read_file_to_string(path).and_then(|s| s.parse().ok())
296}