Clean up unwrap()'s. Print out info in asusctl if error

This commit is contained in:
Luke D. Jones
2021-08-28 11:07:47 +12:00
parent 3d41a7978a
commit c6cc304a42
17 changed files with 143 additions and 70 deletions

1
Cargo.lock generated
View File

@@ -57,6 +57,7 @@ dependencies = [
"rog_profiles",
"rog_supported",
"supergfxctl",
"sysfs-class",
"tinybmp",
"zbus",
]

View File

@@ -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"

View File

@@ -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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
Ok(())
}
fn do_gfx(command: GraphicsCommand) -> Result<(), Box<dyn std::error::Error>> {
fn do_gfx(command: &GraphicsCommand) -> Result<(), Box<dyn std::error::Error>> {
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(<AnimeDataBuffer>::from(&matrix))
.unwrap();
.write(<AnimeDataBuffer>::from(&matrix))?;
}
}
}
@@ -339,23 +383,21 @@ fn handle_led_mode(
println!("{}\n", mode.self_usage());
println!("Commands available");
let commands: Vec<String> = 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<String> = 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");

View File

@@ -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();

View File

@@ -17,7 +17,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
.name("Anime User".into())
.spawn(move || loop {
if let Ok(inner) = inner.try_lock() {
inner.run().unwrap();
inner.run().ok();
}
})?;
}

View File

@@ -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<Mutex<CtrlAnime>>) -> 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

View File

@@ -62,9 +62,11 @@ pub struct CtrlKbdLedTask<'a> {
impl<'a> CtrlKbdLedTask<'a> {
pub fn new(inner: Arc<Mutex<CtrlKbdLed>>) -> 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;

View File

@@ -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;
}
}

View File

@@ -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();

View File

@@ -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)?;
}
}

View File

@@ -68,7 +68,7 @@ pub fn main() -> Result<(), Box<dyn std::error::Error>> {
fn start_daemon() -> Result<(), Box<dyn Error>> {
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<Box<dyn CtrlTask + Send>> = Vec::new();

View File

@@ -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());
}

View File

@@ -95,7 +95,7 @@ impl From<AnimeDataBuffer> for AnimePacketType {
pub fn run_animation(
frames: &AnimeGif,
do_early_return: Arc<AtomicBool>,
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;

View File

@@ -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),
}
}
}

View File

@@ -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
}
}

View File

@@ -27,3 +27,9 @@ impl fmt::Display for ProfileError {
}
impl std::error::Error for ProfileError {}
impl From<std::io::Error> for ProfileError {
fn from(err: std::io::Error) -> Self {
ProfileError::Io(err)
}
}

View File

@@ -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(())
}
}