Add the fan-mapping measurement sweep
source-pr / source (pull_request) Successful in 11s

sweep() drives the probing run that map_fans consumes: it moves one fan at a
time between the low and high duty while the others hold their setting, waits
for the settle interval, and records every zone reading. Repeat readings are
emitted so the mapper averages noise.

Safety is enforced in the loop, not by convention: a probe duty below the
minimum, an empty duty range, an inverted range, zero reads and zero fans are
all refused before any fan is touched, and the run always ends with every fan
restored to the high duty so the machine is not left under-cooled.
This commit is contained in:
2026-10-22 10:21:26 -06:00
parent c616429669
commit 4139576155
+230
View File
@@ -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<E> {
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<i32, Self::Error>;
}
/// 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<B: FanProbe, S: FnMut(u32)>(
backend: &mut B,
config: &SweepConfig,
mut settle: S,
) -> Result<Vec<ProbeSample>, SweepError<B::Error>> {
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<u8>,
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<i32, Self::Error> {
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"))
);
}
}