import { useCallback, useEffect, useMemo, useState } from "react"; import { api, type CurrentUser, type HaEntityChoice, type HaOverview, type HaWatchedEntity } from "../api/client"; import DetailDrawer from "../components/DetailDrawer"; import RangeSelect from "../components/RangeSelect"; import TimeAgo from "../components/TimeAgo"; import TimeChart from "../components/TimeChart"; import EmptyState from "../components/EmptyState"; import { BlockSkeleton } from "../components/Skeleton"; import { ErrorNotice } from "../components/Notice"; import { useChartRange } from "../utils/chartRanges"; import { readableError } from "../utils/errors"; import { toast } from "../utils/toast"; type Integration = HaOverview["integrations"][number]; const shownName = (w: HaWatchedEntity) => w.name ?? w.entity?.friendlyName ?? w.entityId; const numberWords = (v: number, unit: string | null) => `${Math.round(v * 100) / 100}${unit ? ` ${unit}` : ""}`; function StateCell({ w, problem }: { w: HaWatchedEntity; problem: boolean }) { const e = w.entity; if (!e) return not read yet; if (e.unavailableSince !== null || e.state === "missing") { return ( {e.state === "missing" ? "Not in Home Assistant" : e.state} {e.unavailableSince ? <> · : null} ); } return {e.value !== null ? numberWords(e.value, e.unit) : e.state}; } function limitsWords(w: HaWatchedEntity): string { const unit = w.entity?.unit ? ` ${w.entity.unit}` : ""; if (w.below !== null && w.above !== null) return `${w.below}–${w.above}${unit}`; if (w.below !== null) return `not under ${w.below}${unit}`; if (w.above !== null) return `not over ${w.above}${unit}`; return ""; } /** A watched number over time, from what this app has kept (up to 35 days). */ function HistoryDrawer({ integrationId, w, onClose }: { integrationId: number; w: HaWatchedEntity; onClose: () => void }) { const [days, setDays] = useChartRange(7); const shown = days > 30 ? 30 : days; const [points, setPoints] = useState<{ t: string; v: number }[] | null>(null); const [error, setError] = useState(null); const [to, setTo] = useState(() => Date.now()); useEffect(() => { let alive = true; api.homeAssistant .history(integrationId, w.entityId, shown) .then((res) => { if (!alive) return; setPoints(res.points); setTo(Date.now()); setError(null); }) .catch((err) => alive && setError(readableError(err))); return () => { alive = false; }; }, [integrationId, w.entityId, shown]); const unit = w.entity?.unit ?? ""; const series = useMemo(() => [{ name: shownName(w), color: "#4299e1", points: points ?? [] }], [points, w]); return (
{!points && !error && } {points && numberWords(v, unit)} empty="Nothing kept for this in this stretch yet — a reading is added every few minutes." />}
Readings are kept for 35 days.
); } /** Change what is said about an entity already watched: its name and its limits. */ function EditDrawer({ integrationId, w, onClose, onSaved }: { integrationId: number; w: HaWatchedEntity; onClose: () => void; onSaved: () => void }) { const numeric = w.entity?.value !== null && w.entity?.value !== undefined; const [name, setName] = useState(w.name ?? ""); const [below, setBelow] = useState(w.below === null ? "" : String(w.below)); const [above, setAbove] = useState(w.above === null ? "" : String(w.above)); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); async function save() { const parse = (s: string) => (s.trim() === "" ? null : Number(s)); const b = parse(below); const a = parse(above); if ((b !== null && !Number.isFinite(b)) || (a !== null && !Number.isFinite(a))) return setError("The limits have to be numbers."); setBusy(true); try { await api.homeAssistant.watch(integrationId, { entityId: w.entityId, name: name.trim() || null, below: b, above: a }); onSaved(); onClose(); } catch (err) { setError(readableError(err)); } finally { setBusy(false); } } return (
setName(e.target.value)} />
{numeric ? (
setBelow(e.target.value)} placeholder="no limit" />
setAbove(e.target.value)} placeholder="no limit" />
) : (
This one isn’t a number, so there are no limits to set. It is an alert when it has been unavailable for 15 minutes.
)}
); } /** Pick entities to watch: search what Home Assistant has, read live. */ function PickDrawer({ integration, onClose, onChanged }: { integration: Integration; onClose: () => void; onChanged: () => void }) { const [q, setQ] = useState(""); const [found, setFound] = useState<{ total: number; entities: HaEntityChoice[] } | null>(null); const [error, setError] = useState(null); const [busy, setBusy] = useState(null); useEffect(() => { let alive = true; const timer = setTimeout(() => { api.homeAssistant .entities(integration.id, q) .then((res) => { if (!alive) return; setFound(res); setError(null); }) .catch((err) => alive && setError(readableError(err))); }, 250); return () => { alive = false; clearTimeout(timer); }; }, [integration.id, q]); async function watch(e: HaEntityChoice) { setBusy(e.entityId); try { await api.homeAssistant.watch(integration.id, { entityId: e.entityId }); setFound((f) => (f ? { ...f, entities: f.entities.map((x) => (x.entityId === e.entityId ? { ...x, watched: true } : x)) } : f)); onChanged(); } catch (err) { toast.error(readableError(err)); } finally { setBusy(null); } } return (
Search by name or id, like “battery” or “freezer”. Limits are set afterwards, from the list.
setQ(e.target.value)} placeholder="Search Home Assistant…" aria-label="Search entities" autoFocus /> {!found && !error && } {found && ( <>
{found.entities.map((e) => (
{e.name}
{e.entityId} · {e.state} {e.unit ? ` ${e.unit}` : ""}
{e.watched ? ( Watching ) : ( )}
))}
{found.entities.length === 0 &&
Nothing matches.
}
{found.entities.length >= 60 ? "The first 60 of " : ""} {found.total} in Home Assistant.
)}
); } /** * The few things worth watching in Home Assistant — a UPS battery, a freezer, a door sensor, a pump — chosen here, not all several hundred entities. Each is read every * few minutes and kept with its history; it is an alert when it has said nothing for 15 minutes, or a number goes past a limit that was set. Nothing is ever written * to Home Assistant. */ export default function HomeAssistant({ user }: { user: CurrentUser }) { const canAct = user.role === "admin" || user.role === "operator"; const [data, setData] = useState(null); const [error, setError] = useState(null); const [reading, setReading] = useState(false); const [picking, setPicking] = useState(null); const [editing, setEditing] = useState<{ id: number; w: HaWatchedEntity } | null>(null); const [charting, setCharting] = useState<{ id: number; w: HaWatchedEntity } | null>(null); const load = useCallback( () => api.homeAssistant .overview() .then((res) => { setData(res); setError(null); }) .catch((err) => setError(readableError(err))), [], ); useEffect(() => { void load(); const timer = setInterval(() => void load(), 60_000); return () => clearInterval(timer); }, [load]); async function readNow() { setReading(true); try { const res = await api.homeAssistant.sync(); const failed = Object.values(res.statuses).filter((s) => !s.ok); if (failed.length > 0) toast.error(`Couldn't read Home Assistant: ${failed[0].error ?? "no answer"}`); else toast.success("Read from Home Assistant."); await load(); } catch (err) { toast.error(readableError(err)); } finally { setReading(false); } } async function stop(id: number, w: HaWatchedEntity) { try { await api.homeAssistant.unwatch(id, w.entityId); toast.success(`No longer watching ${shownName(w)}.`); await load(); } catch (err) { toast.error(readableError(err)); } } const live = data?.integrations ?? []; return ( <>

Home Assistant

{canAct && live.length > 0 && (
)}
The few things worth an alert in Home Assistant — a UPS battery, a freezer, a pump — chosen here rather than every entity it has. Each is read every five minutes and its history is kept for 35 days. It only reads; nothing is ever sent to Home Assistant.
{data === null && !error && } {data && live.length === 0 && (
)} {live.map((i) => (

{i.name}

{!i.enabled ? ( "Switched off" ) : !i.status ? ( "Not read yet" ) : i.status.ok ? ( <> Read · watching {i.status.entities} ) : ( <> Couldn’t be read: {i.status.error}. Showing what was read ; its alerts are held until it can be read again. )}
{canAct && i.enabled && (
)}
{i.watched.length === 0 ? ( setPicking(i) } : undefined} /> ) : (
{i.watched.map((w) => { const problem = i.problems.some((p) => p.key.endsWith(`:${w.entityId}`)); return ( ); })}
Name Now Alert when Last changed Actions
{shownName(w)}
{w.entityId}
{limitsWords(w) || unavailable for 15 min} {w.entity?.lastChanged ? : —}
{w.entity?.value !== null && w.entity?.value !== undefined && ( )} {canAct && ( <> )}
)}
))} {picking && setPicking(null)} onChanged={() => void load()} />} {editing && setEditing(null)} onSaved={() => void load()} />} {charting && setCharting(null)} />} ); }