Add live daemon WebSocket integration with history backfill, update chamber IDs to match daemon schema, and refine chart styling

Connect to live cultivar-daemon via WebSocket when VITE_DAEMON_URL is set, falling back to mock mode otherwise. Add EnvPayload and EnvAnomaly handling to process real sensor data and anomaly detection. Implement loadHistory REST call to backfill SQLite environment data on mount and reconnect. Add wsConnected state and reconnection logic with 5s retry.

Change chamber IDs from 'main'/'second
This commit is contained in:
grove5_admin committed 2026-04-27 23:58:30 -07:00
1 parent 985905acbc
commit 3ba1e6f4a7
9 files changed
+797 -34

No files matched your search

+4
View File
@@ -28,6 +28,10 @@
// Start mock WebSocket on mount
$effect(() => {
cultivar.startMockWs();
// Backfill history from daemon if live
cultivar.loadHistory('colonization', 24);
cultivar.loadHistory('fruiting', 24);
return () => cultivar.stopMockWs();
});
+9 -8
View File
@@ -154,12 +154,13 @@
vector-effect="non-scaling-stroke"
/>
<text
x={nowX + 4} y={PAD.top + 10}
font-family="var(--font-sans)"
font-size="9"
fill="var(--ink-2)"
letter-spacing="0.08em"
>NOW</text>
x={nowX} y={PAD.top - 5}
text-anchor="middle"
font-family="var(--font-serif)"
font-style="italic"
font-size="10"
fill="var(--ink-muted)"
>now</text>
{/if}
<!-- Ready marker -->
@@ -172,8 +173,8 @@
vector-effect="non-scaling-stroke"
/>
<text
x={ex - 4} y={PAD.top + 10}
text-anchor="end"
x={ex} y={PAD.top - 5}
text-anchor="middle"
font-family="var(--font-serif)"
font-style="italic"
font-size="10"
+1
View File
@@ -100,6 +100,7 @@
display: block;
width: 100%;
height: 100%;
max-height: 28px; /* ← add this */
overflow: visible;
}
</style>
+461
View File
@@ -0,0 +1,461 @@
<script lang="ts">
import type { GasSweepPoint, SweepBaseline } from '../types';
interface Props {
sweep: GasSweepPoint[];
baseline?: SweepBaseline | null;
/** 'normalized' shows deviation from baseline (baseline = perfect circle)
* 'raw' shows log-scale absolute resistance values */
mode?: 'normalized' | 'raw';
size?: number;
}
const {
sweep = [],
baseline = null,
mode = 'normalized',
size = 220,
}: Props = $props();
// ── Toggle state ──────────────────────────────────────────────────────
let activeMode = $state<'normalized' | 'raw'>(mode);
$effect(() => {
activeMode = mode;
});
// ── Geometry ──────────────────────────────────────────────────────────
const cx = $derived(size / 2);
const cy = $derived(size / 2);
const r = $derived(size * 0.38); // outer radius of the chart
// ── Sweep points in temperature order ────────────────────────────────
const TEMPS = [200, 220, 250, 280, 300, 320, 340, 360, 380, 400];
const N = TEMPS.length;
const ZONE_COLORS: Record<number, string> = {
1: '#4b6a84', // blue — baseline zone
2: '#2b5a34', // forest — biological zone
3: '#8a6a3d', // amber — heavy zone
};
const ZONE_LABELS: Record<number, string> = {
1: 'Baseline',
2: 'Biological',
3: 'Heavy',
};
// ── Point mapping ─────────────────────────────────────────────────────
function getSweepPoint(temp: number): GasSweepPoint | undefined {
return sweep.find(p => p.heater_temp_c === temp);
}
function getBaselineR(temp: number): number | null {
if (!baseline?.established) return null;
return baseline.R[temp] ?? null;
}
// ── Value → radius mapping ────────────────────────────────────────────
const MAX_LOG = Math.log10(102_400_000); // ~8.01 — sentinel ceiling
const MIN_LOG = Math.log10(1000); // 3 — practical floor
function rawToRadius(resistance: number): number {
const logR = Math.log10(Math.max(resistance, 1000));
const t = (logR - MIN_LOG) / (MAX_LOG - MIN_LOG);
return t * r;
}
function normalizedToRadius(norm: number | null): number {
if (norm === null) return r * 0.5;
// norm = 1.0 → baseline circle (r * 0.6)
// norm > 1.0 → cleaner air → larger radius
// norm < 1.0 → more gas load → smaller radius
const clamped = Math.max(0.1, Math.min(3.0, norm));
const t = clamped / 2.0; // 0→0, 1→0.5, 2→1.0
return Math.max(r * 0.05, Math.min(r, t * r));
}
// ── Angle for each spoke (0 = top, clockwise) ─────────────────────────
function spokeAngle(i: number): number {
return (i / N) * 2 * Math.PI - Math.PI / 2;
}
// ── Polar to cartesian ────────────────────────────────────────────────
function polar(angle: number, radius: number): [number, number] {
return [
cx + radius * Math.cos(angle),
cy + radius * Math.sin(angle),
];
}
// ── Build polygon path ────────────────────────────────────────────────
function buildPath(points: [number, number][]): string {
if (points.length === 0) return '';
return points.map(([x, y], i) =>
`${i === 0 ? 'M' : 'L'}${x.toFixed(2)},${y.toFixed(2)}`
).join(' ') + ' Z';
}
// ── Derived geometry ──────────────────────────────────────────────────
const spokeData = $derived.by(() => {
return TEMPS.map((temp, i) => {
const angle = spokeAngle(i);
const point = getSweepPoint(temp);
const baseR = getBaselineR(temp);
const zone = point?.zone ?? (temp <= 250 ? 1 : temp <= 340 ? 2 : 3);
const valid = point?.valid ?? false;
const resistance = point?.resistance_raw ?? null;
let currentRadius: number;
let baselineRadius: number | null = null;
if (activeMode === 'raw') {
currentRadius = resistance !== null ? rawToRadius(resistance) : 0;
baselineRadius = baseR !== null ? rawToRadius(baseR) : null;
} else {
const norm = point?.resistance_norm ?? null;
currentRadius = normalizedToRadius(norm);
baselineRadius = baseline?.established ? r * 0.5 : null; // baseline is perfect circle at 0.5r
}
const [x, y] = polar(angle, currentRadius);
const [labelX, labelY] = polar(angle, r + 18);
const [spokeX, spokeY] = polar(angle, r + 4);
return { temp, angle, zone, valid, x, y, labelX, labelY, spokeX, spokeY, currentRadius, baselineRadius };
});
});
const currentPath = $derived(
buildPath(spokeData.map(d => [d.x, d.y]))
);
const baselinePath = $derived.by(() => {
if (!baseline?.established) return '';
const pts = spokeData.map((d, i) => {
if (d.baselineRadius === null) return null;
return polar(spokeAngle(i), d.baselineRadius);
}).filter(Boolean) as [number, number][];
return buildPath(pts);
});
// ── Grid rings ────────────────────────────────────────────────────────
const RINGS = $derived.by(() => {
if (activeMode === 'raw') {
// Log-scale rings at 10k, 100k, 1M, 10M, 100M Ω
return [
{ r: rawToRadius(10_000), label: '10k' },
{ r: rawToRadius(100_000), label: '100k' },
{ r: rawToRadius(1_000_000), label: '1M' },
{ r: rawToRadius(10_000_000), label: '10M' },
];
} else {
// Normalized rings at 0.5x, 1x (baseline), 1.5x, 2x
return [
{ r: normalizedToRadius(0.5), label: '0.5×' },
{ r: normalizedToRadius(1.0), label: 'baseline' },
{ r: normalizedToRadius(1.5), label: '1.5×' },
{ r: normalizedToRadius(2.0), label: '2×' },
];
}
});
// ── Zone arc paths ────────────────────────────────────────────────────
// Draw subtle colored arcs at the outer edge to indicate zones
function arcPath(startI: number, endI: number): string {
const outerR = r + 8;
const a1 = spokeAngle(startI) - (Math.PI / N) * 0.1;
const a2 = spokeAngle(endI) + (Math.PI / N) * 0.9;
const [x1, y1] = polar(a1, outerR);
const [x2, y2] = polar(a2, outerR);
const large = a2 - a1 > Math.PI ? 1 : 0;
return `M${x1.toFixed(2)},${y1.toFixed(2)} A${outerR},${outerR} 0 ${large} 1 ${x2.toFixed(2)},${y2.toFixed(2)}`;
}
const ZONE_ARCS = [
{ zone: 1, startI: 0, endI: 2, color: ZONE_COLORS[1] },
{ zone: 2, startI: 3, endI: 6, color: ZONE_COLORS[2] },
{ zone: 3, startI: 7, endI: 9, color: ZONE_COLORS[3] },
];
// ── Has data? ─────────────────────────────────────────────────────────
const hasData = $derived(sweep.length > 0 && sweep.some(p => p.valid));
const hasBaseline = $derived(baseline?.established ?? false);
const showNormalized = $derived(activeMode === 'normalized' && hasBaseline);
</script>
<div class="radar-wrap">
<!-- Toggle -->
<div class="radar-header">
<div class="mode-toggle">
<button
class="toggle-btn"
class:active={activeMode === 'normalized'}
onclick={() => activeMode = 'normalized'}
type="button"
title="Show deviation from baseline"
>
Δ baseline
</button>
<button
class="toggle-btn"
class:active={activeMode === 'raw'}
onclick={() => activeMode = 'raw'}
type="button"
title="Show raw log-scale resistance"
>
raw Ω
</button>
</div>
</div>
<!-- Radar SVG -->
<div class="radar-svg-wrap">
<svg
width={size}
height={size}
viewBox="0 0 {size} {size}"
class="radar-svg"
aria-label="Gas fingerprint radar chart"
>
<!-- Grid rings -->
{#each RINGS as ring}
<circle
cx={cx} cy={cy} r={ring.r}
fill="none"
stroke="var(--line-soft)"
stroke-width="0.5"
stroke-dasharray={ring.label === 'baseline' ? '2 2' : ''}
opacity={ring.label === 'baseline' ? 0.6 : 0.35}
/>
{/each}
<!-- Baseline ring label -->
{#if activeMode === 'normalized' && hasBaseline}
<text
x={cx + normalizedToRadius(1.0) + 3}
y={cy - 3}
class="ring-label"
fill="var(--ink-muted)"
opacity="0.5"
>baseline</text>
{/if}
<!-- Spokes -->
{#each spokeData as d}
<line
x1={cx} y1={cy}
x2={d.spokeX} y2={d.spokeY}
stroke="var(--line-soft)"
stroke-width="0.5"
opacity="0.4"
/>
{/each}
<!-- Zone arcs -->
{#each ZONE_ARCS as arc}
<path
d={arcPath(arc.startI, arc.endI)}
fill="none"
stroke={arc.color}
stroke-width="2.5"
stroke-linecap="round"
opacity="0.5"
/>
{/each}
<!-- Baseline polygon -->
{#if baselinePath && hasBaseline}
<path
d={baselinePath}
fill="none"
stroke="var(--ink-muted)"
stroke-width="0.8"
stroke-dasharray="3 2"
opacity="0.4"
/>
{/if}
<!-- Current sweep polygon fill -->
{#if hasData && currentPath}
<path
d={currentPath}
fill="var(--forest)"
fill-opacity="0.08"
stroke="none"
/>
{/if}
<!-- Current sweep polygon stroke -->
{#if hasData && currentPath}
<path
d={currentPath}
fill="none"
stroke="var(--forest)"
stroke-width="1.4"
stroke-linejoin="round"
opacity="0.9"
/>
{/if}
<!-- Data points -->
{#each spokeData as d}
{#if d.valid}
<circle
cx={d.x} cy={d.y} r="2.5"
fill={ZONE_COLORS[d.zone]}
opacity="0.9"
/>
{/if}
{/each}
<!-- Temperature labels -->
{#each spokeData as d}
<text
x={d.labelX}
y={d.labelY}
class="spoke-label"
text-anchor="middle"
dominant-baseline="middle"
fill={ZONE_COLORS[d.zone]}
opacity="0.75"
>{d.temp}</text>
{/each}
<!-- Center label -->
{#if !hasData}
<text
x={cx} y={cy}
class="center-label"
text-anchor="middle"
dominant-baseline="middle"
fill="var(--ink-muted)"
opacity="0.4"
>no data</text>
{:else if activeMode === 'normalized' && !hasBaseline}
<text
x={cx} y={cy - 6}
class="center-label"
text-anchor="middle"
dominant-baseline="middle"
fill="var(--ink-muted)"
opacity="0.4"
>establishing</text>
<text
x={cx} y={cy + 10}
class="center-label"
text-anchor="middle"
dominant-baseline="middle"
fill="var(--ink-muted)"
opacity="0.4"
>baseline…</text>
{/if}
</svg>
<!-- Zone legend -->
<div class="zone-legend">
{#each Object.entries(ZONE_LABELS) as [zone, label]}
<span class="zone-tag">
<span class="zone-dot" style="background: {ZONE_COLORS[parseInt(zone)]}"></span>
{label}
</span>
{/each}
</div>
</div>
</div>
<style>
.radar-wrap {
display: flex;
flex-direction: column;
gap: 8px;
align-items: center;
}
.radar-header {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
}
.mode-toggle {
display: inline-flex;
gap: 2px;
padding: 2px;
background: var(--paper-2);
border: 1px solid var(--line);
border-radius: 999px;
}
.toggle-btn {
padding: 4px 10px;
border-radius: 999px;
font-size: 10px;
font-weight: 500;
letter-spacing: 0.04em;
color: var(--ink-muted);
transition: background 0.15s, color 0.15s;
white-space: nowrap;
}
.toggle-btn:hover { color: var(--ink); }
.toggle-btn.active {
background: #fbf7ec;
color: var(--forest);
box-shadow: inset 0 0 0 1px var(--line);
}
.radar-svg-wrap {
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
}
.radar-svg {
overflow: visible;
}
.spoke-label {
font-family: var(--font-sans);
font-size: 8px;
font-weight: 500;
letter-spacing: 0.02em;
}
.ring-label {
font-family: var(--font-sans);
font-size: 7px;
letter-spacing: 0.02em;
}
.center-label {
font-family: var(--font-serif);
font-style: italic;
font-size: 10px;
}
.zone-legend {
display: flex;
gap: 12px;
align-items: center;
}
.zone-tag {
display: flex;
align-items: center;
gap: 5px;
font-family: var(--font-sans);
font-size: 10px;
color: var(--ink-muted);
letter-spacing: 0.02em;
}
.zone-dot {
width: 6px;
height: 6px;
border-radius: 50%;
opacity: 0.8;
}
</style>
+11 -11
View File
@@ -105,7 +105,7 @@ const fullMockState: CultivarState = {
},
chambers: [
{
id: 'main',
id: 'colonization',
label: 'Colonization',
type: 'colonization',
environment: {
@@ -236,7 +236,7 @@ const fullMockState: CultivarState = {
],
},
{
id: 'second',
id: 'fruiting',
label: 'Fruiting',
type: 'fruiting',
environment: {
@@ -369,22 +369,22 @@ const fullMockState: CultivarState = {
],
hardware: {
fans: [
{ id: 'fan-col', chamber_id: 'main', speed_pct: 0, mode: 'auto' },
{ id: 'fan-fruit', chamber_id: 'second', speed_pct: 100, mode: 'auto' },
{ id: 'fan-col', chamber_id: 'colonization', speed_pct: 0, mode: 'auto' },
{ id: 'fan-fruit', chamber_id: 'fruiting', speed_pct: 100, mode: 'auto' },
],
humidifier: { active: true, mode: 'auto', reservoir_pct: 72 },
lights: [
{ id: 'light-col-work', chamber_id: 'main', purpose: 'work', on: true, color_hex: '#f4ecd8', brightness: 0 },
{ id: 'light-col-photo', chamber_id: 'main', purpose: 'photo', on: true, color_hex: '#f4ecd8', brightness: 0 },
{ id: 'light-fruit-grow', chamber_id: 'second', purpose: 'grow', on: true, color_hex: '#f7f0dc', brightness: 0.55 },
{ id: 'light-col-work', chamber_id: 'colonization', purpose: 'work', on: true, color_hex: '#f4ecd8', brightness: 0 },
{ id: 'light-col-photo', chamber_id: 'colonization', purpose: 'photo', on: true, color_hex: '#f4ecd8', brightness: 0 },
{ id: 'light-fruit-grow', chamber_id: 'fruiting', purpose: 'grow', on: true, color_hex: '#f7f0dc', brightness: 0.55 },
],
doors: [
{ id: 'door-col', chamber_id: 'main', open: false },
{ id: 'door-fruit', chamber_id: 'second', open: false },
{ id: 'door-col', chamber_id: 'colonization', open: false },
{ id: 'door-fruit', chamber_id: 'fruiting', open: false },
],
cameras: [
{ id: 'cam-col', chamber_id: 'main', position: 'top', last_capture_ts: NOW - 180 },
{ id: 'cam-fruit', chamber_id: 'second', position: 'top', last_capture_ts: NOW - 180 },
{ id: 'cam-col', chamber_id: 'colonization', position: 'top', last_capture_ts: NOW - 180 },
{ id: 'cam-fruit', chamber_id: 'fruiting', position: 'top', last_capture_ts: NOW - 180 },
],
},
recipe: {
+253 -11
View File
@@ -1,17 +1,44 @@
import { fullMockState, minimalState } from './mock';
import type { CultivarState, EnvironmentReading, WsDiff } from './types';
import type {
CultivarState,
EnvironmentReading,
WsDiff,
EnvPayload,
EnvAnomaly,
SweepBaseline,
} from './types';
function deepClone<T>(v: T): T {
return structuredClone(v);
}
// ── Daemon URL ─────────────────────────────────────────────────────────────
// Set VITE_DAEMON_URL to connect to live daemon.
// Unset → mock mode (dev default).
const DAEMON_URL = (import.meta as any).env?.VITE_DAEMON_URL as string | undefined;
const WS_URL = DAEMON_URL
? DAEMON_URL.replace(/^http/, 'ws') + '/ws'
: null;
// ── VPD calculation ────────────────────────────────────────────────────────
// Vapour Pressure Deficit from temp and RH.
// Used when daemon doesn't provide it directly.
function calcVpd(temp_c: number, rh_pct: number): number {
const svp = 0.6108 * Math.exp((17.27 * temp_c) / (temp_c + 237.3));
return svp * (1 - rh_pct / 100);
}
function createStore() {
// @ts-ignore - Vite provides import.meta.env.DEV
// @ts-ignore
const initialState = (import.meta as any).env?.DEV ? fullMockState : minimalState;
let state = $state<CultivarState>(deepClone(initialState));
// Mock WS diff interval
let mockInterval: ReturnType<typeof setInterval> | null = null;
let ws: WebSocket | null = null;
let wsReconnectTimer: ReturnType<typeof setTimeout> | null = null;
let wsConnected = $state(false);
// ── WsDiff (mock path — unchanged) ───────────────────────────────────────
function applyDiff(diff: WsDiff) {
state.meta.timestamp_utc = diff.t;
@@ -22,7 +49,6 @@ function createStore() {
if (diff.e.co2 !== undefined) state.environment.live.co2_ppm = diff.e.co2;
if (diff.e.vpd !== undefined) state.environment.live.vpd = diff.e.vpd;
// Push to history ring buffer
const reading: EnvironmentReading = {
ts: diff.t,
temp_c: state.environment.live.temp_c,
@@ -43,12 +69,188 @@ function createStore() {
if (state.hardware.fans[i]) state.hardware.fans[i].speed_pct = spd;
});
}
// Cultivar has no temperature control, so heater diffs are ignored
if (diff.hw.humidifier !== undefined) state.hardware.humidifier.active = diff.hw.humidifier;
if (diff.hw.humidifier !== undefined)
state.hardware.humidifier.active = diff.hw.humidifier;
}
}
// ── EnvPayload (live daemon path) ─────────────────────────────────────────
function applyEnvPayload(payload: EnvPayload) {
const chamber = state.chambers.find(c => c.id === payload.chamber_id);
if (!chamber) return;
const ambient = payload.ambient;
if (!ambient.valid) return;
// Update chamber live environment
chamber.environment.temp_c = ambient.temp_c;
chamber.environment.rh_pct = ambient.humidity_pct;
if (payload.co2?.valid) {
chamber.environment.co2_ppm = payload.co2.ppm;
}
if (payload.co2e_ppm !== null) {
chamber.environment.co2e_ppm = payload.co2e_ppm;
}
if (payload.voc_ppb !== null) {
chamber.environment.voc_ppb = payload.voc_ppb;
}
// Update global live environment from fruiting chamber
// (fruiting has SCD43 — most accurate temp/humidity/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;
}
// 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) {
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);
// Surface anomalies as alerts
for (const anomaly of payload.anomalies) {
applyAnomaly(anomaly);
}
}
function applyAnomaly(anomaly: EnvAnomaly) {
// Deduplicate by id
const existing = state.environment.alerts.find(a => a.id === anomaly.id);
if (existing) return;
state.environment.alerts.push({
id: anomaly.id,
type: anomaly.type,
severity: anomaly.severity,
message: anomaly.message,
ts: anomaly.ts,
dismissed: anomaly.dismissed,
});
// Cap alerts list — keep newest 50
if (state.environment.alerts.length > 50) {
state.environment.alerts.shift();
}
}
// ── Real WebSocket ─────────────────────────────────────────────────────────
function connectWs() {
if (!WS_URL) return;
ws = new WebSocket(WS_URL);
ws.onopen = () => {
wsConnected = true;
console.info('[cultivar] WebSocket connected');
// Load history from SQLite on every (re)connect
loadHistory('colonization', 24);
loadHistory('fruiting', 24);
// Clear any pending reconnect
if (wsReconnectTimer) {
clearTimeout(wsReconnectTimer);
wsReconnectTimer = null;
}
// Send periodic ping to keep connection alive
const ping = setInterval(() => {
if (ws?.readyState === WebSocket.OPEN) {
ws.send('ping');
} else {
clearInterval(ping);
}
}, 25000);
};
ws.onmessage = (event) => {
try {
const msg = JSON.parse(event.data) as {
type: 'payload' | 'anomaly' | 'baseline' | 'heartbeat';
chamber_id?: string;
data?: any;
ts: number;
};
switch (msg.type) {
case 'payload':
if (msg.data) applyEnvPayload(msg.data as EnvPayload);
break;
case 'anomaly':
if (msg.data) applyAnomaly(msg.data as EnvAnomaly);
break;
case 'baseline':
// Baseline established — could surface a UI notification here
console.info(`[cultivar] Baseline established for ${msg.chamber_id}`);
break;
case 'heartbeat':
// keepalive — no action needed
break;
}
} catch (e) {
console.warn('[cultivar] WebSocket message parse error', e);
}
};
ws.onclose = (event) => {
wsConnected = false;
console.warn(`[cultivar] WebSocket closed (${event.code}) — reconnecting in 5s`);
wsReconnectTimer = setTimeout(connectWs, 5000);
};
ws.onerror = (err) => {
console.error('[cultivar] WebSocket error', err);
ws?.close();
};
}
function disconnectWs() {
if (wsReconnectTimer) {
clearTimeout(wsReconnectTimer);
wsReconnectTimer = null;
}
ws?.close();
ws = null;
wsConnected = false;
}
// ── Mock WebSocket ─────────────────────────────────────────────────────────
function startMockWs() {
if (WS_URL) {
// Real daemon available — use it instead
connectWs();
return;
}
mockInterval = setInterval(() => {
const now = Math.floor(Date.now() / 1000);
const jitter = (x: number, amt: number) => x + (Math.random() - 0.5) * amt;
@@ -73,8 +275,51 @@ function createStore() {
clearInterval(mockInterval);
mockInterval = null;
}
disconnectWs();
}
// ── REST helpers ───────────────────────────────────────────────────────────
async function loadHistory(chamber_id: string, hours = 24) {
if (!DAEMON_URL) return;
try {
const res = await fetch(
`${DAEMON_URL}/api/environment/${chamber_id}/history?hours=${hours}`
);
if (!res.ok) return;
const rows = await res.json();
// Update the correct chamber's history
const chamber = state.chambers.find(c => c.id === chamber_id);
if (chamber && rows.length) {
// Also backfill global history from fruiting (has SCD43)
if (chamber_id === 'fruiting') {
state.environment.history = rows;
}
}
} catch (e) {
console.warn(`[cultivar] Failed to load history for ${chamber_id}`, e);
}
}
async function dismissAlert(alertId: string) {
const alert = state.environment.alerts.find(a => a.id === alertId);
if (alert) alert.dismissed = true;
// Sync to daemon if live
if (DAEMON_URL) {
try {
await fetch(`${DAEMON_URL}/api/anomalies/${alertId}/dismiss`, {
method: 'POST',
});
} catch (e) {
console.warn('[cultivar] Failed to dismiss anomaly on daemon', e);
}
}
}
// ── Other actions (unchanged) ─────────────────────────────────────────────
function selectBag(bagId: string | null) {
state.ui.selected_bag_id = bagId;
}
@@ -84,11 +329,6 @@ function createStore() {
localStorage.setItem('onboarding_complete', 'true');
}
function dismissAlert(alertId: string) {
const alert = state.environment.alerts.find(a => a.id === alertId);
if (alert) alert.dismissed = true;
}
function markWiped() {
state.maintenance.last_wipe_ts = Math.floor(Date.now() / 1000);
}
@@ -99,8 +339,10 @@ function createStore() {
return {
get state() { return state; },
get wsConnected() { return wsConnected; },
startMockWs,
stopMockWs,
loadHistory,
selectBag,
completeOnboarding,
dismissAlert,
+41 -1
View File
@@ -2,7 +2,8 @@
import { cultivar } from '../store.svelte';
import LineChart from '../charts/LineChart.svelte';
import InfoHint from './InfoHint.svelte';
import type { TimeSeriesPoint, EnvironmentReading, Chamber, ChamberEnvironment } from '../types';
import SweepRadar from '../charts/SweepRadar.svelte';
import type { TimeSeriesPoint, EnvironmentReading, Chamber, ChamberEnvironment, GasSweepPoint, SweepBaseline } from '../types';
type Win = '1h' | '6h' | '24h';
let activeWin = $state<Win>('24h');
@@ -14,6 +15,12 @@
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);
// Track which hint is currently open (only one at a time)
let openHintKey = $state<string | null>(null);
@@ -260,6 +267,26 @@
</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} />
</div>
<div class="cell cell-radar">
<SweepRadar sweep={fruitSweep} baseline={fruitBaseline} size={180} />
</div>
</div>
</section>
<style>
@@ -427,6 +454,8 @@
.cell-chart {
height: 28px;
max-height: 28px;
overflow: hidden;
}
.cell-range {
@@ -437,6 +466,17 @@
letter-spacing: 0.005em;
}
.row-radar {
align-items: center;
padding: 16px 0;
}
.cell-radar {
display: flex;
justify-content: center;
max-width: 42vw;
}
/* Responsive */
@media (max-width: 900px) {
.panel-title { font-size: 22px; }
+16 -2
View File
@@ -117,9 +117,9 @@
</button>
{/if}
<span class="live" aria-label="Connected">
<span class="live" class:disconnected={!cultivar.wsConnected} aria-label={cultivar.wsConnected ? 'Connected' : 'Connecting'}>
<span class="dot"></span>
<span class="live-label">Live</span>
<span class="live-label">{cultivar.wsConnected ? 'Live' : 'Connecting'}</span>
</span>
<button class="menu-btn" aria-label="Menu" type="button">
@@ -201,6 +201,20 @@
letter-spacing: 0.02em;
}
.live.disconnected {
border: 1px solid var(--attention);
opacity: 0.25;
color: var(--paper);
}
.live.disconnected .dot {
background-color: var(--attention);
}
.live.disconnected .live-label {
color: var(--attention);
}
.dot {
width: 6px;
height: 6px;
+1 -1
View File
@@ -207,7 +207,7 @@
<div class="fact">
<dt>
Confidence
<InfoHint title="Confidence" body="How sure Cultivar is about its reading from the photos. Low confidence usually means the camera can't get a good view. Try giving the lens a gentle wipe or repositioning the bag for a clearer shot." side="bottom" />
<InfoHint title="Confidence" body="How sure Cultivar is about its reading from the photos. Low confidence usually means the camera can't get a good view. Try repositioning the bag for a clearer shot." side="bottom" />
</dt>
<dd class="font-serif">{Math.round(bag.vision.colonization_confidence * 100)}%</dd>
</div>