feat: show metered devices below rooms in utility overview

This commit is contained in:
jhartworks committed 2026-11-12 14:44:02 +01:00
1 parent 173d02e3cc
commit df4a6f36a3
14 files changed
+1791 -1577

No files matched your search

+11 -6
View File
@@ -4,7 +4,7 @@ import type { HomeAssistant } from "../types.ts";
import { buildingUtilityReadings, floorUtilityAreas, floorUtilityReadings, UTILITY_ICONS, UTILITY_LABELS, utilityMetricLabel, utilityText, type UtilityReading } from "../utilities.ts";
import { trendButton } from "./trend-button.ts";
/** Building → floors, floor → native areas → rooms with their own explicit meters. */
/** Building → floors, floor → native areas → rooms → placed devices with a linked power value. */
class NfUtilityOverview extends LitElement {
static properties = { hass: { attribute: false }, floors: { attribute: false }, floorId: { attribute: false }, inline: { type: Boolean, reflect: true }, compact: { type: Boolean }, folded: { state: true } };
declare hass: HomeAssistant;
@@ -37,9 +37,9 @@ class NfUtilityOverview extends LitElement {
return readings.length ? html`<div class="meter" aria-label=${`${floor?.name || "Gesamtgebäude"} · ${UTILITY_LABELS[kind]}`}><span class="medium" title=${floor?.name || "Gesamtgebäude"}>${UTILITY_ICONS[kind]} ${UTILITY_LABELS[kind]}</span><div class="values">${readings.map((r) => this.value(r))}</div></div>` : nothing;
})}`;
}
const entries = floor ? floorUtilityAreas(this.hass, floor, rooms)
: [...this.floors].sort((a, b) => b.elevation - a.elevation).map((f) => ({ id: f.id, name: f.name, path: "", readings: floorUtilityReadings(this.hass, f, rooms), rooms: [] }));
const shown = entries.filter((e) => e.readings.length);
const entries = floor ? floorUtilityAreas(this.hass, floor, rooms, true).map((area) => ({ ...area, hasDetails: area.rooms.length > 0 }))
: [...this.floors].sort((a, b) => b.elevation - a.elevation).map((f) => ({ id: f.id, name: f.name, path: "", readings: floorUtilityReadings(this.hass, f, rooms), rooms: [], hasDetails: floorUtilityAreas(this.hass, f, rooms, true).length > 0 }));
const shown = entries.filter((e) => e.readings.length || e.hasDetails);
if (!shown.length) return nothing;
const folded = this.folded ?? this.compact;
return html`<section class="panel" aria-label=${floor ? "Bereichszähler" : "Stockwerkszähler"}>
@@ -48,7 +48,9 @@ class NfUtilityOverview extends LitElement {
${shown.map((entry) => html`<section class="entry" data-area=${floor ? entry.id : nothing}>
${floor ? html`<div class="entry-name area-name" title=${entry.path || entry.name}>${entry.name}</div>` : html`<button class="entry-name" title=${entry.name} @click=${() => this.open(entry.id, false)}>${entry.name}</button>`}
${this.rows(entry.readings)}
${entry.rooms.map((room) => html`<section class="room-entry" data-room=${room.id}><button class="entry-name" title=${room.name} @click=${() => this.open(room.id, true)}><span aria-hidden="true">↳</span> ${room.name}</button>${this.rows(room.readings)}</section>`)}
${entry.rooms.map((room) => html`<section class="room-entry" data-room=${room.id}><button class="entry-name" title=${room.name} @click=${() => this.open(room.id, true)}><span aria-hidden="true">↳</span> ${room.name}</button>${this.rows(room.readings)}
${room.devices.map((device) => html`<section class="device-entry" data-device=${device.id}><div class="entry-name device-name" title=${device.name}><span aria-hidden="true">↳</span> ${device.name}</div>${this.rows(device.readings)}</section>`)}
</section>`)}
</section>`)}
</div>`}
</section>`;
@@ -79,7 +81,10 @@ class NfUtilityOverview extends LitElement {
.entry-name:hover { color:var(--nf-accent); }
.area-name:hover { color:inherit; }
.room-entry { margin-top:5px; padding-top:4px; border-top:1px dotted var(--nf-line); }
.room-entry .entry-name { padding-left:12px; color:var(--nf-muted); font-weight:normal; }
.room-entry>.entry-name { padding-left:12px; color:var(--nf-muted); font-weight:normal; }
.device-entry { margin-top:4px; }
.device-entry>.device-name { padding-left:24px; color:var(--nf-muted); font-weight:normal; }
.device-name:hover { color:var(--nf-muted); }
.row { min-height:20px; }
.kind { color:var(--nf-muted); font-size:10px; white-space:nowrap; }
.row .value b { font-size:11px; font-weight:normal; }
+2 -2
View File
@@ -55,7 +55,7 @@ import { fixtureGlow } from "../entities/kinds.ts";
import { coverTiltEntity } from "../entities/covers.ts";
import { isSymcon, isSymconVariable, nativeBool, nativeText } from "../entities/symcon-values.ts";
import { WEATHER_VARIABLE_LABELS } from "../symcon-weather.ts";
import { floorUtilityReadings, utilityText } from "../utilities.ts";
import { floorUtilityAreas, floorUtilityReadings, utilityText } from "../utilities.ts";
import "./utility-report.ts";
import "./utility-overview.ts";
import { trendButton } from "./trend-button.ts";
@@ -2790,7 +2790,7 @@ export class NfView3d extends LitElement {
const b = this.building;
if (!b || !isSymcon(this.hass) || !this.showEnergy || this.clean || this.roomId || this.panelOpen || (!inline && !this._utilityOverviewVisible)) return nothing;
const rooms = b.floors.flatMap((f) => f.rooms), floors = this.floorId ? b.floors.filter((f) => f.id === this.floorId) : b.floors;
if (!floors.some((f) => floorUtilityReadings(this.hass, f, rooms).length)) return nothing;
if (!floors.some((f) => floorUtilityReadings(this.hass, f, rooms).length || floorUtilityAreas(this.hass, f, rooms, true).length)) return nothing;
return html`<nf-utility-overview ?inline=${inline} .hass=${this.hass} .floors=${b.floors} .floorId=${this.floorId} .compact=${this._narrowStage}
@utility-open=${(e: CustomEvent<{ floorId: string; roomId: string | null }>) => { e.stopPropagation(); if (e.detail.roomId) this.openRoom(e.detail.floorId, e.detail.roomId); else this.fire("floor-tap", { floorId: e.detail.floorId }); }}></nf-utility-overview>`;
}
+10 -4
View File
@@ -2,6 +2,7 @@ import { UTILITY_KINDS, type Floor, type Room, type UtilityKind } from "./model.
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: "❄" };
@@ -15,7 +16,7 @@ export interface UtilityReading {
export interface UtilityArea {
id: string; name: string; path: string; readings: UtilityReading[];
rooms: { id: string; name: 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();
@@ -144,12 +145,13 @@ export function roomUtilityReadings(hass: HomeAssistant, room: Room, rooms: read
}
/** 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): UtilityArea[] {
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) refs.push("unassigned");
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);
@@ -163,7 +165,10 @@ export function floorUtilityAreas(hass: HomeAssistant, floor: Floor, rooms: read
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) })).filter((r) => r.readings.length);
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);
}
@@ -196,6 +201,7 @@ export function utilityWatched(hass: HomeAssistant, floors: readonly Floor[]): s
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),
]))];
}
+82
View File
@@ -0,0 +1,82 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { box, entity, floorWith, hassOf } from "./entities/fixtures.ts";
import type { Furniture } from "./model.ts";
import { roomDevicePowerLinks } from "./utility-device-power.ts";
import { buildingUtilityReadings, floorUtilityAreas, floorUtilityReadings, utilityText, utilityWatched } from "./utilities.ts";
const meter = (id: string, value: number, unit = "W") => entity(id, "open", { symcon_variable_type: 1, symcon_value: value, unit_of_measurement: unit });
const furniture = (id: string, power: string | null, extra: Partial<Furniture> = {}): Furniture => ({ id, type: "desk", name: id, x: 2, z: 2, w: 1, d: 1, h: 1, rotation: 0, variant: null, power, entity: "none", ...extra });
const native = (states: ReturnType<typeof entity>[]) => hassOf(states, {}, { language: "de", symconObjects: [{ object_id: 10, parent_id: 0, name: "Büro", path: "Haus / Büro", object_type: 0 }] });
test("area → room → metered device retains zero and live values without manufacturing room or floor totals", () => {
const room = box("room", 0, 0, 5, 5, "symcon-category-10"), floor = floorWith([room], { furniture: [furniture("Wallbox", "cover.1")] });
const h = native([meter("cover.1", 0)]);
const area = floorUtilityAreas(h, floor, floor.rooms, true)[0];
assert.equal(area.name, "Büro"); assert.deepEqual(area.readings, []);
assert.deepEqual(area.rooms[0].readings, []);
assert.equal(area.rooms[0].devices[0].name, "Wallbox");
assert.equal(utilityText(h, area.rooms[0].devices[0].readings[0]), "0 W");
assert.deepEqual(floorUtilityAreas(h, floor), []);
assert.deepEqual(floorUtilityReadings(h, floor), []);
assert.deepEqual(buildingUtilityReadings(h, [floor]), []);
assert.ok(utilityWatched(h, [floor]).includes("cover.1"));
h.states["cover.1"] = meter("cover.1", -1.5, "kW");
assert.equal(floorUtilityAreas(h, floor, floor.rooms, true)[0].rooms[0].devices[0].readings[0].value, -1500);
h.states["cover.1"].state = "unavailable";
assert.equal(utilityText(h, floorUtilityAreas(h, floor, floor.rooms, true)[0].rooms[0].devices[0].readings[0]), "Err: –");
});
test("device-only rooms and explicitly metered rooms share an area without changing its total or floor override", () => {
const a = box("A", 0, 0, 5, 5, "symcon-category-10"), b = box("B", 5, 0, 10, 5, "symcon-category-10");
b.utility_meters = { electricity: { power: "sensor.2" } };
a.sub_areas = ["symcon-category-20"];
const floor = floorWith([a, b], { furniture: [furniture("Gerät", "light.1")], utility_meters: { electricity: { power: "sensor.3" } } });
const h = native([meter("light.1", 250), meter("sensor.2", 30), meter("sensor.3", 900), meter("sensor.12", 320)]);
h.symconObjects = [...h.symconObjects!, { object_id: 11, parent_id: 10, object_type: 0, name: "Strom", path: "Büro / Strom", hidden: false, position: 0, icon: "" }, { object_id: 12, parent_id: 11, object_type: 2, name: "Leistung", path: "", entity_id: "sensor.12", hidden: false, position: 0, icon: "" }];
const [area] = floorUtilityAreas(h, floor, floor.rooms, true);
assert.equal(area.readings[0].value, 320);
assert.deepEqual(area.rooms.map((r) => [r.id, r.readings.map((v) => v.value), r.devices.map((d) => d.name)]), [["A", [], ["Gerät"]], ["B", [30], []]]);
assert.equal(floorUtilityReadings(h, floor)[0].value, 900);
assert.equal(buildingUtilityReadings(h, [floor])[0].value, 900);
assert.equal(floorUtilityAreas(h, floor, floor.rooms, true).filter((g) => g.rooms.some((r) => r.id === "A")).length, 1);
});
test("geometry assigns devices to their own room once; outside and unlinked items do not create room headers", () => {
const floor = floorWith([box("A", 0, 0, 5, 5), box("B", 5, 0, 10, 5)], { furniture: [furniture("A", "sensor.1"), furniture("B", "sensor.1", { x: 7 }), furniture("outside", "sensor.1", { x: 20 }), furniture("empty", "none")], placements: [{ entity_id: "sensor.1", x: 2, y: 0, z: 2, outside: true }] });
const h = native([meter("sensor.1", 8)]);
assert.deepEqual([...roomDevicePowerLinks(h, floor)].map(([id, ds]) => [id, ds.map((d) => d.name)]), [["A", ["A"]], ["B", ["B"]]]);
const [group] = floorUtilityAreas(h, floor, floor.rooms, true);
assert.equal(group.name, "Nicht zugeordnet"); assert.equal(group.rooms.length, 2);
floor.rooms.push({ ...floor.rooms[0], id: "overlap" });
assert.equal(roomDevicePowerLinks(h, floor).has("overlap"), false);
assert.deepEqual(roomDevicePowerLinks(hassOf(Object.values(h.states)), floor), new Map());
});
test("native numeric power placements and additional readings use metadata regardless of their name or inferred domain", () => {
const floor = floorWith([box("room", 0, 0, 5, 5)], { placements: [{ entity_id: "cover.1", name: "Beliebiger Name", x: 2, y: 0, z: 2 }, { entity_id: "switch.2", x: 1, y: 0, z: 2, values: [{ id: "v", entity: "light.3", icon: "sun" }] }], furniture: [furniture("Zusatzleistung", "none", { values: [{ id: "v", entity: "light.3", icon: "sun" }] }), furniture("Temperatur", "none", { values: [{ id: "v", entity: "sensor.4", icon: "temperature" }] })] });
const h = native([meter("cover.1", 0), entity("switch.2", "off"), meter("light.3", 4), meter("sensor.4", 23, "°C")]);
assert.deepEqual(roomDevicePowerLinks(h, floor).get("room")?.map((d) => [d.name, d.source]), [["Zusatzleistung", "light.3"], ["Beliebiger Name", "cover.1"], ["switch.2", "light.3"]]);
});
test("associated power meters follow placed devices; aliases watch and display their canonical native source", () => {
const h = native([entity("switch.1", "off"), entity("sensor.2", "0", { device_class: "power", unit_of_measurement: "W" }), meter("cover.3", 7), entity("light.alias", "on", { symcon_source_entity: "cover.3" })]);
h.entities = { "switch.1": { entity_id: "switch.1", device_id: "plug" }, "sensor.2": { entity_id: "sensor.2", device_id: "plug" } };
const floor = floorWith([box("r", 0, 0, 5, 5)], { placements: [{ entity_id: "switch.1", x: 2, y: 0, z: 2 }], furniture: [furniture("Alias", "light.alias"), furniture("Fehlt", "sensor.deleted")] });
assert.deepEqual(roomDevicePowerLinks(h, floor).get("r")?.map((d) => d.source), ["cover.3", "sensor.deleted", "sensor.2"]);
assert.deepEqual(utilityWatched(h, [floor]).sort(), ["cover.3", "sensor.2", "sensor.deleted"]);
const ds = floorUtilityAreas(h, floor, floor.rooms, true)[0].rooms[0].devices;
assert.equal(ds[0].readings[0].value, 7); assert.equal(ds[1].readings[0].incomplete, true);
});
test("hidden furniture stays out; a manifold's pump circuits retain separate device values", () => {
const floor = floorWith([box("r", 0, 0, 5, 5)], { furniture: [furniture("Hidden", "sensor.1", { show_when: { entity: "switch.hide" } }), furniture("Verteiler", null, { type: "heating_manifold", hydronic: { circuits: [{ id: "p", kind: "pump", name: "Vorschubpumpe", power: "sensor.1" }, { id: "v", kind: "heating", name: "Nur Ventil", has_pump: false, power: "sensor.1" }] } })] });
const h = native([meter("sensor.1", 0), entity("switch.hide", "off")]);
assert.deepEqual(roomDevicePowerLinks(h, floor).get("r")?.map((d) => [d.name, d.source]), [["Verteiler · Vorschubpumpe", "sensor.1"]]);
});
test("legacy light-pin migration preserves a native power value even when its guessed domain is light", () => {
const h = native([meter("light.1", 120)]);
const floor = floorWith([box("r", 0, 0, 5, 5)], { furniture: [furniture("Serverschrank", null, { type: "lamp_ceiling", entity: "light.1" }), furniture("Abgewählt", "none", { entity: "light.1" })] });
assert.deepEqual(roomDevicePowerLinks(h, floor).get("r")?.map((d) => [d.name, d.source]), [["Serverschrank", "light.1"]]);
});
+59
View File
@@ -0,0 +1,59 @@
import { pointInPolygon, type Floor } from "./model.ts";
import type { HomeAssistant } from "./types.ts";
import { furnitureEntities } from "./entities/furniture-links.ts";
import { entityName } from "./entities/kinds.ts";
import { furnitureShown } from "./entities/visibility.ts";
import { furnitureName } from "./furniture-names.ts";
import { powerSensorFor } from "./energy.ts";
import { hasPump, hydronicConfig, isHydronic, realRef } from "./hydronic-model.ts";
import { isSymcon } from "./entities/symcon-values.ts";
export interface DevicePowerLink { id: string; name: string; source: string }
const sourceOf = (hass: HomeAssistant, id: string) => String(hass.states[id]?.attributes.symcon_source_entity || id);
/** Only metadata establishes whether an additional value is electrical power; names never filter it. */
function knownPower(hass: HomeAssistant, id: string): boolean {
const a = hass.states[sourceOf(hass, id)]?.attributes;
return a?.device_class === "power" || /^[km]?w$/i.test(String(a?.unit_of_measurement ?? "").trim());
}
/** Read-only detail rows for actual placements. These links never become room/area meter totals. */
export function roomDevicePowerLinks(hass: HomeAssistant, floor: Floor): Map<string, DevicePowerLink[]> {
const result = new Map<string, DevicePowerLink[]>();
if (!isSymcon(hass)) return result;
const links = furnitureEntities(hass, [floor]);
const add = (id: string, name: string, x: number, z: number, source: string | null | undefined) => {
if (!realRef(source)) return;
const room = floor.rooms.find((r) => r.points.length >= 3 && pointInPolygon([x, z], r.points));
if (!room) return;
const rows = result.get(room.id) ?? [];
rows.push({ id, name, source: sourceOf(hass, source) }); result.set(room.id, rows);
};
for (const item of floor.furniture) {
if (!furnitureShown(hass, item)) continue;
const name = item.name || furnitureName(hass, item.type);
const extra = (item.values ?? []).find((v) => realRef(v.entity) && knownPower(hass, v.entity));
const entity = links.get(item.id)?.entity;
const power = item.power === "none" ? null : item.power || links.get(item.id)?.power || (entity && knownPower(hass, entity) ? entity : null);
add(`furniture:${item.id}`, name, item.x, item.z, power || extra?.entity);
if (!power && !extra) {
const seen = new Set<string>();
for (const entity of item.gang_entities ?? []) {
if (!realRef(entity)) continue;
const source = powerSensorFor(hass, entity);
if (!source || seen.has(sourceOf(hass, source))) continue;
seen.add(sourceOf(hass, source));
add(`furniture:${item.id}:${entity}`, `${name} · ${entityName(hass, entity)}`, item.x, item.z, source);
}
}
if (isHydronic(item.type)) for (const c of hydronicConfig(item).circuits ?? []) {
if (hasPump(c)) add(`furniture:${item.id}:${c.id}`, `${name} · ${c.name || "Pumpe"}`, item.x, item.z, c.power);
}
}
for (const item of floor.placements) {
if (item.outside) continue;
const extra = (item.values ?? []).find((v) => realRef(v.entity) && knownPower(hass, v.entity));
const power = knownPower(hass, item.entity_id) ? item.entity_id : powerSensorFor(hass, item.entity_id);
add(`device:${item.entity_id}`, item.name || entityName(hass, item.entity_id), item.x, item.z, power || extra?.entity);
}
return result;
}