Thomas Dy 9 жил өмнө
parent
commit
6c38e5718c
1 өөрчлөгдсөн 39 нэмэгдсэн , 0 устгасан
  1. 39 0
      src/sensors.rs

+ 39 - 0
src/sensors.rs

@@ -12,6 +12,40 @@ trait Sensor {
     fn status(&mut self) -> String;
 }
 
+struct BatterySensor {
+    charge_now: File,
+    charge_full: File
+}
+
+impl BatterySensor {
+    fn new(supply: &str) -> BatterySensor {
+        let path = format!("/sys/class/power_supply/{}", supply);
+        BatterySensor {
+            charge_now: File::open(format!("{}/{}", path, "charge_now")).unwrap(),
+            charge_full: File::open(format!("{}/{}", path, "charge_full")).unwrap()
+        }
+    }
+}
+
+impl Sensor for BatterySensor {
+    fn status(&mut self) -> String {
+        let mut s = String::new();
+
+        self.charge_now.read_to_string(&mut s).ok().expect("Could not read current charge");
+        let charge_now : u32 = s.trim().parse().ok().expect("Could not parse charge");
+
+        s.clear();
+
+        self.charge_full.read_to_string(&mut s).ok().expect("Could not read current charge");
+        let charge_full : u32 = s.trim().parse().ok().expect("Could not parse charge");
+
+        self.charge_now.seek(SeekFrom::Start(0)).ok();
+        self.charge_full.seek(SeekFrom::Start(0)).ok();
+
+        format!("{}%", charge_now / (charge_full / 100))
+    }
+}
+
 struct TempSensor {
     file: File
 }
@@ -73,12 +107,17 @@ pub fn sensors(tx: &Channel, config: &Config) {
     let zone = config.lookup("sensors.thermal_zone").unwrap();
     let zone = zone.as_str().unwrap();
 
+
     let mut sensors: Vec<Box<Sensor>> = vec![
         Box::new(TempSensor::new(zone)),
         Box::new(TimeSensor::new("%Y-%m-%d %H:%M", false)),
         Box::new(TimeSensor::new("UTC %H:%M", true))
     ];
 
+    let bat = config.lookup("sensors.battery");
+    let bat = bat.map(|bat| bat.as_str().unwrap());
+    bat.map(|bat| sensors.insert(0, Box::new(BatterySensor::new(bat))));
+
     loop {
         let status = sensors.iter_mut()
             .map(|sensor| sensor.status())