1
Fork 0
mirror of https://github.com/RGBCube/superfreq synced 2025-07-27 17:07:44 +00:00

battery: deduplicate frequency validation logic

This commit is contained in:
NotAShelf 2025-05-16 03:03:35 +03:00
parent 7d28d12c1c
commit c1d81b687c
No known key found for this signature in database
GPG key ID: 29D95B64378DB4BF
2 changed files with 44 additions and 37 deletions

View file

@ -164,14 +164,16 @@ fn write_sysfs_value(path: impl AsRef<Path>, value: &str) -> Result<()> {
/// Read a value from a sysfs file
fn read_sysfs_value(path: impl AsRef<Path>) -> Result<String> {
let p = path.as_ref();
fs::read_to_string(p).map_err(|e| {
let error_msg = format!("Path: {:?}, Error: {}", p.display(), e);
if e.kind() == io::ErrorKind::PermissionDenied {
ControlError::PermissionDenied(error_msg)
} else {
ControlError::ReadError(error_msg)
}
}).map(|s| s.trim().to_string())
fs::read_to_string(p)
.map_err(|e| {
let error_msg = format!("Path: {:?}, Error: {}", p.display(), e);
if e.kind() == io::ErrorKind::PermissionDenied {
ControlError::PermissionDenied(error_msg)
} else {
ControlError::ReadError(error_msg)
}
})
.map(|s| s.trim().to_string())
}
/// Safely check if a path exists and is writable
@ -216,18 +218,18 @@ fn apply_thresholds_to_batteries(
for battery in batteries {
let start_path = battery.path.join(battery.pattern.start_path);
let stop_path = battery.path.join(battery.pattern.stop_path);
// Read current thresholds in case we need to restore them
let current_start = read_sysfs_value(&start_path).ok();
let current_stop = read_sysfs_value(&stop_path).ok();
// Write stop threshold first (must be >= start threshold)
let stop_result = write_sysfs_value(&stop_path, &stop_threshold.to_string());
// Only proceed to set start threshold if stop threshold was set successfully
if let Ok(()) = stop_result {
if matches!(stop_result, Ok(())) {
let start_result = write_sysfs_value(&start_path, &start_threshold.to_string());
match start_result {
Ok(()) => {
debug!(
@ -246,10 +248,13 @@ fn apply_thresholds_to_batteries(
battery.name, re
);
} else {
debug!("Restored previous stop threshold ({}) for battery '{}'", prev_stop, battery.name);
debug!(
"Restored previous stop threshold ({}) for battery '{}'",
prev_stop, battery.name
);
}
}
errors.push(format!(
"Failed to set start threshold for {} battery '{}': {}",
battery.pattern.description, battery.name, e

View file

@ -358,17 +358,9 @@ fn main() {
}
Some(Commands::SetMinFreq { freq_mhz, core_id }) => {
// Basic validation for reasonable CPU frequency values
if freq_mhz == 0 {
error!("Minimum frequency cannot be zero");
Err(Box::new(ControlError::InvalidValueError(
"Minimum frequency cannot be zero".to_string(),
)) as Box<dyn std::error::Error>)
} else if freq_mhz > 10000 {
// Extremely high value unlikely to be valid
error!("Minimum frequency ({freq_mhz} MHz) is unreasonably high");
Err(Box::new(ControlError::InvalidValueError(format!(
"Minimum frequency ({freq_mhz} MHz) is unreasonably high"
))) as Box<dyn std::error::Error>)
if let Err(e) = validate_freq(freq_mhz, "Minimum") {
error!("{e}");
Err(e)
} else {
cpu::set_min_frequency(freq_mhz, core_id)
.map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
@ -376,17 +368,9 @@ fn main() {
}
Some(Commands::SetMaxFreq { freq_mhz, core_id }) => {
// Basic validation for reasonable CPU frequency values
if freq_mhz == 0 {
error!("Maximum frequency cannot be zero");
Err(Box::new(ControlError::InvalidValueError(
"Maximum frequency cannot be zero".to_string(),
)) as Box<dyn std::error::Error>)
} else if freq_mhz > 10000 {
// Extremely high value unlikely to be valid
error!("Maximum frequency ({freq_mhz} MHz) is unreasonably high");
Err(Box::new(ControlError::InvalidValueError(format!(
"Maximum frequency ({freq_mhz} MHz) is unreasonably high"
))) as Box<dyn std::error::Error>)
if let Err(e) = validate_freq(freq_mhz, "Maximum") {
error!("{e}");
Err(e)
} else {
cpu::set_max_frequency(freq_mhz, core_id)
.map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
@ -497,3 +481,21 @@ fn init_logger() {
debug!("Logger initialized with RUST_LOG={env_log}");
});
}
/// Validate CPU frequency input values
fn validate_freq(freq_mhz: u32, label: &str) -> Result<(), Box<dyn std::error::Error>> {
if freq_mhz == 0 {
error!("{label} frequency cannot be zero");
Err(Box::new(ControlError::InvalidValueError(format!(
"{label} frequency cannot be zero"
))) as Box<dyn std::error::Error>)
} else if freq_mhz > 10000 {
// Extremely high value unlikely to be valid
error!("{label} frequency ({freq_mhz} MHz) is unreasonably high");
Err(Box::new(ControlError::InvalidValueError(format!(
"{label} frequency ({freq_mhz} MHz) is unreasonably high"
))) as Box<dyn std::error::Error>)
} else {
Ok(())
}
}