Skip to main content

sys_lib/
power.rs

1//! The system battery and mains power.
2//!
3//! Only batteries that power the machine count: wireless mice, keyboards, and
4//! headsets report batteries too and are left out (E-81). Several internal
5//! batteries are combined by energy, not by averaging percentages (E-82).
6//!
7//! ```
8//! use sys_lib as sys;
9//!
10//! if let Some(b) = sys::power::battery()? {
11//!     println!("battery {} {:?}, empty in {:?}", b.charge, b.state, b.time_to_empty);
12//! }
13//! if sys::power::on_ac()? == Some(false) {
14//!     // on battery: back off background work
15//! }
16//! # Ok::<(), sys_lib::Error>(())
17//! ```
18
19use core::time::Duration;
20use std::sync::OnceLock;
21
22use crate::{Percent, Result};
23
24/// A battery, or several combined.
25#[derive(Clone, Copy, Debug, PartialEq)]
26#[non_exhaustive]
27pub struct Battery {
28    /// How full it is.
29    pub charge: Percent,
30    /// What it is doing.
31    pub state: BatteryState,
32    /// How long it lasts at the present draw, when the OS can tell.
33    pub time_to_empty: Option<Duration>,
34    /// How long until it is full, when the OS can tell.
35    pub time_to_full: Option<Duration>,
36    /// Full capacity over design capacity.
37    pub health: Option<Percent>,
38    /// Charge cycles.
39    pub cycles: Option<u32>,
40}
41
42/// What a battery is doing.
43#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
44#[non_exhaustive]
45pub enum BatteryState {
46    /// Charging.
47    Charging,
48    /// Powering the machine.
49    Discharging,
50    /// Full.
51    Full,
52    /// On mains power and not charging (a charge limit, or a full pack).
53    NotCharging,
54    /// The OS does not say (E-83).
55    Unknown,
56}
57
58/// A battery as a platform reports it, with the energy figures
59/// [`combine`] needs. `energy` is a platform's own unit, compared only with
60/// itself.
61#[derive(Clone, Copy, Debug, PartialEq)]
62pub(crate) struct RawBattery {
63    pub(crate) battery: Battery,
64    /// Energy now and when full; `None` when the OS gives only a percentage.
65    pub(crate) energy: Option<(u64, u64)>,
66}
67
68/// Whether the machine has a system battery. Cached.
69#[must_use]
70pub fn has_battery() -> bool {
71    static FACT: OnceLock<bool> = OnceLock::new();
72    *FACT.get_or_init(crate::sys::has_battery)
73}
74
75/// The system battery, several combined; `None` when there is none.
76///
77/// # Errors
78///
79/// `PermissionDenied` where the OS refuses (SELinux on Android, E-90);
80/// `Unsupported` on iOS.
81pub fn battery() -> Result<Option<Battery>> {
82    Ok(combine(&crate::sys::batteries()?))
83}
84
85/// Every system battery separately, in the order the OS lists them.
86///
87/// # Errors
88///
89/// As [`battery`].
90pub fn batteries() -> Result<Vec<Battery>> {
91    Ok(crate::sys::batteries()?.iter().map(|b| b.battery).collect())
92}
93
94/// Whether the machine runs on mains power; `None` when it cannot be told,
95/// which is the answer on a desktop with no power information.
96///
97/// # Errors
98///
99/// As [`battery`].
100pub fn on_ac() -> Result<Option<bool>> {
101    crate::sys::on_ac()
102}
103
104/// Combines batteries by energy (E-82): the sum of energy now over the sum of
105/// energy when full. Without energy figures on every battery, percentages are
106/// averaged. Times add when discharging together.
107pub(crate) fn combine(all: &[RawBattery]) -> Option<Battery> {
108    let (first, rest) = all.split_first()?;
109    if rest.is_empty() {
110        return Some(first.battery);
111    }
112    let energies: Option<Vec<(u64, u64)>> = all.iter().map(|b| b.energy).collect();
113    let charge = match energies {
114        Some(e) => {
115            let now: u128 = e.iter().map(|&(n, _)| u128::from(n)).sum();
116            let full: u128 = e.iter().map(|&(_, f)| u128::from(f)).sum();
117            if full == 0 {
118                first.battery.charge
119            } else {
120                Percent::from_ratio_u128(now, full)
121            }
122        }
123        None => {
124            let sum: f32 = all.iter().map(|b| b.battery.charge.value()).sum();
125            Percent::from_value(sum / all.len() as f32)
126        }
127    };
128    let state = combined_state(all);
129    let total = |pick: fn(&Battery) -> Option<Duration>| {
130        all.iter()
131            .map(|b| pick(&b.battery))
132            .try_fold(Duration::ZERO, |sum, t| Some(sum.saturating_add(t?)))
133    };
134    Some(Battery {
135        charge,
136        state,
137        time_to_empty: total(|b| b.time_to_empty),
138        time_to_full: all.iter().filter_map(|b| b.battery.time_to_full).max(),
139        // One pack's health or cycles does not describe the set.
140        health: None,
141        cycles: None,
142    })
143}
144
145/// Charging if any pack charges, discharging if any pack discharges, full when
146/// all are.
147fn combined_state(all: &[RawBattery]) -> BatteryState {
148    let any = |s: BatteryState| all.iter().any(|b| b.battery.state == s);
149    if any(BatteryState::Charging) {
150        BatteryState::Charging
151    } else if any(BatteryState::Discharging) {
152        BatteryState::Discharging
153    } else if all.iter().all(|b| b.battery.state == BatteryState::Full) {
154        BatteryState::Full
155    } else if any(BatteryState::NotCharging) {
156        BatteryState::NotCharging
157    } else {
158        BatteryState::Unknown
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    fn raw(charge: f32, state: BatteryState, energy: Option<(u64, u64)>) -> RawBattery {
167        RawBattery {
168            battery: Battery {
169                charge: Percent::from_value(charge),
170                state,
171                time_to_empty: Some(Duration::from_secs(600)),
172                time_to_full: None,
173                health: Some(Percent::from_value(90.0)),
174                cycles: Some(10),
175            },
176            energy,
177        }
178    }
179
180    #[test]
181    fn test_power_combine_by_energy_not_percentage() {
182        // E-82: 10 of 100 and 90 of 100 is 50%; 99 of 100 and 1 of 10 is 90%,
183        // where averaging would say 54.5%.
184        let c = combine(&[
185            raw(99.0, BatteryState::Discharging, Some((99, 100))),
186            raw(10.0, BatteryState::Discharging, Some((1, 10))),
187        ])
188        .unwrap();
189        assert_eq!(c.charge.to_string(), "90.9%");
190        assert_eq!(c.state, BatteryState::Discharging);
191        assert_eq!(c.time_to_empty, Some(Duration::from_secs(1200)));
192        assert_eq!((c.health, c.cycles), (None, None));
193    }
194
195    #[test]
196    fn test_power_combine_edge_cases() {
197        assert_eq!(combine(&[]), None);
198        let one = raw(40.0, BatteryState::Charging, None);
199        assert_eq!(combine(&[one]), Some(one.battery));
200        // No energy figures: the mean of the percentages.
201        let c = combine(&[
202            raw(40.0, BatteryState::Full, None),
203            raw(60.0, BatteryState::Full, None),
204        ])
205        .unwrap();
206        assert_eq!(c.charge.to_string(), "50.0%");
207        assert_eq!(c.state, BatteryState::Full);
208        // Empty packs do not divide by zero.
209        let c = combine(&[
210            raw(0.0, BatteryState::Unknown, Some((0, 0))),
211            raw(0.0, BatteryState::NotCharging, Some((0, 0))),
212        ])
213        .unwrap();
214        assert_eq!(c.state, BatteryState::NotCharging);
215    }
216
217    #[test]
218    fn test_power_live_never_fails_oddly() {
219        let _ = has_battery();
220        if let Ok(Some(b)) = battery() {
221            assert!(b.charge <= Percent::FULL);
222        }
223        let _ = on_ac();
224    }
225}