Files
NextFloor/frontend/src/utilities.ts
T

220 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { UTILITY_KINDS, type Floor, type Room, type UtilityKind } from "./model.ts";
import type { HassEntity, HomeAssistant, SymconObject } from "./types.ts";
import { isSymcon, nativeNumber } from "./entities/symcon-values.ts";
import { formatNumber } from "./i18n.ts";
import { roomDevicePowerLinks, type DevicePowerLink } from "./utility-device-power.ts";
export const UTILITY_LABELS: Record<UtilityKind, string> = { electricity: "Strom", water: "Wasser", gas: "Gas", heating: "Heizen", cooling: "Kühlen" };
export const UTILITY_ICONS: Record<UtilityKind, string> = { electricity: "⚡", water: "💧", gas: "🔥", heating: "♨", cooling: "❄" };
export type UtilityMetric = "power" | "energy";
type Period = "total" | "day" | "month" | "year";
interface Source { kind: UtilityKind; metric: UtilityMetric; id: string; period: Period }
export interface UtilityReading {
kind: UtilityKind; metric: UtilityMetric; unit: string; value: number | null;
period: Period; sources: string[]; manual: boolean; incomplete: boolean;
}
export interface UtilityArea {
id: string; name: string; path: string; readings: UtilityReading[];
rooms: { id: string; name: string; readings: UtilityReading[]; devices: { id: string; name: string; readings: UtilityReading[] }[] }[];
}
const normalize = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/ß/g, "ss").replace(/[^a-z0-9]+/g, " ").trim();
const DUMMY = "{485D0419-BE97-4548-AA9C-C083EB82E61E}";
const kindOf = (node: SymconObject): UtilityKind | null => {
if (node.object_type !== 0 && !(node.object_type === 1 && node.module_id?.toUpperCase() === DUMMY)) return null;
return ({ elektro: "electricity", strom: "electricity", "elektro strom": "electricity", "strom elektro": "electricity", wasser: "water", gas: "gas", heizen: "heating", heizung: "heating", warme: "heating", waerme: "heating", kuhlen: "cooling", kuehlen: "cooling", kuhlung: "cooling", kuehlung: "cooling", kalte: "cooling", kaelte: "cooling" } as Record<string, UtilityKind>)[normalize(node.name)] ?? null;
};
const areaId = (id: string | null | undefined) => /^symcon-category-(\d+)$/.exec(id ?? "")?.[1];
const periodOf = (name: string): Period => /\b(heute|tag|tagesverbrauch|today|daily)\b/.test(name) ? "day" : /monat|month/.test(name) ? "month" : /jahr|year/.test(name) ? "year" : "total";
const canonical = (hass: HomeAssistant, id: string): string => String(hass.states[id]?.attributes.symcon_source_entity || id);
/** Convert only compatible physical quantities; a rate never becomes a cumulative consumption. */
function measure(st: HassEntity | undefined): { metric: UtilityMetric; unit: string; factor: number } | null {
const original = String(st?.attributes.unit_of_measurement ?? "").trim();
const u = original.replace(/[³]/g, "3").replace(/[²]/g, "2").replace(/\s+/g, "").toLowerCase();
if (["w", "kw", "mw"].includes(u)) return { metric: "power", unit: "W", factor: original === "mW" ? 0.001 : u === "kw" ? 1000 : u === "mw" ? 1e6 : 1 };
if (["wh", "kwh", "mwh", "j", "kj", "mj", "gj"].includes(u)) return { metric: "energy", unit: "kWh", factor: ({ wh: 0.001, kwh: 1, mwh: 1000, j: 1 / 3600000, kj: 1 / 3600, mj: 1 / 3.6, gj: 1000 / 3.6 } as Record<string, number>)[u] };
if (["m3/h", "m3h", "m3/min", "m3/s", "l/h", "l/min", "l/s", "liter/h", "liter/min"].includes(u)) return { metric: "power", unit: "m³/h", factor: ({ "m3/h": 1, m3h: 1, "m3/min": 60, "m3/s": 3600, "l/h": 0.001, "l/min": 0.06, "l/s": 3.6, "liter/h": 0.001, "liter/min": 0.06 } as Record<string, number>)[u] };
if (["m3", "l", "liter"].includes(u)) return { metric: "energy", unit: "m³", factor: u === "m3" ? 1 : 0.001 };
return null;
}
function candidate(hass: HomeAssistant, node: SymconObject): { metric: UtilityMetric; score: number; source: string; period: Period; group: string } | null {
if (!node.entity_id || (node.object_type !== 2 && node.object_type !== 6)) return null;
const id = canonical(hass, node.entity_id), st = hass.states[id];
if (!st || ![1, 2].includes(Number(st.attributes.symcon_variable_type))) return null;
const name = normalize(node.name), physical = measure(st);
const power = /^(leistung|wirkleistung|gesamtleistung|aktuelle leistung|durchfluss|volumenstrom)(\b|$)/.test(name);
const energy = /^(verbrauch|energie|energieverbrauch|gesamtverbrauch|gesamtenergie|zahlerstand|zaehlerstand|arbeit)(\b|$)/.test(name);
const metric = physical?.metric ?? (power ? "power" : energy ? "energy" : null);
if (!metric) return null;
const exact = metric === "power" ? /^(leistung|wirkleistung|gesamtleistung|durchfluss|volumenstrom)$/.test(name) : /^(verbrauch|energie|energieverbrauch|gesamtverbrauch|gesamtenergie|zahlerstand|zaehlerstand|arbeit)$/.test(name);
const period = metric === "energy" ? periodOf(name) : "total";
return { metric, source: id, period, group: `${metric}|${physical?.unit ?? String(st.attributes.unit_of_measurement ?? "")}|${period}`, score: /^gesamt(leistung|verbrauch|energie)$/.test(name) ? 110 : exact ? 100 : (metric === "power" ? power : energy) ? 70 : 20 };
}
interface Tree { nodes: Map<number, SymconObject>; children: Map<number, SymconObject[]> }
const indexes = new WeakMap<readonly SymconObject[], Tree>();
const discoveries = new WeakMap<HomeAssistant, Map<string, Source[]>>();
function treeOf(objects: readonly SymconObject[]): Tree {
const existing = indexes.get(objects);
if (existing) return existing;
const tree: Tree = { nodes: new Map(objects.map((n) => [n.object_id, n])), children: new Map() };
for (const n of objects) { const siblings = tree.children.get(n.parent_id) ?? []; siblings.push(n); tree.children.set(n.parent_id, siblings); }
indexes.set(objects, tree);
return tree;
}
/** Traverse real parent IDs, including hidden objects. A parent's own total wins over its sub-meters. */
function roomSources(hass: HomeAssistant, room: Room, rooms: readonly Room[]): Source[] {
if (!isSymcon(hass)) return [];
const roots = [room.area_id, ...(room.sub_areas ?? [])].map(areaId).filter((x): x is string => !!x);
if (!roots.length) return [];
const excluded = new Set(rooms.filter((r) => r.id !== room.id).flatMap((r) => [r.area_id, ...(r.sub_areas ?? [])]).map(areaId).filter((id): id is string => !!id && !roots.includes(id)));
const key = `${roots.join(",")}|${[...excluded].sort().join(",")}`;
const memo = discoveries.get(hass) ?? new Map<string, Source[]>();
discoveries.set(hass, memo);
const previous = memo.get(key);
if (previous) return previous;
const tree = treeOf(hass.symconObjects!), sources: Source[] = [], seen = new Set<number>();
const visit = (id: number, active: UtilityKind | null, blocked: ReadonlySet<string>) => {
if (seen.has(id) || excluded.has(String(id))) return;
seen.add(id);
const node = tree.nodes.get(id);
if (!node) return;
const ownKind = kindOf(node), kind = ownKind ?? active;
const stop = new Set(ownKind && ownKind !== active ? [] : blocked);
const children = tree.children.get(id) ?? [];
if (kind) {
const candidates = children.map((n) => candidate(hass, n)).filter((c) => c !== null);
for (const group of new Set(candidates.map((c) => c.group))) {
if (stop.has(group)) continue;
const fitting = candidates.filter((c) => c.group === group);
const score = Math.max(...fitting.map((c) => c.score));
// Explicit aggregate names are alternatives for the same total, not extra sub-meters.
const selected = fitting.filter((c) => c.score === score);
for (const c of score >= 100 ? selected.slice(0, 1) : selected) sources.push({ kind, metric: c.metric, id: c.source, period: c.period });
stop.add(group);
}
}
for (const child of children) if (child.object_type === 0 || child.object_type === 1) visit(child.object_id, kind, stop);
};
for (const root of roots) visit(Number(root), null, new Set());
memo.set(key, sources);
return sources;
}
function readings(hass: HomeAssistant, sources: Source[], manual = false): UtilityReading[] {
const groups = new Map<string, UtilityReading>();
const counted = new Set<string>();
for (const s of sources) {
const id = canonical(hass, s.id), identity = `${s.kind}|${s.metric}|${id}`;
if (counted.has(identity)) continue;
counted.add(identity);
const st = hass.states[id], unit = measure(st);
const canonicalUnit = unit?.metric === s.metric ? unit.unit : String(st?.attributes.unit_of_measurement ?? "").trim();
const key = `${s.kind}|${s.metric}|${canonicalUnit}|${s.period}`;
const row = groups.get(key) ?? { kind: s.kind, metric: s.metric, unit: canonicalUnit, value: null, period: s.period, sources: [], manual, incomplete: false };
const value = nativeNumber(st);
if (value === null) row.incomplete = true;
else row.value = (row.value ?? 0) + value * (unit?.metric === s.metric ? unit.factor : 1);
row.sources.push(id);
groups.set(key, row);
}
return [...groups.values()];
}
function roomMeterSources(hass: HomeAssistant, room: Room): Source[] {
return UTILITY_KINDS.flatMap((kind) => (["power", "energy"] as const).flatMap((metric) => {
const ref = room.utility_meters?.[kind]?.[metric];
if (!ref || ref === "none") return [];
const id = canonical(hass, ref);
return [{ kind, metric, id, period: metric === "energy" ? periodOf(normalize(String(hass.states[id]?.attributes.friendly_name ?? ""))) : "total" }];
}));
}
/** Room details contain only the explicitly assigned room readings. */
export function ownRoomUtilityReadings(hass: HomeAssistant, room: Room): UtilityReading[] {
return isSymcon(hass) ? readings(hass, roomMeterSources(hass, room), true) : [];
}
export function roomUtilityReadings(hass: HomeAssistant, room: Room, rooms: readonly Room[] = []): UtilityReading[] {
const own = ownRoomUtilityReadings(hass, room);
return own.length ? own : readings(hass, roomSources(hass, room, rooms));
}
/** Group by actual native category IDs, never by plan-room names or repeated meter values. */
export function floorUtilityAreas(hass: HomeAssistant, floor: Floor, rooms: readonly Room[] = floor.rooms, withDevices = false): UtilityArea[] {
if (!isSymcon(hass)) return [];
const devices = withDevices ? roomDevicePowerLinks(hass, floor) : new Map<string, DevicePowerLink[]>();
const groups = new Map<string, { seed: Room; members: Room[] }>();
for (const room of floor.rooms) {
const refs = [...new Set([room.area_id, ...(room.sub_areas ?? [])].filter((id): id is string => !!areaId(id)))];
if (!refs.length && (roomMeterSources(hass, room).length || devices.get(room.id)?.length)) refs.push("unassigned");
for (const id of refs) {
const group = groups.get(id) ?? { seed: room, members: [] };
if (id === refs[0]) group.members.push(room);
groups.set(id, group);
}
}
const nodes = treeOf(hass.symconObjects!).nodes;
return [...groups].map(([id, group]) => {
const node = nodes.get(Number(areaId(id)));
const auto = id === "unassigned" ? [] : readings(hass, roomSources(hass, { ...group.seed, area_id: id, sub_areas: null }, rooms));
const own = readings(hass, group.members.flatMap((r) => roomMeterSources(hass, r)), true);
// A room is a breakdown of an existing area meter, not an additional consumer.
const covered = (r: UtilityReading) => auto.some((a) => a.kind === r.kind && a.metric === r.metric && a.unit === r.unit && a.period === r.period);
const children = group.members.map((r) => ({
id: r.id, name: r.name, readings: ownRoomUtilityReadings(hass, r),
devices: (devices.get(r.id) ?? []).map((device) => ({ id: device.id, name: device.name, readings: readings(hass, [{ kind: "electricity", metric: "power", id: device.source, period: "total" }], true) })),
})).filter((r) => r.readings.length || r.devices.length);
return { id, name: id === "unassigned" ? "Nicht zugeordnet" : node?.name || hass.areas?.[id]?.name || "Bereich nicht verfügbar", path: node?.path || "", readings: [...auto, ...own.filter((r) => !covered(r))], rooms: children };
}).filter((g) => g.readings.length || g.rooms.length);
}
export function floorMeter(hass: HomeAssistant, floor: Floor, kind: UtilityKind, metric: UtilityMetric): string | null {
const refs = floor.utility_meters?.[kind];
const chosen = refs && Object.prototype.hasOwnProperty.call(refs, metric) ? refs[metric] : kind === "electricity" && metric === "power" ? floor.power_entity : null;
return chosen && chosen !== "none" ? canonical(hass, chosen) : null;
}
export function floorUtilityReadings(hass: HomeAssistant, floor: Floor, rooms: readonly Room[] = floor.rooms): UtilityReading[] {
const all = floorUtilityAreas(hass, floor, rooms).flatMap((a) => a.readings.flatMap((r) => r.sources.map((id) => ({ kind: r.kind, metric: r.metric, period: r.period, id }))));
const result: UtilityReading[] = [];
for (const kind of UTILITY_KINDS) for (const metric of ["power", "energy"] as const) {
const manual = floorMeter(hass, floor, kind, metric);
result.push(...readings(hass, manual ? [{ kind, metric, id: manual, period: metric === "energy" ? periodOf(normalize(String(hass.states[manual]?.attributes.friendly_name ?? ""))) : "total" }] : all.filter((s) => s.kind === kind && s.metric === metric), !!manual));
}
return result;
}
/** Sum the effective floor meters; shared native sources count only once for the building. */
export function buildingUtilityReadings(hass: HomeAssistant, floors: readonly Floor[], rooms: readonly Room[] = floors.flatMap((f) => f.rooms)): UtilityReading[] {
const sources = floors.flatMap((f) => floorUtilityReadings(hass, f, rooms).flatMap((r) => r.sources.map((id) => ({ kind: r.kind, metric: r.metric, period: r.period, id }))));
return readings(hass, sources);
}
export function utilityWatched(hass: HomeAssistant, floors: readonly Floor[]): string[] {
const rooms = floors.flatMap((f) => f.rooms);
return [...new Set(floors.flatMap((f) => [
...f.rooms.flatMap((r) => roomSources(hass, r, rooms).map((s) => s.id)),
...f.rooms.flatMap((r) => roomMeterSources(hass, r).map((s) => s.id)),
...[...roomDevicePowerLinks(hass, f).values()].flatMap((devices) => devices.map((device) => device.source)),
...UTILITY_KINDS.flatMap((kind) => [floorMeter(hass, f, kind, "power"), floorMeter(hass, f, kind, "energy")]).filter((id): id is string => !!id),
]))];
}
export function utilityMetricLabel(row: UtilityReading): string {
return row.metric === "power" ? row.unit === "m³/h" ? "Durchfluss" : "Leistung" : ({ total: "Verbrauch", day: "Verbrauch heute", month: "Verbrauch Monat", year: "Verbrauch Jahr" })[row.period];
}
export function utilityText(hass: HomeAssistant | undefined, row: UtilityReading): string {
const prefix = row.incomplete ? "Err: " : "";
if (row.value === null) return `${prefix}–`;
const value = row.unit === "W" && Math.abs(row.value) >= 1000 ? row.value / 1000 : row.value;
const unit = row.unit === "W" && Math.abs(row.value) >= 1000 ? "kW" : row.unit;
const digits = Number.isInteger(value) ? 0 : Math.min(6, Math.max(2, 1 - Math.floor(Math.log10(Math.abs(value)))));
return `${prefix}${formatNumber(hass, value, digits)}${unit ? ` ${unit}` : ""}`;
}