1use core::time::Duration;
20use std::sync::OnceLock;
21
22use crate::{Percent, Result};
23
24#[derive(Clone, Copy, Debug, PartialEq)]
26#[non_exhaustive]
27pub struct Battery {
28 pub charge: Percent,
30 pub state: BatteryState,
32 pub time_to_empty: Option<Duration>,
34 pub time_to_full: Option<Duration>,
36 pub health: Option<Percent>,
38 pub cycles: Option<u32>,
40}
41
42#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
44#[non_exhaustive]
45pub enum BatteryState {
46 Charging,
48 Discharging,
50 Full,
52 NotCharging,
54 Unknown,
56}
57
58#[derive(Clone, Copy, Debug, PartialEq)]
62pub(crate) struct RawBattery {
63 pub(crate) battery: Battery,
64 pub(crate) energy: Option<(u64, u64)>,
66}
67
68#[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
75pub fn battery() -> Result<Option<Battery>> {
82 Ok(combine(&crate::sys::batteries()?))
83}
84
85pub fn batteries() -> Result<Vec<Battery>> {
91 Ok(crate::sys::batteries()?.iter().map(|b| b.battery).collect())
92}
93
94pub fn on_ac() -> Result<Option<bool>> {
101 crate::sys::on_ac()
102}
103
104pub(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 health: None,
141 cycles: None,
142 })
143}
144
145fn 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 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 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 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}