added schema.sql

This commit is contained in:
grove5_admin committed 2026-04-27 18:49:32 -07:00
1 parent a53a499e80
commit 77774a725b
1 file changed
+249
+249
View File
@@ -0,0 +1,249 @@
-- ============================================================
-- cultivar-daemon / schema.sql
-- Grove5 Cultivar — Open source software, honest hardware.
-- https://grovefive.com
--
-- SQLite schema for the Cultivar environmental data pipeline.
-- Applied at daemon startup via storage.py.
--
-- Design principles:
-- - raw_json is never discarded — always the source of truth
-- - denormalized columns exist for query performance only
-- - sweep_points are normalized for time-series queries
-- - baseline and anomaly tables are daemon-managed, not firmware
-- - all timestamps are Unix epoch seconds (INTEGER)
-- ============================================================
PRAGMA journal_mode = WAL;
PRAGMA foreign_keys = ON;
-- ── Cultivation runs ──────────────────────────────────────────────────────
-- A run tracks one cultivation cycle in one chamber,
-- from inoculation to harvest (or abort).
CREATE TABLE IF NOT EXISTS runs (
id TEXT PRIMARY KEY, -- UUID, generated by daemon
chamber_id TEXT NOT NULL, -- 'colonization' | 'fruiting'
species_id TEXT, -- SP-xxx from species.ts
species_name TEXT, -- denormalized for readability
substrate TEXT,
started_at INTEGER NOT NULL, -- unix ts
ended_at INTEGER, -- null until harvest/abort
end_reason TEXT, -- 'harvest' | 'abort' | 'contamination'
notes TEXT,
created_at INTEGER NOT NULL DEFAULT (unixepoch())
);
CREATE INDEX IF NOT EXISTS idx_runs_chamber ON runs (chamber_id);
CREATE INDEX IF NOT EXISTS idx_runs_started ON runs (started_at);
-- ── Environmental payloads ────────────────────────────────────────────────
-- One row per collection cycle per chamber (~every 5 minutes).
-- raw_json is the full STM32 output, preserved forever.
-- Denormalized columns are derived from raw_json for fast queries.
CREATE TABLE IF NOT EXISTS payloads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
run_id TEXT REFERENCES runs(id) ON DELETE SET NULL,
chamber_id TEXT NOT NULL,
collected_at INTEGER NOT NULL, -- unix ts from STM32 millis, adjusted
received_at INTEGER NOT NULL DEFAULT (unixepoch()),
raw_json TEXT NOT NULL,
-- Ambient (BME690, heater off)
temp_c REAL,
humidity_pct REAL,
pressure_hpa REAL,
ambient_valid INTEGER, -- bool
-- CO2 (SCD43, fruiting only)
co2_ppm INTEGER,
co2_valid INTEGER, -- bool
-- Derived on Linux side
co2e_ppm REAL, -- null until baseline established
co2e_confidence TEXT, -- 'uncalibrated'|'low'|'medium'|'high'
voc_ppb REAL, -- Zone 2 score scaled to ppb
-- Zone scores (derived)
z1_score REAL, -- baseline zone mean (corr, norm)
z2_score REAL, -- biological zone mean (corr, norm)
z3_score REAL, -- heavy zone mean (corr, norm)
-- Sensor health
scd43_present INTEGER, -- bool
temp_delta REAL, -- abs(bme_temp - scd43_temp)
humidity_delta REAL, -- abs(bme_hum - scd43_hum)
temp_ok INTEGER, -- bool
humidity_ok INTEGER, -- bool
-- Baseline state at time of collection
baseline_established INTEGER, -- bool
baseline_samples INTEGER
);
CREATE INDEX IF NOT EXISTS idx_payloads_chamber ON payloads (chamber_id);
CREATE INDEX IF NOT EXISTS idx_payloads_collected ON payloads (collected_at);
CREATE INDEX IF NOT EXISTS idx_payloads_run ON payloads (run_id);
-- ── Gas sweep points ──────────────────────────────────────────────────────
-- One row per heater profile point per payload (10 rows per payload).
-- Resistance values progress through three processing stages:
-- raw → corrected (humidity) → normalized (baseline)
CREATE TABLE IF NOT EXISTS sweep_points (
id INTEGER PRIMARY KEY AUTOINCREMENT,
payload_id INTEGER NOT NULL REFERENCES payloads(id) ON DELETE CASCADE,
chamber_id TEXT NOT NULL,
collected_at INTEGER NOT NULL, -- denormalized for time-series queries
-- Profile config
heater_temp_c INTEGER NOT NULL, -- 200|220|250|280|300|320|340|360|380|400
heater_dur_ms INTEGER NOT NULL,
zone INTEGER NOT NULL, -- 1|2|3
-- Resistance progression
resistance_raw REAL, -- Ω from STM32
resistance_corr REAL, -- humidity corrected (null until processed)
resistance_norm REAL, -- baseline normalized (null until baseline)
-- Validity flags
heater_stable INTEGER, -- bool
valid INTEGER -- bool
);
CREATE INDEX IF NOT EXISTS idx_sweep_payload ON sweep_points (payload_id);
CREATE INDEX IF NOT EXISTS idx_sweep_chamber_time ON sweep_points (chamber_id, collected_at);
CREATE INDEX IF NOT EXISTS idx_sweep_temp ON sweep_points (heater_temp_c);
-- ── Baselines ─────────────────────────────────────────────────────────────
-- One active baseline per chamber per run.
-- Stores per-point reference resistance and the environmental
-- conditions under which the baseline was established.
CREATE TABLE IF NOT EXISTS baselines (
id INTEGER PRIMARY KEY AUTOINCREMENT,
run_id TEXT NOT NULL REFERENCES runs(id) ON DELETE CASCADE,
chamber_id TEXT NOT NULL,
established_at INTEGER NOT NULL,
n_samples INTEGER NOT NULL, -- number of sweeps averaged
-- Environmental reference conditions at baseline
humidity_ref REAL NOT NULL,
temp_ref REAL NOT NULL,
co2_ref REAL, -- null if SCD43 not present
-- Per-point baseline resistance (JSON object: {"200": 85000000, "220": ...})
-- Stored as JSON for flexibility — queried rarely, updated infrequently
resistance_json TEXT NOT NULL,
-- Humidity correction coefficients (fit from calibration data)
-- JSON: {"200": {"k": 0.021}, "220": {"k": 0.019}, ...}
-- null until calibration data available
correction_json TEXT,
active INTEGER NOT NULL DEFAULT 1, -- bool, only one active per chamber
created_at INTEGER NOT NULL DEFAULT (unixepoch())
);
CREATE INDEX IF NOT EXISTS idx_baselines_run ON baselines (run_id);
CREATE INDEX IF NOT EXISTS idx_baselines_chamber ON baselines (chamber_id, active);
-- ── Anomalies ─────────────────────────────────────────────────────────────
-- Detected by the daemon processor, surfaced in the UI as
-- Cultivar Rhythm tasks and environment alerts.
CREATE TABLE IF NOT EXISTS anomalies (
id TEXT PRIMARY KEY, -- UUID
payload_id INTEGER REFERENCES payloads(id) ON DELETE SET NULL,
run_id TEXT REFERENCES runs(id) ON DELETE SET NULL,
chamber_id TEXT NOT NULL,
detected_at INTEGER NOT NULL DEFAULT (unixepoch()),
-- Classification
type TEXT NOT NULL, -- EnvAnomalyType values
severity TEXT NOT NULL, -- 'info'|'warn'|'critical'
-- Human-readable, Cultivar-voice message
message TEXT NOT NULL,
-- Optional link to field guide contaminant
contaminant_hint TEXT, -- CONT-xxx id
-- Supporting data (JSON) — zone scores, deltas, etc. at time of detection
evidence_json TEXT,
dismissed INTEGER NOT NULL DEFAULT 0, -- bool
dismissed_at INTEGER
);
CREATE INDEX IF NOT EXISTS idx_anomalies_chamber ON anomalies (chamber_id);
CREATE INDEX IF NOT EXISTS idx_anomalies_run ON anomalies (run_id);
CREATE INDEX IF NOT EXISTS idx_anomalies_detected ON anomalies (detected_at);
CREATE INDEX IF NOT EXISTS idx_anomalies_dismissed ON anomalies (dismissed);
-- ── CO2e calibration samples ──────────────────────────────────────────────
-- Paired (real CO2, sweep fingerprint) samples collected during
-- runs with both sensors populated.
-- Used to fit CO2e model weights on the Linux side.
-- Accumulates across runs — more data = better model.
CREATE TABLE IF NOT EXISTS co2e_calibration (
id INTEGER PRIMARY KEY AUTOINCREMENT,
payload_id INTEGER NOT NULL REFERENCES payloads(id) ON DELETE CASCADE,
chamber_id TEXT NOT NULL,
collected_at INTEGER NOT NULL,
species_id TEXT, -- training label
-- Ground truth
co2_real INTEGER NOT NULL, -- SCD43 reading (ppm)
-- Features (Zone 1 corrected resistances, humidity-corrected)
r_corr_200 REAL,
r_corr_220 REAL,
r_corr_250 REAL,
-- Correction factors applied
humidity_at_read REAL,
temp_at_read REAL,
-- Model output at time of collection (for drift tracking)
co2e_estimate REAL,
model_version TEXT
);
CREATE INDEX IF NOT EXISTS idx_co2e_cal_chamber ON co2e_calibration (chamber_id);
CREATE INDEX IF NOT EXISTS idx_co2e_cal_species ON co2e_calibration (species_id);
-- ── Device metadata ───────────────────────────────────────────────────────
-- One row, updated by daemon on startup and periodically.
CREATE TABLE IF NOT EXISTS device (
id INTEGER PRIMARY KEY DEFAULT 1, -- singleton
device_id TEXT NOT NULL,
firmware_version TEXT,
daemon_version TEXT,
first_seen_at INTEGER NOT NULL DEFAULT (unixepoch()),
last_seen_at INTEGER NOT NULL DEFAULT (unixepoch()),
notes TEXT
);
-- ── Schema version ────────────────────────────────────────────────────────
-- Incremented on every migration. Checked by daemon at startup.
CREATE TABLE IF NOT EXISTS schema_version (
version INTEGER PRIMARY KEY,
applied_at INTEGER NOT NULL DEFAULT (unixepoch()),
description TEXT
);
INSERT OR IGNORE INTO schema_version (version, description)
VALUES (1, 'Initial schema — runs, payloads, sweep_points, baselines, anomalies, co2e_calibration');