diff --git a/src/fanmap.rs b/src/fanmap.rs index 209d2b1..fb2f430 100644 --- a/src/fanmap.rs +++ b/src/fanmap.rs @@ -160,6 +160,107 @@ pub fn map_fans(samples: &[ProbeSample], zones: &[u8], thresholds: MapThresholds map } +/// Safe limits for a fan-mapping sweep. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct SweepConfig { + pub fans: u8, + pub zones: u8, + /// Lowest duty used during probing. Never zero: the boards must keep airflow. + pub low_pwm: u8, + pub high_pwm: u8, + /// Readings taken per (fan, duty) step; the mapper averages them. + pub repeats: u8, + /// Time to wait after a duty change before reading temperatures. + pub settle_ms: u32, +} + +impl Default for SweepConfig { + fn default() -> Self { + Self { + fans: 4, + zones: 3, + low_pwm: 40, + high_pwm: 100, + repeats: 2, + settle_ms: 20_000, + } + } +} + +/// Minimum duty a sweep may use. Airflow is never removed to make a measurement. +pub const MIN_PROBE_PWM: u8 = 20; + +/// Why a sweep did not run. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum SweepError { + Backend(E), + InvalidConfig(&'static str), +} + +/// The two backend actions a sweep needs. +pub trait FanProbe { + type Error; + + fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), Self::Error>; + fn read_zone(&mut self, zone: u8) -> Result; +} + +/// Step every fan between the low and high duty and record what the zones do. +/// +/// One fan is moved at a time while the others hold their previous duty, so the response belongs +/// to that fan. The run ends with every fan back at `high_pwm`: leaving a fan low after probing +/// would be a thermal hazard for whatever runs next. +pub fn sweep( + backend: &mut B, + config: &SweepConfig, + mut settle: S, +) -> Result, SweepError> { + if config.fans == 0 { + return Err(SweepError::InvalidConfig("no fans to sweep")); + } + if config.zones == 0 { + return Err(SweepError::InvalidConfig("no zones to read")); + } + if config.low_pwm < MIN_PROBE_PWM { + return Err(SweepError::InvalidConfig( + "probe duty below the safe minimum", + )); + } + if config.high_pwm > 100 { + return Err(SweepError::InvalidConfig("probe duty above 100 percent")); + } + if config.low_pwm >= config.high_pwm { + return Err(SweepError::InvalidConfig("probe duty range is empty")); + } + if config.repeats == 0 { + return Err(SweepError::InvalidConfig("no readings requested")); + } + + let mut samples = Vec::new(); + for fan in 0..config.fans { + for pwm in [config.low_pwm, config.high_pwm] { + backend.set_fan(fan, pwm).map_err(SweepError::Backend)?; + settle(config.settle_ms); + for _ in 0..config.repeats { + let mut readings = Vec::with_capacity(config.zones as usize); + for zone in 0..config.zones { + readings.push(ZoneReading { + zone, + temp_mc: backend.read_zone(zone).map_err(SweepError::Backend)?, + }); + } + samples.push(ProbeSample { fan, pwm, readings }); + } + } + } + for fan in 0..config.fans { + backend + .set_fan(fan, config.high_pwm) + .map_err(SweepError::Backend)?; + } + Ok(samples) +} + #[cfg(test)] mod tests { use super::*; @@ -236,4 +337,133 @@ mod tests { assert_eq!(map.zones_for(0), vec![0, 1]); assert_eq!(map.zones_for(1), vec![2]); } + + struct ThermalMock { + duty: Vec, + owners: Vec<(u8, u8)>, + fail: bool, + } + + impl ThermalMock { + fn new(owners: &[(u8, u8)]) -> Self { + let fans = owners.iter().map(|(fan, _)| *fan).max().unwrap_or(0) + 1; + Self { + duty: vec![100; fans as usize], + owners: owners.to_vec(), + fail: false, + } + } + } + + impl FanProbe for ThermalMock { + type Error = &'static str; + + fn set_fan(&mut self, fan: u8, pwm: u8) -> Result<(), Self::Error> { + if self.fail { + return Err("fan bus down"); + } + self.duty[fan as usize] = pwm; + Ok(()) + } + + fn read_zone(&mut self, zone: u8) -> Result { + if self.fail { + return Err("sensor bus down"); + } + let owner = self + .owners + .iter() + .find(|(_, candidate)| *candidate == zone) + .map(|(fan, _)| *fan) + .expect("zone has an owner"); + let cooled = self.duty[owner as usize] >= 100; + Ok(if cooled { 50_000 } else { 70_000 }) + } + } + + #[test] + fn sweep_then_map_resolves_each_zone() { + let mut backend = ThermalMock::new(&[(0, 0), (1, 1)]); + let config = SweepConfig { + fans: 2, + zones: 2, + low_pwm: 40, + high_pwm: 100, + repeats: 2, + settle_ms: 0, + }; + let samples = sweep(&mut backend, &config, |_| {}).expect("sweep"); + assert_eq!(samples.len(), 2 * 2 * 2); + let map = map_fans(&samples, &[0, 1], MapThresholds::default()); + assert_eq!(map.zones_for(0), vec![0]); + assert_eq!(map.zones_for(1), vec![1]); + assert!(map.unresolved.is_empty()); + } + + #[test] + fn sweep_restores_every_fan_to_high_duty() { + let mut backend = ThermalMock::new(&[(0, 0), (1, 1)]); + let config = SweepConfig { + fans: 2, + zones: 2, + low_pwm: 40, + high_pwm: 100, + repeats: 1, + settle_ms: 0, + }; + sweep(&mut backend, &config, |_| {}).expect("sweep"); + assert_eq!(backend.duty, vec![100, 100]); + } + + #[test] + fn sweep_refuses_an_unsafe_duty() { + let mut backend = ThermalMock::new(&[(0, 0)]); + let config = SweepConfig { + fans: 1, + zones: 1, + low_pwm: 10, + high_pwm: 100, + repeats: 1, + settle_ms: 0, + }; + assert_eq!( + sweep(&mut backend, &config, |_| {}), + Err(SweepError::InvalidConfig( + "probe duty below the safe minimum" + )) + ); + } + + #[test] + fn sweep_refuses_an_empty_range_and_zero_reads() { + let mut backend = ThermalMock::new(&[(0, 0)]); + let flat = SweepConfig { + fans: 1, + zones: 1, + low_pwm: 60, + high_pwm: 60, + repeats: 1, + settle_ms: 0, + }; + assert!(matches!( + sweep(&mut backend, &flat, |_| {}), + Err(SweepError::InvalidConfig(_)) + )); + let no_reads = SweepConfig { repeats: 0, ..flat }; + assert!(matches!( + sweep(&mut backend, &no_reads, |_| {}), + Err(SweepError::InvalidConfig(_)) + )); + } + + #[test] + fn sweep_propagates_backend_failures() { + let mut backend = ThermalMock::new(&[(0, 0)]); + backend.fail = true; + let config = SweepConfig::default(); + assert_eq!( + sweep(&mut backend, &config, |_| {}), + Err(SweepError::Backend("fan bus down")) + ); + } }