aboutsummaryrefslogtreecommitdiffstats
path: root/src/power.rs
blob: 725e9fef99111578013dbf1cffc8b21d716678cd (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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
use std;
use walkdir;

use std::io::Read;

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

#[derive(PartialEq, Eq, Debug, Clone)]
enum PowerSupplyType {
    AC,
    Battery,
}

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

#[derive(Debug, Clone)]
struct PowerSupplyInfo {
    name: String,
    ty: PowerSupplyType,
    energy_now: Option<u64>,
    energy_full: Option<u64>,
    online: Option<bool>,
}

impl PowerInfo {
    pub fn new() -> PowerInfo {
        let mut power_supplies = vec![];
        for entry in walkdir::WalkDir::new("/sys/class/power_supply/")
            .min_depth(1)
            .max_depth(1)
            .follow_links(true)
        {
            let entry = entry.unwrap();

            let name = entry
                .path()
                .file_name()
                .unwrap()
                .to_string_lossy()
                .into_owned();
            let ty = slurp(entry.path().join("type"))
                .map(|t: String| PowerSupplyType::from_str(&t))
                .expect("couldn't find power supply type");
            let energy_full = slurp(entry.path().join("energy_full"));
            let energy_now = slurp(entry.path().join("energy_now"));
            let online =
                slurp(entry.path().join("online")).map(|n: u8| n != 0);

            power_supplies.push(PowerSupplyInfo {
                name,
                ty,
                energy_now,
                energy_full,
                online,
            })
        }

        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
    }

    fn batteries(&self) -> Vec<&PowerSupplyInfo> {
        self.power_supplies
            .iter()
            .filter(|p| p.ty == PowerSupplyType::Battery)
            .collect()
    }

    fn mains(&self) -> Vec<&PowerSupplyInfo> {
        self.power_supplies
            .iter()
            .filter(|p| p.ty == PowerSupplyType::AC)
            .collect()
    }
}

impl PowerSupplyType {
    fn from_str(ty: &str) -> Self {
        match ty {
            "Mains" => PowerSupplyType::AC,
            "Battery" => PowerSupplyType::Battery,
            _ => panic!("unknown power supply type {}", ty),
        }
    }
}

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())
    })
}