Skip to main content

retch_sysinfo/
battery.rs

1// SPDX-License-Identifier: GPL-3.0-or-later
2// Copyright (C) 2026 l1a
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 output = std::process::Command::new("ioreg")
139        .args(["-r", "-c", "AppleSmartBattery"])
140        .output()
141        .ok()?;
142
143    if !output.status.success() {
144        return None;
145    }
146
147    let stdout = String::from_utf8_lossy(&output.stdout);
148    if stdout.trim().is_empty() {
149        return None;
150    }
151
152    let mut current_capacity: Option<f32> = None;
153    let mut max_capacity: Option<f32> = None;
154    let mut design_capacity: Option<f32> = None;
155    let mut is_charging = false;
156    let mut fully_charged = false;
157    let mut time_remaining_mins: Option<i32> = None;
158    let mut vendor: Option<String> = None;
159    let mut model: Option<String> = None;
160
161    for line in stdout.lines() {
162        if let Some(val) = parse_ioreg_line(line, "CurrentCapacity") {
163            current_capacity = val.parse().ok();
164        } else if let Some(val) = parse_ioreg_line(line, "MaxCapacity") {
165            max_capacity = val.parse().ok();
166        } else if let Some(val) = parse_ioreg_line(line, "DesignCapacity") {
167            design_capacity = val.parse().ok();
168        } else if let Some(val) = parse_ioreg_line(line, "IsCharging") {
169            is_charging = val == "Yes";
170        } else if let Some(val) = parse_ioreg_line(line, "FullyCharged") {
171            fully_charged = val == "Yes";
172        } else if let Some(val) = parse_ioreg_line(line, "TimeRemaining") {
173            time_remaining_mins = val.parse().ok();
174        } else if let Some(val) = parse_ioreg_line(line, "Manufacturer") {
175            vendor = Some(val);
176        } else if let Some(val) = parse_ioreg_line(line, "DeviceName") {
177            model = Some(val);
178        }
179    }
180
181    let max_cap = max_capacity?;
182    let cur_cap = current_capacity?;
183
184    let percentage = (cur_cap / max_cap) * 100.0;
185
186    let mut health = None;
187    if let Some(design_cap) = design_capacity {
188        if design_cap > 0.0 {
189            health = Some((max_cap / design_cap) * 100.0);
190        }
191    }
192
193    let state = if fully_charged {
194        BatteryState::Full
195    } else if is_charging {
196        BatteryState::Charging
197    } else {
198        BatteryState::Discharging
199    };
200
201    let mut time_remaining = None;
202    if let Some(mins) = time_remaining_mins {
203        if mins > 0 && mins < 65535 {
204            time_remaining = Some(std::time::Duration::from_secs((mins * 60) as u64));
205        }
206    }
207
208    Some(BatteryInfo {
209        percentage,
210        health,
211        state,
212        time_remaining,
213        vendor,
214        model,
215    })
216}
217
218#[cfg(target_os = "macos")]
219fn parse_ioreg_line(line: &str, key: &str) -> Option<String> {
220    if let Some(pos) = line.find(&format!("\"{}\"", key)) {
221        let after_key = &line[pos + key.len() + 2..];
222        if let Some(equals_pos) = after_key.find('=') {
223            let val = &after_key[equals_pos + 1..];
224            let val = val.trim().trim_matches('"');
225            return Some(val.to_string());
226        }
227    }
228    None
229}
230
231#[cfg(target_os = "windows")]
232mod win32 {
233    #[repr(C)]
234    pub struct SYSTEM_POWER_STATUS {
235        pub ac_line_status: u8,
236        pub battery_flag: u8,
237        pub battery_life_percent: u8,
238        pub system_status: u8,
239        pub battery_life_time: u32,
240        pub battery_full_life_time: u32,
241    }
242
243    #[link(name = "kernel32")]
244    extern "system" {
245        pub fn GetSystemPowerStatus(lpSystemPowerStatus: *mut SYSTEM_POWER_STATUS) -> i32;
246    }
247}
248
249#[cfg(target_os = "windows")]
250pub fn get_battery_info() -> Option<BatteryInfo> {
251    let mut status = win32::SYSTEM_POWER_STATUS {
252        ac_line_status: 255,
253        battery_flag: 255,
254        battery_life_percent: 255,
255        system_status: 0,
256        battery_life_time: 0xffffffff,
257        battery_full_life_time: 0xffffffff,
258    };
259
260    let res = unsafe { win32::GetSystemPowerStatus(&mut status) };
261    if res == 0 || status.battery_life_percent == 255 {
262        return None;
263    }
264
265    let percentage = status.battery_life_percent as f32;
266    let state = match status.ac_line_status {
267        1 => {
268            if percentage >= 100.0 {
269                BatteryState::Full
270            } else {
271                BatteryState::Charging
272            }
273        }
274        0 => BatteryState::Discharging,
275        _ => BatteryState::Unknown,
276    };
277
278    let time_remaining = if status.battery_life_time != 0xffffffff {
279        Some(std::time::Duration::from_secs(
280            status.battery_life_time as u64,
281        ))
282    } else {
283        None
284    };
285
286    let mut info = BatteryInfo {
287        percentage,
288        health: None,
289        state,
290        time_remaining,
291        vendor: None,
292        model: None,
293    };
294
295    if let Ok(output) = std::process::Command::new("wmic")
296        .args([
297            "path",
298            "Win32_Battery",
299            "get",
300            "DesignCapacity,FullChargeCapacity,Manufacturer,Name",
301            "/value",
302        ])
303        .output()
304    {
305        if let Ok(stdout) = String::from_utf8(output.stdout) {
306            let mut design_capacity: Option<f32> = None;
307            let mut full_charge_capacity: Option<f32> = None;
308
309            for line in stdout.lines() {
310                let line = line.trim();
311                if let Some(pos) = line.find('=') {
312                    let key = line[..pos].trim();
313                    let val = line[pos + 1..].trim();
314                    if !val.is_empty() {
315                        match key {
316                            "DesignCapacity" => design_capacity = val.parse().ok(),
317                            "FullChargeCapacity" => full_charge_capacity = val.parse().ok(),
318                            "Manufacturer" => info.vendor = Some(val.to_string()),
319                            "Name" => info.model = Some(val.to_string()),
320                            _ => {}
321                        }
322                    }
323                }
324            }
325
326            if let (Some(full), Some(design)) = (full_charge_capacity, design_capacity) {
327                if design > 0.0 {
328                    info.health = Some((full / design) * 100.0);
329                }
330            }
331        }
332    }
333
334    Some(info)
335}
336
337#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
338pub fn get_battery_info() -> Option<BatteryInfo> {
339    None
340}
341
342// Helpers
343#[cfg(target_os = "linux")]
344fn read_file_to_string<P: AsRef<Path>>(path: P) -> Option<String> {
345    fs::read_to_string(path).ok().map(|s| s.trim().to_string())
346}
347
348#[cfg(target_os = "linux")]
349fn read_file_to_num<T: std::str::FromStr, P: AsRef<Path>>(path: P) -> Option<T> {
350    read_file_to_string(path).and_then(|s| s.parse().ok())
351}