Improved env monitoring section

This commit is contained in:
grove5_admin committed 2026-05-01 09:12:46 -07:00
1 parent 8233bfd33a
commit 6e54786813
6 files changed
+578 -167

No files matched your search

+2 -5
View File
@@ -26,13 +26,10 @@
router.navigate({ page: 'overview' });
}
// Start mock WebSocket on mount
// Start WebSocket (mock or live) on mount. Live path handles initial
// per-chamber history backfill internally; no separate call needed.
$effect(() => {
cultivar.startMockWs();
// Backfill history from daemon if live
cultivar.loadHistory('colonization', 24);
cultivar.loadHistory('fruiting', 24);
return () => cultivar.stopMockWs();
});
+131 -18
View File
@@ -8,8 +8,16 @@
healthyRange?: [number, number] | null;
yMin?: number | null;
yMax?: number | null;
/** Minimum height reserved for the plot (forced padding if series is flat) */
smooth?: boolean;
/**
* When true, the chart accepts pointer/touch input and emits scrub
* events. Parent renders the value + timestamp at the scrubbed point.
* Robinhood-style: press-and-hold or hover to read a historical value,
* release to return to current.
*/
interactive?: boolean;
/** Fired with the nearest data point while scrubbing, null on release. */
onScrub?: (point: TimeSeriesPoint | null) => void;
}
const {
@@ -19,20 +27,26 @@
yMin = null,
yMax = null,
smooth = false,
interactive = false,
onScrub,
}: Props = $props();
const uid = $derived(
`lc-${color.replace(/[^a-z0-9]/gi, '').slice(0, 6)}-${Math.random().toString(36).slice(2, 6)}`
);
const paths = $derived.by(() => {
if (data.length < 2) return { line: '', area: '', lo: 0, hi: 1, loP: 0, hiP: 1 };
// Domain + projected coordinates in a single derived so the scrub
// crosshair math reuses the exact same mapping as the path.
const projected = $derived.by(() => {
if (data.length < 2) {
return { pts: [] as Array<TimeSeriesPoint & { x: number; y: number }>,
line: '', area: '', loP: 0, hiP: 1 };
}
const minTs = data[0].ts;
const span = (data[data.length - 1].ts - minTs) || 1;
const vals = data.map(d => d.value);
const lo = yMin ?? Math.min(...vals);
const hi = yMax ?? Math.max(...vals);
// Extend the domain to cover the healthy range, so it's always visible
const loR = healthyRange ? Math.min(lo, healthyRange[0]) : lo;
const hiR = healthyRange ? Math.max(hi, healthyRange[1]) : hi;
const pad = Math.max((hiR - loR) * 0.12, 0.5);
@@ -43,28 +57,104 @@
const px = (ts: number) => ((ts - minTs) / span) * 100;
const py = (v: number) => 100 - ((v - loP) / range) * 100;
const line = data.map((p, i) =>
`${i === 0 ? 'M' : 'L'}${px(p.ts).toFixed(2)},${py(p.value).toFixed(2)}`
const pts = data.map(d => ({ ...d, x: px(d.ts), y: py(d.value) }));
const line = pts.map((p, i) =>
`${i === 0 ? 'M' : 'L'}${p.x.toFixed(2)},${p.y.toFixed(2)}`
).join(' ');
const lastX = px(data[data.length - 1].ts).toFixed(2);
const lastX = pts[pts.length - 1].x.toFixed(2);
const area = `${line} L${lastX},100 L0,100 Z`;
return { line, area, lo, hi, loP, hiP };
return { pts, line, area, loP, hiP };
});
// Project healthy range onto 0-100 y space
const healthyPx = $derived.by(() => {
if (!healthyRange) return null;
const { loP, hiP } = paths;
const { loP, hiP } = projected;
const range = hiP - loP || 1;
const yHi = 100 - ((healthyRange[1] - loP) / range) * 100;
const yLo = 100 - ((healthyRange[0] - loP) / range) * 100;
return { yHi, yLo, h: Math.max(0.1, yLo - yHi) };
});
// ── Scrub interaction ───────────────────────────────────────────────
let scrubIdx = $state<number | null>(null);
let svgEl: SVGSVGElement | undefined;
const scrubPt = $derived(
scrubIdx !== null && projected.pts[scrubIdx] ? projected.pts[scrubIdx] : null
);
function nearestIndex(clientX: number): number | null {
if (!svgEl || projected.pts.length < 2) return null;
const rect = svgEl.getBoundingClientRect();
if (rect.width <= 0) return null;
const xPct = Math.max(0, Math.min(100, ((clientX - rect.left) / rect.width) * 100));
// Binary search would be marginally faster but series are short (≤120
// after downsampling) so linear scan is fine and simpler.
let best = 0, bestDist = Infinity;
for (let i = 0; i < projected.pts.length; i++) {
const d = Math.abs(projected.pts[i].x - xPct);
if (d < bestDist) { bestDist = d; best = i; }
}
return best;
}
function updateScrub(clientX: number) {
const i = nearestIndex(clientX);
if (i === null) return;
if (i !== scrubIdx) {
scrubIdx = i;
onScrub?.({ ts: projected.pts[i].ts, value: projected.pts[i].value });
}
}
function endScrub() {
if (scrubIdx === null) return;
scrubIdx = null;
onScrub?.(null);
}
function handlePointerDown(e: PointerEvent) {
if (!interactive) return;
(e.currentTarget as Element).setPointerCapture?.(e.pointerId);
updateScrub(e.clientX);
}
function handlePointerMove(e: PointerEvent) {
if (!interactive) return;
// Mouse hover (no button held) → scrub; touch only scrubs when pressed
// because the element will have captured the pointer in pointerdown.
if (e.pointerType === 'mouse' || e.buttons > 0) {
updateScrub(e.clientX);
}
}
function handlePointerLeave(e: PointerEvent) {
if (!interactive) return;
// For touch, pointerleave fires on release; for mouse it fires on exit.
endScrub();
(e.currentTarget as Element).releasePointerCapture?.(e.pointerId);
}
function handlePointerUp(e: PointerEvent) {
if (!interactive) return;
endScrub();
(e.currentTarget as Element).releasePointerCapture?.(e.pointerId);
}
</script>
<svg class="lc" viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true">
<svg
bind:this={svgEl}
class="lc"
class:interactive
class:scrubbing={scrubIdx !== null}
viewBox="0 0 100 100"
preserveAspectRatio="none"
role={interactive ? 'img' : undefined}
aria-hidden={interactive ? undefined : true}
onpointerdown={handlePointerDown}
onpointermove={handlePointerMove}
onpointerleave={handlePointerLeave}
onpointerup={handlePointerUp}
onpointercancel={handlePointerUp}
>
<defs>
<linearGradient id="{uid}" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color={color} stop-opacity="0.2"/>
@@ -72,7 +162,6 @@
</linearGradient>
</defs>
<!-- Healthy-range band (green) -->
{#if healthyPx}
<rect x="0" y={healthyPx.yHi} width="100" height={healthyPx.h}
fill="#2b5a34" opacity="0.075"/>
@@ -84,15 +173,29 @@
vector-effect="non-scaling-stroke"/>
{/if}
{#if paths.area}
<path d={paths.area} fill="url(#{uid})"/>
{#if projected.area}
<path d={projected.area} fill="url(#{uid})"/>
{/if}
{#if paths.line}
<path d={paths.line} fill="none" stroke={color}
{#if projected.line}
<path d={projected.line} fill="none" stroke={color}
stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"
vector-effect="non-scaling-stroke"/>
{/if}
<!-- Scrub crosshair + dot. Rendered last so it sits above the line. -->
{#if scrubPt}
<line
x1={scrubPt.x} x2={scrubPt.x} y1="0" y2="100"
stroke={color} stroke-width="0.75" stroke-dasharray="1.5 2"
opacity="0.55" vector-effect="non-scaling-stroke"
/>
<circle
cx={scrubPt.x} cy={scrubPt.y} r="2.5"
fill="var(--paper, #fbf7ec)" stroke={color} stroke-width="1.25"
vector-effect="non-scaling-stroke"
/>
{/if}
</svg>
<style>
@@ -100,7 +203,17 @@
display: block;
width: 100%;
height: 100%;
max-height: 28px; /* ← add this */
max-height: 40px;
overflow: visible;
}
/* Interactive charts get a slightly taller, cursor-forward hit target.
touch-action: pan-y lets vertical page scroll continue to work while
horizontal drags are captured for scrubbing. */
.lc.interactive {
cursor: crosshair;
touch-action: pan-y;
}
.lc.interactive.scrubbing {
cursor: crosshair;
}
</style>
+17
View File
@@ -28,6 +28,10 @@ function genSweep(baselineR: number, drift: number, anomaly = false): GasSweepPo
resistance_raw: Math.round(raw),
resistance_corr: Math.round(raw * 0.95),
resistance_norm: Math.round((raw / baselineR) * 100) / 100,
adc_gas_res: 400 + Math.floor(Math.random() * 200),
gas_range: p.zone === 1 ? 13 : p.zone === 2 ? 11 : 9,
res_heat: 100 + p.zone * 20,
idac: 60 + Math.floor(Math.random() * 40),
heater_stable: true,
valid: true,
};
@@ -45,6 +49,7 @@ function genBaseline(): SweepBaseline {
humidity_ref: 87,
temp_ref: 22.5,
co2_ref: 1200,
bme_temp_offset: 4.3,
};
}
@@ -159,6 +164,9 @@ const fullMockState: CultivarState = {
co2e_ppm: 1380,
voc_ppb: 44,
},
history: genEnvHistory(),
last_update_ts: NOW,
burn_in: false,
latestSweep: genSweep(150000, 0.02, true),
baseline: genBaseline(),
slots: [
@@ -292,6 +300,9 @@ const fullMockState: CultivarState = {
co2_ppm: 820,
voc_ppb: 61,
},
history: genEnvHistory(),
last_update_ts: NOW,
burn_in: false,
latestSweep: genSweep(145000, 0.01, false),
baseline: genBaseline(),
slots: [
@@ -482,6 +493,9 @@ const minimalState: CultivarState = {
label: 'Colonization',
type: 'colonization',
environment: { temp_c: 0, rh_pct: 0, co2e_ppm: 0, voc_ppb: 0 },
history: [],
last_update_ts: null,
burn_in: false,
slots: [],
},
{
@@ -489,6 +503,9 @@ const minimalState: CultivarState = {
label: 'Fruiting',
type: 'fruiting',
environment: { temp_c: 0, rh_pct: 0, co2_ppm: 0, voc_ppb: 0 },
history: [],
last_update_ts: null,
burn_in: false,
slots: [],
},
],
+90 -25
View File
@@ -30,11 +30,26 @@ function calcVpd(temp_c: number, rh_pct: number): number {
return svp * (1 - rh_pct / 100);
}
// Ring-buffer cap for per-chamber / global history. 1441 minutes = 24h at
// 1-min resolution, which matches what the backfill endpoint returns.
const HISTORY_MAX = 1441;
function createStore() {
// @ts-ignore
const initialState = (import.meta as any).env?.DEV ? fullMockState : minimalState;
let state = $state<CultivarState>(deepClone(initialState));
// Onboarding completion persists to localStorage. Both mock and
// minimal initial states default to the wrong value for a returning
// user — the mock reads localStorage inline but minimalState doesn't,
// and the IDE/dev build can reset either. Single source of truth here.
try {
state.ui.onboarding_complete =
localStorage.getItem('onboarding_complete') === 'true';
} catch {
/* SSR / private-mode fallbacks keep whatever the initial state had */
}
// Seed maintenance timestamps on first-time startup so cadence measures
// "days since first boot", not "days since the Unix epoch".
const nowTs = Math.floor(Date.now() / 1000);
@@ -91,7 +106,12 @@ function createStore() {
const ambient = payload.ambient;
if (!ambient.valid) return;
// Update chamber live environment
const now = Math.floor(Date.now() / 1000);
// Update chamber live environment — ambient T/H is always safe to
// publish (sampled before the heater fires, per BME690 datasheet),
// even during burn-in. Gas-derived metrics (voc_ppb) are null during
// burn-in per the daemon contract.
chamber.environment.temp_c = ambient.temp_c;
chamber.environment.rh_pct = ambient.humidity_pct;
@@ -105,39 +125,44 @@ function createStore() {
chamber.environment.voc_ppb = payload.voc_ppb;
}
// Update global live environment from fruiting chamber
// (fruiting has SCD43 — most accurate temp/humidity/CO2)
chamber.last_update_ts = now;
chamber.burn_in = payload.burn_in;
chamber.latestSweep = payload.sweep;
chamber.baseline = payload.baseline;
// Per-chamber history ring buffer. voc_ppb is undefined (not 0) when
// the daemon didn't compute it — charts must distinguish "no data"
// from "zero ppb".
const reading: EnvironmentReading = {
ts: now,
temp_c: ambient.temp_c,
rh_pct: ambient.humidity_pct,
co2_ppm: payload.co2?.valid ? payload.co2.ppm : (chamber.environment.co2_ppm ?? 0),
co2e_ppm: payload.co2e_ppm ?? undefined,
voc_ppb: payload.voc_ppb ?? 0,
vpd: calcVpd(ambient.temp_c, ambient.humidity_pct),
};
chamber.history.push(reading);
if (chamber.history.length > HISTORY_MAX) chamber.history.shift();
// Mirror fruiting into the legacy global env.live / env.history for
// the top-bar health score and any code still reading the pre-
// per-chamber shape. Fruiting is the canonical source because it
// carries SCD43 (real CO2).
if (chamber.type === 'fruiting') {
state.environment.live.temp_c = ambient.temp_c;
state.environment.live.rh_pct = ambient.humidity_pct;
state.environment.live.voc_ppb = payload.voc_ppb ?? state.environment.live.voc_ppb;
state.environment.live.vpd = calcVpd(ambient.temp_c, ambient.humidity_pct);
if (payload.co2?.valid) state.environment.live.co2_ppm = payload.co2.ppm;
if (payload.co2?.valid) {
state.environment.live.co2_ppm = payload.co2.ppm;
}
// Push to history ring buffer
const reading: EnvironmentReading = {
ts: Math.floor(Date.now() / 1000),
temp_c: ambient.temp_c,
rh_pct: ambient.humidity_pct,
co2_ppm: payload.co2?.ppm ?? state.environment.live.co2_ppm,
co2e_ppm: payload.co2e_ppm ?? undefined,
voc_ppb: payload.voc_ppb ?? 0,
vpd: calcVpd(ambient.temp_c, ambient.humidity_pct),
};
state.environment.history.push(reading);
if (state.environment.history.length > 1441) {
if (state.environment.history.length > HISTORY_MAX) {
state.environment.history.shift();
}
}
// Stash latest sweep + baseline for radar chart
(chamber as any).latestSweep = payload.sweep;
(chamber as any).baseline = payload.baseline;
state.meta.timestamp_utc = Math.floor(Date.now() / 1000);
state.meta.timestamp_utc = now;
// Surface anomalies as alerts
for (const anomaly of payload.anomalies) {
@@ -252,9 +277,16 @@ function createStore() {
// ── Mock WebSocket ─────────────────────────────────────────────────────────
// Entry point used by App.svelte on mount. Name kept for backward
// compatibility; when a real daemon URL is configured it connects the
// live WebSocket, otherwise it spins up the mock ticker.
function startMockWs() {
if (WS_URL) {
// Real daemon available — use it instead
// Real daemon available. Backfill history per-chamber on boot so
// the UI isn't showing zeros until the next live payload. The WS
// onopen handler also calls loadHistory for reconnect resyncs.
loadHistory('colonization', 24);
loadHistory('fruiting', 24);
connectWs();
return;
}
@@ -308,9 +340,42 @@ function createStore() {
vpd: calcVpd(r.temp_c ?? 0, r.rh_pct ?? 0),
}));
// Backfill global environment history from fruiting (has SCD43 — most accurate)
// Seed the chamber's history AND live environment from the latest
// row. Without this, chamber.environment stays at zero until the
// next live WS payload arrives — which is what the user sees as
// "zeros on refresh".
const chamber = state.chambers.find(c => c.id === chamber_id);
if (chamber) {
chamber.history = readings;
const last = readings[readings.length - 1];
if (last) {
chamber.environment.temp_c = last.temp_c;
chamber.environment.rh_pct = last.rh_pct;
if (chamber.type === 'fruiting') {
chamber.environment.co2_ppm = last.co2_ppm;
} else {
chamber.environment.co2e_ppm = last.co2e_ppm ?? last.co2_ppm;
}
chamber.environment.voc_ppb = last.voc_ppb;
chamber.last_update_ts = last.ts;
}
}
// Mirror fruiting into the legacy global env for the top-bar
// health score and anything still reading env.live directly.
if (chamber_id === 'fruiting') {
state.environment.history = readings;
const last = readings[readings.length - 1];
if (last) {
state.environment.live.temp_c = last.temp_c;
state.environment.live.rh_pct = last.rh_pct;
state.environment.live.co2_ppm = last.co2_ppm;
state.environment.live.voc_ppb = last.voc_ppb;
state.environment.live.vpd = last.vpd;
if (last.co2e_ppm !== undefined) {
state.environment.live.co2e_ppm = last.co2e_ppm;
}
}
}
} catch (e) {
console.warn(`[cultivar] Failed to load history for ${chamber_id}`, e);
+35 -2
View File
@@ -64,9 +64,24 @@ export type Chamber = {
type: 'colonization' | 'fruiting';
environment: ChamberEnvironment;
slots: ChamberSlot[];
/** Latest gas sweep data for radar chart (BME688) */
/**
* Per-chamber history ring buffer. Rehydrated from the daemon on
* connect via /api/environment/:id/history and appended on every
* live EnvPayload. null values allowed — daemon may omit metrics
* during burn-in or when a sensor is unavailable.
*/
history: EnvironmentReading[];
/**
* Unix seconds of the last payload applied for this chamber.
* null means we have never seen data for this chamber — callers
* should render a placeholder rather than the zeroed environment.
*/
last_update_ts: number | null;
/** True while the firmware is still conditioning the MOX hotplate. */
burn_in: boolean;
/** Latest gas sweep data for radar chart (BME690) */
latestSweep?: GasSweepPoint[];
/** Baseline sweep profile for comparison (BME688) */
/** Baseline sweep profile for comparison (BME690) */
baseline?: SweepBaseline;
};
@@ -170,6 +185,10 @@ export type GasSweepPoint = {
resistance_raw: number;
resistance_corr: number | null; // humidity corrected
resistance_norm: number | null; // baseline normalized
adc_gas_res: number | null; // raw 10-bit gas ADC from BME690
gas_range: number | null; // gas range 0-15 (affects resistance calc)
res_heat: number | null; // heater resistance register (DAC target)
idac: number | null; // initial heater DAC drive
heater_stable: boolean;
valid: boolean;
};
@@ -188,6 +207,13 @@ export type SweepBaseline = {
humidity_ref: number;
temp_ref: number;
co2_ref: number | null;
/**
* Mean BME690 temp bias vs SCD43 across the baseline window.
* Used by the daemon to correct BME ambient readings into a single
* calibrated source for humidity correction. null when SCD43 was
* unavailable during baseline establishment.
*/
bme_temp_offset: number | null;
};
export type SensorHealth = {
@@ -217,6 +243,13 @@ export type EnvPayload = {
sweep: GasSweepPoint[];
zone_scores: ZoneScores;
baseline: SweepBaseline;
/**
* True while the firmware is conditioning the MOX hotplate. Payloads
* are still emitted during this window but gas-derived metrics
* (voc_ppb, zone_scores) are suppressed and must not be used for
* fingerprinting or UI signal.
*/
burn_in: boolean;
health: SensorHealth;
anomalies: EnvAnomaly[];
};
+303 -117
View File
@@ -3,7 +3,7 @@
import LineChart from '../charts/LineChart.svelte';
import InfoHint from './InfoHint.svelte';
import SweepRadar from '../charts/SweepRadar.svelte';
import type { TimeSeriesPoint, EnvironmentReading, Chamber, ChamberEnvironment, GasSweepPoint, SweepBaseline } from '../types';
import type { TimeSeriesPoint, EnvironmentReading, Chamber, GasSweepPoint, SweepBaseline } from '../types';
type Win = '1h' | '6h' | '24h';
let activeWin = $state<Win>('24h');
@@ -12,30 +12,70 @@
const winMs: Record<Win, number> = { '1h': 0, '6h': 30_000, '24h': 120_000 };
const chambers = $derived(cultivar.state.chambers);
const colonization = $derived(chambers.find(c => c.type === 'colonization') ?? chambers[0] ?? { type: 'colonization', environment: { temp_c: 0, rh_pct: 0 } });
const fruiting = $derived(chambers.find(c => c.type === 'fruiting') ?? chambers[1] ?? { type: 'fruiting', environment: { temp_c: 0, rh_pct: 0 } });
// Latest sweep per chamber — stashed by applyEnvPayload
const colSweep = $derived((colonization as any).latestSweep as GasSweepPoint[] ?? []);
const colBaseline = $derived((colonization as any).baseline as SweepBaseline ?? null);
const fruitSweep = $derived((fruiting as any).latestSweep as GasSweepPoint[] ?? []);
const fruitBaseline = $derived((fruiting as any).baseline as SweepBaseline ?? null);
// Only render chambers that have actually streamed data. This prevents
// the second chamber showing a full column of zeros + "drift" chips
// when only one chamber is plumbed in.
const visibleChambers = $derived(chambers.filter(c => c.last_update_ts !== null));
const colonization = $derived(visibleChambers.find(c => c.type === 'colonization') ?? null);
const fruiting = $derived(visibleChambers.find(c => c.type === 'fruiting') ?? null);
const singleChamber = $derived(visibleChambers.length === 1 ? visibleChambers[0] : null);
// Track which hint is currently open (only one at a time)
let openHintKey = $state<string | null>(null);
// Throttled snapshot of the global history
const history = $derived(cultivar.state.environment.history);
let chartSnap = $state(cultivar.state.environment.history.slice());
// Active scrub position — keyed by `${chamberId}:${metricKey}`. Only
// one sparkline can be scrubbed at a time (single pointer), so one
// slot suffices; when the pointer moves to a different chart we simply
// overwrite it.
type ScrubState = { key: string; ts: number; value: number };
let scrub = $state<ScrubState | null>(null);
function handleScrub(chamberId: string, metricKey: string, p: TimeSeriesPoint | null) {
const key = `${chamberId}:${metricKey}`;
if (p === null) {
if (scrub?.key === key) scrub = null;
} else {
scrub = { key, ts: p.ts, value: p.value };
}
}
function isScrubbed(ch: Chamber, mk: string): boolean {
return scrub?.key === `${ch.id}:${mk}`;
}
// Relative timestamp formatter for the scrub readout. "now", "2m ago",
// "1h ago", "3h 12m ago". Seconds resolution would be noisy at these
// cadences, so we round to the nearest useful unit.
function formatRelative(ts: number): string {
const now = Math.floor(Date.now() / 1000);
const delta = Math.max(0, now - ts);
if (delta < 45) return 'just now';
if (delta < 90) return '1m ago';
if (delta < 3600) return `${Math.round(delta / 60)}m ago`;
if (delta < 5400) return '1h ago';
const hours = Math.floor(delta / 3600);
const mins = Math.round((delta % 3600) / 60);
if (hours < 24) return mins > 0 ? `${hours}h ${mins}m ago` : `${hours}h ago`;
const days = Math.round(hours / 24);
return days === 1 ? 'yesterday' : `${days}d ago`;
}
// Throttled per-chamber history snapshots. Each chamber now owns its
// own history ring buffer — no more global-offset hack.
let colSnap: EnvironmentReading[] = $state([]);
let fruitSnap: EnvironmentReading[] = $state([]);
let snapMs = 0;
let snapWin: Win = '24h';
$effect(() => {
const h = cultivar.state.environment.history;
// Read reactive deps up front so $effect re-runs on change.
const colHist = colonization?.history ?? [];
const frHist = fruiting?.history ?? [];
const win = activeWin;
const now = Date.now();
if (win !== snapWin || now - snapMs >= winMs[win]) {
chartSnap = h.slice();
colSnap = colHist.slice();
fruitSnap = frHist.slice();
snapMs = now;
snapWin = win;
}
@@ -44,16 +84,7 @@
const pts = $derived(winPts[activeWin]);
const step = $derived(winStep[activeWin]);
// Per-chamber virtual history: the global history, shifted by the gap
// between each chamber's live reading and the history's latest.
type MetricKey = 'temp_c' | 'rh_pct' | 'co2_ppm' | 'co2e_ppm' | 'voc_ppb';
const readCh: Record<MetricKey, (e: ChamberEnvironment | undefined) => number> = {
temp_c: e => e?.temp_c ?? 0,
rh_pct: e => e?.rh_pct ?? 0,
co2_ppm: e => e?.co2_ppm ?? e?.co2e_ppm ?? 0,
co2e_ppm: e => e?.co2e_ppm ?? e?.co2_ppm ?? 0,
voc_ppb: e => e?.voc_ppb ?? 0,
};
const readHist: Record<MetricKey, (r: EnvironmentReading) => number> = {
temp_c: r => r.temp_c,
rh_pct: r => r.rh_pct,
@@ -63,13 +94,11 @@
};
function sliceCh(ch: Chamber, key: MetricKey): TimeSeriesPoint[] {
const last = history[history.length - 1];
if (!last) return [];
const offset = readCh[key](ch.environment) - readHist[key](last);
return chartSnap
const snap = ch.type === 'colonization' ? colSnap : fruitSnap;
return snap
.slice(-pts)
.filter((_, i) => i % step === 0)
.map(r => ({ ts: r.ts, value: readHist[key](r) + offset }));
.map(r => ({ ts: r.ts, value: readHist[key](r) }));
}
// Metric definitions (label, unit, target-ranges per chamber, sparkline color)
@@ -79,6 +108,10 @@
unit: string;
color: string;
valueFor: (ch: Chamber) => string;
/** Format a raw numeric value (from a scrubbed historical point) for
* display. Must match valueFor()'s precision so scrub/live values
* read identically. */
format: (v: number) => string;
seriesFor: (ch: Chamber) => TimeSeriesPoint[];
rangeFor: (ch: Chamber) => [number, number];
rangeLabel: (ch: Chamber) => string;
@@ -112,6 +145,7 @@
unit: '°C',
color: '#2b5a34',
valueFor: (ch) => (ch.environment?.temp_c ?? 0).toFixed(1),
format: (v) => v.toFixed(1),
seriesFor: (ch) => sliceCh(ch, 'temp_c'),
rangeFor: (ch) => RANGES.temp[ch.type],
rangeLabel:(ch) => `${RANGES.temp[ch.type][0]}–${RANGES.temp[ch.type][1]}°C ideal`,
@@ -126,6 +160,7 @@
unit: '%',
color: '#4b6a84',
valueFor: (ch) => (ch.environment?.rh_pct ?? 0).toFixed(0),
format: (v) => v.toFixed(0),
seriesFor: (ch) => sliceCh(ch, 'rh_pct'),
rangeFor: (ch) => RANGES.humid[ch.type],
rangeLabel:(ch) => `${RANGES.humid[ch.type][0]}–${RANGES.humid[ch.type][1]}% ideal`,
@@ -142,6 +177,7 @@
valueFor: (ch) => (ch.type === 'colonization'
? (ch.environment?.co2e_ppm ?? 0)
: (ch.environment?.co2_ppm ?? 0)).toFixed(0),
format: (v) => v.toFixed(0),
seriesFor: (ch) => sliceCh(ch, ch.type === 'colonization' ? 'co2e_ppm' : 'co2_ppm'),
rangeFor: (ch) => RANGES.co2[ch.type],
rangeLabel:(ch) => ch.type === 'colonization' ? '<1600 ppm ideal' : '<900 ppm ideal',
@@ -156,6 +192,7 @@
unit: 'ppb',
color: '#7a6d52',
valueFor: (ch) => (ch.environment?.voc_ppb ?? 0).toFixed(0),
format: (v) => v.toFixed(0),
seriesFor: (ch) => sliceCh(ch, 'voc_ppb'),
rangeFor: (ch) => RANGES.voc[ch.type],
rangeLabel:(ch) => `<${RANGES.voc[ch.type][1]} ppb typical`,
@@ -194,99 +231,144 @@
</div>
</header>
<!-- Two-column header for the chambers -->
<div class="chamber-heads">
<div class="ch-head col-side">
<span class="ch-dot" style="background: #1c251d;"></span>
<span class="ch-name font-serif">Colonization</span>
<span class="ch-desc">dark &amp; still</span>
{#if visibleChambers.length === 0}
<!-- Nothing streaming yet. Show a quiet placeholder rather than a
column of zeros + "drift" chips everywhere. -->
<div class="empty-state font-serif italic">
Waiting for Cultivar to send its first reading…
</div>
<div class="ch-head fruit-side">
<span class="ch-dot" style="background: #d5c48d;"></span>
<span class="ch-name font-serif">Fruiting</span>
<span class="ch-desc">lit &amp; humid</span>
{:else}
<!-- Dynamic-column header — one column per streaming chamber. -->
<div class="chamber-heads" class:single={singleChamber !== null}>
{#each visibleChambers as ch (ch.id)}
<div class="ch-head">
<span
class="ch-dot"
style="background: {ch.type === 'colonization' ? '#1c251d' : '#d5c48d'};"
></span>
<span class="ch-name font-serif">{ch.label}</span>
<span class="ch-desc">
{ch.type === 'colonization' ? 'dark & still' : 'lit & humid'}
</span>
{#if ch.burn_in}
<span class="ch-burn">conditioning</span>
{/if}
</div>
{/each}
</div>
</div>
<!-- Metric rows -->
<div class="rows">
{#each metrics as m (m.key)}
{@const colRange = m.rangeFor(colonization)}
{@const fruitRange = m.rangeFor(fruiting)}
{@const colVal = parseFloat(m.valueFor(colonization))}
{@const fruitVal = parseFloat(m.valueFor(fruiting))}
{@const colOK = inRange(colVal, colRange)}
{@const fruitOK = inRange(fruitVal, fruitRange)}
<!-- Metric rows -->
<div class="rows">
{#each metrics as m (m.key)}
<div class="row" class:single={singleChamber !== null}>
<div class="row-label">
<span class="rl-name">{m.label}</span>
<InfoHint
title={m.hint(visibleChambers[0]).title}
body={m.hint(visibleChambers[0]).body}
side="bottom"
open={openHintKey === m.key}
onOpenChange={(open) => openHintKey = open ? m.key : null}
/>
</div>
<div class="row">
<!-- Metric label (row header, spans both cells via grid) -->
<div class="row-label">
<span class="rl-name">{m.label}</span>
<InfoHint
title={m.hint(colonization).title}
body={m.hint(colonization).body}
side="bottom"
open={openHintKey === m.key}
onOpenChange={(open) => openHintKey = open ? m.key : null}
/>
{#each visibleChambers as ch (ch.id)}
{@const range = m.rangeFor(ch)}
{@const suppressed = ch.burn_in && m.key === 'voc'}
{@const scrubActive = isScrubbed(ch, m.key)}
{@const displayVal = scrubActive && scrub
? scrub.value
: parseFloat(m.valueFor(ch))}
{@const ok = inRange(displayVal, range)}
<div class="cell" class:scrubbing={scrubActive}>
<div class="cell-top">
<span class="cell-value font-serif" class:out={!ok && !suppressed} class:muted={suppressed}>
{#if suppressed}
—<span class="cell-unit">{m.unit}</span>
{:else if scrubActive && scrub}
{m.format(scrub.value)}<span class="cell-unit">{m.unit}</span>
{:else}
{m.valueFor(ch)}<span class="cell-unit">{m.unit}</span>
{/if}
</span>
{#if scrubActive && scrub}
<span class="cell-when font-serif italic">{formatRelative(scrub.ts)}</span>
{:else if !suppressed}
<span class="cell-chip" class:chip-ok={ok} class:chip-off={!ok}>
<span class="chip-dot"></span>
{ok ? 'in range' : 'drift'}
</span>
{/if}
</div>
<div class="cell-chart">
<LineChart
data={m.seriesFor(ch)}
color={m.color}
healthyRange={range}
interactive
onScrub={(p) => handleScrub(ch.id, m.key, p)}
/>
</div>
<div class="cell-range">{m.rangeLabel(ch)}</div>
</div>
{/each}
</div>
{/each}
</div>
<!-- Colonization cell -->
<div class="cell">
<div class="cell-top">
<span class="cell-value font-serif" class:out={!colOK}>
{m.valueFor(colonization)}<span class="cell-unit">{m.unit}</span>
</span>
<span class="cell-chip" class:chip-ok={colOK} class:chip-off={!colOK}>
<span class="chip-dot"></span>
{colOK ? 'in range' : 'drift'}
</span>
</div>
<div class="cell-chart">
<LineChart data={m.seriesFor(colonization)} color={m.color} healthyRange={colRange} />
</div>
<div class="cell-range">{m.rangeLabel(colonization)}</div>
</div>
<!-- Fruiting cell -->
<div class="cell">
<div class="cell-top">
<span class="cell-value font-serif" class:out={!fruitOK}>
{m.valueFor(fruiting)}<span class="cell-unit">{m.unit}</span>
</span>
<span class="cell-chip" class:chip-ok={fruitOK} class:chip-off={!fruitOK}>
<span class="chip-dot"></span>
{fruitOK ? 'in range' : 'drift'}
</span>
</div>
<div class="cell-chart">
<LineChart data={m.seriesFor(fruiting)} color={m.color} healthyRange={fruitRange} />
</div>
<div class="cell-range">{m.rangeLabel(fruiting)}</div>
</div>
<!-- Gas fingerprint row -->
<div class="row row-radar" class:single={singleChamber !== null}>
<div class="row-label">
<span class="rl-name">Gas fingerprint</span>
<InfoHint
title="Gas Fingerprint"
body="The gas fingerprint shows what the air smells like to Cultivar across ten heater temperatures. A smooth, even shape means stable air. A dip in the green zone (280–340°C) can be an early contamination hint — often before you can see anything. The amber zone (360–400°C) responds to ammonia and sulfur, strong signals of bacterial wet rot. Δ baseline compares today to your established baseline. A near-perfect circle means nothing has changed."
open={openHintKey === 'gas'}
onOpenChange={(open) => openHintKey = open ? 'gas' : null}
/>
</div>
{/each}
</div>
<!-- Gas fingerprint row -->
<div class="row row-radar">
<div class="row-label">
<span class="rl-name">Gas fingerprint</span>
<InfoHint
title="Gas Fingerprint"
body="The gas fingerprint shows what the air smells like to Cultivar across ten heater temperatures. A smooth, even shape means stable air. A dip in the green zone (280–340°C) can be an early contamination hint — often before you can see anything. The amber zone (360–400°C) responds to ammonia and sulfur, strong signals of bacterial wet rot. Δ baseline compares today to your established baseline. A near-perfect circle means nothing has changed."
open={openHintKey === 'gas'}
onOpenChange={(open) => openHintKey = open ? 'gas' : null}
/>
</div>
<div class="cell cell-radar">
<SweepRadar sweep={colSweep} baseline={colBaseline} size={180} />
{#each visibleChambers as ch (ch.id)}
<div class="cell cell-radar">
{#if ch.burn_in}
<!-- Fingerprint is meaningless during burn-in — gas readings
are railed while the MOX hotplate conditions. Show a
warm explanation instead of a dead chart so the user
understands why the space is empty. -->
{@const samples = ch.baseline?.n_samples ?? 0}
{@const target = 30}
{@const pct = Math.min(100, Math.round((samples / target) * 100))}
<div class="calibrating">
<div class="cal-pulse" aria-hidden="true">
<span></span><span></span><span></span>
</div>
<div class="cal-title font-serif">Calibrating the sensor</div>
<p class="cal-body font-serif italic">
Cultivar is learning what clean air smells like in your
room. This takes a couple of hours on the first run —
keep the doors closed while it settles in.
</p>
{#if samples > 0}
<div class="cal-progress" aria-label="baseline progress">
<div class="cal-bar" style="width: {pct}%;"></div>
</div>
<div class="cal-progress-label">
sample {samples} of ~{target}
</div>
{/if}
</div>
{:else}
<SweepRadar
sweep={(ch.latestSweep ?? []) as GasSweepPoint[]}
baseline={(ch.baseline ?? null) as SweepBaseline | null}
size={180}
/>
{/if}
</div>
{/each}
</div>
<div class="cell cell-radar">
<SweepRadar sweep={fruitSweep} baseline={fruitBaseline} size={180} />
</div>
</div>
{/if}
</section>
<style>
@@ -334,7 +416,9 @@
.tab:hover { color: var(--ink); }
.tab.active { background: #fbf7ec; color: var(--forest); box-shadow: inset 0 0 0 1px var(--line); }
/* Two-column chamber heads */
/* Chamber heads — grid columns match the metric row below. The first
column is a label gutter (kept empty on the heads). .single collapses
to one chamber column for single-chamber deployments. */
.chamber-heads {
display: grid;
grid-template-columns: 130px 1fr 1fr;
@@ -342,6 +426,9 @@
padding-bottom: 10px;
border-bottom: 1px solid var(--line-soft);
}
.chamber-heads.single {
grid-template-columns: 130px 1fr;
}
.chamber-heads::before { content: ''; }
.ch-head {
@@ -349,8 +436,104 @@
align-items: baseline;
gap: 8px;
}
.ch-head:nth-child(1) { grid-column: 2; }
.ch-head:nth-child(2) { grid-column: 3; }
.chamber-heads .ch-head:nth-of-type(1) { grid-column: 2; }
.chamber-heads:not(.single) .ch-head:nth-of-type(2) { grid-column: 3; }
.ch-burn {
font-family: var(--font-serif);
font-style: italic;
font-size: 11px;
color: var(--ink-muted);
padding: 1px 6px;
border: 1px solid var(--line-soft);
border-radius: 999px;
margin-left: 4px;
}
.empty-state {
padding: 40px 16px;
text-align: center;
color: var(--ink-muted);
font-size: 14px;
border-top: 1px solid var(--line-soft);
}
/* Calibrating placeholder (takes the place of the radar during
burn-in). Friendly, not alarming. */
.calibrating {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
min-height: 180px;
padding: 12px 16px;
text-align: center;
max-width: 280px;
}
.cal-title {
font-size: 14px;
color: var(--ink);
letter-spacing: -0.005em;
}
.cal-body {
font-size: 12.5px;
line-height: 1.5;
color: var(--ink-muted);
margin: 0;
}
.cal-pulse {
display: flex;
gap: 5px;
height: 8px;
}
.cal-pulse span {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--forest);
opacity: 0.35;
animation: cal-pulse 1.4s ease-in-out infinite;
}
.cal-pulse span:nth-child(2) { animation-delay: 0.2s; }
.cal-pulse span:nth-child(3) { animation-delay: 0.4s; }
@keyframes cal-pulse {
0%, 80%, 100% { opacity: 0.25; transform: scale(0.85); }
40% { opacity: 0.9; transform: scale(1.1); }
}
.cal-progress {
width: 100%;
max-width: 180px;
height: 3px;
background: var(--line-soft);
border-radius: 999px;
overflow: hidden;
}
.cal-bar {
height: 100%;
background: var(--forest);
opacity: 0.55;
transition: width 0.6s ease-out;
}
.cal-progress-label {
font-size: 11px;
color: var(--ink-muted);
letter-spacing: 0.02em;
}
/* Scrub readout — replaces the "in range" chip while the user is
holding/hovering a historical point. Italic serif for a soft feel,
paired with the numeric value already rendered in font-serif. */
.cell-when {
font-size: 11.5px;
color: var(--ink-muted);
padding: 2px 8px 2px 6px;
letter-spacing: 0.01em;
font-feature-settings: "tnum";
}
.cell.scrubbing .cell-value { color: var(--forest); }
.cell-value.muted { color: var(--ink-muted); }
.ch-dot {
display: inline-block;
@@ -386,6 +569,9 @@
align-items: start;
border-bottom: 1px solid var(--line-soft);
}
.row.single {
grid-template-columns: 130px 1fr;
}
.row:last-child { border-bottom: none; }
.row-label {
@@ -453,8 +639,8 @@
}
.cell-chart {
height: 28px;
max-height: 28px;
height: 38px;
max-height: 38px;
overflow: hidden;
}