Improve processor (burn-in, saturation detection, etc, gating, )
This commit is contained in:
1 parent
aee70ffbd2
commit
3d1a90032a
1 file changed
+234
-45
+234
-45
@@ -117,6 +117,31 @@ HUMIDITY_DELTA_WARN = 5.0 # %RH between BME690 and SCD43
|
|||||||
# ── Sentinel value (maxed-out resistance from BME690) ─────────────────────
|
# ── Sentinel value (maxed-out resistance from BME690) ─────────────────────
|
||||||
RESISTANCE_MAX = 102_400_000.0 # Ω — treat as "clean air ceiling"
|
RESISTANCE_MAX = 102_400_000.0 # Ω — treat as "clean air ceiling"
|
||||||
|
|
||||||
|
# ── ADC rail detection ────────────────────────────────────────────────────
|
||||||
|
# The BME690 gas ADC is 10-bit. Values of exactly 0 or 1023 mean the ADC
|
||||||
|
# saturated at one rail — the resistance_raw value is then a deterministic
|
||||||
|
# math artifact of the Bosch formula (5600 Ω at adc=1023, 102.4 MΩ at adc=0
|
||||||
|
# on the lowest gas_range), not a real measurement. These points must be
|
||||||
|
# excluded from humidity correction, baseline normalization, zone scores,
|
||||||
|
# and calibration, otherwise they poison downstream state with garbage.
|
||||||
|
ADC_GAS_MIN = 1
|
||||||
|
ADC_GAS_MAX = 1022
|
||||||
|
|
||||||
|
|
||||||
|
def _is_railed(p: GasSweepPoint) -> bool:
|
||||||
|
"""
|
||||||
|
True when the sweep point is an ADC-railed artifact rather than a real
|
||||||
|
resistance measurement. Checks adc_gas_res when present (firmware
|
||||||
|
post-2026-05), falls back to the RESISTANCE_MAX sentinel for older
|
||||||
|
payloads that don't carry the raw ADC.
|
||||||
|
"""
|
||||||
|
if p.adc_gas_res is not None:
|
||||||
|
if p.adc_gas_res < ADC_GAS_MIN or p.adc_gas_res > ADC_GAS_MAX:
|
||||||
|
return True
|
||||||
|
if p.resistance_raw is not None and p.resistance_raw >= RESISTANCE_MAX:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
# ── Main processor ────────────────────────────────────────────────────────
|
# ── Main processor ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -143,10 +168,60 @@ class Processor:
|
|||||||
self.co2e_weights = co2e_weights # None → uncalibrated
|
self.co2e_weights = co2e_weights # None → uncalibrated
|
||||||
self.species_co2_limit = species_co2_limit
|
self.species_co2_limit = species_co2_limit
|
||||||
self._prev_zone_scores: Optional[ZoneScores] = None
|
self._prev_zone_scores: Optional[ZoneScores] = None
|
||||||
|
# Remember the source we last used for correction inputs so we can
|
||||||
|
# log the crossover (bme_corrected ↔ scd43 ↔ bme_raw) exactly
|
||||||
|
# once per transition instead of on every payload.
|
||||||
|
self._last_temp_source: Optional[str] = None
|
||||||
|
self._last_rh_source: Optional[str] = None
|
||||||
|
|
||||||
|
# ── Correction-input source selection ─────────────────────────────────────
|
||||||
|
# Goal: a single stable ambient input feeding humidity correction,
|
||||||
|
# rather than silently switching sensors mid-session.
|
||||||
|
#
|
||||||
|
# Temperature:
|
||||||
|
# 1. If baseline carries bme_temp_offset → corrected BME
|
||||||
|
# (raw.ambient.temp_c - offset). This is the preferred steady
|
||||||
|
# state — one sensor, one calibration, no mid-session jumps.
|
||||||
|
# 2. Else if SCD43 valid and health.temp_ok → SCD43 directly.
|
||||||
|
# Used pre-baseline or when cross-validation passes.
|
||||||
|
# 3. Else BME raw. Least accurate, but always present.
|
||||||
|
#
|
||||||
|
# Humidity:
|
||||||
|
# 1. If SCD43 valid and health.humidity_ok → SCD43.
|
||||||
|
# 2. Else BME raw. We do not yet compute a BME humidity offset;
|
||||||
|
# humidity_delta has been less stable than temp_delta in
|
||||||
|
# observed data, so a fixed correction isn't justified yet.
|
||||||
|
def _select_temp_source(self, raw: STM32Payload) -> tuple[float, str]:
|
||||||
|
if (self.baseline and self.baseline.bme_temp_offset is not None
|
||||||
|
and raw.ambient.valid):
|
||||||
|
return (raw.ambient.temp_c - self.baseline.bme_temp_offset,
|
||||||
|
"bme_corrected")
|
||||||
|
if raw.co2 and raw.co2.valid and raw.health.temp_ok:
|
||||||
|
return (raw.co2.temp_c, "scd43")
|
||||||
|
return (raw.ambient.temp_c, "bme_raw")
|
||||||
|
|
||||||
|
def _select_rh_source(self, raw: STM32Payload) -> tuple[float, str]:
|
||||||
|
if raw.co2 and raw.co2.valid and raw.health.humidity_ok:
|
||||||
|
return (raw.co2.humidity_pct, "scd43")
|
||||||
|
return (raw.ambient.humidity_pct, "bme_raw")
|
||||||
|
|
||||||
def update_baseline(self, baseline: SweepBaseline) -> None:
|
def update_baseline(self, baseline: SweepBaseline) -> None:
|
||||||
|
# Detect the pre→post established transition here rather than in
|
||||||
|
# process(), since update_baseline() is the only place baseline
|
||||||
|
# state actually changes. Reset prev zone scores so anomaly
|
||||||
|
# deltas aren't computed across scoring regimes.
|
||||||
|
was_established = bool(self.baseline and self.baseline.established)
|
||||||
self.baseline = baseline
|
self.baseline = baseline
|
||||||
log.info(f"[{self.chamber_id}] Baseline updated ({baseline.n_samples} samples)")
|
if not was_established and baseline.established:
|
||||||
|
self._prev_zone_scores = None
|
||||||
|
log.info(
|
||||||
|
f"[{self.chamber_id}] Baseline established — zone score "
|
||||||
|
f"history reset (bme_temp_offset="
|
||||||
|
f"{baseline.bme_temp_offset})"
|
||||||
|
)
|
||||||
|
log.info(
|
||||||
|
f"[{self.chamber_id}] Baseline updated ({baseline.n_samples} samples)"
|
||||||
|
)
|
||||||
|
|
||||||
def update_species(self, co2_limit_ppm: Optional[int]) -> None:
|
def update_species(self, co2_limit_ppm: Optional[int]) -> None:
|
||||||
self.species_co2_limit = co2_limit_ppm
|
self.species_co2_limit = co2_limit_ppm
|
||||||
@@ -155,15 +230,34 @@ class Processor:
|
|||||||
"""
|
"""
|
||||||
Process a raw STM32 payload into a fully enriched EnvPayload.
|
Process a raw STM32 payload into a fully enriched EnvPayload.
|
||||||
Returns (EnvPayload, calibration_samples).
|
Returns (EnvPayload, calibration_samples).
|
||||||
Calibration samples are non-empty only when SCD43 CO2 is valid.
|
Calibration samples are non-empty only when SCD43 CO2 is valid and
|
||||||
|
the payload is not flagged burn_in.
|
||||||
"""
|
"""
|
||||||
points = list(raw.sweep)
|
points = list(raw.sweep)
|
||||||
|
now_established = bool(self.baseline and self.baseline.established)
|
||||||
|
|
||||||
|
# Pick correction inputs. See _select_*_source for the policy;
|
||||||
|
# log only on source transitions to avoid per-payload spam.
|
||||||
|
corr_temp, temp_src = self._select_temp_source(raw)
|
||||||
|
corr_rh, rh_src = self._select_rh_source(raw)
|
||||||
|
if temp_src != self._last_temp_source:
|
||||||
|
log.info(
|
||||||
|
f"[{self.chamber_id}] correction temp source: "
|
||||||
|
f"{self._last_temp_source} → {temp_src} ({corr_temp:.2f} °C)"
|
||||||
|
)
|
||||||
|
self._last_temp_source = temp_src
|
||||||
|
if rh_src != self._last_rh_source:
|
||||||
|
log.info(
|
||||||
|
f"[{self.chamber_id}] correction rh source: "
|
||||||
|
f"{self._last_rh_source} → {rh_src} ({corr_rh:.2f} %RH)"
|
||||||
|
)
|
||||||
|
self._last_rh_source = rh_src
|
||||||
|
|
||||||
# 1. Humidity correction
|
# 1. Humidity correction
|
||||||
points = self._humidity_correct(
|
points = self._humidity_correct(
|
||||||
points,
|
points,
|
||||||
rh=raw.ambient.humidity_pct,
|
rh=corr_rh,
|
||||||
temp=raw.ambient.temp_c,
|
temp=corr_temp,
|
||||||
)
|
)
|
||||||
|
|
||||||
# 2. Baseline normalization
|
# 2. Baseline normalization
|
||||||
@@ -172,13 +266,16 @@ class Processor:
|
|||||||
# 3. Zone scores
|
# 3. Zone scores
|
||||||
zone_scores = self._compute_zone_scores(points)
|
zone_scores = self._compute_zone_scores(points)
|
||||||
|
|
||||||
# 4. CO2e estimate
|
# 4. CO2e estimate — self-gates on burn_in
|
||||||
co2e_ppm, co2e_confidence = self._estimate_co2e(zone_scores, raw)
|
co2e_ppm, co2e_confidence = self._estimate_co2e(zone_scores, raw)
|
||||||
|
|
||||||
# 5. VOC ppb (Zone 2 score scaled)
|
# 5. VOC ppb (Zone 2 score scaled) — suppressed during burn-in
|
||||||
voc_ppb = self._scale_voc(zone_scores)
|
voc_ppb = None if raw.burn_in else self._scale_voc(zone_scores)
|
||||||
|
|
||||||
# 6. Anomaly detection
|
# 6. Anomaly detection — individual checks self-gate on burn_in
|
||||||
|
# where the underlying signal is unreliable (temp/humidity drift
|
||||||
|
# during heater conditioning). CO2 threshold anomalies fire
|
||||||
|
# regardless since SCD43 is independent of gas sensor state.
|
||||||
anomalies = self._detect_anomalies(raw, zone_scores, co2e_ppm)
|
anomalies = self._detect_anomalies(raw, zone_scores, co2e_ppm)
|
||||||
|
|
||||||
# 7. Build EnvPayload
|
# 7. Build EnvPayload
|
||||||
@@ -194,14 +291,21 @@ class Processor:
|
|||||||
sweep = points,
|
sweep = points,
|
||||||
zone_scores = zone_scores,
|
zone_scores = zone_scores,
|
||||||
baseline = self.baseline or raw.baseline,
|
baseline = self.baseline or raw.baseline,
|
||||||
|
burn_in = raw.burn_in,
|
||||||
health = raw.health,
|
health = raw.health,
|
||||||
anomalies = anomalies,
|
anomalies = anomalies,
|
||||||
)
|
)
|
||||||
|
|
||||||
# 8. Collect CO2e calibration sample if SCD43 present and valid
|
# 8. Collect CO2e calibration sample if SCD43 present and valid.
|
||||||
cal_samples = self._collect_calibration(raw, points, co2e_ppm)
|
# _collect_calibration() self-gates on burn_in and railed Z1 points.
|
||||||
|
cal_samples = self._collect_calibration(
|
||||||
|
raw, points, co2e_ppm,
|
||||||
|
corr_rh=corr_rh, corr_temp=corr_temp,
|
||||||
|
)
|
||||||
|
|
||||||
# Update previous zone scores for delta detection
|
# Update previous zone scores for delta detection — but only when
|
||||||
|
# the scores are actually usable (post-baseline, not burn-in).
|
||||||
|
if not raw.burn_in and now_established:
|
||||||
self._prev_zone_scores = zone_scores
|
self._prev_zone_scores = zone_scores
|
||||||
|
|
||||||
return payload, cal_samples
|
return payload, cal_samples
|
||||||
@@ -229,11 +333,13 @@ class Processor:
|
|||||||
corrected.append(p.model_copy(update={"resistance_corr": None}))
|
corrected.append(p.model_copy(update={"resistance_corr": None}))
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Skip maxed-out sentinel values
|
# Skip ADC-railed points at either rail. These resistances are
|
||||||
if p.resistance_raw >= RESISTANCE_MAX:
|
# deterministic artifacts of the Bosch formula consuming a
|
||||||
corrected.append(p.model_copy(update={
|
# saturated ADC reading, not real measurements — feeding them
|
||||||
"resistance_corr": RESISTANCE_MAX,
|
# through correction would produce plausible-looking numbers
|
||||||
}))
|
# that poison baseline, zone scores, and calibration.
|
||||||
|
if _is_railed(p):
|
||||||
|
corrected.append(p.model_copy(update={"resistance_corr": None}))
|
||||||
continue
|
continue
|
||||||
|
|
||||||
coeffs = self.correction_coeffs or {}
|
coeffs = self.correction_coeffs or {}
|
||||||
@@ -290,25 +396,29 @@ class Processor:
|
|||||||
def _compute_zone_scores(self, points: list[GasSweepPoint]) -> ZoneScores:
|
def _compute_zone_scores(self, points: list[GasSweepPoint]) -> ZoneScores:
|
||||||
"""
|
"""
|
||||||
Compute mean normalized resistance per zone.
|
Compute mean normalized resistance per zone.
|
||||||
Uses corrected values if baseline not yet established,
|
Post-baseline: mean of resistance_norm across the zone's valid,
|
||||||
normalized values once baseline is available.
|
non-railed points. Pre-baseline: returns None — the UI should read
|
||||||
|
burn_in / baseline.established and show a placeholder rather than
|
||||||
|
a synthetic score.
|
||||||
|
|
||||||
|
TODO(#8): the previous log-scaled pre-baseline fallback
|
||||||
|
(math.log10(R_corr)/8.0) produced numbers that looked like zone
|
||||||
|
scores but weren't on the same scale as the post-baseline scores,
|
||||||
|
causing cross-regime delta anomalies and misleading VOC readouts.
|
||||||
|
Removed in favor of None + the explicit burn_in signal. Revisit
|
||||||
|
if we need a usable pre-baseline indicator for the UI.
|
||||||
"""
|
"""
|
||||||
def zone_mean(zone: SweepZone) -> Optional[float]:
|
def zone_mean(zone: SweepZone) -> Optional[float]:
|
||||||
zone_points = [p for p in points if p.zone == zone and p.valid]
|
# Only consider points that are valid, non-railed, and have a
|
||||||
if not zone_points:
|
# normalized value (implies baseline established and the point
|
||||||
return None
|
# wasn't filtered out upstream).
|
||||||
|
values = [
|
||||||
# Prefer normalized; fall back to corrected
|
p.resistance_norm for p in points
|
||||||
values = []
|
if p.zone == zone
|
||||||
for p in zone_points:
|
and p.valid
|
||||||
if p.resistance_norm is not None:
|
and not _is_railed(p)
|
||||||
values.append(p.resistance_norm)
|
and p.resistance_norm is not None
|
||||||
elif p.resistance_corr is not None:
|
]
|
||||||
# Scale corrected to a 0-1ish range for pre-baseline usefulness
|
|
||||||
# Using log scale since resistance spans many orders of magnitude
|
|
||||||
if p.resistance_corr > 0:
|
|
||||||
values.append(math.log10(p.resistance_corr) / 8.0)
|
|
||||||
|
|
||||||
return sum(values) / len(values) if values else None
|
return sum(values) / len(values) if values else None
|
||||||
|
|
||||||
return ZoneScores(
|
return ZoneScores(
|
||||||
@@ -336,6 +446,9 @@ class Processor:
|
|||||||
|
|
||||||
Both are labeled with appropriate confidence levels.
|
Both are labeled with appropriate confidence levels.
|
||||||
"""
|
"""
|
||||||
|
if raw.burn_in:
|
||||||
|
return None, Co2eConfidence.uncalibrated
|
||||||
|
|
||||||
if not self.baseline or not self.baseline.established:
|
if not self.baseline or not self.baseline.established:
|
||||||
return None, Co2eConfidence.uncalibrated
|
return None, Co2eConfidence.uncalibrated
|
||||||
|
|
||||||
@@ -493,8 +606,11 @@ class Processor:
|
|||||||
evidence_json = {"co2e_ppm": co2e_ppm},
|
evidence_json = {"co2e_ppm": co2e_ppm},
|
||||||
))
|
))
|
||||||
|
|
||||||
# Sensor health — temp drift
|
# Sensor health — temp drift. Skip during burn-in: BME ambient is
|
||||||
if (raw.health.scd43_present and
|
# structurally elevated while the hotplate is cycling hard, so
|
||||||
|
# the delta would spam warnings for the whole conditioning window.
|
||||||
|
if (not raw.burn_in and
|
||||||
|
raw.health.scd43_present and
|
||||||
raw.health.temp_delta is not None and
|
raw.health.temp_delta is not None and
|
||||||
raw.health.temp_delta > TEMP_DELTA_WARN):
|
raw.health.temp_delta > TEMP_DELTA_WARN):
|
||||||
anomalies.append(EnvAnomaly(
|
anomalies.append(EnvAnomaly(
|
||||||
@@ -510,8 +626,10 @@ class Processor:
|
|||||||
evidence_json = {"temp_delta": raw.health.temp_delta},
|
evidence_json = {"temp_delta": raw.health.temp_delta},
|
||||||
))
|
))
|
||||||
|
|
||||||
# Sensor health — humidity drift
|
# Sensor health — humidity drift. Skip during burn-in for the
|
||||||
if (raw.health.scd43_present and
|
# same reason as temp drift above.
|
||||||
|
if (not raw.burn_in and
|
||||||
|
raw.health.scd43_present and
|
||||||
raw.health.humidity_delta is not None and
|
raw.health.humidity_delta is not None and
|
||||||
raw.health.humidity_delta > HUMIDITY_DELTA_WARN):
|
raw.health.humidity_delta > HUMIDITY_DELTA_WARN):
|
||||||
anomalies.append(EnvAnomaly(
|
anomalies.append(EnvAnomaly(
|
||||||
@@ -542,21 +660,40 @@ class Processor:
|
|||||||
raw: STM32Payload,
|
raw: STM32Payload,
|
||||||
points: list[GasSweepPoint],
|
points: list[GasSweepPoint],
|
||||||
co2e_ppm: Optional[float],
|
co2e_ppm: Optional[float],
|
||||||
|
corr_rh: float,
|
||||||
|
corr_temp: float,
|
||||||
) -> list[Co2eCalibrationSample]:
|
) -> list[Co2eCalibrationSample]:
|
||||||
"""
|
"""
|
||||||
Collect a calibration sample when SCD43 CO2 is valid.
|
Collect a calibration sample when SCD43 CO2 is valid and the
|
||||||
Only Zone 1 points (200, 220, 250°C) are used as features.
|
payload is not flagged burn_in. Only Zone 1 points (200, 220,
|
||||||
|
250°C) are used as features, and only when their ADC wasn't railed.
|
||||||
|
|
||||||
|
humidity_at_read / temp_at_read record the *actual* RH/T values
|
||||||
|
fed into humidity correction (not raw BME or raw SCD43) so the
|
||||||
|
model fits and predicts against identical conditions.
|
||||||
"""
|
"""
|
||||||
|
if raw.burn_in:
|
||||||
|
return []
|
||||||
if not raw.co2 or not raw.co2.valid:
|
if not raw.co2 or not raw.co2.valid:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
# Extract Zone 1 corrected resistances
|
# Extract Zone 1 corrected resistances — skip railed points.
|
||||||
|
# _humidity_correct already nulls resistance_corr for railed points,
|
||||||
|
# but keep the explicit check as a belt-and-braces guard.
|
||||||
z1_points = {
|
z1_points = {
|
||||||
p.heater_temp_c: p.resistance_corr
|
p.heater_temp_c: p.resistance_corr
|
||||||
for p in points
|
for p in points
|
||||||
if p.zone == SweepZone.baseline and p.valid and p.resistance_corr is not None
|
if p.zone == SweepZone.baseline
|
||||||
|
and p.valid
|
||||||
|
and not _is_railed(p)
|
||||||
|
and p.resistance_corr is not None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Require at least one usable Z1 feature — a sample with all
|
||||||
|
# features None is useless for fitting.
|
||||||
|
if not z1_points:
|
||||||
|
return []
|
||||||
|
|
||||||
sample = Co2eCalibrationSample(
|
sample = Co2eCalibrationSample(
|
||||||
payload_id = 0, # filled in by storage.py after insert
|
payload_id = 0, # filled in by storage.py after insert
|
||||||
chamber_id = raw.chamber_id,
|
chamber_id = raw.chamber_id,
|
||||||
@@ -565,8 +702,11 @@ class Processor:
|
|||||||
r_corr_200 = z1_points.get(200),
|
r_corr_200 = z1_points.get(200),
|
||||||
r_corr_220 = z1_points.get(220),
|
r_corr_220 = z1_points.get(220),
|
||||||
r_corr_250 = z1_points.get(250),
|
r_corr_250 = z1_points.get(250),
|
||||||
humidity_at_read = raw.ambient.humidity_pct,
|
# Record the actual values fed into humidity correction —
|
||||||
temp_at_read = raw.ambient.temp_c,
|
# corr_rh and corr_temp already reflect the source policy
|
||||||
|
# (bme_corrected / scd43 / bme_raw) chosen by process().
|
||||||
|
humidity_at_read = corr_rh,
|
||||||
|
temp_at_read = corr_temp,
|
||||||
co2e_estimate = co2e_ppm,
|
co2e_estimate = co2e_ppm,
|
||||||
model_version = "v0" if not self.co2e_weights else "v1",
|
model_version = "v0" if not self.co2e_weights else "v1",
|
||||||
)
|
)
|
||||||
@@ -598,12 +738,45 @@ class BaselineBuilder:
|
|||||||
):
|
):
|
||||||
self.min_samples = min_samples
|
self.min_samples = min_samples
|
||||||
self.humidity_variance = humidity_variance
|
self.humidity_variance = humidity_variance
|
||||||
|
# Cap the buffer so a long run without an explicit reset doesn't
|
||||||
|
# leak memory. 2x min_samples is plenty for the rolling window
|
||||||
|
# established() / build() need.
|
||||||
|
self._max_samples = max(min_samples * 2, 20)
|
||||||
self._samples: list[STM32Payload] = []
|
self._samples: list[STM32Payload] = []
|
||||||
|
|
||||||
def feed(self, raw: STM32Payload) -> None:
|
def feed(self, raw: STM32Payload) -> None:
|
||||||
"""Add a payload to the accumulator."""
|
"""
|
||||||
if raw.ambient.valid:
|
Add a payload to the accumulator. Rejects payloads that would
|
||||||
|
poison the baseline:
|
||||||
|
- burn_in=True (firmware is still conditioning the MOX film)
|
||||||
|
- ambient invalid
|
||||||
|
- no usable sweep points (every point ADC-railed)
|
||||||
|
|
||||||
|
TODO(#9): once we have a few runs of real data, also reject
|
||||||
|
payloads where idac is pinned at 0x00 or 0x7F for upper-zone
|
||||||
|
points — that indicates the DAC rail, meaning the heater never
|
||||||
|
reached target regardless of what heater_stable says.
|
||||||
|
"""
|
||||||
|
if raw.burn_in:
|
||||||
|
return
|
||||||
|
if not raw.ambient.valid:
|
||||||
|
return
|
||||||
|
|
||||||
|
# Require at least one non-railed, valid sweep point. If every
|
||||||
|
# point is a rail artifact, this payload carries no usable gas
|
||||||
|
# information for the baseline.
|
||||||
|
usable = any(p.valid and not _is_railed(p) for p in raw.sweep)
|
||||||
|
if not usable:
|
||||||
|
log.debug(
|
||||||
|
f"BaselineBuilder: rejecting payload ts={raw.ts} — "
|
||||||
|
f"all {len(raw.sweep)} sweep points ADC-railed"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
self._samples.append(raw)
|
self._samples.append(raw)
|
||||||
|
# Keep buffer bounded
|
||||||
|
if len(self._samples) > self._max_samples:
|
||||||
|
self._samples = self._samples[-self._max_samples:]
|
||||||
|
|
||||||
def established(self) -> bool:
|
def established(self) -> bool:
|
||||||
"""Return True if enough stable samples have been collected."""
|
"""Return True if enough stable samples have been collected."""
|
||||||
@@ -648,6 +821,21 @@ class BaselineBuilder:
|
|||||||
temps = [s.ambient.temp_c for s in recent]
|
temps = [s.ambient.temp_c for s in recent]
|
||||||
co2_vals = [s.co2.ppm for s in recent if s.co2 and s.co2.valid]
|
co2_vals = [s.co2.ppm for s in recent if s.co2 and s.co2.valid]
|
||||||
|
|
||||||
|
# BME690 self-heating offset: mean (BME - SCD43) across samples
|
||||||
|
# where both sensors are valid. The BME runs hot from hotplate
|
||||||
|
# cycling; this is a stable per-enclosure bias. Recomputed every
|
||||||
|
# baseline refresh so the offset tracks enclosure thermalization
|
||||||
|
# over the course of a long grow cycle.
|
||||||
|
temp_offsets = [
|
||||||
|
s.ambient.temp_c - s.co2.temp_c
|
||||||
|
for s in recent
|
||||||
|
if s.co2 and s.co2.valid
|
||||||
|
]
|
||||||
|
bme_temp_offset = (
|
||||||
|
sum(temp_offsets) / len(temp_offsets)
|
||||||
|
if temp_offsets else None
|
||||||
|
)
|
||||||
|
|
||||||
return SweepBaseline(
|
return SweepBaseline(
|
||||||
established = True,
|
established = True,
|
||||||
established_at = int(time.time()),
|
established_at = int(time.time()),
|
||||||
@@ -656,6 +844,7 @@ class BaselineBuilder:
|
|||||||
humidity_ref = sum(humidities) / len(humidities),
|
humidity_ref = sum(humidities) / len(humidities),
|
||||||
temp_ref = sum(temps) / len(temps),
|
temp_ref = sum(temps) / len(temps),
|
||||||
co2_ref = sum(co2_vals) / len(co2_vals) if co2_vals else None,
|
co2_ref = sum(co2_vals) / len(co2_vals) if co2_vals else None,
|
||||||
|
bme_temp_offset = bme_temp_offset,
|
||||||
)
|
)
|
||||||
|
|
||||||
def reset(self) -> None:
|
def reset(self) -> None:
|
||||||
|
|||||||
Reference in new issue
Block a user