58 lines
1.5 KiB
Rust
Executable File

#!/usr/bin/env rust-script
use std::{fmt, fs::read_to_string, str::FromStr};
const BASE_PATH: &str = "/sys/class/power_supply/BAT1/";
const CURRENT_NOW_PATH: &str = "current_now";
const VOLTAGE_NOW_PATH: &str = "voltage_now";
const STATUS_PATH: &str = "status";
const FACTOR: f32 = 1e6_f32;
#[derive(Debug)]
enum Status {
Charging,
Discharging,
NotCharging,
}
impl FromStr for Status {
type Err = &'static str;
fn from_str(input: &str) -> Result<Status, Self::Err> {
match input {
"Charging" => Ok(Status::Charging),
"Discharging" => Ok(Status::Discharging),
"Not charging" => Ok(Status::NotCharging),
_ => Err("unknown state"),
}
}
}
impl fmt::Display for Status {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
fn fetch_and_trim_into<T: FromStr<Err = impl fmt::Debug>>(path: &str) -> T {
let mut content = read_to_string(BASE_PATH.to_owned() + path).unwrap();
content.pop();
T::from_str(&content).unwrap()
}
fn fetch_bat_info(path: &str) -> f32 {
let value: f32 = fetch_and_trim_into(path);
value / FACTOR
}
fn main() {
let current_now: f32 = fetch_bat_info(CURRENT_NOW_PATH);
let voltage_now: f32 = fetch_bat_info(VOLTAGE_NOW_PATH);
let watts: f32 = current_now * voltage_now;
let status: Status = fetch_and_trim_into(STATUS_PATH);
println!(
"voltage: {:.4}\ncurrent: {:.4}\nwatts: {:.4}\nstatus: {}",
voltage_now, current_now, watts, status
);
}