From 10d6c57128e05aa6289bbbb6c6338fe056cb6626 Mon Sep 17 00:00:00 2001 From: Lucien Cartier-Tilet Date: Tue, 11 Aug 2020 18:04:25 +0200 Subject: [PATCH] Bring PumoPM to a working state PumoPM successfuly runs now, displays a notification on low battery, warning on very low battery, and suspends the computer on critical battery level. --- Cargo.lock | 94 ++++++++++--------- Cargo.toml | 7 +- src/battery_state.rs | 215 ++++++++++++++++++++++++++++++++----------- src/main.rs | 15 +-- 4 files changed, 215 insertions(+), 116 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b687852..81cd68f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12,17 +12,6 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cff77d8686867eceff3105329d4698d96c2391c176d5d03adc90c7389162b5b8" -[[package]] -name = "atty" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -dependencies = [ - "hermit-abi", - "libc", - "winapi", -] - [[package]] name = "autocfg" version = "1.0.0" @@ -101,7 +90,7 @@ checksum = "c74d84029116787153e02106bf53e66828452a4b325cc8652b788b5967c0a0b6" dependencies = [ "num-integer", "num-traits", - "time", + "time 0.1.43", ] [[package]] @@ -110,14 +99,11 @@ version = "3.0.0-beta.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "860643c53f980f0d38a5e25dfab6c3c93b2cb3aa1fe192643d17a293c6c41936" dependencies = [ - "atty", "bitflags 1.2.1", "clap_derive", "indexmap", "lazy_static", "os_str_bytes", - "strsim", - "termcolor", "textwrap", "unicode-width", "vec_map", @@ -219,15 +205,6 @@ dependencies = [ "unicode-segmentation", ] -[[package]] -name = "hermit-abi" -version = "0.1.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3deed196b6e7f9e44a2ae8d94225d80302d81208b1bb673fd21fe634645c85a9" -dependencies = [ - "libc", -] - [[package]] name = "indexmap" version = "1.5.1" @@ -405,6 +382,12 @@ dependencies = [ "version_check", ] +[[package]] +name = "proc-macro-hack" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99c605b9a0adc77b7211c6b1f722dcb613d68d66859a44f3d485a6da332b0598" + [[package]] name = "proc-macro2" version = "1.0.19" @@ -421,6 +404,7 @@ dependencies = [ "battery", "clap", "notify-rust", + "time 0.2.16", ] [[package]] @@ -468,10 +452,13 @@ dependencies = [ ] [[package]] -name = "strsim" -version = "0.10.0" +name = "standback" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" +checksum = "b0437cfb83762844799a60e1e3b489d5ceb6a650fbacb86437badc1b6d87b246" +dependencies = [ + "version_check", +] [[package]] name = "strum" @@ -531,15 +518,6 @@ dependencies = [ "unicode-xid 0.0.4", ] -[[package]] -name = "termcolor" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb6bfa289a4d7c5766392812c0a1f4c1ba45afa1ad47803c11e1f407d846d75f" -dependencies = [ - "winapi-util", -] - [[package]] name = "textwrap" version = "0.11.0" @@ -559,6 +537,41 @@ dependencies = [ "winapi", ] +[[package]] +name = "time" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a51cadc5b1eec673a685ff7c33192ff7b7603d0b75446fb354939ee615acb15" +dependencies = [ + "cfg-if", + "standback", + "time-macros", + "version_check", +] + +[[package]] +name = "time-macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae9b6e9f095bc105e183e3cd493d72579be3181ad4004fceb01adbe9eecab2d" +dependencies = [ + "proc-macro-hack", + "time-macros-impl", +] + +[[package]] +name = "time-macros-impl" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5c3be1edfad6027c69f5491cf4cb310d1a71ecd6af742788c6ff8bced86b8fa" +dependencies = [ + "proc-macro-hack", + "proc-macro2", + "quote 1.0.7", + "standback", + "syn 1.0.38", +] + [[package]] name = "typenum" version = "1.12.0" @@ -639,15 +652,6 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" -[[package]] -name = "winapi-util" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" -dependencies = [ - "winapi", -] - [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" diff --git a/Cargo.toml b/Cargo.toml index 99dc74c..e8a4948 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ publish = false # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -battery = "0.7.5" -notify-rust = "4" -clap = "3.0.0-beta.1" +battery = { version = "0.7.5", default-features = false } +notify-rust = { version = "4", default-features = false } +clap = { version = "3.0.0-beta.1", default-features = false, features = ["std", "derive"] } +time = { version = "0.2", default-features = false } diff --git a/src/battery_state.rs b/src/battery_state.rs index d100e35..b836531 100644 --- a/src/battery_state.rs +++ b/src/battery_state.rs @@ -1,19 +1,23 @@ +use std::cmp::PartialOrd; + use notify_rust::{Hint, Notification, Urgency}; +#[derive(PartialEq, PartialOrd, Eq, Debug)] pub enum VerbosityLevel { None = 0, Some = 1, Lots = 2, } +#[derive(Debug)] pub struct BatteryState { manager: battery::Manager, battery: battery::Battery, refresh_rate: u64, - low_level: f32, - very_low_level: f32, - critical_level: f32, + low_level: u8, + very_low_level: u8, + critical_level: u8, is_triggered_low: bool, is_triggered_very_low: bool, @@ -21,16 +25,39 @@ pub struct BatteryState { verbosity: VerbosityLevel, } -pub const DEFAULT_LOW: f32 = 25_f32; -pub const DEFAULT_VERY_LOW: f32 = 15_f32; -pub const DEFAULT_CRITICAL: f32 = 10_f32; +pub const DEFAULT_LOW: u8 = 25_u8; +pub const DEFAULT_VERY_LOW: u8 = 15_u8; +pub const DEFAULT_CRITICAL: u8 = 10_u8; pub const DEFAULT_REFRESH: u64 = 5; +macro_rules! trigger_warning { + ($message:literal, $urgency:ident, $trigger:expr, $battery:expr, $verbosity:expr, $self:expr) => { + if $trigger { + return; + } + $trigger = true; + let level = ($battery.state_of_charge().value * 100_f32) as u8; + let message = format!($message, $self.remaining_time($self.battery.time_to_full()), level); + match $verbosity { + VerbosityLevel::None => {} + _ => println!("{}", message), + } + Notification::new() + .summary("Low battery") + .body(message.as_str()) + .hint(Hint::Category("battery".to_owned())) + .urgency($urgency) + .show() + .unwrap(); + }; +} + impl BatteryState { + /// Create and initialize new `BatteryState` object pub fn new( - low_level: f32, - mut very_low_level: f32, - mut critical_level: f32, + low_level: u8, + mut very_low_level: u8, + mut critical_level: u8, refresh_rate: u64, verbosity: VerbosityLevel, ) -> battery::Result { @@ -48,14 +75,29 @@ impl BatteryState { } }; - let low_level = low_level.min(50_f32).max(5_f32); + // Keep values safe + let low_level = low_level.min(95_u8).max(5_u8); if very_low_level > low_level { - very_low_level = f32::max(low_level - 1_f32, 5_f32) + very_low_level = u8::max(low_level - 1_u8, 5_u8) }; if critical_level > very_low_level { - critical_level = f32::max(very_low_level - 1_f32, 5_f32) + critical_level = u8::max(very_low_level - 1_u8, 5_u8) }; + match verbosity { + VerbosityLevel::None => {} + _ => { + println!("Low battery: {}%", low_level); + println!("Very low battery: {}%", very_low_level); + println!("Critical battery: {}%", critical_level); + println!("Refresh rate: {}s", refresh_rate); + match verbosity { + VerbosityLevel::Some => println!("Some verbose info"), + _ => println!("Lots of verbose info"), + } + } + } + Ok(Self { manager, battery, @@ -72,66 +114,127 @@ impl BatteryState { }) } - fn get_charge(&self) -> f32 { - self.battery.state_of_charge().value * 100_f32 - } - + /// Reset current progress toward an empty battery fn reset_levels(&mut self) { self.is_triggered_low = false; self.is_triggered_very_low = false; } - fn trigger_low(&mut self) { - if !self.is_triggered_low { - self.is_triggered_low = true; - let time = match self.battery.time_to_empty() { - Some(e) => e.value.to_string(), - None => String::from("unknown"), - }; - let level = self.battery.state_of_charge().value * 100.0; - let message = - format!("Battery level is low! {} left ({}%)", time, level); - Notification::new() - .summary("Low Battery") - .body(message.as_str()) - .hint(Hint::Category("battery".to_owned())) - .urgency(Urgency::Normal) - .show() + /// Get level of charge of the battery + fn get_charge(&self) -> u8 { + (self.battery.state_of_charge().value * 100_f32) as u8 + } + + pub fn remaining_time(&self, time: Option) -> String { + match time { + Some(e) => { + let time = e.value as u64; + let time = time::Time::try_from_hms( + (time / 3600) as u8, + ((time % 3600) / 60) as u8, + (time % 60) as u8, + ) .unwrap(); + time.to_string() + } + None => { + eprintln!("Couldn’t read remaining time"); + String::from("unknown remaining time") + } } } + /// Warn the user once about low battery + fn trigger_low(&mut self) { + use Urgency::Normal; + trigger_warning!( + "Battery level is low! {} left ({}%)", + Normal, + self.is_triggered_low, + self.battery, + self.verbosity, + &self + ); + } + + /// Warn the user once about very low battery fn trigger_very_low(&mut self) { - if !self.is_triggered_very_low { - self.is_triggered_very_low = true; - let time = match self.battery.time_to_empty() { - Some(e) => e.value.to_string(), - None => String::from("unknown"), - }; - let level = self.battery.state_of_charge().value * 100.0; - let message = format!( - "Battery level is very low! {} left ({}%)", - time, level - ); - Notification::new() - .summary("Low Battery") - .body(message.as_str()) - .hint(Hint::Category("battery".to_owned())) - .urgency(Urgency::Critical) - .show() - .unwrap(); + use Urgency::Critical; + trigger_warning!( + "Battery level is low! {} left ({}%)", + Critical, + self.is_triggered_very_low, + self.battery, + self.verbosity, + &self + ); + } + + fn trigger_critical(&mut self) { + use std::process::Command; + let out = Command::new("systemctl") + .arg("suspend") + .output() + .expect("process failed to execute"); + eprintln!("{}", out.status); + eprintln!( + "{}", + String::from_utf8(out.stderr) + .unwrap_or(String::from("Could not read stderr")) + ); + eprintln!( + "{:?}", + String::from_utf8(out.stdout) + .unwrap_or(String::from("Could not read stdin")) + ); + loop { + self.manager.refresh(&mut self.battery).unwrap(); + use std::{thread, time::Duration}; + thread::sleep(Duration::from_secs(self.refresh_rate)); + if self.battery.state() == battery::State::Charging { + break; + } } } pub fn update(&mut self) { self.manager.refresh(&mut self.battery).unwrap(); - use battery::State::{Discharging, Empty}; + + let charge = self.get_charge(); + + if self.verbosity >= VerbosityLevel::Some { + match self.battery.state() { + battery::State::Charging => println!( + "Charging: {}%, time left: {}", + charge, + self.remaining_time(self.battery.time_to_full()) + ), + battery::State::Discharging => println!( + "Discharging: {}%, time left: {}", + charge, + self.remaining_time(self.battery.time_to_empty()) + ), + battery::State::Full => println!("Full"), + battery::State::Empty => println!("Empty"), + _ => eprintln!("Error: unknown battery state"), + } + } + if self.verbosity == VerbosityLevel::Lots { + eprintln!("====\nDebug self:\n{:?}\n====", self); + } + match self.battery.state() { - Discharging | Empty => match self.get_charge() { - x if x < self.very_low_level => self.trigger_very_low(), - x if x < self.low_level => self.trigger_low(), - _ => {} - }, + battery::State::Discharging | battery::State::Empty => { + if !self.is_triggered_low && charge <= self.low_level { + self.trigger_low(); + } else if !self.is_triggered_very_low + && charge <= self.very_low_level + { + self.trigger_very_low(); + } else if charge <= self.critical_level { + self.trigger_critical(); + } + } _ => self.reset_levels(), } diff --git a/src/main.rs b/src/main.rs index 317f934..3e98008 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,13 +11,13 @@ use clap::Clap; )] struct Opts { #[clap(short, long, default_value = "25")] - low: f32, + low: u8, #[clap(short = "L", long, default_value = "15")] - very_low: f32, + very_low: u8, #[clap(short, long, default_value = "10")] - critical: f32, + critical: u8, #[clap(short, long = "refresh-rate", default_value = "5")] refresh_rate: u64, @@ -28,15 +28,6 @@ struct Opts { fn main() { let opts: Opts = Opts::parse(); - println!("Low battery: {}%", opts.low); - println!("Very low battery: {}%", opts.very_low); - println!("Critical battery: {}%", opts.critical); - println!("Refresh rate: {}s", opts.refresh_rate); - match opts.verbose { - 0 => println!("No verbose info"), - 1 => println!("Some verbose info"), - _ => println!("Lots of verbose info"), - } let mut battery = BatteryState::new( opts.low,