Files
Homelab-manager/server/src/services/homeAssistantSync.ts
T
bobbanandClaude Sonnet 5.5 18ceed62e8 Racks, notes and to-do, OS support, suggested dependencies, Nginx Proxy Manager and Home Assistant
- Racks page and a network diagram (UniFi tree with servers, printable)
- Notes on servers and devices; To do list shown in Coming up and My work
- Agents report the operating system (Linux 7, Windows 6); end-of-life badge and alert
- Suggested dependencies from where a service is reached
- Nginx Proxy Manager integration: proxy hosts page, certificate and host alerts, suggested checks
- Home Assistant integration: watch chosen entities, history chart, limit and unavailable alerts
- TimeChart gets a "value" scale that fits negatives; docs updated

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 21:47:56 +02:00

183 lines
9.4 KiB
TypeScript

/**
* Keeps what was chosen to watch in each Home Assistant up to date: every few minutes the entities are read (one call lists them all), the watched ones are
* stored with their state, and a numeric one adds a point to its history. The page, the chart and the alerts are built from what is stored — so none of them talks to
* Home Assistant — and a Home Assistant that is down costs only how fresh they are.
*
* What makes an alert: a watched entity that has been "unavailable" or "unknown" for a while, or a number past a limit somebody set (a UPS battery under 30, a
* freezer over -10).
*/
import { and, desc, eq, lt } from "drizzle-orm";
import { db } from "../db/client.js";
import { haEntities, haReadings, haWatched, integrations } from "../db/schema.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { createHomeAssistantAdapter, type HaEntity } from "../integrations/homeassistant/adapter.js";
import { getInternalFlag, setInternalFlag } from "./settingsStore.js";
export const SYNC_INTERVAL_MS = 5 * 60_000;
/** The stored states are only as good as the last good pass: after this long, alerts for them are held rather than judged. */
export const STALE_AFTER_MS = 20 * 60_000;
/** An entity must have said nothing for this long before it is an alert. */
export const UNAVAILABLE_MINUTES = 15;
export const READING_KEEP_DAYS = 35;
/** Two passes closer than this add one point to a history, not two. */
const MIN_READING_GAP_MS = 2 * 60_000;
const STATUS_FLAG = "homeAssistantSync";
export interface HaSyncStatus {
at: string;
ok: boolean;
error: string | null;
entities: number;
}
async function readStatuses(): Promise<Record<string, HaSyncStatus>> {
try {
const raw = await getInternalFlag(STATUS_FLAG);
return raw ? (JSON.parse(raw) as Record<string, HaSyncStatus>) : {};
} catch {
return {};
}
}
export async function haSyncStatuses(): Promise<Record<number, HaSyncStatus>> {
return Object.fromEntries(Object.entries(await readStatuses()).map(([k, v]) => [Number(k), v]));
}
export function isHaFresh(status: HaSyncStatus | undefined, nowMs: number): boolean {
return !!status && status.ok && nowMs - Date.parse(status.at) <= STALE_AFTER_MS;
}
/** Pure: when an entity first stopped saying anything, kept until it does. */
export function trackUnavailable(previous: string | null | undefined, unavailable: boolean, nowIso: string): string | null {
return unavailable ? (previous ?? nowIso) : null;
}
/** Stores one read of one Home Assistant: the watched entities' states and, for the numeric ones, a reading. */
export async function storeEntities(integrationId: number, entities: HaEntity[], now: Date = new Date()): Promise<number> {
const nowIso = now.toISOString();
const watched = await db.select().from(haWatched).where(eq(haWatched.integrationId, integrationId));
if (watched.length === 0) return 0;
const byId = new Map(entities.map((e) => [e.entityId, e]));
const before = new Map((await db.select().from(haEntities).where(eq(haEntities.integrationId, integrationId))).map((r) => [r.entityId, r]));
for (const w of watched) {
const e = byId.get(w.entityId);
// An entity that is no longer in Home Assistant at all is as good as unavailable.
const state = e?.state ?? "missing";
const unavailable = e ? e.unavailable : true;
const values = {
friendlyName: e?.name ?? null,
state,
value: e?.value ?? null,
unit: e?.unit ?? null,
deviceClass: e?.deviceClass ?? null,
lastChanged: e?.lastChanged ?? null,
unavailableSince: trackUnavailable(before.get(w.entityId)?.unavailableSince, unavailable, nowIso),
updatedAt: nowIso,
};
await db.insert(haEntities).values({ integrationId, entityId: w.entityId, ...values }).onConflictDoUpdate({ target: [haEntities.integrationId, haEntities.entityId], set: values });
if (e?.value !== null && e?.value !== undefined && !unavailable) {
const [newest] = await db.select({ at: haReadings.at }).from(haReadings).where(and(eq(haReadings.integrationId, integrationId), eq(haReadings.entityId, w.entityId))).orderBy(desc(haReadings.at)).limit(1);
if (!newest || now.getTime() - Date.parse(newest.at) >= MIN_READING_GAP_MS) await db.insert(haReadings).values({ integrationId, entityId: w.entityId, at: nowIso, value: e.value });
}
}
// What is no longer watched is no longer kept.
const watchedIds = watched.map((w) => w.entityId);
for (const id of before.keys()) if (!watchedIds.includes(id)) await db.delete(haEntities).where(and(eq(haEntities.integrationId, integrationId), eq(haEntities.entityId, id)));
await db.delete(haReadings).where(and(eq(haReadings.integrationId, integrationId), lt(haReadings.at, new Date(now.getTime() - READING_KEEP_DAYS * 86_400_000).toISOString())));
return watched.length;
}
/** Reads one Home Assistant and stores what is watched. Never throws: how it went is the answer, and what was stored is left alone when it failed. */
export async function syncHomeAssistant(integrationId: number, now: Date = new Date()): Promise<HaSyncStatus> {
let status: HaSyncStatus;
try {
const loaded = await loadIntegrationConfig(integrationId);
if (!loaded || loaded.integration.type !== "homeassistant") throw new Error("not a Home Assistant integration");
const entities = await createHomeAssistantAdapter(loaded.config as never).listEntities();
const count = await storeEntities(integrationId, entities, now);
status = { at: now.toISOString(), ok: true, error: null, entities: count };
} catch (err) {
const previous = (await readStatuses())[String(integrationId)];
status = { at: previous?.at ?? now.toISOString(), ok: false, error: err instanceof Error ? err.message : String(err), entities: previous?.entities ?? 0 };
console.error(`[home-assistant] couldn't read integration ${integrationId}:`, status.error);
}
try {
const all = await readStatuses();
all[String(integrationId)] = status;
await setInternalFlag(STATUS_FLAG, JSON.stringify(all));
} catch (err) {
console.error("[home-assistant] couldn't record the result:", err);
}
return status;
}
export async function syncAllHomeAssistants(now: Date = new Date()): Promise<Record<number, HaSyncStatus>> {
const rows = await db.select({ id: integrations.id }).from(integrations).where(and(eq(integrations.type, "homeassistant"), eq(integrations.enabled, true)));
const out: Record<number, HaSyncStatus> = {};
for (const r of rows) out[r.id] = await syncHomeAssistant(r.id, now);
return out;
}
/** Forgets everything of one integration when it is removed (and its status). */
export async function removeHomeAssistantData(integrationId: number): Promise<void> {
await db.delete(haReadings).where(eq(haReadings.integrationId, integrationId));
await db.delete(haEntities).where(eq(haEntities.integrationId, integrationId));
await db.delete(haWatched).where(eq(haWatched.integrationId, integrationId));
const all = await readStatuses();
if (String(integrationId) in all) {
delete all[String(integrationId)];
await setInternalFlag(STATUS_FLAG, JSON.stringify(all));
}
}
export interface HaProblem {
key: string;
kind: "unavailable" | "limit";
severity: "critical" | "warning";
message: string;
}
const durationWords = (ms: number) => {
const m = Math.floor(ms / 60_000);
return m < 60 ? `${m} min` : m < 48 * 60 ? `${Math.floor(m / 60)} h` : `${Math.floor(m / 1440)} days`;
};
/** Pure: what is wrong with the watched entities, from what is stored. */
export function haProblems(
integrationId: number,
integrationName: string,
watched: { entityId: string; name: string | null; above: number | null; below: number | null }[],
entities: Map<string, { friendlyName: string | null; state: string; value: number | null; unit: string | null; unavailableSince: string | null }>,
now: Date,
): HaProblem[] {
const out: HaProblem[] = [];
for (const w of watched) {
const e = entities.get(w.entityId);
if (!e) continue;
const name = w.name ?? e.friendlyName ?? w.entityId;
if (e.unavailableSince !== null) {
const ms = now.getTime() - Date.parse(e.unavailableSince);
if (ms >= UNAVAILABLE_MINUTES * 60_000) {
out.push({ key: `ha-unavailable:${integrationId}:${w.entityId}`, kind: "unavailable", severity: "warning", message: `${name} has been ${e.state === "missing" ? "missing from" : e.state} in Home Assistant for ${durationWords(ms)} [${integrationName}]` });
}
continue;
}
if (e.value === null) continue;
const unit = e.unit ? ` ${e.unit}` : "";
if (w.above !== null && e.value > w.above) out.push({ key: `ha-limit:${integrationId}:${w.entityId}`, kind: "limit", severity: "warning", message: `${name} is ${e.value}${unit}, above its limit of ${w.above}${unit} [${integrationName}]` });
else if (w.below !== null && e.value < w.below) out.push({ key: `ha-limit:${integrationId}:${w.entityId}`, kind: "limit", severity: "warning", message: `${name} is ${e.value}${unit}, below its limit of ${w.below}${unit} [${integrationName}]` });
}
return out;
}
let timer: ReturnType<typeof setInterval> | null = null;
export function initHomeAssistantSync(): void {
if (timer) return;
const pass = () => void syncAllHomeAssistants().catch((err) => console.error("[home-assistant] pass failed:", err));
timer = setInterval(pass, SYNC_INTERVAL_MS);
setTimeout(pass, 7_000);
console.log(`[home-assistant] reading watched entities every ${SYNC_INTERVAL_MS / 60000} minutes`);
}