feat: discover Symcon room utility meters and sum floor consumption
This commit is contained in:
1 parent
18e73194e0
commit
a804fc8e15
27 files changed
+2504
-1874
No files matched your search
@@ -0,0 +1,160 @@
|
||||
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";
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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: 0, period: s.period, sources: [], manual, incomplete: false };
|
||||
const value = nativeNumber(st);
|
||||
if (value === null) row.incomplete = true;
|
||||
else row.value! += value * (unit?.metric === s.metric ? unit.factor : 1);
|
||||
row.sources.push(id);
|
||||
groups.set(key, row);
|
||||
}
|
||||
return [...groups.values()].map((row) => row.incomplete ? { ...row, value: null } : row);
|
||||
}
|
||||
|
||||
export function roomUtilityReadings(hass: HomeAssistant, room: Room, rooms: readonly Room[] = []): UtilityReading[] {
|
||||
return readings(hass, roomSources(hass, room, rooms));
|
||||
}
|
||||
|
||||
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 = floor.rooms.flatMap((r) => roomSources(hass, r, rooms));
|
||||
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;
|
||||
}
|
||||
|
||||
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)),
|
||||
...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 {
|
||||
if (row.value === null) return "–";
|
||||
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 `${formatNumber(hass, value, digits)}${unit ? ` ${unit}` : ""}`;
|
||||
}
|
||||
Reference in new issue
Block a user