aboutsummaryrefslogtreecommitdiffstats
path: root/src/power/mod.rs
blob: afe519424f7e3f24e73fbee9a92a4f47bb6dcced (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use std;

use std::io::Read;

mod sys;

// XXX maybe extract this out into a separate crate?

#[derive(Debug)]
pub struct PowerInfo {
    power_supplies: Vec<sys::PowerSupplyInfo>,
}

impl PowerInfo {
    pub fn new() -> PowerInfo {
        let power_supplies = sys::power_supplies();

        PowerInfo {
            power_supplies,
        }
    }

    pub fn battery_usage(&self) -> Option<f64> {
        let mut total_now = 0;
        let mut total_full = 0;
        for battery in self.batteries() {
            if let Some(now) = battery.energy_now {
                total_now += now;
            }
            else {
                return None;
            }
            if let Some(full) = battery.energy_full {
                total_full += full;
            }
            else {
                return None;
            }
        }

        if total_full > 0 {
            Some((total_now as f64) / (total_full as f64))
        }
        else {
            None
        }
    }

    pub fn charging(&self) -> bool {
        for mains in self.mains() {
            if mains.online == Some(true) {
                return true;
            }
        }
        false
    }

    pub fn has_batteries(&self) -> bool {
        self.batteries().count() > 0
    }

    fn batteries(&self) -> impl Iterator<Item=&sys::PowerSupplyInfo> {
        self.power_supplies
            .iter()
            .filter(|p| p.ty == sys::PowerSupplyType::Battery)
    }

    fn mains(&self) -> impl Iterator<Item=&sys::PowerSupplyInfo> {
        self.power_supplies
            .iter()
            .filter(|p| p.ty == sys::PowerSupplyType::AC)
    }
}

fn slurp<T, U>(path: U) -> Option<T>
where
    T: std::str::FromStr,
    U: AsRef<std::path::Path>,
{
    let mut contents = String::new();
    std::fs::File::open(path).ok().and_then(|mut fh| {
        fh.read_to_string(&mut contents)
            .ok()
            .and_then(|_| contents.trim().parse().ok())
    })
}