| 1 |
use super::Block;
|
| 2 |
use crate::errors::BlockError;
|
| 3 |
use std::fs;
|
| 4 |
use std::time::Duration;
|
| 5 |
|
| 6 |
pub struct Battery {
|
| 7 |
format_charging: String,
|
| 8 |
format_discharging: String,
|
| 9 |
format_full: String,
|
| 10 |
interval: Duration,
|
| 11 |
color: u32,
|
| 12 |
battery_path: String,
|
| 13 |
}
|
| 14 |
|
| 15 |
impl Battery {
|
| 16 |
pub fn new(
|
| 17 |
format_charging: &str,
|
| 18 |
format_discharging: &str,
|
| 19 |
format_full: &str,
|
| 20 |
interval_secs: u64,
|
| 21 |
color: u32,
|
| 22 |
) -> Self {
|
| 23 |
Self {
|
| 24 |
format_charging: format_charging.to_string(),
|
| 25 |
format_discharging: format_discharging.to_string(),
|
| 26 |
format_full: format_full.to_string(),
|
| 27 |
interval: Duration::from_secs(interval_secs),
|
| 28 |
color,
|
| 29 |
battery_path: "/sys/class/power_supply/BAT0".to_string(),
|
| 30 |
}
|
| 31 |
}
|
| 32 |
|
| 33 |
fn read_file(&self, filename: &str) -> Result<String, BlockError> {
|
| 34 |
let path = format!("{}/{}", self.battery_path, filename);
|
| 35 |
Ok(fs::read_to_string(path)?.trim().to_string())
|
| 36 |
}
|
| 37 |
|
| 38 |
fn get_capacity(&self) -> Result<u32, BlockError> {
|
| 39 |
Ok(self.read_file("capacity")?.parse()?)
|
| 40 |
}
|
| 41 |
|
| 42 |
fn get_status(&self) -> Result<String, BlockError> {
|
| 43 |
self.read_file("status")
|
| 44 |
}
|
| 45 |
}
|
| 46 |
|
| 47 |
impl Block for Battery {
|
| 48 |
fn content(&mut self) -> Result<String, BlockError> {
|
| 49 |
let capacity = self.get_capacity()?;
|
| 50 |
let status = self.get_status()?;
|
| 51 |
|
| 52 |
let format = match status.as_str() {
|
| 53 |
"Charging" => &self.format_charging,
|
| 54 |
"Full" => &self.format_full,
|
| 55 |
_ => &self.format_discharging,
|
| 56 |
};
|
| 57 |
|
| 58 |
Ok(format.replace("{}", &capacity.to_string()))
|
| 59 |
}
|
| 60 |
|
| 61 |
fn interval(&self) -> Duration {
|
| 62 |
self.interval
|
| 63 |
}
|
| 64 |
|
| 65 |
fn color(&self) -> u32 {
|
| 66 |
self.color
|
| 67 |
}
|
| 68 |
}
|