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
//! An interface to read data from the system’s power_supply class.
//! Uses the built-in legoev3-battery if none is specified.

use std::fs;

use crate::{utils::OrErr, Attribute, Device, Driver, Ev3Error, Ev3Result};

/// An interface to read data from the system’s power_supply class.
/// Uses the built-in legoev3-battery if none is specified.
#[derive(Debug, Clone, Device)]
pub struct PowerSupply {
    driver: Driver,
}

impl PowerSupply {
    /// Create a new instance of `PowerSupply`.
    pub fn new() -> Ev3Result<PowerSupply> {
        let paths = fs::read_dir("/sys/class/power_supply")?;

        for path in paths {
            let file_name = path?.file_name();
            let name = file_name.to_str().or_err()?;

            if name.contains("ev3-battery") {
                return Ok(PowerSupply {
                    driver: Driver::new("power_supply", name),
                });
            }
        }

        Err(Ev3Error::NotConnected {
            device: "power_supply".to_owned(),
            port: None,
        })
    }

    /// Returns the battery current in microamps
    pub fn get_current_now(&self) -> Ev3Result<i32> {
        self.get_attribute("current_now").get()
    }

    /// Always returns System.
    pub fn get_scope(&self) -> Ev3Result<String> {
        self.get_attribute("zscope").get()
    }

    /// Returns Unknown or Li-ion depending on if the rechargeable battery is present.
    pub fn get_technology(&self) -> Ev3Result<String> {
        self.get_attribute("technology").get()
    }

    /// Always returns Battery.
    pub fn get_type(&self) -> Ev3Result<String> {
        self.get_attribute("type").get()
    }

    /// Returns the nominal “full” battery voltage. The value returned depends on technology.
    pub fn get_voltage_max_design(&self) -> Ev3Result<i32> {
        self.get_attribute("voltage_max_design").get()
    }

    /// Returns the nominal “empty” battery voltage. The value returned depends on technology.
    pub fn get_voltage_min_design(&self) -> Ev3Result<i32> {
        self.get_attribute("voltage_min_design").get()
    }

    /// Returns the battery voltage in microvolts.
    pub fn get_voltage_now(&self) -> Ev3Result<i32> {
        self.get_attribute("voltage_now").get()
    }
}