add cultivar_types.py

This commit is contained in:
grove5_admin committed 2026-04-27 18:53:22 -07:00
1 parent 3f9e1fef4f
commit e929b3c05d
1 file changed
+267
+267
View File
@@ -0,0 +1,267 @@
"""
cultivar_types.py
Pydantic models for the Cultivar environmental data pipeline.
Grove5 — Open source software, honest hardware.
https://grovefive.com
Python mirror of cultivar-types/typescript/types.ts.
Used by cultivar-daemon for:
- Serial JSON validation (STM32 → daemon)
- FastAPI request/response models
- SQLite serialization/deserialization
- WebSocket payload construction
Keep in sync with types.ts. When types.ts changes, update here.
"""
from __future__ import annotations
from enum import Enum
from typing import Optional
import time
from pydantic import BaseModel, Field, model_validator
# ── Enums ─────────────────────────────────────────────────────────────────
class ChamberType(str, Enum):
colonization = "colonization"
fruiting = "fruiting"
class Co2eConfidence(str, Enum):
uncalibrated = "uncalibrated"
low = "low"
medium = "medium"
high = "high"
class AnomalySeverity(str, Enum):
info = "info"
warn = "warn"
critical = "critical"
class AnomalyType(str, Enum):
z2_deviation = "z2_deviation"
z3_spike = "z3_spike"
co2_threshold = "co2_threshold"
humidity_drift = "humidity_drift"
temp_drift = "temp_drift"
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
# ── Gas sweep ─────────────────────────────────────────────────────────────
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 ZoneScores(BaseModel):
"""Aggregated zone scores derived from normalized sweep points."""
Z1: Optional[float] = None
Z2: Optional[float] = None
Z3: Optional[float] = None
# ── 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
# ── STM32 raw payload ─────────────────────────────────────────────────────
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
"""
ts: int # millis() from STM32
chamber_id: str # 'colonization' | 'fruiting'
ambient: AmbientReading
co2: Optional[CO2Reading] = None
health: SensorHealth
baseline: SweepBaseline
sweep: list[GasSweepPoint]
@model_validator(mode='after')
def validate_sweep_count(self) -> STM32Payload:
if len(self.sweep) == 0:
raise ValueError("sweep must have at least 1 point")
if len(self.sweep) > 10:
raise ValueError("sweep cannot exceed 10 points")
return self
@model_validator(mode='after')
def validate_chamber_id(self) -> STM32Payload:
valid = {'colonization', 'fruiting'}
if self.chamber_id not in valid:
raise ValueError(f"chamber_id must be one of {valid}")
return self
# ── Processed payload (daemon → UI) ──────────────────────────────────────
class EnvPayload(BaseModel):
"""
Fully processed payload sent to the 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()))
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)
# ── 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
class WsMessage(BaseModel):
"""WebSocket message envelope. Wraps all real-time events to the UI."""
type: WsMessageType
chamber_id: Optional[str] = None
data: Optional[dict] = None
ts: int = Field(default_factory=lambda: int(time.time()))
# ── Run ───────────────────────────────────────────────────────────────────
class RunEndReason(str, Enum):
harvest = "harvest"
abort = "abort"
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
started_at: int
ended_at: Optional[int] = None
end_reason: Optional[RunEndReason] = 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
humidity_at_read: Optional[float] = None
temp_at_read: Optional[float] = None
co2e_estimate: Optional[float] = None
model_version: Optional[str] = None