updated URL in schema.sql header comment

This commit is contained in:
grove5_admin committed 2026-04-27 19:22:40 -07:00
1 parent 77774a725b
commit ea11403528
8 files changed
+2145 -1

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
# cultivar-daemon/.gitignore
# Python
__pycache__/
*.py[cod]
*.pyo
.venv/
venv/
*.egg-info/
# Database — never commit the live DB
cultivar.db
cultivar.db-wal
cultivar.db-shm
# Shared types — symlinked from cultivar-types
cultivar_types.py
# Replay samples with real data
samples/*.jsonl
# Logs
*.log
# Environment / secrets
.env
.env.*
# OS
.DS_Store
+284
View File
@@ -0,0 +1,284 @@
"""
api.py
FastAPI REST and WebSocket API for the Cultivar daemon.
Grove5 — Open source software, honest hardware.
https://grove5.com
"""
import logging
import time
from pathlib import Path
from typing import Optional
import aiosqlite
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from pydantic import BaseModel
from cultivar_types import (
EnvPayload,
EnvAnomaly,
Run,
RunEndReason,
WsMessage,
WsMessageType,
)
import storage
log = logging.getLogger(__name__)
UI_DIST = Path(__file__).parent.parent / "cultivar-ui" / "dist"
app = FastAPI(title="Cultivar Daemon", version="0.2.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class ConnectionManager:
def __init__(self):
self._connections: list[WebSocket] = []
async def connect(self, ws: WebSocket) -> None:
await ws.accept()
self._connections.append(ws)
log.info(f"WebSocket connected — {len(self._connections)} active")
def disconnect(self, ws: WebSocket) -> None:
self._connections.remove(ws)
log.info(f"WebSocket disconnected — {len(self._connections)} active")
async def broadcast(self, message: WsMessage) -> None:
if not self._connections:
return
data = message.model_dump_json()
dead = []
for ws in self._connections:
try:
await ws.send_text(data)
except Exception:
dead.append(ws)
for ws in dead:
self._connections.remove(ws)
async def broadcast_payload(self, payload: EnvPayload) -> None:
await self.broadcast(WsMessage(
type=WsMessageType.payload,
chamber_id=payload.chamber_id,
data=payload.model_dump(),
))
async def broadcast_anomaly(self, anomaly: EnvAnomaly) -> None:
await self.broadcast(WsMessage(
type=WsMessageType.anomaly,
chamber_id=anomaly.chamber_id,
data=anomaly.model_dump(),
))
async def broadcast_heartbeat(self) -> None:
await self.broadcast(WsMessage(type=WsMessageType.heartbeat))
@property
def connection_count(self) -> int:
return len(self._connections)
ws_manager = ConnectionManager()
async def get_db() -> aiosqlite.Connection:
db = await storage.init_db()
try:
yield db
finally:
await db.close()
@app.websocket("/ws")
async def websocket_endpoint(ws: WebSocket):
await ws_manager.connect(ws)
try:
while True:
await ws.receive_text()
except WebSocketDisconnect:
ws_manager.disconnect(ws)
@app.get("/api/health")
async def health():
return {
"status": "ok",
"ts": int(time.time()),
"ws_clients": ws_manager.connection_count,
"version": "0.2.0",
}
@app.get("/api/environment/{chamber_id}/history")
async def get_environment_history(
chamber_id: str,
hours: int = 24,
db: aiosqlite.Connection = Depends(get_db),
):
since = int(time.time()) - (hours * 3600)
return await storage.get_environment_history(db, chamber_id, since)
@app.get("/api/environment/{chamber_id}/latest")
async def get_latest(
chamber_id: str,
db: aiosqlite.Connection = Depends(get_db),
):
row = await storage.get_latest_payload(db, chamber_id)
if not row:
raise HTTPException(status_code=404, detail="No data for chamber")
return row
@app.get("/api/environment/{chamber_id}/sweep")
async def get_sweep_history(
chamber_id: str,
hours: int = 24,
db: aiosqlite.Connection = Depends(get_db),
):
since = int(time.time()) - (hours * 3600)
return await storage.get_sweep_history(db, chamber_id, since)
class CreateRunRequest(BaseModel):
chamber_id: str
species_id: Optional[str] = None
species_name: Optional[str] = None
substrate: Optional[str] = None
notes: Optional[str] = None
class EndRunRequest(BaseModel):
reason: RunEndReason
notes: Optional[str] = None
class UpdateRunRequest(BaseModel):
species_id: Optional[str] = None
species_name: Optional[str] = None
substrate: Optional[str] = None
notes: Optional[str] = None
@app.post("/api/runs", response_model=Run)
async def create_run(
req: CreateRunRequest,
db: aiosqlite.Connection = Depends(get_db),
):
return await storage.create_run(
db,
chamber_id=req.chamber_id,
species_id=req.species_id,
species_name=req.species_name,
substrate=req.substrate,
notes=req.notes,
)
@app.get("/api/runs/{chamber_id}/active", response_model=Optional[Run])
async def get_active_run(
chamber_id: str,
db: aiosqlite.Connection = Depends(get_db),
):
return await storage.get_active_run(db, chamber_id)
@app.post("/api/runs/{run_id}/end")
async def end_run(
run_id: str,
req: EndRunRequest,
db: aiosqlite.Connection = Depends(get_db),
):
await storage.end_run(db, run_id, req.reason, req.notes)
return {"ok": True, "run_id": run_id, "reason": req.reason}
@app.patch("/api/runs/{run_id}")
async def update_run(
run_id: str,
req: UpdateRunRequest,
db: aiosqlite.Connection = Depends(get_db),
):
updates = {k: v for k, v in req.model_dump().items() if v is not None}
if not updates:
return {"ok": True, "updated": 0}
set_clause = ", ".join(f"{k} = ?" for k in updates)
values = list(updates.values()) + [run_id]
await db.execute(f"UPDATE runs SET {set_clause} WHERE id = ?", values)
await db.commit()
return {"ok": True, "run_id": run_id, "updated": len(updates)}
@app.get("/api/anomalies/{chamber_id}")
async def get_anomalies(
chamber_id: str,
limit: int = 20,
db: aiosqlite.Connection = Depends(get_db),
):
return await storage.get_active_anomalies(db, chamber_id, limit)
@app.post("/api/anomalies/{anomaly_id}/dismiss")
async def dismiss_anomaly(
anomaly_id: str,
db: aiosqlite.Connection = Depends(get_db),
):
await storage.dismiss_anomaly(db, anomaly_id)
return {"ok": True, "anomaly_id": anomaly_id}
@app.get("/api/baseline/{chamber_id}")
async def get_baseline(
chamber_id: str,
db: aiosqlite.Connection = Depends(get_db),
):
baseline = await storage.get_active_baseline(db, chamber_id)
if not baseline:
return {"established": False}
return baseline.model_dump()
@app.post("/api/baseline/{chamber_id}/reset")
async def reset_baseline(
chamber_id: str,
db: aiosqlite.Connection = Depends(get_db),
):
await db.execute(
"UPDATE baselines SET active = 0 WHERE chamber_id = ? AND active = 1",
(chamber_id,),
)
await db.commit()
log.info(f"[{chamber_id}] Baseline reset via API")
return {"ok": True, "chamber_id": chamber_id}
if UI_DIST.exists():
app.mount("/assets", StaticFiles(directory=UI_DIST / "assets"), name="assets")
@app.get("/{full_path:path}")
async def serve_ui(full_path: str):
index = UI_DIST / "index.html"
if index.exists():
return FileResponse(index)
raise HTTPException(status_code=404, detail="UI not built")
else:
log.warning(f"UI dist not found at {UI_DIST} — run npm run build in cultivar-ui")
@app.get("/")
async def no_ui():
return {
"message": "Cultivar Daemon running — UI not built",
"api": "/api/health",
"ws": "/ws",
}
+371
View File
@@ -0,0 +1,371 @@
"""
cultivar_daemon.py
Main entrypoint for the Cultivar environmental data daemon.
Grove5 — Open source software, honest hardware.
https://grove5.com
Wires together:
- SerialManager (serial_reader.py) — reads STM32 payloads
- Processor (processor.py) — corrects, normalizes, scores
- BaselineBuilder (processor.py) — establishes per-chamber baseline
- storage (storage.py) — persists everything to SQLite
- ConnectionManager (api.py) — broadcasts to Svelte UI via WebSocket
- FastAPI (api.py) — REST + WebSocket + static UI
Architecture:
Two serial readers (one per chamber) push STM32Payload objects
onto a shared asyncio.Queue. A single consumer loop processes
them sequentially, persists to SQLite, and broadcasts to the UI.
asyncio.Queue decouples serial I/O from processing —
a slow DB write never blocks the serial readers.
FastAPI runs in the same event loop via uvicorn.
Startup sequence:
1. Init SQLite (apply schema)
2. Load active baselines per chamber
3. Start serial readers
4. Start FastAPI (uvicorn)
5. Start heartbeat task
6. Start payload consumer loop
Configuration via environment variables (see Config below).
"""
import asyncio
import logging
import os
import signal
import sys
import time
from pathlib import Path
import uvicorn
from cultivar_types import STM32Payload, Co2eCalibrationSample
from serial_reader import SerialManager
from processor import Processor, BaselineBuilder
from api import app, ws_manager
import storage
# ── Logging ───────────────────────────────────────────────────────────────
logging.basicConfig(
level = logging.INFO,
format = "%(asctime)s %(levelname)-8s %(name)s — %(message)s",
datefmt= "%Y-%m-%d %H:%M:%S",
)
log = logging.getLogger("cultivar_daemon")
# ── Configuration ─────────────────────────────────────────────────────────
class Config:
"""
Runtime configuration from environment variables.
Sensible defaults for UNO Q production deployment.
"""
# Serial ports — one per ENV-1 board
# On UNO Q: STM32 exposes multiple UARTs; adjust to match wiring
COLONIZATION_PORT: str = os.getenv("COLONIZATION_PORT", "/dev/ttyS0")
FRUITING_PORT: str = os.getenv("FRUITING_PORT", "/dev/ttyS1")
SERIAL_BAUD: int = int(os.getenv("SERIAL_BAUD", "115200"))
# Disable a chamber entirely (e.g. single-chamber dev setup)
ENABLE_COLONIZATION: bool = os.getenv("ENABLE_COLONIZATION", "true").lower() == "true"
ENABLE_FRUITING: bool = os.getenv("ENABLE_FRUITING", "true").lower() == "true"
# Replay mode — no hardware, replay from .jsonl files
REPLAY_MODE: bool = os.getenv("REPLAY_MODE", "false").lower() == "true"
REPLAY_COLONIZATION: str = os.getenv("REPLAY_COLONIZATION", "samples/colonization.jsonl")
REPLAY_FRUITING: str = os.getenv("REPLAY_FRUITING", "samples/fruiting.jsonl")
REPLAY_DELAY: float = float(os.getenv("REPLAY_DELAY", "5.0"))
# API server
API_HOST: str = os.getenv("API_HOST", "0.0.0.0")
API_PORT: int = int(os.getenv("API_PORT", "8000"))
# Database
DB_PATH: str = os.getenv("DB_PATH", str(storage.DB_PATH))
# Baseline
BASELINE_MIN_SAMPLES: int = int(os.getenv("BASELINE_MIN_SAMPLES", "6"))
BASELINE_HUM_VARIANCE: float = float(os.getenv("BASELINE_HUM_VARIANCE", "5.0"))
# Heartbeat interval (seconds)
HEARTBEAT_INTERVAL: int = int(os.getenv("HEARTBEAT_INTERVAL", "30"))
cfg = Config()
# ── Per-chamber state ─────────────────────────────────────────────────────
class ChamberState:
"""Holds runtime state for one chamber."""
def __init__(self, chamber_id: str):
self.chamber_id = chamber_id
self.processor = Processor(chamber_id)
self.baseline_builder = BaselineBuilder(
min_samples = cfg.BASELINE_MIN_SAMPLES,
humidity_variance = cfg.BASELINE_HUM_VARIANCE,
)
self.run_id: str | None = None
def __repr__(self) -> str:
return f"ChamberState({self.chamber_id}, run={self.run_id})"
# ── Payload consumer ──────────────────────────────────────────────────────
async def consume_payloads(
queue: asyncio.Queue,
chambers: dict[str, ChamberState],
db,
) -> None:
"""
Main consumer loop — processes payloads from the shared queue.
Runs forever until cancelled.
"""
log.info("Payload consumer started")
while True:
try:
raw: STM32Payload = await queue.get()
await _handle_payload(raw, chambers, db)
queue.task_done()
except asyncio.CancelledError:
log.info("Payload consumer cancelled")
break
except Exception as e:
log.exception(f"Unhandled error in payload consumer: {e}")
# Continue — don't let one bad payload kill the daemon
async def _handle_payload(
raw: STM32Payload,
chambers: dict[str, ChamberState],
db,
) -> None:
chamber_id = raw.chamber_id
state = chambers.get(chamber_id)
if state is None:
log.warning(f"Received payload for unknown chamber: {chamber_id}")
return
# Ensure an active run exists
if state.run_id is None:
run = await storage.get_or_create_run(db, chamber_id)
state.run_id = run.id
log.info(f"[{chamber_id}] Active run: {state.run_id}")
# Feed baseline builder
state.baseline_builder.feed(raw)
# Check if baseline just became established
if (not state.processor.baseline or
not state.processor.baseline.established):
if state.baseline_builder.established():
baseline = state.baseline_builder.build()
state.processor.update_baseline(baseline)
# Persist to DB
await storage.save_baseline(db, state.run_id, chamber_id, baseline)
log.info(
f"[{chamber_id}] ✓ Baseline established "
f"({baseline.n_samples} samples, "
f"RH={baseline.humidity_ref:.1f}%, "
f"T={baseline.temp_ref:.1f}°C)"
)
# Notify UI
await ws_manager.broadcast(
__import__("cultivar_types").WsMessage(
type = __import__("cultivar_types").WsMessageType.baseline,
chamber_id = chamber_id,
data = baseline.model_dump(),
)
)
else:
log.debug(
f"[{chamber_id}] Building baseline — "
f"{state.baseline_builder.sample_count}/{cfg.BASELINE_MIN_SAMPLES} samples"
)
# Process payload
processed, cal_samples = state.processor.process(raw)
# Persist payload
payload_id = await storage.insert_payload(db, raw, processed, state.run_id)
# Persist sweep points
await storage.insert_sweep_points(
db,
payload_id = payload_id,
chamber_id = chamber_id,
collected_at = raw.ts,
points = processed.sweep,
)
# Persist anomalies
for anomaly in processed.anomalies:
await storage.insert_anomaly(db, anomaly, payload_id, state.run_id)
# Persist CO2e calibration samples
for sample in cal_samples:
sample = sample.model_copy(update={"payload_id": payload_id})
await storage.insert_co2e_sample(db, sample)
# Broadcast to UI
await ws_manager.broadcast_payload(processed)
# Broadcast individual anomalies
for anomaly in processed.anomalies:
await ws_manager.broadcast_anomaly(anomaly)
log.info(
f"[{chamber_id}] Processed payload {payload_id} — "
f"T={raw.ambient.temp_c:.1f}°C "
f"RH={raw.ambient.humidity_pct:.1f}% "
f"{'CO2=' + str(raw.co2.ppm) + 'ppm ' if raw.co2 and raw.co2.valid else ''}"
f"Z1={processed.zone_scores.Z1:.3f} " if processed.zone_scores.Z1 else ""
f"anomalies={len(processed.anomalies)}"
)
# ── Heartbeat ─────────────────────────────────────────────────────────────
async def heartbeat_loop() -> None:
"""Periodically broadcast a heartbeat to keep WebSocket connections alive."""
while True:
await asyncio.sleep(cfg.HEARTBEAT_INTERVAL)
await ws_manager.broadcast_heartbeat()
# ── Main ──────────────────────────────────────────────────────────────────
async def main() -> None:
log.info("╔══════════════════════════════════════╗")
log.info("║ Cultivar Daemon v0.2.0 ║")
log.info("║ Grove5 — Open source software, ║")
log.info("║ honest hardware. grove5.com ║")
log.info("╚══════════════════════════════════════╝")
# Init DB
db_path = Path(cfg.DB_PATH)
db = await storage.init_db(db_path)
log.info(f"Database: {db_path}")
# Init chamber state
chambers: dict[str, ChamberState] = {}
if cfg.ENABLE_COLONIZATION:
state = ChamberState("colonization")
# Load existing baseline if available
baseline = await storage.get_active_baseline(db, "colonization")
if baseline:
state.processor.update_baseline(baseline)
log.info(f"[colonization] Loaded existing baseline ({baseline.n_samples} samples)")
chambers["colonization"] = state
if cfg.ENABLE_FRUITING:
state = ChamberState("fruiting")
baseline = await storage.get_active_baseline(db, "fruiting")
if baseline:
state.processor.update_baseline(baseline)
log.info(f"[fruiting] Loaded existing baseline ({baseline.n_samples} samples)")
chambers["fruiting"] = state
if not chambers:
log.error("No chambers enabled — set ENABLE_COLONIZATION or ENABLE_FRUITING")
sys.exit(1)
log.info(f"Chambers: {list(chambers.keys())}")
# Shared queue
queue: asyncio.Queue[STM32Payload] = asyncio.Queue(maxsize=50)
# Serial readers
tasks = []
if cfg.REPLAY_MODE:
log.info("REPLAY MODE — no hardware required")
from serial_reader import replay_from_file
if cfg.ENABLE_COLONIZATION and Path(cfg.REPLAY_COLONIZATION).exists():
tasks.append(asyncio.create_task(
replay_from_file(cfg.REPLAY_COLONIZATION, queue, cfg.REPLAY_DELAY),
name="replay_colonization",
))
if cfg.ENABLE_FRUITING and Path(cfg.REPLAY_FRUITING).exists():
tasks.append(asyncio.create_task(
replay_from_file(cfg.REPLAY_FRUITING, queue, cfg.REPLAY_DELAY),
name="replay_fruiting",
))
else:
serial_mgr = SerialManager(queue)
if cfg.ENABLE_COLONIZATION:
serial_mgr.add_chamber(cfg.COLONIZATION_PORT, cfg.SERIAL_BAUD)
log.info(f"[colonization] Serial: {cfg.COLONIZATION_PORT}")
if cfg.ENABLE_FRUITING:
serial_mgr.add_chamber(cfg.FRUITING_PORT, cfg.SERIAL_BAUD)
log.info(f"[fruiting] Serial: {cfg.FRUITING_PORT}")
await serial_mgr.start()
# Consumer
tasks.append(asyncio.create_task(
consume_payloads(queue, chambers, db),
name="consumer",
))
# Heartbeat
tasks.append(asyncio.create_task(
heartbeat_loop(),
name="heartbeat",
))
# FastAPI via uvicorn
uvicorn_config = uvicorn.Config(
app = app,
host = cfg.API_HOST,
port = cfg.API_PORT,
log_level = "warning", # uvicorn logs are noisy — let our logger lead
loop = "none", # use existing event loop
)
server = uvicorn.Server(uvicorn_config)
log.info(f"API: http://{cfg.API_HOST}:{cfg.API_PORT}")
log.info(f"WS: ws://{cfg.API_HOST}:{cfg.API_PORT}/ws")
# Graceful shutdown
def _shutdown(sig, frame):
log.info(f"Signal {sig} received — shutting down")
for task in tasks:
task.cancel()
signal.signal(signal.SIGINT, _shutdown)
signal.signal(signal.SIGTERM, _shutdown)
# Run everything
try:
await asyncio.gather(server.serve(), *tasks, return_exceptions=True)
finally:
if not cfg.REPLAY_MODE:
await serial_mgr.stop()
await db.close()
log.info("Cultivar Daemon stopped")
if __name__ == "__main__":
asyncio.run(main())
+666
View File
@@ -0,0 +1,666 @@
"""
processor.py
Environmental data processor for the Cultivar daemon.
Grove5 — Open source software, honest hardware.
https://grove5.com
Responsibilities:
- Humidity correction of raw gas resistance values
- Baseline normalization of corrected resistance values
- Zone score aggregation (Z1/Z2/Z3)
- CO2e estimation from Zone 1 (when baseline established)
- VOC ppb scaling from Zone 2
- Anomaly detection
- CO2e calibration sample collection
Processing pipeline per payload:
STM32Payload
→ humidity_correct() resistance_raw → resistance_corr
→ baseline_normalize() resistance_corr → resistance_norm
→ compute_zone_scores() zone aggregates
→ estimate_co2e() CO2e from Z1 (if baseline + calibration)
→ scale_voc() VOC ppb from Z2
→ detect_anomalies() EnvAnomaly list
→ EnvPayload
Humidity correction model:
The correction factor follows the approach from PMC9101743
(Correction Model for Metal Oxide Sensor Drift):
CF(RH, T) = exp(k_rh * (RH - RH_ref)) * exp(k_t * (T - T_ref))
R_corr = R_raw / CF
Where k_rh and k_t are per-temperature-point coefficients.
Default values are literature-derived starting points;
they improve as CO2e calibration data accumulates.
CO2e model:
Starting model: weighted inverse of normalized Z1 score.
Weights and offsets are fit from paired (SCD43, sweep) training data.
Until calibration data exists, co2e_confidence = 'uncalibrated'
and the output is clearly labeled as an estimate.
co2e = co2_baseline * (1 / Z1_norm) * k + offset
This is intentionally simple — the goal is a useful trend indicator,
not a calibrated absolute measurement. The SCD43 remains authoritative
for species where CO2 control is critical (fruiting chamber).
"""
import logging
import math
import time
import uuid
from typing import Optional
from cultivar_types import (
STM32Payload,
EnvPayload,
EnvAnomaly,
GasSweepPoint,
ZoneScores,
SweepBaseline,
SweepZone,
AnomalyType,
AnomalySeverity,
Co2eConfidence,
Co2eCalibrationSample,
)
log = logging.getLogger(__name__)
# ── Default humidity correction coefficients ──────────────────────────────
# k_rh: resistance change per % RH unit (negative — RH increases conductivity)
# k_t: resistance change per °C (small effect at high heater temps)
# Indexed by heater temperature (°C).
# These are conservative starting values; updated by calibration.
DEFAULT_K_RH: dict[int, float] = {
200: -0.021,
220: -0.020,
250: -0.019,
280: -0.015,
300: -0.013,
320: -0.012,
340: -0.011,
360: -0.009,
380: -0.008,
400: -0.007,
}
DEFAULT_K_T: dict[int, float] = {
200: 0.004,
220: 0.004,
250: 0.003,
280: 0.003,
300: 0.002,
320: 0.002,
340: 0.002,
360: 0.001,
380: 0.001,
400: 0.001,
}
# Reference conditions for correction (typical indoor baseline)
RH_REF = 50.0 # %RH
T_REF = 23.0 # °C
# ── Anomaly detection thresholds ──────────────────────────────────────────
Z2_DEVIATION_WARN = 0.25 # 25% deviation from baseline → warn
Z2_DEVIATION_CRITICAL = 0.50 # 50% deviation → critical
Z3_SPIKE_THRESHOLD = 0.30 # 30% drop in Z3 normalized → heavy compound spike
TEMP_DELTA_WARN = 2.0 # °C between BME690 and SCD43
HUMIDITY_DELTA_WARN = 5.0 # %RH between BME690 and SCD43
# ── Sentinel value (maxed-out resistance from BME690) ─────────────────────
RESISTANCE_MAX = 102_400_000.0 # Ω — treat as "clean air ceiling"
# ── Main processor ────────────────────────────────────────────────────────
class Processor:
"""
Stateless-ish processor. Holds per-chamber state for:
- previous payload (for delta detection)
- current baseline
One Processor instance per chamber.
"""
def __init__(
self,
chamber_id: str,
baseline: Optional[SweepBaseline] = None,
correction_coeffs: Optional[dict] = None, # {temp_c: {k_rh, k_t}}
co2e_weights: Optional[dict] = None, # model weights
species_co2_limit: Optional[int] = None, # ppm from species.ts
):
self.chamber_id = chamber_id
self.baseline = baseline
self.correction_coeffs = correction_coeffs # None → use defaults
self.co2e_weights = co2e_weights # None → uncalibrated
self.species_co2_limit = species_co2_limit
self._prev_zone_scores: Optional[ZoneScores] = None
def update_baseline(self, baseline: SweepBaseline) -> None:
self.baseline = baseline
log.info(f"[{self.chamber_id}] Baseline updated ({baseline.n_samples} samples)")
def update_species(self, co2_limit_ppm: Optional[int]) -> None:
self.species_co2_limit = co2_limit_ppm
def process(self, raw: STM32Payload) -> tuple[EnvPayload, list[Co2eCalibrationSample]]:
"""
Process a raw STM32 payload into a fully enriched EnvPayload.
Returns (EnvPayload, calibration_samples).
Calibration samples are non-empty only when SCD43 CO2 is valid.
"""
points = list(raw.sweep)
# 1. Humidity correction
points = self._humidity_correct(
points,
rh=raw.ambient.humidity_pct,
temp=raw.ambient.temp_c,
)
# 2. Baseline normalization
points = self._baseline_normalize(points)
# 3. Zone scores
zone_scores = self._compute_zone_scores(points)
# 4. CO2e estimate
co2e_ppm, co2e_confidence = self._estimate_co2e(zone_scores, raw)
# 5. VOC ppb (Zone 2 score scaled)
voc_ppb = self._scale_voc(zone_scores)
# 6. Anomaly detection
anomalies = self._detect_anomalies(raw, zone_scores, co2e_ppm)
# 7. Build EnvPayload
payload = EnvPayload(
ts = raw.ts,
chamber_id = raw.chamber_id,
received_at = int(time.time()),
ambient = raw.ambient,
co2 = raw.co2,
co2e_ppm = co2e_ppm,
co2e_confidence = co2e_confidence,
voc_ppb = voc_ppb,
sweep = points,
zone_scores = zone_scores,
baseline = self.baseline or raw.baseline,
health = raw.health,
anomalies = anomalies,
)
# 8. Collect CO2e calibration sample if SCD43 present and valid
cal_samples = self._collect_calibration(raw, points, co2e_ppm)
# Update previous zone scores for delta detection
self._prev_zone_scores = zone_scores
return payload, cal_samples
# ── Humidity correction ───────────────────────────────────────────────
def _humidity_correct(
self,
points: list[GasSweepPoint],
rh: float,
temp: float,
) -> list[GasSweepPoint]:
"""
Apply humidity and temperature correction to raw resistance values.
CF = exp(k_rh * (RH - RH_ref)) * exp(k_t * (T - T_ref))
R_corr = R_raw / CF
Correcting by dividing removes the humidity-induced resistance
change, giving resistance as if measured at reference conditions.
"""
corrected = []
for p in points:
if not p.valid or p.resistance_raw is None:
corrected.append(p.model_copy(update={"resistance_corr": None}))
continue
# Skip maxed-out sentinel values
if p.resistance_raw >= RESISTANCE_MAX:
corrected.append(p.model_copy(update={
"resistance_corr": RESISTANCE_MAX,
}))
continue
coeffs = self.correction_coeffs or {}
t = p.heater_temp_c
k_rh = coeffs.get(t, {}).get("k_rh", DEFAULT_K_RH.get(t, -0.015))
k_t = coeffs.get(t, {}).get("k_t", DEFAULT_K_T.get(t, 0.002))
cf = (
math.exp(k_rh * (rh - RH_REF)) *
math.exp(k_t * (temp - T_REF))
)
cf = max(cf, 0.01) # guard against division by zero
r_corr = p.resistance_raw / cf
corrected.append(p.model_copy(update={"resistance_corr": r_corr}))
return corrected
# ── Baseline normalization ────────────────────────────────────────────
def _baseline_normalize(
self,
points: list[GasSweepPoint],
) -> list[GasSweepPoint]:
"""
Normalize corrected resistance against the established baseline.
R_norm = R_corr / R_baseline
Values > 1 = cleaner than baseline, < 1 = more gas load.
"""
if not self.baseline or not self.baseline.established:
return points
normalized = []
for p in points:
if p.resistance_corr is None:
normalized.append(p)
continue
key = str(p.heater_temp_c)
r_base = self.baseline.R.get(key)
if r_base is None or r_base <= 0:
normalized.append(p)
continue
r_norm = p.resistance_corr / r_base
normalized.append(p.model_copy(update={"resistance_norm": r_norm}))
return normalized
# ── Zone scores ───────────────────────────────────────────────────────
def _compute_zone_scores(self, points: list[GasSweepPoint]) -> ZoneScores:
"""
Compute mean normalized resistance per zone.
Uses corrected values if baseline not yet established,
normalized values once baseline is available.
"""
def zone_mean(zone: SweepZone) -> Optional[float]:
zone_points = [p for p in points if p.zone == zone and p.valid]
if not zone_points:
return None
# Prefer normalized; fall back to corrected
values = []
for p in zone_points:
if p.resistance_norm is not None:
values.append(p.resistance_norm)
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 ZoneScores(
Z1=zone_mean(SweepZone.baseline),
Z2=zone_mean(SweepZone.biological),
Z3=zone_mean(SweepZone.heavy),
)
# ── CO2e estimation ───────────────────────────────────────────────────
def _estimate_co2e(
self,
zone_scores: ZoneScores,
raw: STM32Payload,
) -> tuple[Optional[float], Co2eConfidence]:
"""
Estimate CO2 equivalent from Zone 1 normalized score.
Without calibration data:
Returns uncalibrated estimate using simple inverse ratio.
co2e = co2_baseline * (1 / Z1_norm) * 1.0
With calibration data (co2e_weights set):
co2e = co2_baseline * (1 / Z1_norm) * k + offset
Both are labeled with appropriate confidence levels.
"""
if not self.baseline or not self.baseline.established:
return None, Co2eConfidence.uncalibrated
if zone_scores.Z1 is None or zone_scores.Z1 <= 0:
return None, Co2eConfidence.uncalibrated
co2_baseline = self.baseline.co2_ref or 500.0 # fallback to ~ambient CO2
if self.co2e_weights:
k = self.co2e_weights.get("k", 1.0)
offset = self.co2e_weights.get("offset", 0.0)
n_samples = self.co2e_weights.get("n_samples", 0)
co2e = co2_baseline * (1.0 / zone_scores.Z1) * k + offset
co2e = max(300.0, min(co2e, 10000.0)) # physical bounds
if n_samples >= 100:
confidence = Co2eConfidence.high
elif n_samples >= 30:
confidence = Co2eConfidence.medium
else:
confidence = Co2eConfidence.low
else:
# Uncalibrated: simple inverse ratio, clearly labeled
co2e = co2_baseline * (1.0 / zone_scores.Z1)
co2e = max(300.0, min(co2e, 10000.0))
confidence = Co2eConfidence.uncalibrated
return round(co2e, 1), confidence
# ── VOC scaling ───────────────────────────────────────────────────────
def _scale_voc(self, zone_scores: ZoneScores) -> Optional[float]:
"""
Scale Zone 2 score to a VOC ppb value for the UI.
Zone 2 normalized score of 1.0 = baseline (clean air).
Deviations below 1.0 indicate increased biological VOC load.
Scaling: deviation from baseline mapped to 0-500 ppb range.
This is an index, not an absolute measurement.
"""
if zone_scores.Z2 is None:
return None
# Lower Z2 = more VOCs = higher ppb
deviation = max(0.0, 1.0 - zone_scores.Z2)
voc_ppb = deviation * 500.0 # 0-500 ppb index
return round(voc_ppb, 1)
# ── Anomaly detection ─────────────────────────────────────────────────
def _detect_anomalies(
self,
raw: STM32Payload,
zone_scores: ZoneScores,
co2e_ppm: Optional[float],
) -> list[EnvAnomaly]:
anomalies = []
# Z2 deviation from baseline
if (self.baseline and self.baseline.established and
zone_scores.Z2 is not None and self._prev_zone_scores):
prev_z2 = self._prev_zone_scores.Z2
if prev_z2 is not None and prev_z2 > 0:
delta = abs(zone_scores.Z2 - prev_z2) / prev_z2
if delta >= Z2_DEVIATION_CRITICAL:
anomalies.append(EnvAnomaly(
id = str(uuid.uuid4()),
type = AnomalyType.z2_deviation,
severity = AnomalySeverity.critical,
chamber_id = self.chamber_id,
message = (
f"Biological zone shifted sharply — "
f"{delta*100:.0f}% change from last reading. "
f"Check for contamination or a door open event."
),
contaminant_hint = "CONT-004", # Bacterial contamination
evidence_json = {
"z2_current": zone_scores.Z2,
"z2_prev": prev_z2,
"delta_pct": round(delta * 100, 1),
},
))
elif delta >= Z2_DEVIATION_WARN:
anomalies.append(EnvAnomaly(
id = str(uuid.uuid4()),
type = AnomalyType.z2_deviation,
severity = AnomalySeverity.warn,
chamber_id = self.chamber_id,
message = (
f"Faint biological zone shift — "
f"{delta*100:.0f}% from last reading. "
f"Worth a quick visual check."
),
evidence_json = {
"z2_current": zone_scores.Z2,
"z2_prev": prev_z2,
"delta_pct": round(delta * 100, 1),
},
))
# Z3 spike (ammonia/sulfur — strong contamination signal)
if (self.baseline and self.baseline.established and
zone_scores.Z3 is not None):
if zone_scores.Z3 < (1.0 - Z3_SPIKE_THRESHOLD):
anomalies.append(EnvAnomaly(
id = str(uuid.uuid4()),
type = AnomalyType.z3_spike,
severity = AnomalySeverity.critical,
chamber_id = self.chamber_id,
message = (
"Heavy compound detected — possible ammonia or sulfur. "
"This is a strong contamination signal. "
"Inspect bags immediately, especially for wet rot or bacterial smell."
),
contaminant_hint = "CONT-004",
evidence_json = {"z3_norm": zone_scores.Z3},
))
# Species CO2 threshold (fruiting chamber only)
if self.species_co2_limit and raw.co2 and raw.co2.valid:
if raw.co2.ppm > self.species_co2_limit:
anomalies.append(EnvAnomaly(
id = str(uuid.uuid4()),
type = AnomalyType.co2_threshold,
severity = AnomalySeverity.warn,
chamber_id = self.chamber_id,
message = (
f"CO₂ at {raw.co2.ppm} ppm — above the {self.species_co2_limit} ppm "
f"limit for this species. Fresh air exchange may help pin formation."
),
evidence_json = {
"co2_ppm": raw.co2.ppm,
"limit_ppm": self.species_co2_limit,
},
))
# CO2e threshold (colonization chamber)
if (self.species_co2_limit and co2e_ppm and
not (raw.co2 and raw.co2.valid)):
if co2e_ppm > self.species_co2_limit * 1.2: # 20% headroom for estimate error
anomalies.append(EnvAnomaly(
id = str(uuid.uuid4()),
type = AnomalyType.co2_threshold,
severity = AnomalySeverity.info,
chamber_id = self.chamber_id,
message = (
f"CO₂e estimate at {co2e_ppm:.0f} ppm — "
f"the air exchange ports may need a quick wipe or filter change. "
f"Alternatively, open a window near Cultivar to aid fresh air exchange."
),
evidence_json = {"co2e_ppm": co2e_ppm},
))
# Sensor health — temp drift
if (raw.health.scd43_present and
raw.health.temp_delta is not None and
raw.health.temp_delta > TEMP_DELTA_WARN):
anomalies.append(EnvAnomaly(
id = str(uuid.uuid4()),
type = AnomalyType.temp_drift,
severity = AnomalySeverity.warn,
chamber_id = self.chamber_id,
message = (
f"Temperature sensors diverging — "
f"{raw.health.temp_delta:.1f}°C difference between BME690 and SCD43. "
f"May indicate condensation on the sensor or a hardware issue."
),
evidence_json = {"temp_delta": raw.health.temp_delta},
))
# Sensor health — humidity drift
if (raw.health.scd43_present and
raw.health.humidity_delta is not None and
raw.health.humidity_delta > HUMIDITY_DELTA_WARN):
anomalies.append(EnvAnomaly(
id = str(uuid.uuid4()),
type = AnomalyType.humidity_drift,
severity = AnomalySeverity.warn,
chamber_id = self.chamber_id,
message = (
f"Humidity sensors diverging — "
f"{raw.health.humidity_delta:.1f}% RH difference. "
f"Check for condensation on the BME690 sensor."
),
evidence_json = {"humidity_delta": raw.health.humidity_delta},
))
if anomalies:
log.info(
f"[{self.chamber_id}] {len(anomalies)} anomaly(s) detected: "
f"{[a.type.value for a in anomalies]}"
)
return anomalies
# ── CO2e calibration sample collection ────────────────────────────────
def _collect_calibration(
self,
raw: STM32Payload,
points: list[GasSweepPoint],
co2e_ppm: Optional[float],
) -> list[Co2eCalibrationSample]:
"""
Collect a calibration sample when SCD43 CO2 is valid.
Only Zone 1 points (200, 220, 250°C) are used as features.
"""
if not raw.co2 or not raw.co2.valid:
return []
# Extract Zone 1 corrected resistances
z1_points = {
p.heater_temp_c: p.resistance_corr
for p in points
if p.zone == SweepZone.baseline and p.valid and p.resistance_corr is not None
}
sample = Co2eCalibrationSample(
payload_id = 0, # filled in by storage.py after insert
chamber_id = raw.chamber_id,
collected_at = raw.ts,
co2_real = raw.co2.ppm,
r_corr_200 = z1_points.get(200),
r_corr_220 = z1_points.get(220),
r_corr_250 = z1_points.get(250),
humidity_at_read = raw.ambient.humidity_pct,
temp_at_read = raw.ambient.temp_c,
co2e_estimate = co2e_ppm,
model_version = "v0" if not self.co2e_weights else "v1",
)
return [sample]
# ── Baseline builder ──────────────────────────────────────────────────────
class BaselineBuilder:
"""
Accumulates sweep payloads and establishes a baseline
once enough stable samples have been collected.
Call feed() for each new payload.
Once established() returns True, call build() to get the SweepBaseline.
Then reset() for the next run.
Baseline is established when:
- n_samples >= min_samples
- Humidity variance across samples is within tolerance
(prevents establishing a baseline during a humidity swing)
"""
def __init__(
self,
min_samples: int = 6, # 30 min at 5-min intervals
humidity_variance: float = 5.0, # max %RH variance across samples
):
self.min_samples = min_samples
self.humidity_variance = humidity_variance
self._samples: list[STM32Payload] = []
def feed(self, raw: STM32Payload) -> None:
"""Add a payload to the accumulator."""
if raw.ambient.valid:
self._samples.append(raw)
def established(self) -> bool:
"""Return True if enough stable samples have been collected."""
if len(self._samples) < self.min_samples:
return False
recent = self._samples[-self.min_samples:]
humidities = [s.ambient.humidity_pct for s in recent]
variance = max(humidities) - min(humidities)
if variance > self.humidity_variance:
log.debug(
f"Baseline not ready — humidity variance {variance:.1f}% "
f"exceeds {self.humidity_variance}% tolerance"
)
return False
return True
def build(self) -> SweepBaseline:
"""
Build a SweepBaseline from accumulated samples.
Per-point resistance is the mean of corrected values across samples.
"""
recent = self._samples[-self.min_samples:]
# Gather all valid corrected resistances per temperature point
r_by_temp: dict[int, list[float]] = {}
for payload in recent:
for p in payload.sweep:
if p.valid and p.resistance_corr is not None:
r_by_temp.setdefault(p.heater_temp_c, []).append(p.resistance_corr)
# Mean per point
R = {
str(temp): sum(vals) / len(vals)
for temp, vals in r_by_temp.items()
if vals
}
humidities = [s.ambient.humidity_pct 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]
return SweepBaseline(
established = True,
established_at = int(time.time()),
n_samples = len(recent),
R = R,
humidity_ref = sum(humidities) / len(humidities),
temp_ref = sum(temps) / len(temps),
co2_ref = sum(co2_vals) / len(co2_vals) if co2_vals else None,
)
def reset(self) -> None:
self._samples.clear()
@property
def sample_count(self) -> int:
return len(self._samples)
+19
View File
@@ -0,0 +1,19 @@
# cultivar-daemon/requirements.txt
# Grove5 Cultivar — Open source software, honest hardware.
# https://grove5.com
#
# Install: pip install -r requirements.txt
# On UNO Q Debian: pip install -r requirements.txt --break-system-packages
# ── Web framework ─────────────────────────────────────────────────────────
fastapi==0.136.1
uvicorn[standard]==0.46.0 # [standard] includes websockets + httptools
# ── Data validation ───────────────────────────────────────────────────────
pydantic==2.13.3
# ── Database ──────────────────────────────────────────────────────────────
aiosqlite==0.22.1
# ── Serial I/O ────────────────────────────────────────────────────────────
pyserial-asyncio==0.6
+1 -1
View File
@@ -1,7 +1,7 @@
-- ============================================================ -- ============================================================
-- cultivar-daemon / schema.sql -- cultivar-daemon / schema.sql
-- Grove5 Cultivar — Open source software, honest hardware. -- Grove5 Cultivar — Open source software, honest hardware.
-- https://grovefive.com -- https://grove5.com
-- --
-- SQLite schema for the Cultivar environmental data pipeline. -- SQLite schema for the Cultivar environmental data pipeline.
-- Applied at daemon startup via storage.py. -- Applied at daemon startup via storage.py.
+261
View File
@@ -0,0 +1,261 @@
"""
serial_reader.py
Reads JSON payloads from STM32 over serial and validates them.
Grove5 — Open source software, honest hardware.
https://grove5.com
Responsibilities:
- Open and maintain serial connection to STM32
- Read newline-delimited JSON from /dev/ttyS*
- Validate against STM32Payload Pydantic model
- Emit validated payloads to an asyncio queue
- Handle reconnection on serial errors
- Log malformed/invalid payloads for debugging
One ChamberReader instance per chamber (per serial port).
Both instances share a single asyncio queue consumed by the processor.
"""
import asyncio
import json
import logging
from dataclasses import dataclass
from datetime import datetime
import serial_asyncio
from pydantic import ValidationError
from cultivar_types import STM32Payload
log = logging.getLogger(__name__)
# ── Config ────────────────────────────────────────────────────────────────
@dataclass
class SerialConfig:
port: str # e.g. '/dev/ttyS0'
baud: int = 115200
timeout: float = 5.0
reconnect_delay: float = 3.0 # seconds between reconnect attempts
# ── Chamber reader ────────────────────────────────────────────────────────
class ChamberReader:
"""
Async serial reader for one ENV-1 chamber board.
Reads newline-delimited JSON from the STM32, validates it,
and puts valid STM32Payload objects onto the shared queue.
Usage:
queue = asyncio.Queue()
reader = ChamberReader(SerialConfig('/dev/ttyS0'), queue)
asyncio.create_task(reader.run())
"""
def __init__(self, config: SerialConfig, queue: asyncio.Queue):
self.config = config
self.queue = queue
self._running = False
self._rx_count = 0
self._err_count = 0
async def run(self) -> None:
"""Main loop — connects and reads forever, reconnecting on errors."""
self._running = True
log.info(f"[{self.config.port}] Starting chamber reader")
while self._running:
try:
await self._connect_and_read()
except asyncio.CancelledError:
log.info(f"[{self.config.port}] Reader cancelled")
self._running = False
break
except Exception as e:
log.warning(
f"[{self.config.port}] Serial error: {e} — "
f"reconnecting in {self.config.reconnect_delay}s"
)
await asyncio.sleep(self.config.reconnect_delay)
async def stop(self) -> None:
self._running = False
@property
def stats(self) -> dict:
return {
"port": self.config.port,
"rx_count": self._rx_count,
"err_count": self._err_count,
}
# ── Internal ──────────────────────────────────────────────────────────
async def _connect_and_read(self) -> None:
log.info(f"[{self.config.port}] Connecting at {self.config.baud} baud")
reader, _ = await serial_asyncio.open_serial_connection(
url=self.config.port,
baudrate=self.config.baud,
)
log.info(f"[{self.config.port}] Connected")
async for line in self._readlines(reader):
if not self._running:
break
await self._handle_line(line)
async def _readlines(self, reader: asyncio.StreamReader):
"""Yield decoded lines from the serial stream."""
while self._running:
try:
raw = await asyncio.wait_for(
reader.readline(),
timeout=self.config.timeout
)
except asyncio.TimeoutError:
# No data for timeout seconds — not an error, just quiet
log.debug(f"[{self.config.port}] Read timeout (no data)")
continue
if not raw:
log.warning(f"[{self.config.port}] EOF on serial — disconnected?")
return
line = raw.decode("utf-8", errors="replace").strip()
if line:
yield line
async def _handle_line(self, line: str) -> None:
"""Parse and validate a single line of JSON from the STM32."""
# Skip non-JSON lines (startup messages, debug prints)
if not line.startswith("{"):
log.debug(f"[{self.config.port}] Skipping non-JSON: {line[:80]}")
return
# Parse JSON
try:
raw = json.loads(line)
except json.JSONDecodeError as e:
self._err_count += 1
log.warning(f"[{self.config.port}] JSON parse error: {e} — line: {line[:120]}")
return
# Validate against STM32Payload
try:
payload = STM32Payload.model_validate(raw)
except ValidationError as e:
self._err_count += 1
log.warning(
f"[{self.config.port}] Payload validation failed:\n"
f" errors: {e.error_count()}\n"
f" detail: {e.errors(include_url=False)}\n"
f" raw: {line[:200]}"
)
return
self._rx_count += 1
log.info(
f"[{self.config.port}] ✓ payload "
f"chamber={payload.chamber_id} "
f"sweep={len(payload.sweep)}pts "
f"co2={'yes' if payload.co2 and payload.co2.valid else 'no'} "
f"ambient={'ok' if payload.ambient.valid else 'invalid'}"
)
await self.queue.put(payload)
# ── Multi-chamber reader ──────────────────────────────────────────────────
class SerialManager:
"""
Manages multiple ChamberReader instances — one per ENV-1 board.
Usage:
queue = asyncio.Queue()
manager = SerialManager(queue)
manager.add_chamber('/dev/ttyS0')
manager.add_chamber('/dev/ttyS1')
await manager.start()
# ... later ...
await manager.stop()
"""
def __init__(self, queue: asyncio.Queue):
self.queue = queue
self._readers: list[ChamberReader] = []
self._tasks: list[asyncio.Task] = []
def add_chamber(
self,
port: str,
baud: int = 115200,
reconnect_delay: float = 3.0,
) -> None:
config = SerialConfig(
port=port,
baud=baud,
reconnect_delay=reconnect_delay,
)
self._readers.append(ChamberReader(config, self.queue))
log.info(f"Registered chamber on {port}")
async def start(self) -> None:
if not self._readers:
log.warning("SerialManager started with no chambers registered")
return
for reader in self._readers:
task = asyncio.create_task(reader.run())
self._tasks.append(task)
log.info(f"SerialManager started — {len(self._readers)} chamber(s)")
async def stop(self) -> None:
for reader in self._readers:
await reader.stop()
for task in self._tasks:
task.cancel()
await asyncio.gather(*self._tasks, return_exceptions=True)
log.info("SerialManager stopped")
@property
def stats(self) -> list[dict]:
return [r.stats for r in self._readers]
# ── Dev utility: replay from file ─────────────────────────────────────────
async def replay_from_file(path: str, queue: asyncio.Queue, delay: float = 1.0) -> None:
"""
Replay saved JSON payloads from a file into the queue.
Useful for UI development without hardware attached.
File format: one JSON payload per line (same as STM32 output).
Usage:
asyncio.create_task(replay_from_file('samples/fruiting.jsonl', queue))
"""
log.info(f"Replaying payloads from {path} (delay={delay}s)")
with open(path) as f:
lines = [l.strip() for l in f if l.strip().startswith("{")]
for line in lines:
try:
raw = json.loads(line)
payload = STM32Payload.model_validate(raw)
await queue.put(payload)
log.info(f"[replay] queued chamber={payload.chamber_id}")
except Exception as e:
log.warning(f"[replay] skipping invalid line: {e}")
await asyncio.sleep(delay)
log.info(f"[replay] done — {len(lines)} payloads replayed")
+512
View File
@@ -0,0 +1,512 @@
"""
storage.py
SQLite storage layer for the Cultivar environmental data pipeline.
Grove5 — Open source software, honest hardware.
https://grove5.com
Responsibilities:
- Initialize database from schema.sql
- Persist raw STM32 payloads and processed EnvPayloads
- Store and retrieve sweep points
- Manage baselines per chamber/run
- Store anomalies
- Store CO2e calibration samples
- Provide query methods for the API layer
Uses aiosqlite for async access.
All methods are async-safe and use WAL mode for concurrent reads.
"""
import json
import logging
import time
import uuid
from pathlib import Path
from typing import Optional
import aiosqlite
from cultivar_types import (
STM32Payload,
EnvPayload,
EnvAnomaly,
GasSweepPoint,
SweepBaseline,
Run,
RunEndReason,
Co2eCalibrationSample,
)
log = logging.getLogger(__name__)
SCHEMA_PATH = Path(__file__).parent / "schema.sql"
DB_PATH = Path(__file__).parent / "cultivar.db"
# ── Database lifecycle ────────────────────────────────────────────────────
async def init_db(db_path: Path = DB_PATH) -> aiosqlite.Connection:
"""
Open the database, apply schema, return connection.
Safe to call on every startup — all statements use CREATE IF NOT EXISTS.
"""
db = await aiosqlite.connect(db_path)
db.row_factory = aiosqlite.Row
# Apply schema
schema = SCHEMA_PATH.read_text()
await db.executescript(schema)
await db.commit()
# Verify schema version
async with db.execute("SELECT MAX(version) as v FROM schema_version") as cur:
row = await cur.fetchone()
log.info(f"Database ready — schema version {row['v']} at {db_path}")
return db
# ── Runs ──────────────────────────────────────────────────────────────────
async def create_run(
db: aiosqlite.Connection,
chamber_id: str,
species_id: Optional[str] = None,
species_name: Optional[str] = None,
substrate: Optional[str] = None,
notes: Optional[str] = None,
) -> Run:
"""Create a new cultivation run for a chamber."""
run = Run(
id = str(uuid.uuid4()),
chamber_id = chamber_id,
species_id = species_id,
species_name = species_name,
substrate = substrate,
started_at = int(time.time()),
notes = notes,
)
await db.execute(
"""
INSERT INTO runs (id, chamber_id, species_id, species_name, substrate, started_at, notes)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(run.id, run.chamber_id, run.species_id, run.species_name,
run.substrate, run.started_at, run.notes),
)
await db.commit()
log.info(f"[{chamber_id}] Created run {run.id}")
return run
async def end_run(
db: aiosqlite.Connection,
run_id: str,
reason: RunEndReason,
notes: Optional[str] = None,
) -> None:
await db.execute(
"UPDATE runs SET ended_at = ?, end_reason = ?, notes = COALESCE(?, notes) WHERE id = ?",
(int(time.time()), reason.value, notes, run_id),
)
await db.commit()
log.info(f"Run {run_id} ended: {reason.value}")
async def get_active_run(
db: aiosqlite.Connection,
chamber_id: str,
) -> Optional[Run]:
"""Return the active (non-ended) run for a chamber, or None."""
async with db.execute(
"SELECT * FROM runs WHERE chamber_id = ? AND ended_at IS NULL ORDER BY started_at DESC LIMIT 1",
(chamber_id,),
) as cur:
row = await cur.fetchone()
if row:
return Run(**dict(row))
return None
async def get_or_create_run(
db: aiosqlite.Connection,
chamber_id: str,
) -> Run:
"""
Return the active run for a chamber, creating one if none exists.
Used by the processor when no explicit run has been started.
"""
run = await get_active_run(db, chamber_id)
if run:
return run
log.info(f"[{chamber_id}] No active run — creating default run")
return await create_run(db, chamber_id)
# ── Payloads ──────────────────────────────────────────────────────────────
async def insert_payload(
db: aiosqlite.Connection,
raw: STM32Payload,
processed: EnvPayload,
run_id: str,
) -> int:
"""
Persist a payload — both raw JSON and denormalized columns.
Returns the new payload row ID.
"""
raw_json = raw.model_dump_json()
async with db.execute(
"""
INSERT INTO payloads (
run_id, chamber_id, collected_at, received_at, raw_json,
temp_c, humidity_pct, pressure_hpa, ambient_valid,
co2_ppm, co2_valid,
co2e_ppm, co2e_confidence, voc_ppb,
z1_score, z2_score, z3_score,
scd43_present, temp_delta, humidity_delta, temp_ok, humidity_ok,
baseline_established, baseline_samples
) VALUES (
?, ?, ?, ?, ?,
?, ?, ?, ?,
?, ?,
?, ?, ?,
?, ?, ?,
?, ?, ?, ?, ?,
?, ?
)
""",
(
run_id,
raw.chamber_id,
raw.ts,
int(time.time()),
raw_json,
raw.ambient.temp_c,
raw.ambient.humidity_pct,
raw.ambient.pressure_hpa,
int(raw.ambient.valid),
raw.co2.ppm if raw.co2 else None,
int(raw.co2.valid) if raw.co2 else None,
processed.co2e_ppm,
processed.co2e_confidence.value,
processed.voc_ppb,
processed.zone_scores.Z1,
processed.zone_scores.Z2,
processed.zone_scores.Z3,
int(raw.health.scd43_present),
raw.health.temp_delta,
raw.health.humidity_delta,
int(raw.health.temp_ok),
int(raw.health.humidity_ok),
int(raw.baseline.established),
raw.baseline.n_samples,
),
) as cur:
payload_id = cur.lastrowid
await db.commit()
log.debug(f"[{raw.chamber_id}] Inserted payload {payload_id}")
return payload_id
# ── Sweep points ──────────────────────────────────────────────────────────
async def insert_sweep_points(
db: aiosqlite.Connection,
payload_id: int,
chamber_id: str,
collected_at: int,
points: list[GasSweepPoint],
) -> None:
"""Persist all sweep points for a payload."""
rows = [
(
payload_id,
chamber_id,
collected_at,
p.heater_temp_c,
p.heater_dur_ms,
p.zone.value,
p.resistance_raw,
p.resistance_corr,
p.resistance_norm,
int(p.heater_stable),
int(p.valid),
)
for p in points
]
await db.executemany(
"""
INSERT INTO sweep_points (
payload_id, chamber_id, collected_at,
heater_temp_c, heater_dur_ms, zone,
resistance_raw, resistance_corr, resistance_norm,
heater_stable, valid
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
rows,
)
await db.commit()
log.debug(f"[{chamber_id}] Inserted {len(rows)} sweep points for payload {payload_id}")
# ── Baselines ─────────────────────────────────────────────────────────────
async def save_baseline(
db: aiosqlite.Connection,
run_id: str,
chamber_id: str,
baseline: SweepBaseline,
correction_json: Optional[dict] = None,
) -> int:
"""
Save a new established baseline, deactivating any previous one.
Returns the new baseline row ID.
"""
# Deactivate previous baselines for this chamber
await db.execute(
"UPDATE baselines SET active = 0 WHERE chamber_id = ? AND active = 1",
(chamber_id,),
)
async with db.execute(
"""
INSERT INTO baselines (
run_id, chamber_id, established_at, n_samples,
humidity_ref, temp_ref, co2_ref,
resistance_json, correction_json, active
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
""",
(
run_id,
chamber_id,
baseline.established_at or int(time.time()),
baseline.n_samples,
baseline.humidity_ref,
baseline.temp_ref,
baseline.co2_ref,
json.dumps(baseline.R),
json.dumps(correction_json) if correction_json else None,
),
) as cur:
baseline_id = cur.lastrowid
await db.commit()
log.info(f"[{chamber_id}] Saved baseline {baseline_id} ({baseline.n_samples} samples)")
return baseline_id
async def get_active_baseline(
db: aiosqlite.Connection,
chamber_id: str,
) -> Optional[SweepBaseline]:
"""Return the active baseline for a chamber, or None."""
async with db.execute(
"SELECT * FROM baselines WHERE chamber_id = ? AND active = 1 ORDER BY established_at DESC LIMIT 1",
(chamber_id,),
) as cur:
row = await cur.fetchone()
if not row:
return None
return SweepBaseline(
established = True,
established_at = row["established_at"],
n_samples = row["n_samples"],
R = json.loads(row["resistance_json"]),
humidity_ref = row["humidity_ref"],
temp_ref = row["temp_ref"],
co2_ref = row["co2_ref"],
)
# ── Anomalies ─────────────────────────────────────────────────────────────
async def insert_anomaly(
db: aiosqlite.Connection,
anomaly: EnvAnomaly,
payload_id: Optional[int] = None,
run_id: Optional[str] = None,
) -> None:
await db.execute(
"""
INSERT OR IGNORE INTO anomalies (
id, payload_id, run_id, chamber_id, detected_at,
type, severity, message, contaminant_hint,
evidence_json, dismissed
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)
""",
(
anomaly.id,
payload_id,
run_id,
anomaly.chamber_id,
anomaly.ts,
anomaly.type.value,
anomaly.severity.value,
anomaly.message,
anomaly.contaminant_hint,
json.dumps(anomaly.evidence_json) if anomaly.evidence_json else None,
),
)
await db.commit()
log.info(f"[{anomaly.chamber_id}] Anomaly: {anomaly.type.value} — {anomaly.severity.value}")
async def dismiss_anomaly(db: aiosqlite.Connection, anomaly_id: str) -> None:
await db.execute(
"UPDATE anomalies SET dismissed = 1, dismissed_at = ? WHERE id = ?",
(int(time.time()), anomaly_id),
)
await db.commit()
async def get_active_anomalies(
db: aiosqlite.Connection,
chamber_id: str,
limit: int = 20,
) -> list[dict]:
"""Return undismissed anomalies for a chamber, newest first."""
async with db.execute(
"""
SELECT * FROM anomalies
WHERE chamber_id = ? AND dismissed = 0
ORDER BY detected_at DESC
LIMIT ?
""",
(chamber_id, limit),
) as cur:
rows = await cur.fetchall()
return [dict(r) for r in rows]
# ── CO2e calibration ──────────────────────────────────────────────────────
async def insert_co2e_sample(
db: aiosqlite.Connection,
sample: Co2eCalibrationSample,
) -> None:
await db.execute(
"""
INSERT INTO co2e_calibration (
payload_id, chamber_id, collected_at, species_id,
co2_real, r_corr_200, r_corr_220, r_corr_250,
humidity_at_read, temp_at_read,
co2e_estimate, model_version
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
sample.payload_id,
sample.chamber_id,
sample.collected_at,
sample.species_id,
sample.co2_real,
sample.r_corr_200,
sample.r_corr_220,
sample.r_corr_250,
sample.humidity_at_read,
sample.temp_at_read,
sample.co2e_estimate,
sample.model_version,
),
)
await db.commit()
# ── History queries ───────────────────────────────────────────────────────
async def get_environment_history(
db: aiosqlite.Connection,
chamber_id: str,
since: int, # unix ts
limit: int = 288, # 24h at 5min intervals
) -> list[dict]:
"""
Return environment readings for a chamber since a given timestamp.
Used by the API to serve EnvironmentReading history to the UI.
"""
async with db.execute(
"""
SELECT
collected_at AS ts,
temp_c,
humidity_pct AS rh_pct,
co2_ppm,
co2e_ppm,
voc_ppb,
z1_score,
z2_score,
z3_score,
pressure_hpa,
baseline_established
FROM payloads
WHERE chamber_id = ? AND collected_at >= ? AND ambient_valid = 1
ORDER BY collected_at ASC
LIMIT ?
""",
(chamber_id, since, limit),
) as cur:
rows = await cur.fetchall()
return [dict(r) for r in rows]
async def get_sweep_history(
db: aiosqlite.Connection,
chamber_id: str,
since: int,
limit: int = 288,
) -> list[dict]:
"""
Return sweep point history for a chamber.
Used to build the heatmap visualization.
Each row is one sweep point — group by collected_at for full sweeps.
"""
async with db.execute(
"""
SELECT
collected_at,
heater_temp_c,
zone,
resistance_raw,
resistance_corr,
resistance_norm,
heater_stable,
valid
FROM sweep_points
WHERE chamber_id = ? AND collected_at >= ? AND valid = 1
ORDER BY collected_at ASC, heater_temp_c ASC
LIMIT ?
""",
(chamber_id, since, limit * 10), # 10 points per payload
) as cur:
rows = await cur.fetchall()
return [dict(r) for r in rows]
async def get_latest_payload(
db: aiosqlite.Connection,
chamber_id: str,
) -> Optional[dict]:
"""Return the most recent payload for a chamber."""
async with db.execute(
"""
SELECT * FROM payloads
WHERE chamber_id = ? AND ambient_valid = 1
ORDER BY collected_at DESC
LIMIT 1
""",
(chamber_id,),
) as cur:
row = await cur.fetchone()
return dict(row) if row else None