From c6cc304a426dba9ca4a403b79c1af7a272b5b1e8 Mon Sep 17 00:00:00 2001 From: "Luke D. Jones" Date: Sat, 28 Aug 2021 11:07:47 +1200 Subject: [PATCH] Clean up unwrap()'s. Print out info in asusctl if error --- Cargo.lock | 1 + asusctl/Cargo.toml | 2 + asusctl/src/main.rs | 116 +++++++++++++++++-------- daemon-user/src/ctrl_anime.rs | 12 ++- daemon-user/src/daemon.rs | 6 +- daemon/src/ctrl_anime/mod.rs | 22 +++-- daemon/src/ctrl_aura/controller.rs | 10 ++- daemon/src/ctrl_profiles/controller.rs | 6 +- daemon/src/ctrl_profiles/zbus.rs | 4 +- daemon/src/ctrl_rog_bios.rs | 6 +- daemon/src/daemon.rs | 2 +- daemon/src/laptops.rs | 2 - rog-anime/src/data.rs | 4 +- rog-anime/src/error.rs | 2 + rog-aura/src/builtin_modes.rs | 3 +- rog-profiles/src/error.rs | 6 ++ rog-profiles/src/lib.rs | 9 +- 17 files changed, 143 insertions(+), 70 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 03220719..987a33a6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -57,6 +57,7 @@ dependencies = [ "rog_profiles", "rog_supported", "supergfxctl", + "sysfs-class", "tinybmp", "zbus", ] diff --git a/asusctl/Cargo.toml b/asusctl/Cargo.toml index 8d2fbe07..1635021d 100644 --- a/asusctl/Cargo.toml +++ b/asusctl/Cargo.toml @@ -17,6 +17,8 @@ daemon = { path = "../daemon" } gumdrop = "^0.8" supergfxctl = { git = "https://gitlab.com/asus-linux/supergfxctl.git", tag = "2.0.0" } +sysfs-class = "^0.1.2" + [dev-dependencies] tinybmp = "^0.2.3" glam = "0.14.0" diff --git a/asusctl/src/main.rs b/asusctl/src/main.rs index 20669e72..2e67f67f 100644 --- a/asusctl/src/main.rs +++ b/asusctl/src/main.rs @@ -9,6 +9,7 @@ use profiles_cli::ProfileCommand; use rog_anime::{AnimeDataBuffer, AnimeImage, Vec2, ANIME_DATA_LEN}; use rog_aura::{self, AuraEffect}; use rog_dbus::RogDbusClient; +use rog_supported::SupportedFunctions; use rog_supported::{ AnimeSupportedFunctions, LedSupportedFunctions, PlatformProfileFunctions, RogBiosSupportedFunctions, @@ -139,40 +140,84 @@ fn main() -> Result<(), Box> { let (dbus, _) = RogDbusClient::new()?; - let supported = dbus.proxies().supported().get_supported_functions()?; + let supported = dbus + .proxies() + .supported() + .get_supported_functions() + .map_err(|e| { + println!("\nIs asusd running?\n\n{}", e); + e + })?; if parsed.version { - println!("\nApp and daemon versions:"); - println!(" asusctl v{}", env!("CARGO_PKG_VERSION")); - println!(" asusd v{}", daemon::VERSION); - println!("\nComponent crate versions:"); - println!(" rog-anime v{}", rog_anime::VERSION); - println!(" rog-aura v{}", rog_aura::VERSION); - println!(" rog-dbus v{}", rog_dbus::VERSION); - println!(" rog-profiles v{}", rog_profiles::VERSION); - println!("rog-supported v{}", rog_supported::VERSION); - println!(" supergfxctl v{}", supergfxctl::VERSION); + print_versions(); return Ok(()); } - match parsed.command { - Some(CliCommand::LedMode(mode)) => handle_led_mode(&dbus, &supported.keyboard_led, &mode)?, - Some(CliCommand::Profile(cmd)) => handle_profile(&dbus, &supported.platform_profile, &cmd)?, + if let Err(err) = do_parsed(&parsed, &supported, &dbus) { + println!("Error: {}", err); + println!(); + print_versions(); + println!(); + print_laptop_info(); + println!(); + println!("Supported laptop functions:\n\n{}", supported); + } + + Ok(()) +} + +fn print_versions() { + println!("\nApp and daemon versions:"); + println!(" asusctl v{}", env!("CARGO_PKG_VERSION")); + println!(" asusd v{}", daemon::VERSION); + println!("\nComponent crate versions:"); + println!(" rog-anime v{}", rog_anime::VERSION); + println!(" rog-aura v{}", rog_aura::VERSION); + println!(" rog-dbus v{}", rog_dbus::VERSION); + println!(" rog-profiles v{}", rog_profiles::VERSION); + println!("rog-supported v{}", rog_supported::VERSION); + println!(" supergfxctl v{}", supergfxctl::VERSION); +} + +fn print_laptop_info() { + let dmi = sysfs_class::DmiId::default(); + let board_name = dmi.board_name().expect("Could not get board_name"); + let prod_family = dmi.product_family().expect("Could not get product_family"); + + println!("Product family: {}", prod_family.trim()); + println!("Board name: {}", board_name.trim()); +} + +fn do_parsed( + parsed: &CliStart, + supported: &SupportedFunctions, + dbus: &RogDbusClient, +) -> Result<(), Box> { + match &parsed.command { + Some(CliCommand::LedMode(mode)) => handle_led_mode(dbus, &supported.keyboard_led, &mode)?, + Some(CliCommand::Profile(cmd)) => handle_profile(dbus, &supported.platform_profile, &cmd)?, Some(CliCommand::Graphics(cmd)) => do_gfx(cmd)?, - Some(CliCommand::Anime(cmd)) => handle_anime(&dbus, &supported.anime_ctrl, &cmd)?, - Some(CliCommand::Bios(cmd)) => handle_bios_option(&dbus, &supported.rog_bios_ctrl, &cmd)?, + Some(CliCommand::Anime(cmd)) => handle_anime(dbus, &supported.anime_ctrl, &cmd)?, + Some(CliCommand::Bios(cmd)) => handle_bios_option(dbus, &supported.rog_bios_ctrl, &cmd)?, None => { - if (!parsed.show_supported && parsed.kbd_bright.is_none() && parsed.chg_limit.is_none() - && !parsed.next_kbd_bright && !parsed.prev_kbd_bright) || parsed.help + if (!parsed.show_supported + && parsed.kbd_bright.is_none() + && parsed.chg_limit.is_none() + && !parsed.next_kbd_bright + && !parsed.prev_kbd_bright) + || parsed.help { println!("{}", CliStart::usage()); println!(); - println!("{}", CliStart::command_list().unwrap()); + if let Some(cmdlist) = CliStart::command_list() { + println!("{}", cmdlist); + } } } } - if let Some(brightness) = parsed.kbd_bright { + if let Some(brightness) = &parsed.kbd_bright { match brightness.level() { None => { let level = dbus.proxies().led().get_led_brightness()?; @@ -204,7 +249,7 @@ fn main() -> Result<(), Box> { Ok(()) } -fn do_gfx(command: GraphicsCommand) -> Result<(), Box> { +fn do_gfx(command: &GraphicsCommand) -> Result<(), Box> { if command.mode.is_none() && !command.get && !command.pow && !command.force || command.help { println!("{}", command.self_usage()); } @@ -314,8 +359,7 @@ fn handle_anime( dbus.proxies() .anime() - .write(::from(&matrix)) - .unwrap(); + .write(::from(&matrix))?; } } } @@ -339,23 +383,21 @@ fn handle_led_mode( println!("{}\n", mode.self_usage()); println!("Commands available"); - let commands: Vec = LedModeCommand::command_list() - .unwrap() - .lines() - .map(|s| s.to_string()) - .collect(); - for command in commands.iter().filter(|command| { - for mode in &supported.stock_led_modes { - if command.contains(&<&str>::from(mode).to_lowercase()) { + if let Some(cmdlist) = LedModeCommand::command_list() { + let commands: Vec = cmdlist.lines().map(|s| s.to_string()).collect(); + for command in commands.iter().filter(|command| { + for mode in &supported.stock_led_modes { + if command.contains(&<&str>::from(mode).to_lowercase()) { + return true; + } + } + if supported.multizone_led_mode { return true; } + false + }) { + println!("{}", command); } - if supported.multizone_led_mode { - return true; - } - false - }) { - println!("{}", command); } println!("\nHelp can also be requested on modes, e.g: static --help"); diff --git a/daemon-user/src/ctrl_anime.rs b/daemon-user/src/ctrl_anime.rs index baeb2598..40c6226b 100644 --- a/daemon-user/src/ctrl_anime.rs +++ b/daemon-user/src/ctrl_anime.rs @@ -1,3 +1,4 @@ +use rog_anime::error::AnimeError; use rog_anime::{ActionData, ActionLoader, AnimTime, Fade, Sequences, Vec2}; use rog_dbus::RogDbusClient; use serde_derive::{Deserialize, Serialize}; @@ -91,16 +92,19 @@ impl<'a> CtrlAnimeInner<'static> { match action { ActionData::Animation(frames) => { rog_anime::run_animation(frames, self.do_early_return.clone(), &|output| { - self.client.proxies().anime().write(output).unwrap() - }) - .unwrap(); + self.client + .proxies() + .anime() + .write(output) + .map_err(|e| AnimeError::Dbus(format!("{}", e))) + })?; } ActionData::Image(image) => { self.client .proxies() .anime() .write(image.as_ref().clone()) - .unwrap(); + .ok(); } ActionData::Pause(duration) => { let start = Instant::now(); diff --git a/daemon-user/src/daemon.rs b/daemon-user/src/daemon.rs index d105f1de..e194c24a 100644 --- a/daemon-user/src/daemon.rs +++ b/daemon-user/src/daemon.rs @@ -17,7 +17,7 @@ fn main() -> Result<(), Box> { println!(" rog-dbus v{}", rog_dbus::VERSION); println!("rog-supported v{}", rog_supported::VERSION); - let (client, _) = RogDbusClient::new().unwrap(); + let (client, _) = RogDbusClient::new()?; let supported = client.proxies().supported().get_supported_functions()?; let mut config = UserConfig::new(); @@ -44,7 +44,7 @@ fn main() -> Result<(), Box> { early_return.clone(), )?)); // Need new client object for dbus control part - let (client, _) = RogDbusClient::new().unwrap(); + let (client, _) = RogDbusClient::new()?; let anime_control = CtrlAnime::new(anime_config, inner.clone(), client, early_return)?; anime_control.add_to_server(&mut server); // Thread using inner @@ -52,7 +52,7 @@ fn main() -> Result<(), Box> { .name("Anime User".into()) .spawn(move || loop { if let Ok(inner) = inner.try_lock() { - inner.run().unwrap(); + inner.run().ok(); } })?; } diff --git a/daemon/src/ctrl_anime/mod.rs b/daemon/src/ctrl_anime/mod.rs index 3628ea6e..694036d4 100644 --- a/daemon/src/ctrl_anime/mod.rs +++ b/daemon/src/ctrl_anime/mod.rs @@ -13,7 +13,12 @@ use rog_anime::{ }; use rog_supported::AnimeSupportedFunctions; use rusb::{Device, DeviceHandle}; -use std::{cell::RefCell, error::Error, sync::{Arc, Mutex}, thread::sleep}; +use std::{ + cell::RefCell, + error::Error, + sync::{Arc, Mutex}, + thread::sleep, +}; use std::{ sync::atomic::{AtomicBool, Ordering}, time::Duration, @@ -176,12 +181,17 @@ impl CtrlAnime { for action in actions.iter() { match action { ActionData::Animation(frames) => { - rog_anime::run_animation(frames, thread_exit.clone(), &|frame| { + if rog_anime::run_animation(frames, thread_exit.clone(), &|frame| { if let Ok(lock) = inner.try_lock() { lock.write_data_buffer(frame); } + Ok(()) }) - .unwrap(); + .map_err(|err| warn!("rog_anime::run_animation: {}", err)) + .is_err() + { + break 'main; + }; if thread_exit.load(Ordering::SeqCst) { break 'main; @@ -289,9 +299,11 @@ pub struct CtrlAnimeTask<'a> { impl<'a> CtrlAnimeTask<'a> { pub fn new(inner: Arc>) -> Self { - let connection = Connection::new_system().unwrap(); + let connection = + Connection::new_system().expect("CtrlAnimeTask could not create dbus connection"); - let manager = ManagerProxy::new(&connection).unwrap(); + let manager = + ManagerProxy::new(&connection).expect("CtrlAnimeTask could not create ManagerProxy"); let c1 = inner.clone(); // Run this action when the system starts shutting down diff --git a/daemon/src/ctrl_aura/controller.rs b/daemon/src/ctrl_aura/controller.rs index 67e4b21e..e08a996f 100644 --- a/daemon/src/ctrl_aura/controller.rs +++ b/daemon/src/ctrl_aura/controller.rs @@ -62,9 +62,11 @@ pub struct CtrlKbdLedTask<'a> { impl<'a> CtrlKbdLedTask<'a> { pub fn new(inner: Arc>) -> Self { - let connection = Connection::new_system().unwrap(); + let connection = + Connection::new_system().expect("CtrlKbdLedTask could not create dbus connection"); - let manager = ManagerProxy::new(&connection).unwrap(); + let manager = + ManagerProxy::new(&connection).expect("CtrlKbdLedTask could not create ManagerProxy"); let c1 = inner.clone(); // Run this action when the system wakes up from sleep @@ -239,7 +241,7 @@ impl CtrlKbdLed { Ok(()) } - pub fn next_brightness(&mut self) -> Result<(), RogError> { + pub fn next_brightness(&mut self) -> Result<(), RogError> { let mut bright = (self.config.brightness as u32) + 1; if bright > 3 { bright = 0; @@ -249,7 +251,7 @@ impl CtrlKbdLed { self.set_brightness(self.config.brightness) } - pub fn prev_brightness(&mut self) -> Result<(), RogError> { + pub fn prev_brightness(&mut self) -> Result<(), RogError> { let mut bright = self.config.brightness as u32; if bright == 0 { bright = 3; diff --git a/daemon/src/ctrl_profiles/controller.rs b/daemon/src/ctrl_profiles/controller.rs index b0f571fd..3b292e63 100644 --- a/daemon/src/ctrl_profiles/controller.rs +++ b/daemon/src/ctrl_profiles/controller.rs @@ -100,15 +100,15 @@ impl CtrlPlatformProfile { match config.active { Profile::Balanced => { - Profile::set_profile(Profile::Performance); + Profile::set_profile(Profile::Performance)?; config.active = Profile::Performance; } Profile::Performance => { - Profile::set_profile(Profile::Quiet); + Profile::set_profile(Profile::Quiet)?; config.active = Profile::Quiet; } Profile::Quiet => { - Profile::set_profile(Profile::Balanced); + Profile::set_profile(Profile::Balanced)?; config.active = Profile::Balanced; } } diff --git a/daemon/src/ctrl_profiles/zbus.rs b/daemon/src/ctrl_profiles/zbus.rs index 4f26d79a..572dca34 100644 --- a/daemon/src/ctrl_profiles/zbus.rs +++ b/daemon/src/ctrl_profiles/zbus.rs @@ -62,7 +62,9 @@ impl ProfileZbus { if let Ok(mut cfg) = ctrl.config.try_lock() { // Read first just incase the user has modified the config before calling this cfg.read(); - Profile::set_profile(profile); + Profile::set_profile(profile) + .map_err(|e| warn!("Profile::set_profile, {}", e)) + .ok(); cfg.active = profile; } ctrl.save_config(); diff --git a/daemon/src/ctrl_rog_bios.rs b/daemon/src/ctrl_rog_bios.rs index d9fbef7c..b95ac5c5 100644 --- a/daemon/src/ctrl_rog_bios.rs +++ b/daemon/src/ctrl_rog_bios.rs @@ -168,7 +168,7 @@ impl CtrlRogBios { .map_err(|err| RogError::Path(path.into(), err))?; let mut data = Vec::new(); - file.read_to_end(&mut data).unwrap(); + file.read_to_end(&mut data)?; let idx = data.len() - 1; if dedicated { @@ -269,7 +269,7 @@ impl CtrlRogBios { RogError::Write(module_include.to_string_lossy().to_string(), err) })?; // add nvidia modules to module_include - file.write_all(modules.concat().as_bytes()).unwrap(); + file.write_all(modules.concat().as_bytes())?; } else { let file = std::fs::OpenOptions::new() .read(true) @@ -292,7 +292,7 @@ impl CtrlRogBios { .map_err(|err| { RogError::Write(module_include.to_string_lossy().to_string(), err) })?; - std::io::BufWriter::new(file).write_all(&buf).unwrap(); + std::io::BufWriter::new(file).write_all(&buf)?; } } diff --git a/daemon/src/daemon.rs b/daemon/src/daemon.rs index 573b77a9..61797021 100644 --- a/daemon/src/daemon.rs +++ b/daemon/src/daemon.rs @@ -68,7 +68,7 @@ pub fn main() -> Result<(), Box> { fn start_daemon() -> Result<(), Box> { let supported = SupportedFunctions::get_supported(); print_board_info(); - println!("{}", serde_json::to_string_pretty(&supported).unwrap()); + println!("{}", serde_json::to_string_pretty(&supported)?); // Collect tasks for task thread let mut tasks: Vec> = Vec::new(); diff --git a/daemon/src/laptops.rs b/daemon/src/laptops.rs index cd62f6f3..3f20a720 100644 --- a/daemon/src/laptops.rs +++ b/daemon/src/laptops.rs @@ -10,10 +10,8 @@ pub const ASUS_KEYBOARD_DEVICES: [&str; 4] = ["1866", "1869", "1854", "19b6"]; pub fn print_board_info() { let dmi = sysfs_class::DmiId::default(); let board_name = dmi.board_name().expect("Could not get board_name"); - let prod_name = dmi.product_name().expect("Could not get product_name"); let prod_family = dmi.product_family().expect("Could not get product_family"); - info!("Product name: {}", prod_name.trim()); info!("Product family: {}", prod_family.trim()); info!("Board name: {}", board_name.trim()); } diff --git a/rog-anime/src/data.rs b/rog-anime/src/data.rs index df3420a6..991115da 100644 --- a/rog-anime/src/data.rs +++ b/rog-anime/src/data.rs @@ -95,7 +95,7 @@ impl From for AnimePacketType { pub fn run_animation( frames: &AnimeGif, do_early_return: Arc, - callback: &dyn Fn(AnimeDataBuffer), + callback: &dyn Fn(AnimeDataBuffer) -> Result<(), AnimeError>, ) -> Result<(), AnimeError> { let mut count = 0; let start = Instant::now(); @@ -164,7 +164,7 @@ pub fn run_animation( } } - callback(output); + callback(output)?; if timed && Instant::now().duration_since(start) > run_time { break 'animation; diff --git a/rog-anime/src/error.rs b/rog-anime/src/error.rs index f52ee35b..ee12a440 100644 --- a/rog-anime/src/error.rs +++ b/rog-anime/src/error.rs @@ -12,6 +12,7 @@ pub enum AnimeError { Format, /// The input was incorrect size, expected size is `IncorrectSize(width, height)` IncorrectSize(u32, u32), + Dbus(String), } impl fmt::Display for AnimeError { @@ -28,6 +29,7 @@ impl fmt::Display for AnimeError { "The input image size is incorrect, expected {}x{}", width, height ), + AnimeError::Dbus(detail) => write!(f, "{}", detail), } } } diff --git a/rog-aura/src/builtin_modes.rs b/rog-aura/src/builtin_modes.rs index 52640c13..212eecd9 100644 --- a/rog-aura/src/builtin_modes.rs +++ b/rog-aura/src/builtin_modes.rs @@ -29,7 +29,8 @@ pub enum LedBrightness { impl LedBrightness { pub fn as_char_code(&self) -> u8 { - std::char::from_digit(*self as u32, 10).unwrap() as u8 + std::char::from_digit(*self as u32, 10) + .expect("LedBrightness.as_char_code failed to convert") as u8 } } diff --git a/rog-profiles/src/error.rs b/rog-profiles/src/error.rs index f057e040..baa11c2c 100644 --- a/rog-profiles/src/error.rs +++ b/rog-profiles/src/error.rs @@ -27,3 +27,9 @@ impl fmt::Display for ProfileError { } impl std::error::Error for ProfileError {} + +impl From for ProfileError { + fn from(err: std::io::Error) -> Self { + ProfileError::Io(err) + } +} \ No newline at end of file diff --git a/rog-profiles/src/lib.rs b/rog-profiles/src/lib.rs index eaa12415..5d20051d 100644 --- a/rog-profiles/src/lib.rs +++ b/rog-profiles/src/lib.rs @@ -41,7 +41,7 @@ impl Profile { .unwrap_or_else(|_| panic!("{} not found", &PLATFORM_PROFILE)); let mut buf = String::new(); - file.read_to_string(&mut buf).unwrap(); + file.read_to_string(&mut buf)?; Ok(buf.as_str().into()) } @@ -52,17 +52,18 @@ impl Profile { .unwrap_or_else(|_| panic!("{} not found", &PLATFORM_PROFILES)); let mut buf = String::new(); - file.read_to_string(&mut buf).unwrap(); + file.read_to_string(&mut buf)?; Ok(buf.rsplit(' ').map(|p| p.into()).collect()) } - pub fn set_profile(profile: Profile) { + pub fn set_profile(profile: Profile) -> Result<(), ProfileError> { let mut file = OpenOptions::new() .write(true) .open(PLATFORM_PROFILE) .unwrap_or_else(|_| panic!("{} not found", PLATFORM_PROFILE)); - file.write_all(<&str>::from(profile).as_bytes()).unwrap(); + file.write_all(<&str>::from(profile).as_bytes())?; + Ok(()) } }