Created
August 13, 2017 12:44
-
-
Save Ploppz/9f6b9912ef58930d85471e55008e16e7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::sync::mpsc::Sender; | |
use std::time::Duration; | |
use std::thread; | |
use std::sync::{Arc, RwLock}; | |
use super::base::Widget; | |
use format::data::Format; | |
use std::fs::File; | |
use std::io::{Read, Seek, SeekFrom}; | |
pub struct BatteryState { | |
pub remaining: u32, | |
pub charging: bool, | |
} | |
pub struct Battery<F: Fn(BatteryState) -> Format> { | |
updater: Arc<Box<F>>, | |
last_value: Arc<RwLock<Format>>, | |
} | |
impl<F> Widget for Battery<F> where F: Fn(BatteryState) -> Format + Sync + Send + 'static { | |
fn current_value(&self) -> Format { | |
(*self.last_value).read().unwrap().clone() | |
} | |
fn spawn_notifier(&mut self, tx: Sender<()>) { | |
let updater = self.updater.clone(); | |
let last_value = self.last_value.clone(); | |
thread::spawn(move || { | |
let mut capacity_file = File::open("/tmp/capacity").unwrap(); | |
let mut status_file = File::open("/tmp/status").unwrap(); | |
loop { | |
capacity_file.seek(SeekFrom::Start(0)); | |
status_file.seek(SeekFrom::Start(0)); | |
// Read capacity (remaining %) | |
let mut capacity = String::new(); | |
capacity_file.read_to_string(&mut capacity).unwrap(); | |
let remaining = capacity.trim().parse::<u32>().unwrap(); | |
// Read status (charging/discharging) | |
let mut status = String::new(); | |
status_file.read_to_string(&mut status).unwrap(); | |
let charging = match status.trim() { | |
"Charging" => true, | |
_ => false, | |
}; | |
let battery_state = BatteryState { | |
remaining: remaining, | |
charging: charging, | |
}; | |
let mut writer = last_value.write().unwrap(); | |
*writer = (*updater)(battery_state); | |
let _ = tx.send(()); | |
thread::sleep(Duration::from_secs(5)); | |
} | |
}); | |
} | |
} | |
impl<F> Battery<F> where F: Fn(BatteryState) -> Format { | |
pub fn new(updater: F) -> Box<Battery<F>> { | |
Box::new(Battery { | |
updater: Arc::new(Box::new(updater)), | |
last_value: Arc::new(RwLock::new(Format::Str("".to_owned()))), | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment