From 6b17d3815f009e2e55802624030dec8c9347c524 Mon Sep 17 00:00:00 2001 From: Stefan Gehr Date: Tue, 20 Jul 2021 09:53:22 +0200 Subject: [PATCH] Use pwm_min, pwm_max for converting speed to pwm Don't hardcode 0 and 255 anymore. Instead use pwm_min and pwm_max as boundaries when converting from a speed (0 to 100) to a pwm value. 0 gets mapped to pwm_min, 100 gets mapped to pwm_max everything inbetween gets linearly interpoltated. --- src/config.rs | 8 +------- src/main.rs | 14 +++++++++----- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/src/config.rs b/src/config.rs index e3837d9..c9bec04 100644 --- a/src/config.rs +++ b/src/config.rs @@ -119,12 +119,6 @@ impl From for LevelFilter { } } -// linear mapping between two points -fn linear_map(x: f64, x1: f64, y1: f64, x2: f64, y2: f64) -> f64 { - let m = (y2 - y1) / (x2 - x1); - m * (x - x1) + y1 -} - #[derive(Serialize, Deserialize, Debug)] pub struct Config { log_level: LogLevel, @@ -147,7 +141,7 @@ impl Config { return self.max_speed(); } - linear_map(temp, self.speed_matrix[idx].temp, self.speed_matrix[idx].speed, self.speed_matrix[idx+1].temp, self.speed_matrix[idx+1].speed) + crate::linear_map(temp, self.speed_matrix[idx].temp, self.speed_matrix[idx+1].temp, self.speed_matrix[idx].speed, self.speed_matrix[idx+1].speed) } pub fn log_level(&self) -> LogLevel { diff --git a/src/main.rs b/src/main.rs index bd5f630..892370c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,7 +3,6 @@ mod config; extern crate log; use std::io::ErrorKind; -use std::cmp::{min, max}; use crate::config::{load_config, Card, Config}; use gumdrop::Options; @@ -22,6 +21,12 @@ pub enum AmdFanError { FailedReadVendor, } +// linear mapping from the xrange to the yrange +fn linear_map(x: f64, x1: f64, x2: f64, y1: f64, y2: f64) -> f64 { + let m = (y2 - y1) / (x2 - x1); + m * (x - x1) + y1 +} + #[derive(Debug)] pub struct HwMon { card: Card, @@ -124,10 +129,9 @@ impl HwMon { } pub fn set_speed(&mut self, speed: f64) -> std::io::Result<()> { - let mut pwm = (speed / 100f64 * 255f64).round() as u32; - // stay in the range - pwm = max(pwm, self.pwm_min()); - pwm = min(pwm, self.pwm_max()); + let min = self.pwm_min() as f64; + let max = self.pwm_max() as f64; + let pwm = linear_map(speed, 0f64, 100f64, min, max).round() as u32; self.set_pwm(pwm) }