2021-06-25 07:20:50 +02:00

79 lines
2.1 KiB
Rust

use std::io;
use std::io::Read;
/// Battery parser using linux' `power_supply` class
#[allow(dead_code)]
pub struct Battery {
state_file: String,
capacity_file: String,
}
impl Battery {
/// Returns a battery representing object.
/// # Arguments:
/// * `name` - The name of the battery as it is represented in the sys file system.
/// (`/sys/class/power_supply/<name>`)
/// # Example:
/// ```
/// mod battery;
/// use battery::Battery;
/// let mut battery = Battery::new("BAT0");
/// ```
#[allow(dead_code)]
pub fn new(name: &str) -> Battery {
let path: String = format!("/sys/class/power_supply/{}/", name);
Battery {
state_file: format!("{}status", path),
capacity_file: format!("{}capacity", path),
}
}
/// Get the current state of the battery.
/// Return values:
/// * `"Unknown"`
/// * `"Charging"`
/// * `"Discharging"`
/// * `"Not_Charging"`
/// * `"Full"`
/// # Example:
/// ```
/// println!("Battery state: {}", battery.state());
/// ```
#[allow(dead_code)]
pub fn state(&mut self) -> String {
match Battery::read_file(&self.state_file) {
Ok(status) => String::from(status.trim()),
Err(_) => String::from("Unknown"),
}
}
/// Get the current capacity of the battery [%].
/// # Example:
/// ```
/// match battery.capacity() {
/// Some(cap) => println!("{} %", cap),
/// None => {},
/// }
/// ```
#[allow(dead_code)]
pub fn capacity(&mut self) ->Option<u8> {
match Battery::read_file(&self.capacity_file) {
Ok(capacity) => Some(capacity.trim().parse::<u8>().unwrap_or(0)),
Err(_) => None,
}
}
fn read_file(name: &str) -> Result<String, io::Error> {
let f = std::fs::File::open(name);
let mut f = match f {
Ok(file) => file,
Err(e) => return Err(e),
};
let mut line = String::new();
match f.read_to_string(&mut line) {
Ok(_) => Ok(line),
Err(e) =>Err(e),
}
}
}