From b28d83890ab4ea5319446c57ba4aca1f267a0e2b Mon Sep 17 00:00:00 2001 From: killingerr Date: Mon, 19 Oct 2026 14:06:18 -0600 Subject: [PATCH] Strip boilerplate and dead code, keeping the CLI, DBus interface, config format and GUI. Saving is now a single atomic write in FanCurveConfig::save_to_file, shared by the daemon and GUI, replacing the daemon's retry loop and validate_persistence, which re-wrote the live config non-atomically after every save. The daemon's DBus methods share one save and signal path and take their locks in one order (SetFanCurve took them in the opposite order, which could deadlock). The CLI client is a single match over subcommands, main.rs drops its error-boxing map_errs, and fan_detector no longer logs at info level on every control loop tick. Unused error variants, accessors and TempSource::id/from_id are gone. --- src/channels.rs | 28 +--- src/client.rs | 371 +++++++++++++++-------------------------- src/cpu_temp.rs | 258 ++++++++--------------------- src/daemon/mod.rs | 348 ++++++++++----------------------------- src/errors.rs | 20 --- src/fan.rs | 214 +++++------------------- src/fan_curve_gui.rs | 148 +++++------------ src/fan_detector.rs | 383 +++++++++---------------------------------- src/fan_monitor.rs | 55 ++----- src/main.rs | 74 +++------ 10 files changed, 485 insertions(+), 1414 deletions(-) diff --git a/src/channels.rs b/src/channels.rs index 943c8f4..993f2da 100644 --- a/src/channels.rs +++ b/src/channels.rs @@ -39,19 +39,6 @@ pub enum TempSource { impl TempSource { pub const ALL: [TempSource; 3] = [TempSource::Cpu, TempSource::Gpu, TempSource::Hottest]; - /// Short name for CLI and logs. - pub fn id(self) -> &'static str { - match self { - TempSource::Cpu => "cpu", - TempSource::Gpu => "gpu", - TempSource::Hottest => "hottest", - } - } - - pub fn from_id(id: &str) -> Option { - Self::ALL.into_iter().find(|s| s.id() == id) - } - pub fn label(self) -> &'static str { match self { TempSource::Cpu => "CPU", @@ -531,7 +518,7 @@ impl GpuTemp { } else if self.nvidia_paused() { Vec::new() } else { - match nvidia_temperatures() { + match nvidia_query("temperature.gpu") { Ok(temps) => temps, Err(e) => { // Back off rather than calling a failing nvidia-smi every @@ -600,11 +587,6 @@ impl GpuTemp { } } -/// Temperatures in °C of every NVIDIA GPU, via nvidia-smi. -fn nvidia_temperatures() -> std::io::Result> { - nvidia_query("temperature.gpu") -} - /// One numeric nvidia-smi query field for every NVIDIA GPU. fn nvidia_query(field: &str) -> std::io::Result> { let output = Command::new("nvidia-smi") @@ -766,14 +748,6 @@ mod tests { assert!(!fan.is_missing()); } - #[test] - fn temp_source_ids_round_trip() { - for source in TempSource::ALL { - assert_eq!(TempSource::from_id(source.id()), Some(source)); - } - assert_eq!(TempSource::from_id("bogus"), None); - } - #[test] fn missing_sensor_falls_back_to_the_other() { assert_eq!(source_temp(TempSource::Gpu, Some(40.0), None), Some(40.0)); diff --git a/src/client.rs b/src/client.rs index 8e51c7d..6758ac1 100644 --- a/src/client.rs +++ b/src/client.rs @@ -1,258 +1,151 @@ -//! Client implementation for the fan curve application +//! CLI client: sends `fan-curve` subcommands to the daemon over DBus use crate::{ - args::{Args, Commands, FanCurveCommands}, + args::FanCurveCommands, errors::{FanCurveError, Result}, fan::FanCurve, DBUS_INTERFACE_NAME, DBUS_OBJECT_PATH, DBUS_SERVICE_NAME, }; -use log::{debug, error}; -use zbus::Connection; - -/// Client for communicating with the fan curve daemon -pub struct FanCurveClient { - connection: Connection, -} - -impl FanCurveClient { - /// Create a new client - pub async fn new() -> Result { - let connection = Connection::system().await.map_err(FanCurveError::DBus)?; - - Ok(Self { connection }) - } - - /// Create a proxy to the fan curve daemon - async fn proxy(&self) -> Result> { - zbus::Proxy::new( - &self.connection, - DBUS_SERVICE_NAME, - DBUS_OBJECT_PATH, - DBUS_INTERFACE_NAME, +use zbus::{Connection, Proxy}; + +/// Map a DBus call error to something actionable for the user +fn daemon_error(e: zbus::Error) -> FanCurveError { + let msg = e.to_string(); + if msg.contains("ServiceUnknown") || msg.contains("NameHasNoOwner") { + FanCurveError::Config( + "Fan curve daemon is not running. Start it with: sudo fan-curve daemon \ + (or: sudo systemctl start fan-curve-daemon)" + .to_string(), ) - .await - .map_err(FanCurveError::DBus) - } - - /// Map a DBus call error to something actionable for the user - fn map_call_error(e: zbus::Error) -> FanCurveError { - let msg = e.to_string(); - if msg.contains("ServiceUnknown") || msg.contains("NameHasNoOwner") { - FanCurveError::Config( - "Fan curve daemon is not running. Start it with: sudo fan-curve daemon \ - (or: sudo systemctl start fan-curve-daemon)" - .to_string(), - ) - } else { - FanCurveError::DBus(e) - } + } else { + FanCurveError::DBus(e) } +} - /// Handle CLI commands - pub async fn handle_args(&self, args: Args) -> Result<()> { - match args.command { - Some(Commands::Daemon | Commands::Notify | Commands::RestoreFans { .. }) => { - error!("Daemon, notify and restore-fans commands should not be handled by client"); - Err(FanCurveError::Unknown( - "Invalid command for client".to_string(), - )) +/// Run a `fan-curve` subcommand against the daemon +pub async fn run(command: FanCurveCommands) -> Result<()> { + let connection = Connection::system().await?; + let proxy = Proxy::new( + &connection, + DBUS_SERVICE_NAME, + DBUS_OBJECT_PATH, + DBUS_INTERFACE_NAME, + ) + .await?; + + match command { + FanCurveCommands::List => { + let curves: Vec = proxy + .call("GetFanCurves", &()) + .await + .map_err(daemon_error)?; + let current: FanCurve = proxy + .call("GetCurrentFanCurve", &()) + .await + .map_err(daemon_error)?; + let default: FanCurve = proxy + .call("GetDefaultFanCurve", &()) + .await + .map_err(daemon_error)?; + + println!("Available fan curves:"); + for curve in &curves { + let mut markers = Vec::new(); + if curve.name() == current.name() { + markers.push("current"); + } + if curve.name() == default.name() { + markers.push("default"); + } + if markers.is_empty() { + println!(" - {}", curve.name()); + } else { + println!(" - {} ({})", curve.name(), markers.join(", ")); + } } - Some(Commands::FanCurve { command }) => self.handle_fan_curve_command(command).await, - None => { - error!("No command specified"); - Err(FanCurveError::Unknown("No command specified".to_string())) + } + FanCurveCommands::Get => { + let curve: FanCurve = proxy + .call("GetCurrentFanCurve", &()) + .await + .map_err(daemon_error)?; + println!("Current fan curve: {}", curve.name()); + for point in curve.points() { + println!(" {:>3}°C -> {:>3}%", point.temp, point.duty_percent()); } } - } - - /// Handle fan curve commands - async fn handle_fan_curve_command(&self, command: FanCurveCommands) -> Result<()> { - match command { - FanCurveCommands::List => self.list_fan_curves().await, - FanCurveCommands::Get => self.get_current_fan_curve().await, - FanCurveCommands::Set { name } => self.set_fan_curve_by_name(&name).await, - FanCurveCommands::SetDefault { name } => self.set_default_fan_curve(&name).await, - FanCurveCommands::AddPoint { temp, duty } => self.add_fan_curve_point(temp, duty).await, - FanCurveCommands::RemovePoint => self.remove_fan_curve_point().await, - FanCurveCommands::Save => self.save_config().await, - FanCurveCommands::Load => self.load_config().await, - FanCurveCommands::Status => self.show_status().await, + FanCurveCommands::Set { name } => { + proxy + .call::<_, _, ()>("SetFanCurveByName", &(name.as_str(),)) + .await + .map_err(daemon_error)?; + println!("Fan curve set to: {}", name); } - } - - /// List all fan curves - async fn list_fan_curves(&self) -> Result<()> { - debug!("Listing fan curves"); - - let proxy = self.proxy().await?; - let curves: Vec = proxy - .call("GetFanCurves", &()) - .await - .map_err(Self::map_call_error)?; - let current: FanCurve = proxy - .call("GetCurrentFanCurve", &()) - .await - .map_err(Self::map_call_error)?; - let default: FanCurve = proxy - .call("GetDefaultFanCurve", &()) - .await - .map_err(Self::map_call_error)?; - - println!("Available fan curves:"); - for curve in &curves { - let mut markers = Vec::new(); - if curve.name() == current.name() { - markers.push("current"); - } - if curve.name() == default.name() { - markers.push("default"); - } - if markers.is_empty() { - println!(" - {}", curve.name()); - } else { - println!(" - {} ({})", curve.name(), markers.join(", ")); - } + FanCurveCommands::SetDefault { name } => { + proxy + .call::<_, _, ()>("SetDefaultFanCurve", &(name.as_str(),)) + .await + .map_err(daemon_error)?; + println!( + "Default fan curve set to: {} (persists across reboots)", + name + ); } - - Ok(()) - } - - /// Get current fan curve - async fn get_current_fan_curve(&self) -> Result<()> { - debug!("Getting current fan curve"); - - let proxy = self.proxy().await?; - let curve: FanCurve = proxy - .call("GetCurrentFanCurve", &()) - .await - .map_err(Self::map_call_error)?; - - println!("Current fan curve: {}", curve.name()); - for point in curve.points() { - println!(" {:>3}°C -> {:>3}%", point.temp, point.duty_percent()); + FanCurveCommands::AddPoint { temp, duty } => { + proxy + .call::<_, _, ()>("AddFanCurvePoint", &(temp, duty)) + .await + .map_err(daemon_error)?; + println!("Added point to current curve: {}°C -> {}%", temp, duty); } - - Ok(()) - } - - /// Set fan curve by name - async fn set_fan_curve_by_name(&self, name: &str) -> Result<()> { - debug!("Setting fan curve to: {}", name); - - let proxy = self.proxy().await?; - proxy - .call::<_, _, ()>("SetFanCurveByName", &(name,)) - .await - .map_err(Self::map_call_error)?; - - println!("Fan curve set to: {}", name); - Ok(()) - } - - /// Set default fan curve - async fn set_default_fan_curve(&self, name: &str) -> Result<()> { - debug!("Setting default fan curve to: {}", name); - - let proxy = self.proxy().await?; - proxy - .call::<_, _, ()>("SetDefaultFanCurve", &(name,)) - .await - .map_err(Self::map_call_error)?; - - println!( - "Default fan curve set to: {} (persists across reboots)", - name - ); - Ok(()) - } - - /// Add fan curve point (duty is a percentage, 0-100) - async fn add_fan_curve_point(&self, temp: i16, duty: u16) -> Result<()> { - debug!("Adding fan curve point: {}°C -> {}%", temp, duty); - - let proxy = self.proxy().await?; - proxy - .call::<_, _, ()>("AddFanCurvePoint", &(temp, duty)) - .await - .map_err(Self::map_call_error)?; - - println!("Added point to current curve: {}°C -> {}%", temp, duty); - Ok(()) - } - - /// Remove fan curve point - async fn remove_fan_curve_point(&self) -> Result<()> { - debug!("Removing last fan curve point"); - - let proxy = self.proxy().await?; - proxy - .call::<_, _, ()>("RemoveFanCurvePoint", &()) - .await - .map_err(Self::map_call_error)?; - - println!("Removed last point from current curve"); - Ok(()) - } - - /// Save configuration - async fn save_config(&self) -> Result<()> { - debug!("Saving configuration"); - - let proxy = self.proxy().await?; - proxy - .call::<_, _, ()>("SaveConfig", &()) - .await - .map_err(Self::map_call_error)?; - - println!("Configuration saved"); - Ok(()) - } - - /// Reload configuration from disk - async fn load_config(&self) -> Result<()> { - debug!("Reloading configuration"); - - let proxy = self.proxy().await?; - proxy - .call::<_, _, ()>("ReloadConfig", &()) - .await - .map_err(Self::map_call_error)?; - - println!("Configuration reloaded from disk"); - Ok(()) - } - - /// Show live daemon status - async fn show_status(&self) -> Result<()> { - let proxy = self.proxy().await?; - let (temp, duty, pwm, speeds): (f64, u16, u8, Vec<(u8, u16, String)>) = proxy - .call("GetStatus", &()) - .await - .map_err(Self::map_call_error)?; - - let curve: FanCurve = proxy - .call("GetCurrentFanCurve", &()) - .await - .map_err(Self::map_call_error)?; - let default: FanCurve = proxy - .call("GetDefaultFanCurve", &()) - .await - .map_err(Self::map_call_error)?; - - println!("Daemon status:"); - println!(" Current: {}", curve.name()); - println!(" Default: {} (used after reboot)", default.name()); - println!(" Temperature: {:.1}°C", temp); - println!(" Duty: {}%", duty / 100); - println!(" PWM: {}", pwm); - if speeds.is_empty() { - println!(" Fans: (none reported yet)"); - } else { - for (num, rpm, label) in speeds { - println!(" Fan {}: {} — {} RPM", num, label, rpm); + FanCurveCommands::RemovePoint => { + proxy + .call::<_, _, ()>("RemoveFanCurvePoint", &()) + .await + .map_err(daemon_error)?; + println!("Removed last point from current curve"); + } + FanCurveCommands::Save => { + proxy + .call::<_, _, ()>("SaveConfig", &()) + .await + .map_err(daemon_error)?; + println!("Configuration saved"); + } + FanCurveCommands::Load => { + proxy + .call::<_, _, ()>("ReloadConfig", &()) + .await + .map_err(daemon_error)?; + println!("Configuration reloaded from disk"); + } + FanCurveCommands::Status => { + let (temp, duty, pwm, speeds): (f64, u16, u8, Vec<(u8, u16, String)>) = + proxy.call("GetStatus", &()).await.map_err(daemon_error)?; + let curve: FanCurve = proxy + .call("GetCurrentFanCurve", &()) + .await + .map_err(daemon_error)?; + let default: FanCurve = proxy + .call("GetDefaultFanCurve", &()) + .await + .map_err(daemon_error)?; + + println!("Daemon status:"); + println!(" Current: {}", curve.name()); + println!(" Default: {} (used after reboot)", default.name()); + println!(" Temperature: {:.1}°C", temp); + println!(" Duty: {}%", duty / 100); + println!(" PWM: {}", pwm); + if speeds.is_empty() { + println!(" Fans: (none reported yet)"); + } else { + for (num, rpm, label) in speeds { + println!(" Fan {}: {} — {} RPM", num, label, rpm); + } } } - - Ok(()) } + + Ok(()) } diff --git a/src/cpu_temp.rs b/src/cpu_temp.rs index ac0b8f0..5b8c17e 100644 --- a/src/cpu_temp.rs +++ b/src/cpu_temp.rs @@ -1,11 +1,9 @@ -use crate::errors::FanCurveError; -use crate::errors::Result; -use log::{info, warn}; +use crate::errors::{FanCurveError, Result}; +use log::info; use std::fs; -use std::path::Path; /// CPU manufacturer types -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, Copy, PartialEq)] pub enum CpuManufacturer { Intel, Amd, @@ -17,6 +15,7 @@ pub enum CpuManufacturer { pub struct CpuTempSensor { pub manufacturer: CpuManufacturer, pub temp_input_path: String, + /// hwmon driver name, e.g. "k10temp" pub sensor_name: String, } @@ -60,111 +59,72 @@ fn parse_model_name(cpuinfo: &str) -> Option { } /// CPU temperature detector +#[derive(Default)] pub struct CpuTempDetector { sensor: Option, } impl CpuTempDetector { - /// Create a new CPU temperature detector pub fn new() -> Self { - Self { sensor: None } + Self::default() } - /// Initialize the detector by scanning for CPU temperature sensors + /// Find the CPU package temperature: coretemp "Package id 0" (or + /// "Core 0") on Intel, k10temp "Tctl" on AMD pub fn initialize(&mut self) -> Result<()> { - info!("Initializing CPU temperature detector..."); - - // First detect CPU manufacturer - let manufacturer = self.detect_cpu_manufacturer()?; - info!("Detected CPU manufacturer: {:?}", manufacturer); - - // Find the appropriate temperature sensor - let sensor = self.find_cpu_temp_sensor(&manufacturer)?; - self.sensor = Some(sensor); - - info!("CPU temperature sensor initialized: {:?}", self.sensor); - Ok(()) - } - - /// Detect CPU manufacturer by reading /proc/cpuinfo - fn detect_cpu_manufacturer(&self) -> Result { let cpuinfo = fs::read_to_string("/proc/cpuinfo")?; - - for line in cpuinfo.lines() { - if line.starts_with("vendor_id") { - let vendor = line - .split(':') - .nth(1) - .ok_or_else(|| FanCurveError::Config("Invalid cpuinfo format".to_string()))? - .trim(); - - return match vendor { - "GenuineIntel" => Ok(CpuManufacturer::Intel), - "AuthenticAMD" => Ok(CpuManufacturer::Amd), - _ => { - warn!("Unknown CPU vendor: {}", vendor); - Ok(CpuManufacturer::Unknown) - } - }; - } - } - - Err(FanCurveError::Config( - "Could not determine CPU manufacturer".to_string(), - )) - } - - /// Find the CPU temperature sensor in /sys/class/hwmon - fn find_cpu_temp_sensor(&self, manufacturer: &CpuManufacturer) -> Result { - let hwmon_dir = Path::new("/sys/class/hwmon"); - - if !hwmon_dir.exists() { - return Err(FanCurveError::Config( - "Hardware monitoring directory not found".to_string(), - )); - } - - // Read all hwmon directories - let entries = fs::read_dir(hwmon_dir)?; - - for entry in entries { - let entry = entry?; - let hwmon_path = entry.path(); - - if !hwmon_path.is_dir() { + let vendor = cpuinfo + .lines() + .find(|line| line.starts_with("vendor_id")) + .and_then(|line| line.split_once(':')) + .map(|(_, v)| v.trim()); + let manufacturer = match vendor { + Some("GenuineIntel") => CpuManufacturer::Intel, + Some("AuthenticAMD") => CpuManufacturer::Amd, + _ => CpuManufacturer::Unknown, + }; + + let (drivers, labels): (&[&str], &[&str]) = match manufacturer { + CpuManufacturer::Intel => (&["coretemp"], &["Package id 0", "Core 0"]), + CpuManufacturer::Amd => (&["k10temp"], &["Tctl"]), + CpuManufacturer::Unknown => ( + &["coretemp", "k10temp"], + &["Package id 0", "Core 0", "Tctl"], + ), + }; + + for hwmon in fs::read_dir("/sys/class/hwmon")? + .flatten() + .map(|e| e.path()) + { + let name = fs::read_to_string(hwmon.join("name")).unwrap_or_default(); + let name = name.trim(); + if !drivers.contains(&name) { continue; } - - // Read the name file to identify the sensor type - let name_path = hwmon_path.join("name"); - if let Ok(name_content) = fs::read_to_string(&name_path) { - let sensor_name = name_content.trim().to_string(); - - // Check if this is the sensor we want based on manufacturer - let is_target_sensor = match manufacturer { - CpuManufacturer::Intel => sensor_name == "coretemp", - CpuManufacturer::Amd => sensor_name == "k10temp", - CpuManufacturer::Unknown => { - // Try both if we can't determine manufacturer - sensor_name == "coretemp" || sensor_name == "k10temp" - } + for entry in fs::read_dir(&hwmon)?.flatten() { + let file = entry.file_name().to_string_lossy().into_owned(); + let Some(temp) = file + .strip_suffix("_input") + .filter(|t| t.starts_with("temp")) + else { + continue; }; - - if is_target_sensor { - // Find the correct temperature input file - if let Ok(temp_input_path) = - self.find_temp_input_file(&hwmon_path, manufacturer) - { - // The sensor must have a label, as the input file was - // picked by it - self.find_temp_label_file(&hwmon_path, &temp_input_path)?; - - return Ok(CpuTempSensor { - manufacturer: manufacturer.clone(), - temp_input_path, - sensor_name, - }); - } + let label = + fs::read_to_string(hwmon.join(format!("{}_label", temp))).unwrap_or_default(); + if labels.iter().any(|l| label.contains(l)) { + info!( + "CPU temperature sensor: {} {} ({:?} CPU)", + name, + label.trim(), + manufacturer + ); + self.sensor = Some(CpuTempSensor { + manufacturer, + temp_input_path: entry.path().to_string_lossy().into_owned(), + sensor_name: name.to_string(), + }); + return Ok(()); } } } @@ -175,127 +135,37 @@ impl CpuTempDetector { ))) } - /// Find the correct temperature input file - fn find_temp_input_file( - &self, - hwmon_path: &Path, - manufacturer: &CpuManufacturer, - ) -> Result { - let entries = fs::read_dir(hwmon_path)?; - - for entry in entries { - let entry = entry?; - let path = entry.path(); - - if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) { - if file_name.starts_with("temp") && file_name.ends_with("_input") { - // Check if this is the right temperature sensor by reading the label - if let Ok(label_path) = - self.find_temp_label_file(hwmon_path, &path.to_string_lossy()) - { - if let Ok(label_content) = fs::read_to_string(&label_path) { - let label = label_content.trim(); - - let is_correct_sensor = match manufacturer { - CpuManufacturer::Intel => { - label.contains("Package id 0") || label.contains("Core 0") - } - CpuManufacturer::Amd => label.contains("Tctl"), - CpuManufacturer::Unknown => { - // Try both patterns - label.contains("Package id 0") - || label.contains("Core 0") - || label.contains("Tctl") - } - }; - - if is_correct_sensor { - return Ok(path.to_string_lossy().to_string()); - } - } - } - } - } - } - - Err(FanCurveError::Config(format!( - "Could not find temperature input file for {:?}", - manufacturer - ))) - } - - /// Find the corresponding temperature label file - fn find_temp_label_file(&self, hwmon_path: &Path, temp_input_path: &str) -> Result { - // Extract the temp number from the input path (e.g., "temp1_input" -> "temp1") - let temp_input_name = Path::new(temp_input_path) - .file_name() - .and_then(|n| n.to_str()) - .ok_or_else(|| FanCurveError::Config("Invalid temp input path".to_string()))?; - - if let Some(temp_num) = temp_input_name.strip_suffix("_input") { - let label_file = format!("{}_label", temp_num); - let label_path = hwmon_path.join(&label_file); - - if label_path.exists() { - Ok(label_path.to_string_lossy().to_string()) - } else { - Err(FanCurveError::Config(format!( - "Label file not found: {}", - label_file - ))) - } - } else { - Err(FanCurveError::Config( - "Invalid temp input file format".to_string(), - )) - } - } - - /// Read the current CPU temperature + /// Read the current CPU temperature in °C pub fn read_temperature(&self) -> Result { let sensor = self.sensor.as_ref().ok_or_else(|| { FanCurveError::Config("CPU temperature sensor not initialized".to_string()) })?; - let temp_content = fs::read_to_string(&sensor.temp_input_path)?; - - // Temperature is typically in millidegrees Celsius - let temp_millidegrees: i32 = temp_content + let millidegrees: i32 = fs::read_to_string(&sensor.temp_input_path)? .trim() .parse() .map_err(|_| FanCurveError::Config("Failed to parse temperature".to_string()))?; + let celsius = millidegrees as f32 / 1000.0; - // Convert to degrees Celsius - let temp_celsius = temp_millidegrees as f32 / 1000.0; - - // Validate temperature range (reasonable CPU temperature range) - if !(-50.0..=200.0).contains(&temp_celsius) { + // Reject readings no CPU can produce, so a glitched sensor can't stop the fans + if !(-50.0..=200.0).contains(&celsius) { return Err(FanCurveError::Config(format!( "Temperature reading out of range: {:.1}°C", - temp_celsius + celsius ))); } - - Ok(temp_celsius) + Ok(celsius) } - /// Get sensor information pub fn get_sensor_info(&self) -> Option<&CpuTempSensor> { self.sensor.as_ref() } - /// Check if the detector is initialized pub fn is_initialized(&self) -> bool { self.sensor.is_some() } } -impl Default for CpuTempDetector { - fn default() -> Self { - Self::new() - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/src/daemon/mod.rs b/src/daemon/mod.rs index f01c55f..bd65ca4 100644 --- a/src/daemon/mod.rs +++ b/src/daemon/mod.rs @@ -4,7 +4,7 @@ use crate::{ alerts::fan_control, channels::{ChannelAssignment, GpuReading, GpuTemp, IoBoard, TempSource}, cpu_temp::CpuTempDetector, - errors::{zbus_error_from_display, FanCurveError, Result}, + errors::{FanCurveError, Result}, fan::{FanCurve, FanCurveConfig}, fan_detector::FanDetector, overheat::OverheatGuard, @@ -13,6 +13,7 @@ use crate::{ use log::{debug, error, info, warn}; use std::sync::{Arc, Mutex}; use tokio::time::{sleep, Duration}; +use zbus::fdo::Error::Failed; use zbus::{dbus_interface, ConnectionBuilder, SignalContext}; const SYSTEM76_POWER_SERVICE: &str = "com.system76.PowerDaemon"; @@ -69,12 +70,9 @@ impl FanCurveDaemon { initial_index ); - let config = Arc::new(Mutex::new(loaded)); - let current_curve_index = Arc::new(Mutex::new(initial_index)); - Ok(Self { - config, - current_curve_index, + config: Arc::new(Mutex::new(loaded)), + current_curve_index: Arc::new(Mutex::new(initial_index)), status: Arc::new(Mutex::new(DaemonStatus { fan_control: (fan_control::STARTING.to_string(), String::new()), ..Default::default() @@ -97,80 +95,31 @@ impl FanCurveDaemon { } } - /// Save configuration to file with proper error handling - fn save_config_internal(&self) -> Result<()> { + /// Index of the curve called `name` + fn curve_index(&self, name: &str) -> zbus::fdo::Result { let config = self.config.lock().unwrap(); - let config_path = FanCurveConfig::get_config_path(); - - // Ensure the directory exists - if let Some(parent) = config_path.parent() { - std::fs::create_dir_all(parent).map_err(|e| { - error!("Failed to create config directory: {}", e); - FanCurveError::Io(e) + config + .curves + .iter() + .position(|c| c.name() == name) + .ok_or_else(|| Failed(format!("Fan curve not found: {}", name))) + } + + /// Persist the in-memory config, reporting failure as a DBus error + fn save(&self) -> zbus::fdo::Result<()> { + let path = FanCurveConfig::get_config_path(); + self.config + .lock() + .unwrap() + .save_to_file(&path) + .map_err(|e| { + error!("Failed to save config: {}", e); + Failed(format!("Failed to save config: {}", e)) })?; - } - - // Create a temporary file first, then rename for atomic operation - let temp_path = config_path.with_extension("tmp"); - - // Save to temporary file - config.save_to_file(&temp_path).map_err(|e| { - error!("Failed to save config to temp file: {}", e); - FanCurveError::Config(format!("Failed to save config: {}", e)) - })?; - - // Atomically rename temp file to final location - std::fs::rename(&temp_path, &config_path).map_err(|e| { - error!("Failed to rename temp config file: {}", e); - // Try to clean up temp file - let _ = std::fs::remove_file(&temp_path); - FanCurveError::Io(e) - })?; - - info!( - "Configuration saved successfully to: {}", - config_path.display() - ); + info!("Configuration saved to {}", path.display()); Ok(()) } - /// Ensure configuration is saved with retry logic - fn ensure_config_saved(&self) -> Result<()> { - let mut retries = 3; - while retries > 0 { - match self.save_config_internal() { - Ok(()) => { - // Validate persistence after successful save - if let Err(e) = self.validate_persistence() { - error!("Persistence validation failed: {}", e); - // Don't fail the save operation, but log the issue - } - return Ok(()); - } - Err(e) => { - retries -= 1; - if retries > 0 { - error!( - "Failed to save config, retrying... ({} attempts left): {}", - retries, e - ); - std::thread::sleep(std::time::Duration::from_millis(100)); - } else { - error!("Failed to save config after all retries: {}", e); - return Err(e); - } - } - } - } - Ok(()) - } - - /// Validate that configuration persists correctly - fn validate_persistence(&self) -> Result<()> { - let config = self.config.lock().unwrap(); - config.validate_persistence() - } - /// Run the daemon: serve the DBus interface and drive the fan control loop pub async fn run(self) -> Result<()> { info!("Starting fan curve daemon"); @@ -685,7 +634,7 @@ impl FanCurveDaemon { debug!("Getting current fan curve"); let config = self.config.lock().unwrap(); if config.curves.is_empty() { - return Err(zbus_error_from_display("No fan curves configured")); + return Err(Failed("No fan curves configured".into())); } let current_index = (*self.current_curve_index.lock().unwrap()).min(config.curves.len() - 1); @@ -700,23 +649,17 @@ impl FanCurveDaemon { ) -> zbus::fdo::Result<()> { debug!("Setting fan curve to index {}", index); let curve_name = { - let mut current_index = self.current_curve_index.lock().unwrap(); let config = self.config.lock().unwrap(); - - if index as usize >= config.curves.len() { - return Err(zbus_error_from_display("Invalid fan curve index")); - } - - *current_index = index as usize; - config.curves[*current_index].name().to_string() + let curve = config + .curves + .get(index as usize) + .ok_or_else(|| Failed("Invalid fan curve index".into()))?; + *self.current_curve_index.lock().unwrap() = index as usize; + curve.name().to_string() }; info!("Fan curve set to: {}", curve_name); - - if let Err(e) = Self::fan_curve_changed(&ctxt).await { - warn!("Failed to emit FanCurveChanged signal: {}", e); - } - + emit_curve_changed(&ctxt).await; Ok(()) } @@ -727,29 +670,12 @@ impl FanCurveDaemon { #[zbus(signal_context)] ctxt: SignalContext<'_>, ) -> zbus::fdo::Result<()> { debug!("Setting fan curve to name: {}", name); - let found = { - let config = self.config.lock().unwrap(); - config.curves.iter().position(|c| c.name() == name) - }; - - if let Some(index) = found { - { - let mut current_index = self.current_curve_index.lock().unwrap(); - *current_index = index; - } - info!("Fan curve set to: {}", name); - - if let Err(e) = Self::fan_curve_changed(&ctxt).await { - warn!("Failed to emit FanCurveChanged signal: {}", e); - } + let index = self.curve_index(name)?; + *self.current_curve_index.lock().unwrap() = index; - Ok(()) - } else { - Err(zbus_error_from_display(format!( - "Fan curve not found: {}", - name - ))) - } + info!("Fan curve set to: {}", name); + emit_curve_changed(&ctxt).await; + Ok(()) } /// Set the persistent default fan curve (survives reboots) and activate it now. @@ -759,43 +685,13 @@ impl FanCurveDaemon { #[zbus(signal_context)] ctxt: SignalContext<'_>, ) -> zbus::fdo::Result<()> { debug!("Setting default fan curve to: {}", name); - let index = { - let config = self.config.lock().unwrap(); - config.curves.iter().position(|c| c.name() == name) - }; - - let Some(index) = index else { - return Err(zbus_error_from_display(format!( - "Fan curve not found: {}", - name - ))); - }; - - { - let mut config = self.config.lock().unwrap(); - let mut current = self.current_curve_index.lock().unwrap(); - config.default_curve_index = Some(index); - *current = index; - } - - if let Err(e) = self.ensure_config_saved() { - error!("Failed to save config after setting default: {}", e); - return Err(zbus_error_from_display(format!( - "Failed to save config: {}", - e - ))); - } - - info!( - "Default fan curve set to '{}' and persisted to {}", - name, - FanCurveConfig::get_config_path().display() - ); - - if let Err(e) = Self::fan_curve_changed(&ctxt).await { - warn!("Failed to emit FanCurveChanged signal: {}", e); - } + let index = self.curve_index(name)?; + self.config.lock().unwrap().default_curve_index = Some(index); + *self.current_curve_index.lock().unwrap() = index; + self.save()?; + info!("Default fan curve set to '{}'", name); + emit_curve_changed(&ctxt).await; Ok(()) } @@ -803,7 +699,7 @@ impl FanCurveDaemon { async fn get_default_fan_curve(&self) -> zbus::fdo::Result { let config = self.config.lock().unwrap(); if config.curves.is_empty() { - return Err(zbus_error_from_display("No fan curves configured")); + return Err(Failed("No fan curves configured".into())); } let index = config .default_curve_index @@ -823,44 +719,26 @@ impl FanCurveDaemon { debug!("Adding fan curve point: {}°C -> {}%", temp, duty); if !(0..=100).contains(&temp) || duty > 100 { - return Err(zbus_error_from_display("Invalid fan curve point values")); + return Err(Failed("Invalid fan curve point values".into())); } - let valid_index = { + { let mut config = self.config.lock().unwrap(); - let current_index = self.current_curve_index.lock().unwrap(); - - if *current_index < config.curves.len() { - if config.curves[*current_index].is_builtin() { - return Err(zbus_error_from_display(BUILTIN_READ_ONLY)); - } - config.curves[*current_index].add_point(temp, duty * 100); - true - } else { - false - } - }; - - if valid_index { - // Ensure config is saved immediately - if let Err(e) = self.ensure_config_saved() { - error!("Failed to save config after adding point: {}", e); - return Err(zbus_error_from_display(format!( - "Failed to save config: {}", - e - ))); - } - - info!("Added fan curve point: {}°C -> {}%", temp, duty); - - if let Err(e) = Self::fan_curve_changed(&ctxt).await { - warn!("Failed to emit FanCurveChanged signal: {}", e); + let index = *self.current_curve_index.lock().unwrap(); + let curve = config + .curves + .get_mut(index) + .ok_or_else(|| Failed("Invalid current fan curve index".into()))?; + if curve.is_builtin() { + return Err(Failed(BUILTIN_READ_ONLY.into())); } - - Ok(()) - } else { - Err(zbus_error_from_display("Invalid current fan curve index")) + curve.add_point(temp, duty * 100); } + self.save()?; + + info!("Added fan curve point: {}°C -> {}%", temp, duty); + emit_curve_changed(&ctxt).await; + Ok(()) } /// Remove last fan curve point @@ -870,56 +748,30 @@ impl FanCurveDaemon { ) -> zbus::fdo::Result<()> { debug!("Removing last fan curve point"); - let point_removed = { + { let mut config = self.config.lock().unwrap(); - let current_index = self.current_curve_index.lock().unwrap(); - - if *current_index < config.curves.len() { - if config.curves[*current_index].is_builtin() { - return Err(zbus_error_from_display(BUILTIN_READ_ONLY)); - } - config.curves[*current_index].remove_last_point().is_some() - } else { - return Err(zbus_error_from_display("Invalid current fan curve index")); - } - }; - - if point_removed { - // Ensure config is saved immediately - if let Err(e) = self.ensure_config_saved() { - error!("Failed to save config after removing point: {}", e); - return Err(zbus_error_from_display(format!( - "Failed to save config: {}", - e - ))); - } - - info!("Removed last fan curve point"); - - if let Err(e) = Self::fan_curve_changed(&ctxt).await { - warn!("Failed to emit FanCurveChanged signal: {}", e); + let index = *self.current_curve_index.lock().unwrap(); + let curve = config + .curves + .get_mut(index) + .ok_or_else(|| Failed("Invalid current fan curve index".into()))?; + if curve.is_builtin() { + return Err(Failed(BUILTIN_READ_ONLY.into())); } - - Ok(()) - } else { - Err(zbus_error_from_display("No points to remove")) + curve + .remove_last_point() + .ok_or_else(|| Failed("No points to remove".into()))?; } + self.save()?; + + info!("Removed last fan curve point"); + emit_curve_changed(&ctxt).await; + Ok(()) } /// Save configuration async fn save_config(&self) -> zbus::fdo::Result<()> { - debug!("Saving configuration"); - - if let Err(e) = self.ensure_config_saved() { - error!("Failed to save config: {}", e); - return Err(zbus_error_from_display(format!( - "Failed to save config: {}", - e - ))); - } - - info!("Configuration saved"); - Ok(()) + self.save() } /// Replace the daemon's in-memory curves with a full config from a client @@ -933,7 +785,7 @@ impl FanCurveDaemon { #[zbus(signal_context)] ctxt: SignalContext<'_>, ) -> zbus::fdo::Result<()> { if curves.is_empty() { - return Err(zbus_error_from_display("Cannot set an empty curve list")); + return Err(Failed("Cannot set an empty curve list".into())); } // Built-in profiles are read-only: whatever a client sends for them, // they keep their factory definitions. @@ -946,7 +798,7 @@ impl FanCurveDaemon { .iter() .position(|c| c.name() == current_name) .ok_or_else(|| { - zbus_error_from_display(format!( + Failed(format!( "Current curve not found in provided config: {}", current_name )) @@ -957,7 +809,7 @@ impl FanCurveDaemon { } else if (default_index as usize) < curves.len() { Some(default_index as usize) } else { - return Err(zbus_error_from_display("Invalid default curve index")); + return Err(Failed("Invalid default curve index".into())); }; { @@ -972,24 +824,13 @@ impl FanCurveDaemon { }; *index = current_pos; } - - if let Err(e) = self.ensure_config_saved() { - error!("Failed to save config after SetConfig: {}", e); - return Err(zbus_error_from_display(format!( - "Failed to save config: {}", - e - ))); - } + self.save()?; info!( "Config replaced via DBus; active curve: {} (index {})", current_name, current_pos ); - - if let Err(e) = Self::fan_curve_changed(&ctxt).await { - warn!("Failed to emit FanCurveChanged signal: {}", e); - } - + emit_curve_changed(&ctxt).await; Ok(()) } @@ -1030,10 +871,7 @@ impl FanCurveDaemon { /// profile isn't independent. Unlisted channels are unchanged. async fn set_channels(&self, channels: Vec<(u8, TempSource)>) -> zbus::fdo::Result<()> { if let Some((number, _)) = channels.iter().find(|(n, _)| !(1..=4).contains(n)) { - return Err(zbus_error_from_display(format!( - "Invalid channel: {}", - number - ))); + return Err(Failed(format!("Invalid channel: {}", number))); } { @@ -1050,13 +888,7 @@ impl FanCurveDaemon { } } - if let Err(e) = self.ensure_config_saved() { - error!("Failed to save config after SetChannels: {}", e); - return Err(zbus_error_from_display(format!( - "Failed to save config: {}", - e - ))); - } + self.save()?; info!("Fan channel temperature sources updated"); Ok(()) } @@ -1079,7 +911,7 @@ impl FanCurveDaemon { ) -> zbus::fdo::Result<()> { debug!("Reloading configuration from disk"); - let new_config = Self::load_config().map_err(zbus_error_from_display)?; + let new_config = Self::load_config().map_err(|e| Failed(e.to_string()))?; { let mut config = self.config.lock().unwrap(); @@ -1092,15 +924,17 @@ impl FanCurveDaemon { } info!("Configuration reloaded from disk"); - - if let Err(e) = Self::fan_curve_changed(&ctxt).await { - warn!("Failed to emit FanCurveChanged signal: {}", e); - } - + emit_curve_changed(&ctxt).await; Ok(()) } } +async fn emit_curve_changed(ctxt: &SignalContext<'_>) { + if let Err(e) = FanCurveDaemon::fan_curve_changed(ctxt).await { + warn!("Failed to emit FanCurveChanged signal: {}", e); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/errors.rs b/src/errors.rs index ce3f823..6d9b71d 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -19,24 +19,4 @@ pub enum FanCurveError { #[error("Configuration error: {0}")] Config(String), - - #[error("Fan curve not found: {name}")] - FanCurveNotFound { name: String }, - - #[error("Invalid fan curve point: temperature {temp}°C, duty {duty}%")] - InvalidFanPoint { temp: i16, duty: u16 }, - - #[error("Permission denied: {0}")] - PermissionDenied(String), - - #[error("Daemon not running")] - DaemonNotRunning, - - #[error("Unknown error: {0}")] - Unknown(String), -} - -/// Helper function to convert display errors to zbus errors -pub fn zbus_error_from_display(err: impl std::fmt::Display) -> zbus::fdo::Error { - zbus::fdo::Error::Failed(format!("{}", err)) } diff --git a/src/fan.rs b/src/fan.rs index 04d2bfc..d3ff4c7 100644 --- a/src/fan.rs +++ b/src/fan.rs @@ -150,10 +150,6 @@ impl FanCurve { &self.points } - pub fn points_mut(&mut self) -> &mut Vec { - &mut self.points - } - pub fn add_point(&mut self, temp: i16, duty: u16) { self.points.push(FanPoint::new(temp, duty)); self.points.sort_by_key(|p| p.temp); @@ -164,15 +160,7 @@ impl FanCurve { } pub fn remove_point(&mut self, index: usize) -> Option { - if index < self.points.len() { - Some(self.points.remove(index)) - } else { - None - } - } - - pub fn get_point(&self, index: usize) -> Option<&FanPoint> { - self.points.get(index) + (index < self.points.len()).then(|| self.points.remove(index)) } /// Calculate fan duty for a given temperature using linear interpolation @@ -182,12 +170,9 @@ impl FanCurve { duty_for_temperature(&self.points, temp_thousandths) } - /// Calculate fan duty percentage for a given temperature using linear interpolation - /// This is a convenience method that maintains backward compatibility + /// Same as `calculate_duty_for_temperature`, with the temperature in °C pub fn calculate_duty_for_temperature_celsius(&self, temperature: f32) -> u16 { - // Convert Celsius to thousandths of Celsius - let temp_thousandths = (temperature * 1000.0) as u32; - self.calculate_duty_for_temperature(temp_thousandths) + self.calculate_duty_for_temperature((temperature * 1000.0) as u32) } // Built-in curves mirror system76-power's FanCurve definitions (src/fan.rs @@ -261,66 +246,33 @@ impl FanCurve { _ => "Standard", } } - - pub fn save_to_file(&self, path: &Path) -> Result<()> { - let json = serde_json::to_string_pretty(self)?; - fs::write(path, json)?; - Ok(()) - } - - pub fn load_from_file(path: &Path) -> Result { - let json = fs::read_to_string(path)?; - let curve: FanCurve = serde_json::from_str(&json)?; - Ok(curve) - } } /// Fan duty (ten-thousandths, 0-10000) for a temperature in thousandths of /// a degree Celsius, linearly interpolated between `points`. pub fn duty_for_temperature(points: &[FanPoint], temp_thousandths: u32) -> u16 { - if points.is_empty() { + // Curve points store whole °C (e.g. 30000 thousandths -> 30°C) + let temp = (temp_thousandths / 1000) as i16; + let (Some(first), Some(last)) = (points.first(), points.last()) else { return 0; - } - - // Convert thousandths of Celsius to whole degrees, since curve points - // store temperature in whole °C (e.g. 30000 thousandths -> 30°C) - let temp_celsius = (temp_thousandths / 1000) as i16; - - // If temperature is below the lowest point, return the duty of the lowest point - if temp_celsius <= points[0].temp { - return points[0].duty; - } - - // If temperature is above the highest point, return the duty of the highest point - if temp_celsius >= points.last().unwrap().temp { - return points.last().unwrap().duty; - } - - // Find the two points to interpolate between - for i in 0..points.len() - 1 { - let point1 = &points[i]; - let point2 = &points[i + 1]; - - if temp_celsius >= point1.temp && temp_celsius <= point2.temp { - // Linear interpolation between the two points - let temp1 = point1.temp as f32; - let temp2 = point2.temp as f32; - let duty1 = point1.duty as f32; - let duty2 = point2.duty as f32; - let temp_current = temp_celsius as f32; - - // Calculate the interpolation factor - let factor = (temp_current - temp1) / (temp2 - temp1); - - // Interpolate the duty - let interpolated_duty = duty1 + factor * (duty2 - duty1); - - return interpolated_duty.round() as u16; - } - } - - // Fallback (should not reach here) - 0 + }; + if temp <= first.temp { + return first.duty; + } + if temp >= last.temp { + return last.duty; + } + + // Points are sorted, so the first segment ending at or above `temp` contains it + points + .windows(2) + .find(|w| temp <= w[1].temp) + .map(|w| { + let (a, b) = (&w[0], &w[1]); + let factor = f32::from(temp - a.temp) / f32::from(b.temp - a.temp); + (f32::from(a.duty) + factor * (f32::from(b.duty) - f32::from(a.duty))).round() as u16 + }) + .unwrap_or(0) } #[derive(Debug, Serialize, Deserialize)] @@ -360,7 +312,13 @@ impl FanCurveConfig { pub fn save_to_file(&self, path: &Path) -> Result<()> { // Never persist edits over built-in profiles; custom curves save as-is. let json = serde_json::to_string_pretty(&self.for_persistence())?; - fs::write(path, json)?; + if let Some(dir) = path.parent() { + fs::create_dir_all(dir)?; + } + // Write then rename, so a crash mid-write never leaves a truncated config + let tmp = path.with_extension("tmp"); + fs::write(&tmp, json)?; + fs::rename(&tmp, path)?; Ok(()) } @@ -397,68 +355,6 @@ impl FanCurveConfig { channels: self.channels.clone(), } } - - /// Validate that the configuration is properly saved and can be loaded - pub fn validate_persistence(&self) -> Result<()> { - let config_path = Self::get_config_path(); - let expected = self.for_persistence(); - - // Save the current config - self.save_to_file(&config_path)?; - - // Try to load it back - let loaded_config = Self::load_from_file(&config_path)?; - - // Validate that the loaded config matches what persistence writes - if loaded_config.curves.len() != expected.curves.len() { - return Err(crate::errors::FanCurveError::Config( - "Curve count mismatch after save/load".to_string(), - )); - } - - for (i, (original, loaded)) in expected - .curves - .iter() - .zip(loaded_config.curves.iter()) - .enumerate() - { - if original.name() != loaded.name() { - return Err(crate::errors::FanCurveError::Config(format!( - "Curve {} name mismatch after save/load", - i - ))); - } - - if original.points().len() != loaded.points().len() { - return Err(crate::errors::FanCurveError::Config(format!( - "Curve {} point count mismatch after save/load", - i - ))); - } - - for (j, (orig_point, load_point)) in original - .points() - .iter() - .zip(loaded.points().iter()) - .enumerate() - { - if orig_point.temp != load_point.temp || orig_point.duty != load_point.duty { - return Err(crate::errors::FanCurveError::Config(format!( - "Curve {} point {} data mismatch after save/load", - i, j - ))); - } - } - } - - if expected.default_curve_index != loaded_config.default_curve_index { - return Err(crate::errors::FanCurveError::Config( - "Default curve index mismatch after save/load".to_string(), - )); - } - - Ok(()) - } } impl Default for FanCurveConfig { @@ -619,13 +515,6 @@ mod tests { assert_eq!(loaded_custom.name(), "Custom Test"); assert_eq!(loaded_custom.points().len(), 5); - // Round-trip through for_persistence (what save_to_file writes) - let expected = config.for_persistence(); - let reloaded = - FanCurveConfig::load_from_file(&config_path).expect("Failed to reload config"); - assert_eq!(reloaded.curves.len(), expected.curves.len()); - assert_eq!(reloaded.default_curve_index, expected.default_curve_index); - // Clean up test file let _ = std::fs::remove_dir_all(&dir); } @@ -638,41 +527,12 @@ mod tests { curve.add_point(50, 10000); // 100% = 10000/10000 at 50°C curve.add_point(100, 10000); - // Test at exactly 50°C - let temp_50c = 50.0; - let temp_thousandths = (temp_50c * 1000.0) as u32; // 50000 thousandths - let duty = curve.calculate_duty_for_temperature(temp_thousandths); - - println!( - "Temperature: {}°C ({} thousandths)", - temp_50c, temp_thousandths - ); - println!("Calculated duty: {} (should be 10000 for 100%)", duty); - println!("Duty percentage: {}%", duty / 100); - - // Test PWM conversion - let pwm = ((u32::from(duty) * 255) / 10000) as u8; - println!("PWM value: {} (should be 255 for 100%)", pwm); - - // Verify the calculations - assert_eq!(duty, 10000, "Duty should be 10000 for 100% at 50°C"); - assert_eq!(pwm, 255, "PWM should be 255 for 100% duty"); - - // Test at 51°C (should still be 100% due to interpolation) - let temp_51c = 51.0; - let temp_thousandths_51 = (temp_51c * 1000.0) as u32; - let duty_51 = curve.calculate_duty_for_temperature(temp_thousandths_51); - let pwm_51 = ((u32::from(duty_51) * 255) / 10000) as u8; - - println!("Temperature: {}°C", temp_51c); - println!("Calculated duty: {} (should be 10000 for 100%)", duty_51); - println!("Duty percentage: {}%", duty_51 / 100); - println!("PWM value: {} (should be 255 for 100%)", pwm_51); - - // At 51°C, it should interpolate between 50°C (100%) and 100°C (100%) - // So it should still be 100% - assert_eq!(duty_51, 10000, "Duty should be 10000 for 100% at 51°C"); - assert_eq!(pwm_51, 255, "PWM should be 255 for 100% duty at 51°C"); + // At 50°C and between two 100% points at 51°C + for temp in [50_000, 51_000] { + let duty = curve.calculate_duty_for_temperature(temp); + assert_eq!(duty, 10000); + assert_eq!(((u32::from(duty) * 255) / 10000) as u8, 255); + } } #[test] diff --git a/src/fan_curve_gui.rs b/src/fan_curve_gui.rs index 1a9c185..cdf4922 100644 --- a/src/fan_curve_gui.rs +++ b/src/fan_curve_gui.rs @@ -214,9 +214,7 @@ impl FanCurveApp { load_initial_curves(daemon.as_ref()); let mut fan_monitor = FanMonitor::new(); - if let Err(e) = fan_monitor.initialize() { - eprintln!("Warning: Failed to detect sensors: {}", e); - } + fan_monitor.initialize(); let fans = daemon.as_ref().and_then(fetch_channels).unwrap_or_default(); @@ -265,47 +263,16 @@ impl FanCurveApp { fn save_config(&self) -> Result<()> { let config_path = FanCurveConfig::get_config_path(); - - // Ensure the directory exists - if let Some(parent) = config_path.parent() { - std::fs::create_dir_all(parent).map_err(|e| { - eprintln!("Failed to create config directory: {}", e); - e - })?; - } - // Channel settings live in the daemon's config; keep any in this file. let channels = FanCurveConfig::load_from_file(&config_path) .map(|c| c.channels) .unwrap_or_default(); - let config = FanCurveConfig { + FanCurveConfig { curves: self.fan_curves.clone(), default_curve_index: self.default_curve_index, channels, - }; - - // Create a temporary file first, then rename for atomic operation - let temp_path = config_path.with_extension("tmp"); - - // Save to temporary file - config.save_to_file(&temp_path).map_err(|e| { - eprintln!("Failed to save config to temp file: {}", e); - e - })?; - - // Atomically rename temp file to final location - std::fs::rename(&temp_path, &config_path).map_err(|e| { - eprintln!("Failed to rename temp config file: {}", e); - // Try to clean up temp file - let _ = std::fs::remove_file(&temp_path); - e - })?; - - println!( - "Configuration saved successfully to: {}", - config_path.display() - ); - Ok(()) + } + .save_to_file(&config_path) } fn set_status(&mut self, message: String) { @@ -864,6 +831,17 @@ impl FanCurveApp { } } +/// Parse a point dialog's temperature (°C) and duty (%) fields. +fn parse_point(temp: &str, duty: &str) -> std::result::Result<(i16, u16), String> { + let (Ok(temp), Ok(duty)) = (temp.parse::(), duty.parse::()) else { + return Err("Invalid input: Please enter valid numbers".to_string()); + }; + if !(0..=100).contains(&temp) || duty > 100 { + return Err("Invalid values: Temperature must be 0-100°C, Duty must be 0-100%".to_string()); + } + Ok((temp, duty)) +} + /// A fan's current duty in the editors, or that no fan is connected. fn show_fan_now(ui: &mut egui::Ui, duty: u16, missing: bool) { if missing { @@ -1097,8 +1075,6 @@ impl eframe::App for FanCurveApp { self.cpu_clock = crate::cpu_temp::cpu_clock_mhz(); } - // No test mode state to manage - // Request periodic repaint for smooth updates ctx.request_repaint_after(std::time::Duration::from_millis(500)); @@ -1254,12 +1230,10 @@ impl eframe::App for FanCurveApp { } } - // (Test mode removed) - // Add point dialog if self.show_add_point_dialog { let mut should_close = false; - let mut should_add = false; + let mut added = None; let mut error_message = None; egui::Window::new("Add Fan Curve Point") @@ -1283,19 +1257,12 @@ impl eframe::App for FanCurveApp { ui.horizontal(|ui| { if ui.button("Add Point").clicked() { - // Validate inputs - if let (Ok(temp), Ok(duty)) = ( - self.new_point_temp.parse::(), - self.new_point_duty.parse::() - ) { - if (0..=100).contains(&temp) && duty <= 100 { - should_add = true; + match parse_point(&self.new_point_temp, &self.new_point_duty) { + Ok(point) => { + added = Some(point); should_close = true; - } else { - error_message = Some("Invalid values: Temperature must be 0-100°C, Duty must be 0-100%".to_string()); } - } else { - error_message = Some("Invalid input: Please enter valid numbers".to_string()); + Err(e) => error_message = Some(e), } } if ui.button("Cancel").clicked() { @@ -1304,24 +1271,16 @@ impl eframe::App for FanCurveApp { }); }); + if let Some((temp, duty)) = added { + // Dialog input is percent; store as ten-thousandths (0-10000) + self.add_target_point(temp, duty * 100); + self.set_status(format!("Added point: {}°C -> {}%", temp, duty)); + self.auto_save_config(); + } if should_close { self.show_add_point_dialog = false; - if should_add { - if let (Ok(temp), Ok(duty)) = ( - self.new_point_temp.parse::(), - self.new_point_duty.parse::() - ) { - // Dialog input is percent; store as ten-thousandths (0-10000) - self.add_target_point(temp, duty * 100); - self.set_status(format!("Added point: {}°C -> {}%", temp, duty)); - self.auto_save_config(); - } - self.new_point_temp.clear(); - self.new_point_duty.clear(); - } else { - self.new_point_temp.clear(); - self.new_point_duty.clear(); - } + self.new_point_temp.clear(); + self.new_point_duty.clear(); } if let Some(error) = error_message { @@ -1332,7 +1291,7 @@ impl eframe::App for FanCurveApp { // Edit point dialog if self.show_edit_point_dialog { let mut should_close = false; - let mut should_edit = false; + let mut edited = None; let mut error_message = None; egui::Window::new("Edit Fan Curve Point") @@ -1356,19 +1315,12 @@ impl eframe::App for FanCurveApp { ui.horizontal(|ui| { if ui.button("Update Point").clicked() { - // Validate inputs - if let (Ok(temp), Ok(duty)) = ( - self.edit_point_temp.parse::(), - self.edit_point_duty.parse::() - ) { - if (0..=100).contains(&temp) && duty <= 100 { - should_edit = true; + match parse_point(&self.edit_point_temp, &self.edit_point_duty) { + Ok(point) => { + edited = Some(point); should_close = true; - } else { - error_message = Some("Invalid values: Temperature must be 0-100°C, Duty must be 0-100%".to_string()); } - } else { - error_message = Some("Invalid input: Please enter valid numbers".to_string()); + Err(e) => error_message = Some(e), } } if ui.button("Cancel").clicked() { @@ -1377,31 +1329,19 @@ impl eframe::App for FanCurveApp { }); }); + if let (Some((temp, duty)), Some(index)) = (edited, self.edit_point_index) { + // Replace the old point; dialog input is percent, stored as ten-thousandths + if self.remove_target_point(index).is_some() { + self.add_target_point(temp, duty * 100); + self.set_status(format!("Updated point {}: {}°C -> {}%", index + 1, temp, duty)); + self.auto_save_config(); + } + } if should_close { self.show_edit_point_dialog = false; - if should_edit { - if let (Ok(temp), Ok(duty)) = ( - self.edit_point_temp.parse::(), - self.edit_point_duty.parse::() - ) { - if let Some(index) = self.edit_point_index { - // Remove the old point and add the new one - // Dialog input is percent; store as ten-thousandths (0-10000) - if self.remove_target_point(index).is_some() { - self.add_target_point(temp, duty * 100); - self.set_status(format!("Updated point {}: {}°C -> {}%", index + 1, temp, duty)); - self.auto_save_config(); - } - } - } - self.edit_point_temp.clear(); - self.edit_point_duty.clear(); - self.edit_point_index = None; - } else { - self.edit_point_temp.clear(); - self.edit_point_duty.clear(); - self.edit_point_index = None; - } + self.edit_point_temp.clear(); + self.edit_point_duty.clear(); + self.edit_point_index = None; } if let Some(error) = error_message { diff --git a/src/fan_detector.rs b/src/fan_detector.rs index 7c29778..c3e3927 100644 --- a/src/fan_detector.rs +++ b/src/fan_detector.rs @@ -1,5 +1,5 @@ -use crate::errors::Result; -use log::{debug, error, info, warn}; +use crate::errors::{FanCurveError, Result}; +use log::{debug, info, warn}; use std::fs; use std::path::{Path, PathBuf}; @@ -44,345 +44,119 @@ pub fn restore_automatic(root: &Path) -> Vec { #[derive(Debug, Clone)] pub struct FanSensor { pub fan_number: u8, - pub hwmon_path: String, - pub fan_input_path: String, + pub hwmon_path: PathBuf, pub fan_label: String, } -/// Fan detector for System76 Thelio IO +/// CPU fan control for System76 hwmon devices without a Thelio Io board's +/// per-channel support (e.g. laptops) +#[derive(Default)] pub struct FanDetector { fans: Vec, - hwmon_path: Option, } impl FanDetector { - /// Create a new fan detector pub fn new() -> Self { - Self { - fans: Vec::new(), - hwmon_path: None, - } + Self::default() } - /// Initialize the detector by finding System76 Thelio IO sensors + /// Find the CPU fan on the System76 hwmon device pub fn initialize(&mut self) -> Result<()> { - info!("Initializing fan detector..."); - - // Find the System76 Thelio IO hwmon directory - self.find_thelio_io_sensor()?; - - // Find all fan sensors in that directory - self.find_fan_sensors()?; - - info!( - "Fan detector initialized with {} fans found", - self.fans.len() - ); - - // Log details about each detected fan - for fan in &self.fans { - info!( - "Fan {}: {} at {}", - fan.fan_number, fan.fan_label, fan.hwmon_path - ); - - // Check PWM file status - let pwm_path = Path::new(&fan.hwmon_path).join(format!("pwm{}", fan.fan_number)); - let pwm_enable_path = - Path::new(&fan.hwmon_path).join(format!("pwm{}_enable", fan.fan_number)); - - if pwm_path.exists() { - info!("PWM file exists: {}", pwm_path.display()); - - // Check if PWM file is writable - match std::fs::OpenOptions::new().write(true).open(&pwm_path) { - Ok(_) => info!("PWM file is writable"), - Err(e) => warn!("PWM file not writable: {}", e), - } - } else { - warn!("PWM file missing: {}", pwm_path.display()); + let hwmon = fs::read_dir("/sys/class/hwmon")? + .flatten() + .map(|e| e.path()) + .find(|p| { + let name = fs::read_to_string(p.join("name")).unwrap_or_default(); + matches!( + name.trim(), + "system76_thelio_io" | "system76_io" | "system76" + ) + }) + .ok_or_else(|| FanCurveError::Config("System76 Thelio IO sensor not found".into()))?; + + // fanN_label / fanN_input pairs are numbered from 1 without gaps + for fan_number in 1..=10 { + let Ok(label) = fs::read_to_string(hwmon.join(format!("fan{}_label", fan_number))) + else { + break; + }; + if !hwmon.join(format!("fan{}_input", fan_number)).exists() { + break; } - - if pwm_enable_path.exists() { - info!("PWM enable file exists: {}", pwm_enable_path.display()); - } else { + let fan_label = label.trim().to_string(); + if fan_label.to_lowercase().contains("cpu") { info!( - "PWM enable file missing: {} (may not be required)", - pwm_enable_path.display() + "Found CPU fan: fan{} '{}' at {}", + fan_number, + fan_label, + hwmon.display() ); + self.fans.push(FanSensor { + fan_number, + hwmon_path: hwmon, + fan_label, + }); + return Ok(()); } } - // Debug: List all found fans - for (i, fan) in self.fans.iter().enumerate() { - info!( - "Fan {}: number={}, label='{}', input_path='{}'", - i, fan.fan_number, fan.fan_label, fan.fan_input_path - ); - } - - Ok(()) - } - - /// Find the System76 Thelio IO sensor directory - fn find_thelio_io_sensor(&mut self) -> Result<()> { - let hwmon_dir = Path::new("/sys/class/hwmon"); - - if !hwmon_dir.exists() { - return Err(crate::errors::FanCurveError::Config( - "Hardware monitoring directory not found".to_string(), - )); - } - - let entries = fs::read_dir(hwmon_dir)?; - - for entry in entries { - let entry = entry?; - let path = entry.path(); - - if path.is_dir() { - let name_file = path.join("name"); - if name_file.exists() { - if let Ok(name_content) = fs::read_to_string(&name_file) { - let name = name_content.trim(); - info!("Checking hwmon device: {} -> '{}'", path.display(), name); - - if name == "system76_thelio_io" - || name == "system76_io" - || name == "system76" - { - self.hwmon_path = Some(path.to_string_lossy().to_string()); - info!("Found System76 sensor '{}' at: {}", name, path.display()); - return Ok(()); - } - } - } - } - } - - Err(crate::errors::FanCurveError::Config( - "System76 Thelio IO sensor not found".to_string(), - )) - } - - /// Find the CPU Fan sensor in the System76 Thelio IO directory - fn find_fan_sensors(&mut self) -> Result<()> { - let hwmon_path = self.hwmon_path.as_ref().ok_or_else(|| { - crate::errors::FanCurveError::Config( - "System76 Thelio IO sensor path not found".to_string(), - ) - })?; - - let hwmon_dir = Path::new(hwmon_path); - info!( - "Searching for CPU Fan in directory: {}", - hwmon_dir.display() - ); - - // Search through fan1_label, fan2_label, fan3_label, etc. until we find "CPU Fan" - let mut fan_number = 1; - loop { - let label_path = hwmon_dir.join(format!("fan{}_label", fan_number)); - let input_path = hwmon_dir.join(format!("fan{}_input", fan_number)); - - info!( - "Checking fan{}_label at: {}", - fan_number, - label_path.display() - ); - - if label_path.exists() && input_path.exists() { - if let Ok(label_content) = fs::read_to_string(&label_path) { - let fan_label = label_content.trim().to_string(); - info!("Found fan{}_label: '{}'", fan_number, fan_label); - - if fan_label == "CPU Fan" - || fan_label == "CPU fan" - || fan_label.to_lowercase().contains("cpu") - { - info!( - "Found CPU Fan at fan{}! Using fan{}_input for data", - fan_number, fan_number - ); - - let fan_sensor = FanSensor { - fan_number, - hwmon_path: hwmon_path.clone(), - fan_input_path: input_path.to_string_lossy().to_string(), - fan_label: fan_label.clone(), - }; - - self.fans.push(fan_sensor); - info!( - "CPU Fan sensor added: Fan {} - {} -> {}", - fan_number, - fan_label, - input_path.display() - ); - return Ok(()); - } - } - } else { - // No more fan files found, stop searching - break; - } - - fan_number += 1; - - // Safety limit to prevent infinite loop - if fan_number > 10 { - break; - } - } - - Err(crate::errors::FanCurveError::Config( + Err(FanCurveError::Config( "CPU Fan not found in System76 Thelio IO".to_string(), )) } - /// Read fan speed for a specific fan - pub fn read_fan_speed(&self, fan_number: u8) -> Result { - if let Some(fan) = self.fans.iter().find(|f| f.fan_number == fan_number) { - info!( - "Reading fan {} from path: {}", - fan_number, fan.fan_input_path - ); - let speed_content = fs::read_to_string(&fan.fan_input_path)?; - let raw_speed: u16 = speed_content.trim().parse().map_err(|_| { - crate::errors::FanCurveError::Config("Failed to parse fan speed".to_string()) - })?; - - info!( - "Fan {} raw reading: {} RPM from {}", - fan_number, raw_speed, fan.fan_input_path - ); - - // Use raw sensor reading directly as RPM - Ok(raw_speed) - } else { - warn!( - "Fan {} not found in detected fans: {:?}", - fan_number, - self.fans.iter().map(|f| f.fan_number).collect::>() - ); - Err(crate::errors::FanCurveError::Config(format!( - "Fan {} not found", - fan_number - ))) - } - } - - /// Read all fan speeds + /// RPM of each detected fan, as (fan_number, rpm, label) pub fn read_all_fan_speeds(&self) -> Result> { - let mut speeds = Vec::new(); - - // Since fans are already prioritized with CPU Fan first, just read them in order - for fan in &self.fans { - let speed = self.read_fan_speed(fan.fan_number)?; - speeds.push((fan.fan_number, speed, fan.fan_label.clone())); - } - - Ok(speeds) + self.fans + .iter() + .map(|fan| { + let path = fan.hwmon_path.join(format!("fan{}_input", fan.fan_number)); + let rpm = fs::read_to_string(path)? + .trim() + .parse() + .map_err(|_| FanCurveError::Config("Failed to parse fan speed".to_string()))?; + Ok((fan.fan_number, rpm, fan.fan_label.clone())) + }) + .collect() } - /// Check if the detector is initialized pub fn is_initialized(&self) -> bool { !self.fans.is_empty() } - /// Get the number of detected fans - pub fn fan_count(&self) -> usize { - self.fans.len() - } - - /// Set duty cycle for all fans (0-255) - matches system76-power approach - /// If duty_opt is None, enables automatic mode (pwm1_enable = "2") - /// If duty_opt is Some(duty), sets all fans to the same duty value - pub fn set_duty(&self, duty_opt: Option) -> Result<()> { - if let Some(duty) = duty_opt { - let duty_str = format!("{}", duty); - debug!("Setting all fans to PWM duty: {} (0-255 scale)", duty); - debug!("Found {} fans to control", self.fans.len()); - - // Set all available fans to the same duty - for fan in &self.fans { - let pwm_path = Path::new(&fan.hwmon_path).join(format!("pwm{}", fan.fan_number)); - let pwm_enable_path = - Path::new(&fan.hwmon_path).join(format!("pwm{}_enable", fan.fan_number)); - - debug!("Processing fan {}: {}", fan.fan_number, fan.fan_label); - debug!("PWM path: {}", pwm_path.display()); - debug!("Enable path: {}", pwm_enable_path.display()); - - // Check if PWM file exists and is writable - if !pwm_path.exists() { - warn!("PWM file does not exist: {}", pwm_path.display()); - continue; - } - - // Enable manual PWM control - debug!("Enabling manual PWM control for fan {}...", fan.fan_number); - if let Err(e) = fs::write(&pwm_enable_path, "1") { - warn!( - "Failed to enable PWM control for fan {} at {}: {}", - fan.fan_number, - pwm_enable_path.display(), - e - ); - // Continue anyway - some systems don't require enable files - } else { - debug!("PWM control enabled for fan {}", fan.fan_number); - } - - // Set PWM duty - debug!("Setting PWM duty to {} for fan {}...", duty, fan.fan_number); - if let Err(e) = fs::write(&pwm_path, &duty_str) { - error!( - "Failed to set PWM duty for fan {} at {}: {}", - fan.fan_number, - pwm_path.display(), - e - ); - return Err(crate::errors::FanCurveError::Io(e)); - } else { - debug!( - "Fan {} PWM successfully set to {} at {}", - fan.fan_number, - duty, - pwm_path.display() - ); - } - } - } else { - info!("Enabling automatic fan control mode"); + /// Set every fan to `duty` (PWM 0-255), or return them to automatic + /// control (pwmN_enable = 2) when `duty` is None, like system76-power + pub fn set_duty(&self, duty: Option) -> Result<()> { + for fan in &self.fans { + let pwm_path = fan.hwmon_path.join(format!("pwm{}", fan.fan_number)); + let enable_path = fan.hwmon_path.join(format!("pwm{}_enable", fan.fan_number)); - // Enable automatic mode for all fans - for fan in &self.fans { - let pwm_enable_path = - Path::new(&fan.hwmon_path).join(format!("pwm{}_enable", fan.fan_number)); - if let Err(e) = fs::write(&pwm_enable_path, "2") { - warn!( + let Some(duty) = duty else { + match fs::write(&enable_path, "2") { + Ok(()) => info!("Fan {} set to automatic mode", fan.fan_number), + Err(e) => warn!( "Failed to enable automatic mode for fan {} at {}: {}", fan.fan_number, - pwm_enable_path.display(), + enable_path.display(), e - ); - } else { - info!("Fan {} set to automatic mode", fan.fan_number); + ), } + continue; + }; + + if !pwm_path.exists() { + warn!("PWM file does not exist: {}", pwm_path.display()); + continue; } + // Some boards have no enable file; the PWM write still takes effect. + let _ = fs::write(&enable_path, "1"); + fs::write(&pwm_path, duty.to_string())?; + debug!("Fan {} PWM set to {}", fan.fan_number, duty); } - Ok(()) } } -impl Default for FanDetector { - fn default() -> Self { - Self::new() - } -} - #[cfg(test)] mod tests { use super::*; @@ -415,11 +189,4 @@ mod tests { assert_eq!(fs::read_to_string(other.join("pwm1_enable")).unwrap(), "1"); let _ = fs::remove_dir_all(&root); } - - #[test] - fn test_fan_detector_creation() { - let detector = FanDetector::new(); - assert!(!detector.is_initialized()); - assert_eq!(detector.fan_count(), 0); - } } diff --git a/src/fan_monitor.rs b/src/fan_monitor.rs index f70237c..6a3e8c2 100644 --- a/src/fan_monitor.rs +++ b/src/fan_monitor.rs @@ -5,7 +5,7 @@ use crate::cpu_temp::CpuTempDetector; use crate::errors::{FanCurveError, Result}; use crate::fan_detector::FanDetector; use chrono::{DateTime, Local}; -use log::{info, warn}; +use log::warn; use std::fs; use std::sync::Mutex; @@ -20,6 +20,7 @@ pub struct FanDataPoint { } /// Reads the CPU temperature sensor and fans directly +#[derive(Default)] pub struct FanMonitor { current_fan_curve: Option, cpu_temp_detector: CpuTempDetector, @@ -31,27 +32,17 @@ pub struct FanMonitor { impl FanMonitor { pub fn new() -> Self { - Self { - current_fan_curve: None, - cpu_temp_detector: CpuTempDetector::new(), - fan_detector: FanDetector::new(), - prev_cpu_times: Mutex::new(None), - } + Self::default() } - /// Detect the CPU temperature sensor and fans - pub fn initialize(&mut self) -> Result<()> { + /// Detect the CPU temperature sensor and fans; either may be missing + pub fn initialize(&mut self) { if let Err(e) = self.cpu_temp_detector.initialize() { warn!("Failed to initialize CPU temperature detection: {}", e); } if let Err(e) = self.fan_detector.initialize() { warn!("Failed to initialize fan detection: {}", e); } - info!( - "Fan monitor initialized with {} fans detected", - self.fan_detector.fan_count() - ); - Ok(()) } /// Curve used to show the duty the fans would run at @@ -71,11 +62,8 @@ impl FanMonitor { )); } let temperature = self.cpu_temp_detector.read_temperature()?; - let fan_speeds = if self.fan_detector.is_initialized() { - self.fan_detector.read_all_fan_speeds()? - } else { - Vec::new() - }; + // Empty when no fans were detected + let fan_speeds = self.fan_detector.read_all_fan_speeds()?; let fan_duty = self .current_fan_curve .as_ref() @@ -92,40 +80,27 @@ impl FanMonitor { /// CPU usage in percent since the previous call (since boot on the first) pub fn read_cpu_usage(&self) -> Result { - let stat_content = fs::read_to_string("/proc/stat").map_err(FanCurveError::Io)?; - let current = parse_cpu_times(&stat_content)?; + let current = parse_cpu_times(&fs::read_to_string("/proc/stat")?)?; let previous = self.prev_cpu_times.lock().unwrap().replace(current); Ok(cpu_usage_between(previous.unwrap_or((0, 0)), current)) } } -impl Default for FanMonitor { - fn default() -> Self { - Self::new() - } -} - /// Aggregate CPU times from /proc/stat as (idle, total), in clock ticks. fn parse_cpu_times(stat_content: &str) -> Result<(u64, u64)> { - let first_line = stat_content + let invalid = || FanCurveError::Config("Invalid /proc/stat format".to_string()); + // cpu user nice system idle iowait irq softirq steal ... + let fields: Vec = stat_content .lines() .next() - .ok_or_else(|| crate::errors::FanCurveError::Config("Empty /proc/stat".to_string()))?; - - // cpu user nice system idle iowait irq softirq steal ... - let fields: Vec = first_line + .ok_or_else(invalid)? .split_whitespace() .skip(1) .take(8) - .map(|f| f.parse()) - .collect::>() - .map_err(|_| { - crate::errors::FanCurveError::Config("Invalid /proc/stat format".to_string()) - })?; + .map(|f| f.parse().map_err(|_| invalid())) + .collect::>()?; if fields.len() < 7 { - return Err(crate::errors::FanCurveError::Config( - "Invalid /proc/stat format".to_string(), - )); + return Err(invalid()); } let idle = fields[3] + fields[4]; // idle + iowait diff --git a/src/main.rs b/src/main.rs index 18c3bee..9a56673 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,73 +3,51 @@ use clap::Parser; use eframe::egui; use fan_curve_app::{ - args::Args, client::FanCurveClient, daemon::FanCurveDaemon, fan_curve_gui::FanCurveApp, logging, + args::{Args, Commands}, + client, + daemon::FanCurveDaemon, + fan_curve_gui::{self, FanCurveApp}, + fan_detector, logging, notifier, }; fn main() -> Result<(), Box> { let args = Args::parse(); - logging::setup(args.verbose).map_err(|e| Box::new(e) as Box)?; + logging::setup(args.verbose)?; // GUI uses zbus's blocking API, which cannot run inside a Tokio runtime. // Keep this path fully synchronous. if args.gui { - return run_gui().map_err(|e| Box::new(e) as Box); + return Ok(run_gui()?); } let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build()?; - rt.block_on(async_main(args)) -} - -async fn async_main(args: Args) -> Result<(), Box> { - // Handle daemon mode - if let Some(fan_curve_app::args::Commands::Daemon) = args.command { - let daemon = - FanCurveDaemon::new().map_err(|e| Box::new(e) as Box)?; - daemon - .run() - .await - .map_err(|e| Box::new(e) as Box)?; - return Ok(()); - } - - if let Some(fan_curve_app::args::Commands::RestoreFans { hwmon_root }) = &args.command { - let written = fan_curve_app::fan_detector::restore_automatic(hwmon_root); - for path in &written { - println!("Automatic fan control: {}", path.display()); - } - if written.is_empty() { - println!("No System76 fan controls to restore"); + rt.block_on(async { + match args.command { + Some(Commands::Daemon) => FanCurveDaemon::new()?.run().await?, + Some(Commands::Notify) => notifier::run().await?, + Some(Commands::RestoreFans { hwmon_root }) => { + let written = fan_detector::restore_automatic(&hwmon_root); + for path in &written { + println!("Automatic fan control: {}", path.display()); + } + if written.is_empty() { + println!("No System76 fan controls to restore"); + } + } + Some(Commands::FanCurve { command }) => client::run(command).await?, + None => return Err("No command specified".into()), } - return Ok(()); - } - - if let Some(fan_curve_app::args::Commands::Notify) = args.command { - fan_curve_app::notifier::run() - .await - .map_err(|e| Box::new(e) as Box)?; - return Ok(()); - } - - // Handle client mode - let client = FanCurveClient::new() - .await - .map_err(|e| Box::new(e) as Box)?; - client - .handle_args(args) - .await - .map_err(|e| Box::new(e) as Box)?; - - Ok(()) + Ok(()) + }) } -/// Run the GUI application fn run_gui() -> Result<(), eframe::Error> { let native_options = eframe::NativeOptions { viewport: egui::ViewportBuilder::default() - .with_inner_size(fan_curve_app::fan_curve_gui::initial_window_size()) - .with_min_inner_size(fan_curve_app::fan_curve_gui::MIN_WINDOW_SIZE) + .with_inner_size(fan_curve_gui::initial_window_size()) + .with_min_inner_size(fan_curve_gui::MIN_WINDOW_SIZE) .with_resizable(true) .with_decorations(true) .with_title("Fan Curve Control"),