update types to match expected
This commit is contained in:
1 parent
e9f45e521b
commit
f1be2f53e6
1 file changed
+205
-147
+205
-147
@@ -12,7 +12,8 @@ Used by cultivar-daemon for:
|
||||
- SQLite serialization/deserialization
|
||||
- WebSocket payload construction
|
||||
|
||||
Keep in sync with types.ts. When types.ts changes, update here.
|
||||
Compact JSON keys match firmware toJSON() output for minimal serial bandwidth.
|
||||
Full field names are used internally after parsing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -50,98 +51,48 @@ class AnomalyType(str, Enum):
|
||||
baseline_unstable = "baseline_unstable"
|
||||
|
||||
class SweepZone(int, Enum):
|
||||
baseline = 1 # 200-250°C — humidity/CO2 proxy
|
||||
biological = 2 # 280-340°C — mycelium/contamination
|
||||
heavy = 3 # 360-400°C — ammonia/sulfur/heavy VOC
|
||||
baseline = 1
|
||||
biological = 2
|
||||
heavy = 3
|
||||
|
||||
|
||||
# ── Gas sweep ─────────────────────────────────────────────────────────────
|
||||
# ── STM32 compact models (match firmware toJSON() output) ─────────────────
|
||||
|
||||
class GasSweepPoint(BaseModel):
|
||||
"""Single point in the 10-step gas sweep. Mirrors GasSweepPoint in types.ts."""
|
||||
heater_temp_c: int
|
||||
heater_dur_ms: int
|
||||
zone: SweepZone
|
||||
resistance_raw: Optional[float] = None
|
||||
resistance_corr: Optional[float] = None # humidity corrected, set by daemon
|
||||
resistance_norm: Optional[float] = None # baseline normalized, set by daemon
|
||||
heater_stable: bool
|
||||
valid: bool
|
||||
class STM32Ambient(BaseModel):
|
||||
"""Compact ambient reading from firmware. Keys match toJSON() output."""
|
||||
temp: float # °C
|
||||
hum: float # %RH
|
||||
pres: float # hPa
|
||||
ok: bool
|
||||
|
||||
class STM32CO2(BaseModel):
|
||||
"""Compact CO2 reading from firmware."""
|
||||
ppm: int
|
||||
temp: float # °C — cross-validation only
|
||||
hum: float # %RH — cross-validation only
|
||||
ok: bool
|
||||
|
||||
class ZoneScores(BaseModel):
|
||||
"""Aggregated zone scores derived from normalized sweep points."""
|
||||
Z1: Optional[float] = None
|
||||
Z2: Optional[float] = None
|
||||
Z3: Optional[float] = None
|
||||
class STM32Health(BaseModel):
|
||||
"""Compact sensor health from firmware."""
|
||||
scd43: bool
|
||||
tdelta: Optional[float] = None
|
||||
hdelta: Optional[float] = None
|
||||
tok: bool = True
|
||||
hok: bool = True
|
||||
|
||||
class STM32Baseline(BaseModel):
|
||||
"""Compact baseline state from firmware."""
|
||||
established: bool
|
||||
samples: int
|
||||
|
||||
# ── Sensor health ─────────────────────────────────────────────────────────
|
||||
|
||||
class SensorHealth(BaseModel):
|
||||
"""Cross-validation between BME690 and SCD43. Mirrors SensorHealth in types.ts."""
|
||||
scd43_present: bool
|
||||
temp_delta: Optional[float] = None
|
||||
humidity_delta: Optional[float] = None
|
||||
temp_ok: bool = True
|
||||
humidity_ok: bool = True
|
||||
|
||||
|
||||
# ── Ambient reading ───────────────────────────────────────────────────────
|
||||
|
||||
class AmbientReading(BaseModel):
|
||||
"""BME690 ambient reading (heater off). Mirrors ambient in EnvPayload."""
|
||||
temp_c: float
|
||||
humidity_pct: float
|
||||
pressure_hpa: float
|
||||
valid: bool
|
||||
|
||||
|
||||
# ── CO2 reading ───────────────────────────────────────────────────────────
|
||||
|
||||
class CO2Reading(BaseModel):
|
||||
"""SCD43 CO2 reading. Only present in fruiting chamber."""
|
||||
ppm: int
|
||||
temp_c: float # cross-validation only
|
||||
humidity_pct: float # cross-validation only
|
||||
valid: bool
|
||||
|
||||
|
||||
# ── Baseline state ────────────────────────────────────────────────────────
|
||||
|
||||
class SweepBaseline(BaseModel):
|
||||
"""
|
||||
Baseline state for a chamber run.
|
||||
R is a dict of heater_temp_c (str) → baseline resistance (float).
|
||||
Stored as JSON in the baselines table.
|
||||
"""
|
||||
established: bool
|
||||
established_at: Optional[int] = None # unix ts
|
||||
n_samples: int = 0
|
||||
R: dict[str, float] = Field(default_factory=dict)
|
||||
humidity_ref: Optional[float] = None
|
||||
temp_ref: Optional[float] = None
|
||||
co2_ref: Optional[float] = None
|
||||
|
||||
|
||||
# ── Anomaly ───────────────────────────────────────────────────────────────
|
||||
|
||||
class EnvAnomaly(BaseModel):
|
||||
"""
|
||||
Daemon-detected environmental anomaly.
|
||||
Mirrors EnvAnomaly in types.ts.
|
||||
Surfaces in Cultivar Rhythm as tasks/alerts.
|
||||
"""
|
||||
id: str
|
||||
type: AnomalyType
|
||||
severity: AnomalySeverity
|
||||
chamber_id: str
|
||||
message: str # Cultivar-voice, human-readable
|
||||
contaminant_hint: Optional[str] = None # CONT-xxx id
|
||||
evidence_json: Optional[dict] = None # zone scores, deltas at detection
|
||||
ts: int = Field(default_factory=lambda: int(time.time()))
|
||||
dismissed: bool = False
|
||||
dismissed_at: Optional[int] = None
|
||||
class STM32SweepPoint(BaseModel):
|
||||
"""Compact sweep point from firmware."""
|
||||
t: int # heater_temp_c
|
||||
dur: int # heater_dur_ms
|
||||
zone: int # 1 | 2 | 3
|
||||
r: float # resistance Ω
|
||||
stable: bool
|
||||
ok: bool
|
||||
|
||||
|
||||
# ── STM32 raw payload ─────────────────────────────────────────────────────
|
||||
@@ -150,18 +101,15 @@ class STM32Payload(BaseModel):
|
||||
"""
|
||||
Raw JSON payload from STM32 over Serial.
|
||||
Validated immediately on receipt by serial_reader.py.
|
||||
Mirrors the output of CultivarEnv::toJSON().
|
||||
|
||||
Fields match the compact JSON keys from the firmware:
|
||||
ts, ambient, co2, health, baseline, sweep
|
||||
Compact keys match firmware toJSON() output.
|
||||
"""
|
||||
ts: int # millis() from STM32
|
||||
chamber_id: str # 'colonization' | 'fruiting'
|
||||
ambient: AmbientReading
|
||||
co2: Optional[CO2Reading] = None
|
||||
health: SensorHealth
|
||||
baseline: SweepBaseline
|
||||
sweep: list[GasSweepPoint]
|
||||
ts: int
|
||||
chamber_id: str
|
||||
ambient: STM32Ambient
|
||||
co2: Optional[STM32CO2] = None
|
||||
health: STM32Health
|
||||
baseline: STM32Baseline
|
||||
sweep: list[STM32SweepPoint]
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_sweep_count(self) -> STM32Payload:
|
||||
@@ -179,47 +127,166 @@ class STM32Payload(BaseModel):
|
||||
return self
|
||||
|
||||
|
||||
# ── Expanded internal models (used after parsing) ─────────────────────────
|
||||
|
||||
class GasSweepPoint(BaseModel):
|
||||
"""Expanded sweep point with processing fields. Mirrors GasSweepPoint in types.ts."""
|
||||
heater_temp_c: int
|
||||
heater_dur_ms: int
|
||||
zone: SweepZone
|
||||
resistance_raw: Optional[float] = None
|
||||
resistance_corr: Optional[float] = None
|
||||
resistance_norm: Optional[float] = None
|
||||
heater_stable: bool
|
||||
valid: bool
|
||||
|
||||
@classmethod
|
||||
def from_stm32(cls, p: STM32SweepPoint) -> GasSweepPoint:
|
||||
return cls(
|
||||
heater_temp_c = p.t,
|
||||
heater_dur_ms = p.dur,
|
||||
zone = SweepZone(p.zone),
|
||||
resistance_raw = p.r,
|
||||
heater_stable = p.stable,
|
||||
valid = p.ok,
|
||||
)
|
||||
|
||||
|
||||
class ZoneScores(BaseModel):
|
||||
Z1: Optional[float] = None
|
||||
Z2: Optional[float] = None
|
||||
Z3: Optional[float] = None
|
||||
|
||||
|
||||
class SensorHealth(BaseModel):
|
||||
"""Expanded sensor health. Mirrors SensorHealth in types.ts."""
|
||||
scd43_present: bool
|
||||
temp_delta: Optional[float] = None
|
||||
humidity_delta: Optional[float] = None
|
||||
temp_ok: bool = True
|
||||
humidity_ok: bool = True
|
||||
|
||||
@classmethod
|
||||
def from_stm32(cls, h: STM32Health) -> SensorHealth:
|
||||
return cls(
|
||||
scd43_present = h.scd43,
|
||||
temp_delta = h.tdelta,
|
||||
humidity_delta = h.hdelta,
|
||||
temp_ok = h.tok,
|
||||
humidity_ok = h.hok,
|
||||
)
|
||||
|
||||
|
||||
class AmbientReading(BaseModel):
|
||||
"""Expanded ambient reading. Mirrors ambient in EnvPayload."""
|
||||
temp_c: float
|
||||
humidity_pct: float
|
||||
pressure_hpa: float
|
||||
valid: bool
|
||||
|
||||
@classmethod
|
||||
def from_stm32(cls, a: STM32Ambient) -> AmbientReading:
|
||||
return cls(
|
||||
temp_c = a.temp,
|
||||
humidity_pct = a.hum,
|
||||
pressure_hpa = a.pres,
|
||||
valid = a.ok,
|
||||
)
|
||||
|
||||
|
||||
class CO2Reading(BaseModel):
|
||||
"""Expanded CO2 reading."""
|
||||
ppm: int
|
||||
temp_c: float
|
||||
humidity_pct: float
|
||||
valid: bool
|
||||
|
||||
@classmethod
|
||||
def from_stm32(cls, c: STM32CO2) -> CO2Reading:
|
||||
return cls(
|
||||
ppm = c.ppm,
|
||||
temp_c = c.temp,
|
||||
humidity_pct = c.hum,
|
||||
valid = c.ok,
|
||||
)
|
||||
|
||||
|
||||
class SweepBaseline(BaseModel):
|
||||
"""Baseline fingerprint. Mirrors SweepBaseline in types.ts."""
|
||||
established: bool
|
||||
established_at: Optional[int] = None
|
||||
n_samples: int = 0
|
||||
R: dict[str, float] = Field(default_factory=dict)
|
||||
humidity_ref: Optional[float] = None
|
||||
temp_ref: Optional[float] = None
|
||||
co2_ref: Optional[float] = None
|
||||
|
||||
|
||||
class EnvAnomaly(BaseModel):
|
||||
"""Daemon-detected anomaly. Mirrors EnvAnomaly in types.ts."""
|
||||
id: str
|
||||
type: AnomalyType
|
||||
severity: AnomalySeverity
|
||||
chamber_id: str
|
||||
message: str
|
||||
contaminant_hint: Optional[str] = None
|
||||
evidence_json: Optional[dict] = None
|
||||
ts: int = Field(default_factory=lambda: int(time.time()))
|
||||
dismissed: bool = False
|
||||
dismissed_at: Optional[int] = None
|
||||
|
||||
|
||||
# ── Processed payload (daemon → UI) ──────────────────────────────────────
|
||||
|
||||
class EnvPayload(BaseModel):
|
||||
"""
|
||||
Fully processed payload sent to the UI via WebSocket and REST.
|
||||
Fully processed payload sent to UI via WebSocket and REST.
|
||||
Mirrors EnvPayload in types.ts.
|
||||
Extends STM32Payload with daemon-derived fields.
|
||||
"""
|
||||
ts: int
|
||||
chamber_id: str
|
||||
received_at: int = Field(default_factory=lambda: int(time.time()))
|
||||
ts: int
|
||||
chamber_id: str
|
||||
received_at: int = Field(default_factory=lambda: int(time.time()))
|
||||
ambient: AmbientReading
|
||||
co2: Optional[CO2Reading] = None
|
||||
co2e_ppm: Optional[float] = None
|
||||
co2e_confidence: Co2eConfidence = Co2eConfidence.uncalibrated
|
||||
voc_ppb: Optional[float] = None
|
||||
sweep: list[GasSweepPoint]
|
||||
zone_scores: ZoneScores = Field(default_factory=ZoneScores)
|
||||
baseline: SweepBaseline
|
||||
health: SensorHealth
|
||||
anomalies: list[EnvAnomaly] = Field(default_factory=list)
|
||||
|
||||
ambient: AmbientReading
|
||||
co2: Optional[CO2Reading] = None
|
||||
|
||||
# Daemon-derived
|
||||
co2e_ppm: Optional[float] = None
|
||||
co2e_confidence: Co2eConfidence = Co2eConfidence.uncalibrated
|
||||
voc_ppb: Optional[float] = None
|
||||
|
||||
sweep: list[GasSweepPoint]
|
||||
zone_scores: ZoneScores = Field(default_factory=ZoneScores)
|
||||
baseline: SweepBaseline
|
||||
health: SensorHealth
|
||||
anomalies: list[EnvAnomaly] = Field(default_factory=list)
|
||||
@classmethod
|
||||
def from_stm32(cls, raw: STM32Payload) -> EnvPayload:
|
||||
"""Convert a raw STM32Payload into an EnvPayload for processing."""
|
||||
return cls(
|
||||
ts = raw.ts,
|
||||
chamber_id = raw.chamber_id,
|
||||
ambient = AmbientReading.from_stm32(raw.ambient),
|
||||
co2 = CO2Reading.from_stm32(raw.co2) if raw.co2 else None,
|
||||
health = SensorHealth.from_stm32(raw.health),
|
||||
baseline = SweepBaseline(
|
||||
established = raw.baseline.established,
|
||||
n_samples = raw.baseline.samples,
|
||||
),
|
||||
sweep = [GasSweepPoint.from_stm32(p) for p in raw.sweep],
|
||||
)
|
||||
|
||||
|
||||
# ── WebSocket message envelope ────────────────────────────────────────────
|
||||
|
||||
class WsMessageType(str, Enum):
|
||||
payload = "payload" # new EnvPayload available
|
||||
anomaly = "anomaly" # new anomaly detected
|
||||
baseline = "baseline" # baseline established/updated
|
||||
heartbeat = "heartbeat" # keepalive
|
||||
payload = "payload"
|
||||
anomaly = "anomaly"
|
||||
baseline = "baseline"
|
||||
heartbeat = "heartbeat"
|
||||
|
||||
class WsMessage(BaseModel):
|
||||
"""WebSocket message envelope. Wraps all real-time events to the UI."""
|
||||
type: WsMessageType
|
||||
type: WsMessageType
|
||||
chamber_id: Optional[str] = None
|
||||
data: Optional[dict] = None
|
||||
ts: int = Field(default_factory=lambda: int(time.time()))
|
||||
data: Optional[dict] = None
|
||||
ts: int = Field(default_factory=lambda: int(time.time()))
|
||||
|
||||
|
||||
# ── Run ───────────────────────────────────────────────────────────────────
|
||||
@@ -230,38 +297,29 @@ class RunEndReason(str, Enum):
|
||||
contamination = "contamination"
|
||||
|
||||
class Run(BaseModel):
|
||||
"""A cultivation run — one species, one chamber, start to finish."""
|
||||
id: str
|
||||
chamber_id: str
|
||||
species_id: Optional[str] = None # SP-xxx
|
||||
species_name: Optional[str] = None
|
||||
substrate: Optional[str] = None
|
||||
species_id: Optional[str] = None
|
||||
species_name: Optional[str] = None
|
||||
substrate: Optional[str] = None
|
||||
started_at: int
|
||||
ended_at: Optional[int] = None
|
||||
ended_at: Optional[int] = None
|
||||
end_reason: Optional[RunEndReason] = None
|
||||
notes: Optional[str] = None
|
||||
notes: Optional[str] = None
|
||||
|
||||
|
||||
# ── CO2e calibration sample ───────────────────────────────────────────────
|
||||
|
||||
class Co2eCalibrationSample(BaseModel):
|
||||
"""
|
||||
Paired (real CO2, sweep fingerprint) sample for CO2e model training.
|
||||
Collected automatically during fruiting chamber runs where SCD43 is present.
|
||||
"""
|
||||
payload_id: int
|
||||
chamber_id: str
|
||||
collected_at: int
|
||||
species_id: Optional[str] = None
|
||||
|
||||
co2_real: int # SCD43 ground truth (ppm)
|
||||
|
||||
r_corr_200: Optional[float] = None
|
||||
r_corr_220: Optional[float] = None
|
||||
r_corr_250: Optional[float] = None
|
||||
|
||||
payload_id: int
|
||||
chamber_id: str
|
||||
collected_at: int
|
||||
species_id: Optional[str] = None
|
||||
co2_real: int
|
||||
r_corr_200: Optional[float] = None
|
||||
r_corr_220: Optional[float] = None
|
||||
r_corr_250: Optional[float] = None
|
||||
humidity_at_read: Optional[float] = None
|
||||
temp_at_read: Optional[float] = None
|
||||
|
||||
co2e_estimate: Optional[float] = None
|
||||
model_version: Optional[str] = None
|
||||
co2e_estimate: Optional[float] = None
|
||||
model_version: Optional[str] = None
|
||||
Reference in new issue
Block a user