feat: discover Symcon room utility meters and sum floor consumption

This commit is contained in:
jhartworks committed 2026-11-11 09:55:26 +01:00
1 parent 18e73194e0
commit a804fc8e15
27 files changed
+2504 -1874

No files matched your search

+2 -1
View File
@@ -106,7 +106,8 @@ function copySymconAssets() {
// Size budgets, small enough for old wall tablets. The editor bundles only load for admins and the card's settings, so they
// may grow more than the view; German and English texts ride in every bundle.
const BUDGET = { "nextfloor.js": 650 * 1024, "nextfloor-3d.js": 1000 * 1024, "nextfloor-editor.js": 720 * 1024, "nextfloor-card-editor.js": 240 * 1024 };
// Native multi-utility discovery and reports add about 8 KB to the shared runtime.
const BUDGET = { "nextfloor.js": 660 * 1024, "nextfloor-3d.js": 1000 * 1024, "nextfloor-editor.js": 720 * 1024, "nextfloor-card-editor.js": 240 * 1024 };
copyAssets();
copySymconAssets();
+21 -3
View File
@@ -1,7 +1,10 @@
// The side panel's floor part: the floors of the house as chips, and the form of the selected floor.
import { html, nothing, type TemplateResult } from "lit";
import { DEFAULT_PAINT_OUTSIDE, type Floor } from "../../../model.ts";
import { DEFAULT_PAINT_OUTSIDE, UTILITY_KINDS, type Floor } from "../../../model.ts";
import { isSymcon, isSymconVariable } from "../../../entities/symcon-values.ts";
import { floorMeter, floorUtilityReadings, UTILITY_ICONS, UTILITY_LABELS } from "../../../utilities.ts";
import "../../utility-report.ts";
import type { HassFloor } from "../../../types.ts";
import { checkField, colorField, entityField, hint, numberField, selectField, textField } from "../fields.ts";
import { entityOptions } from "../entities.ts";
@@ -93,6 +96,22 @@ function copyChoices(host: EditorHost, state: SideState, floorActions: FloorActi
</div>`;
}
function utilityMeters(host: EditorHost, floor: Floor): TemplateResult {
const options = entityOptions(host.hass, (id) => isSymconVariable(host.hass, id, [1, 2]));
return html`<details class="nf-wide nf-utility-meters"><summary>Stockwerkszähler</summary><div class="nf-form">
${hint("Ohne eigenen Stockwerkszähler werden die Bereichszähler der Räume summiert. In der verknüpften Bereichskategorie werden Kategorien oder Dummy-Module namens Elektro/Strom, Wasser, Gas, Heizen und Kühlen durchsucht. Darin werden Leistung bzw. Durchfluss und Verbrauch bzw. Energie erkannt. Ein eigener Stockwerkszähler ersetzt nur die zugehörige Raumsumme. × stellt die automatische Raumsumme wieder her. Einheiten und Verbrauchszeiträume werden getrennt ausgewertet.", "nf-wide")}
${UTILITY_KINDS.map((kind) => html`<b class="nf-wide">${UTILITY_ICONS[kind]} ${UTILITY_LABELS[kind]}</b>${(["power", "energy"] as const).map((metric) => html`<label class="nf-field nf-wide">${metric === "power" ? "Leistung / Durchfluss" : "Energie / Verbrauch"}
<nf-entity-picker .options=${options} .objectTree=${host.hass?.symconObjects} .fixed=${[{ id: "__auto", label: "Raumsumme (automatisch)" }]} .value=${floorMeter(host.hass!, floor, kind, metric) ?? "__auto"} ?disabled=${!host.admin}
@change=${(e: CustomEvent<{ value: string | null }>) => {
e.stopPropagation();
const value = e.detail.value;
host.change((_, f) => { f.utility_meters = { ...f.utility_meters, [kind]: { ...f.utility_meters?.[kind], [metric]: value && value !== "__auto" && value !== "none" ? value : null } }; });
}}></nf-entity-picker>
</label>`)}`)}
<nf-utility-report class="nf-wide" .hass=${host.hass} .readings=${floorUtilityReadings(host.hass!, floor, host.doc.floors.flatMap((f) => f.rooms))}></nf-utility-report>
</div></details>`;
}
function floorForm(host: EditorHost, state: SideState, floorActions: FloorActions, floor: Floor): TemplateResult {
const t = host.t;
const update = (patch: Partial<Floor>) => host.change((_, f) => Object.assign(f, patch));
@@ -106,8 +125,7 @@ function floorForm(host: EditorHost, state: SideState, floorActions: FloorAction
${numberField(host, t("height"), floor.height, (v) => update({ height: Math.max(1, v) }), 0.05, 1)}
${Object.keys(host.hass?.floors ?? {}).length > 0 ? selectField(host, t("ha_floor"), floor.ha_floor ?? "", haChoices, (v) => update({ ha_floor: v || null }), { wide: true }) : nothing}
${checkField(host, t("floor_layer"), !!floor.layer, (on) => update({ layer: on || undefined }), { title: t("floor_layer_hint") })}
${entityField(host, t("floor_power"), floor.power_entity ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("sensor.") && host.hass?.states[id]?.attributes.device_class === "power"), (v) => update({ power_entity: v && v !== "none" ? v : null }))}
${floor.power_entity ? hint(t("floor_power_hint"), "nf-wide") : nothing}
${isSymcon(host.hass) ? utilityMeters(host, floor) : html`${entityField(host, t("floor_power"), floor.power_entity ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("sensor.") && host.hass?.states[id]?.attributes.device_class === "power"), (v) => update({ power_entity: v && v !== "none" ? v : null }))}${floor.power_entity ? hint(t("floor_power_hint"), "nf-wide") : nothing}`}
${floor.layer ? nothing : colorField(host, t("wall_paint_floor"), floor.wall_paint_outside, host.doc.settings.wall_paint_outside ?? DEFAULT_PAINT_OUTSIDE, (v) => update({ wall_paint_outside: v }))}
${areaRow(host, floor, floorActions)}
${host.admin && lacking.length > 0
+4
View File
@@ -10,6 +10,8 @@ import { pluginRoomSections } from "../plugins/registry.ts";
import { canAnnounce, roomHasSpeaker } from "../live/announce.ts";
import { isSymcon, nativeText } from "../entities/symcon-values.ts";
import "./room-hvac.ts";
import "./utility-report.ts";
import { roomUtilityReadings } from "../utilities.ts";
import type { Building, Floor, LightMood, LightSetting, Room } from "../model.ts";
import { roomPower, roomPowerSensors } from "../heatmap.ts";
import { energyCost, loadRoomEnergy, type RoomEnergy } from "../live/room-energy.ts";
@@ -209,6 +211,7 @@ export class NfRoomPanel extends LitElement {
private async loadEnergy(room: Room): Promise<void> {
if (!this.floor || !this.building) return;
if (isSymcon(this.hass)) { this._energy = null; return; }
const ids = roomPowerSensors(this.hass, this.building, this.floor, room);
try {
const energy = await loadRoomEnergy(this.hass, ids);
@@ -482,6 +485,7 @@ export class NfRoomPanel extends LitElement {
</button>
</header>
<div class="nf-rp-body" ?hidden=${this._folded}>
<nf-utility-report .hass=${this.hass} .readings=${roomUtilityReadings(this.hass, room, this.building?.floors.flatMap((f) => f.rooms))}></nf-utility-report>
${this.renderAllOff([...lights, ...media, ...switches])}
${this.renderClean(room)}
${!room.area_id && !outside && !(isSymcon(this.hass) && hvacRefs.length)
+34
View File
@@ -0,0 +1,34 @@
import { css, html, LitElement } from "lit";
import { UTILITY_KINDS } from "../model.ts";
import type { HomeAssistant } from "../types.ts";
import { UTILITY_ICONS, UTILITY_LABELS, utilityMetricLabel, utilityText, type UtilityReading } from "../utilities.ts";
/** The same metered readings in the room panel and the floor overview. */
class NfUtilityReport extends LitElement {
static properties = { hass: { attribute: false }, readings: { attribute: false } };
declare hass: HomeAssistant;
declare readings: UtilityReading[];
constructor() { super(); this.readings = []; }
render() {
return html`${UTILITY_KINDS.filter((kind) => this.readings.some((r) => r.kind === kind)).map((kind) => html`<section aria-label=${UTILITY_LABELS[kind]}>
<h4>${UTILITY_ICONS[kind]} ${UTILITY_LABELS[kind]}</h4>
${this.readings.filter((r) => r.kind === kind).map((r) => html`<div class="reading" title=${`${r.manual ? "Stockwerkszähler" : "Bereichszähler"}${r.incomplete ? " · Wert nicht verfügbar" : ""}\n${r.sources.map((id) => this.hass.states[id]?.attributes.symcon_path || this.hass.states[id]?.attributes.friendly_name || id).join("\n")}`}>
<span>${utilityMetricLabel(r)}${r.manual ? html` <small>· Zähler</small>` : ""}</span><b>${utilityText(this.hass, r)}</b>
</div>`)}
</section>`)}`;
}
static styles = css`
:host { display:block; color:var(--nf-text); font:inherit; }
section { padding:10px 0; border-bottom:1px solid var(--nf-line,#ffffff20); }
section:last-child { border:0; }
h4 { font:inherit; font-weight:600; margin:0 0 6px; }
.reading { display:flex; justify-content:space-between; gap:16px; margin:4px 0; }
.reading span { color:var(--nf-muted,#aaa); }
b { white-space:nowrap; font-variant-numeric:tabular-nums; }
small { font-size:.85em; }
`;
}
if (!customElements.get("nf-utility-report")) customElements.define("nf-utility-report", NfUtilityReport);
+7 -2
View File
@@ -52,6 +52,8 @@ 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 } from "../utilities.ts";
import "./utility-report.ts";
import { deviceValuesText } from "../entities/device-values.ts";
import { furnitureShown, hiddenFurniture, withoutHidden } from "../entities/visibility.ts";
import { pictureUrl } from "../entities/pictures.ts";
@@ -2598,7 +2600,7 @@ export class NfView3d extends LitElement {
const hass = this.hass;
const rows: { icon: string; label: string; value: string }[] = [];
const floor = this.floorId ? b.floors.find((f) => f.id === this.floorId) : undefined;
const floorPower = floor?.power_entity ? readPower(hass?.states[floor.power_entity]) : null;
const floorPower = floor && isSymcon(hass) ? floorUtilityReadings(hass, floor, b.floors.flatMap((f) => f.rooms)).find((r) => r.kind === "electricity" && r.metric === "power" && r.unit === "W")?.value ?? null : floor?.power_entity ? readPower(hass?.states[floor.power_entity]) : null;
if (floor && floorPower !== null) {
const share = consumption && consumption > 0 ? ` · ${translate(hass, "floor_power_share", { n: Math.round((Math.max(0, floorPower) / consumption) * 100) })}` : "";
rows.push({ icon: "⚡", label: floor.name, value: `${powerText(hass, floorPower)}${share}` });
@@ -2749,7 +2751,10 @@ export class NfView3d extends LitElement {
if (isSymcon(this.hass) && this.building?.settings.rain_sensor && this.building.settings.rain_sensor !== "none") weather.push(["Regensensor", this.building.settings.rain_sensor]);
const weatherValues = weather.length ? html`<button class="nf-energy-item nf-flow-toggle nf-weather-values" aria-label="Wetterwerte anzeigen" title="Wetterwerte anzeigen" aria-haspopup="dialog" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>(".nf-weather-dialog")?.showModal()}><span>Wetter</span><b aria-hidden="true">⛅</b></button>
<dialog class="nf-weather-dialog" aria-label="Wetterwerte" @keydown=${(event: KeyboardEvent) => event.stopPropagation()}><header><b>Wetter</b><button type="button" class="nf-chip" aria-label="Schließen" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>(".nf-weather-dialog")?.close()}>×</button></header>${weather.map(([label, id]) => html`<p><span>${label}</span><b>${nativeText(this.hass.states[id])}</b></p>`)}</dialog>` : nothing;
return [...people, weatherValues, ...ids
const floors = isSymcon(this.hass) ? (this.building?.floors ?? []).filter((f) => !this.floorId || f.id === this.floorId).map((f) => ({ floor: f, readings: floorUtilityReadings(this.hass, f, this.building?.floors.flatMap((x) => x.rooms)) })).filter((f) => f.readings.length) : [];
const utilities = floors.length ? html`<button class="nf-energy-item nf-flow-toggle nf-utility-toggle" aria-label="Stockwerkszähler anzeigen" title="Stockwerkszähler anzeigen" aria-haspopup="dialog" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>(".nf-utility-dialog")?.showModal()}><span>Stockwerkszähler</span><b aria-hidden="true">⚡ 💧</b></button>
<dialog class="nf-weather-dialog nf-utility-dialog" aria-label="Stockwerkszähler" @keydown=${(event: KeyboardEvent) => event.stopPropagation()}><header><b>Stockwerkszähler</b><button type="button" class="nf-chip" aria-label="Schließen" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>(".nf-utility-dialog")?.close()}>×</button></header>${floors.map(({ floor, readings }) => html`<h3>${floor.name}</h3><nf-utility-report .hass=${this.hass} .readings=${readings}></nf-utility-report>`)}</dialog>` : nothing;
return [...people, weatherValues, utilities, ...ids
.filter((id) => this.hass.states[id])
.map(
(id) => html`<button class="nf-energy-item nf-own-sensor" title=${entityName(this.hass, id)} @click=${() => openMoreInfo(this, id)}>
@@ -10,6 +10,7 @@ import { parkingEntities } from "../../parking.ts";
import { pluginWatched } from "../../plugins/registry.ts";
import type { HomeAssistant } from "../../types.ts";
import { weatherEntity } from "../../weather.ts";
import { utilityWatched } from "../../utilities.ts";
export interface WatchInputs {
hass: HomeAssistant;
@@ -64,6 +65,7 @@ export function watchedEntities(inputs: WatchInputs): string[] {
: []));
const ids: MaybeId[] = [
...placed,
...utilityWatched(hass, b.floors),
...b.floors.flatMap((f) => f.placements.flatMap((p) => [p.cover_tilt, p.position, ...(p.values ?? []).map((v) => v.entity)])),
...openingIds(inputs.openingLinks),
...placed.map((id) => powerSensorFor(hass, id)),
+3 -2
View File
@@ -6,6 +6,7 @@ import { entityAreaId, isHubDevice, powerSensorsOf } from "./devices.ts";
import { generateWalls } from "./geometry/walls.ts";
import type { Building, EnergySettings, Furniture } from "./model.ts";
import type { HassEntity, HomeAssistant } from "./types.ts";
import { nativeNumber } from "./entities/symcon-values.ts";
export interface EnergySummary {
/** Grid power in W: positive is import, negative is export. */
@@ -231,8 +232,8 @@ export function proposeEnergySensors(hass: HomeAssistant, prefs: EnergyPrefs): P
/** A power state in watts (kW and MW are converted), optionally with the sign flipped. Null when it is no number. */
export function readPower(st: HassEntity | undefined, invert = false): number | null {
const value = st ? Number(st.state) : NaN;
if (!Number.isFinite(value)) return null;
const value = st?.attributes.symcon_id ? nativeNumber(st) : st ? Number(st.state) : null;
if (value === null || !Number.isFinite(value)) return null;
const factor = { kW: 1e3, MW: 1e6 }[String(st!.attributes.unit_of_measurement ?? "W")] ?? 1;
return invert ? -value * factor : value * factor;
}
+7 -2
View File
@@ -2,6 +2,7 @@
import { roomClimateValue } from "./devices.ts";
import { powerSensorFor, readPower } from "./energy.ts";
import { roomUtilityReadings } from "./utilities.ts";
import { roomSun } from "./live/sun-hours.ts";
import { comfortScore, isSummer, mouldRisk } from "./live/room-climate.ts";
import { pointInPolygon, type Building, type Floor, type Room } from "./model.ts";
@@ -93,7 +94,9 @@ export function heatColor(mode: HeatColorMode, value: number, summer = false): R
* What the devices of a room draw now, in watts: the power sensors of its device pins and of its furniture (a piece's own power
* sensor, else the one on its entity's device), each counted once. Null when the room has none. The house's meters stay out.
*/
export function roomPower(hass: HomeAssistant, building: Pick<Building, "energy">, floor: Floor, room: Room): number | null {
export function roomPower(hass: HomeAssistant, building: Pick<Building, "energy"> & Partial<Pick<Building, "floors">>, floor: Floor, room: Room): number | null {
const metered = roomUtilityReadings(hass, room, building.floors?.flatMap((f) => f.rooms) ?? floor.rooms).filter((r) => r.kind === "electricity" && r.metric === "power");
if (metered.length) return metered.find((r) => r.unit === "W")?.value ?? null;
let sum: number | null = null;
for (const s of roomPowerSensors(hass, building, floor, room)) {
const w = readPower(hass.states[s]);
@@ -103,7 +106,9 @@ export function roomPower(hass: HomeAssistant, building: Pick<Building, "energy"
}
/** The power sensors of a room's device pins and furniture, each once, without the house's meters. */
export function roomPowerSensors(hass: HomeAssistant, building: Pick<Building, "energy">, floor: Floor, room: Room): string[] {
export function roomPowerSensors(hass: HomeAssistant, building: Pick<Building, "energy"> & Partial<Pick<Building, "floors">>, floor: Floor, room: Room): string[] {
const metered = roomUtilityReadings(hass, room, building.floors?.flatMap((f) => f.rooms) ?? floor.rooms).filter((r) => r.kind === "electricity" && r.metric === "power");
if (metered.length) return metered.filter((r) => r.unit === "W").flatMap((r) => r.sources);
const { grid, solar, battery } = building.energy;
const meters = new Set([grid, solar, battery].filter(Boolean));
const sensors = new Set<string>();
+6
View File
@@ -11,6 +11,10 @@ import type { ShowWhen } from "./entities/visibility.ts";
export type Vec2 = [number, number];
export const UTILITY_KINDS = ["electricity", "water", "gas", "heating", "cooling"] as const;
export type UtilityKind = typeof UTILITY_KINDS[number];
export interface UtilityMeterRefs { power?: EntityRef; energy?: EntityRef }
/** Sensors a room's climate is read from (null = automatic, "none" = no value). */
export interface RoomClimate {
temperature?: string | string[] | null;
@@ -439,6 +443,8 @@ export interface Floor {
layer?: boolean;
/** The floor's own meter: a power sensor whose use shows on the floor label and, in this floor's view, on the house card. */
power_entity?: string | null;
/** Native meters override the matching room sum, independently for each medium and metric. */
utility_meters?: Partial<Record<UtilityKind, UtilityMeterRefs>> | null;
/** Notes pinned to a spot of the floor ("filter due in March", "fuse 12"), shown in 3D and found by the search. */
notes?: PlanNote[];
/** Paint of this floor's outer walls in the solid wall view ("#rrggbb"; null = the building's outside colour): a plinth, a garage (#110). */
+2 -1
View File
@@ -3,6 +3,7 @@
import { fromCelsius, kindOf, openingState, primaryEntities, roomClimateValue, tempUnit, type OpeningEntities, roomEntities } from "./devices.ts";
import { readPower } from "./energy.ts";
import { floorUtilityReadings } from "./utilities.ts";
import { formatNumber, translate } from "./i18n.ts";
import { centroid, type Building, type Floor, type Room } from "./model.ts";
import type { HomeAssistant } from "./types.ts";
@@ -135,7 +136,7 @@ export function floorCounts(hass: HomeAssistant, building: Building, links: Map<
lightsOn: lightsOnFloor(hass, floor),
open: openingsOnFloor(hass, floor, links),
persons: persons.filter((p) => p.floorId === floor.id).length,
power: floor.power_entity ? readPower(hass.states[floor.power_entity]) : null,
power: isSymcon(hass) ? floorUtilityReadings(hass, floor, building.floors.flatMap((f) => f.rooms)).find((r) => r.kind === "electricity" && r.metric === "power" && r.unit === "W")?.value ?? null : floor.power_entity ? readPower(hass.states[floor.power_entity]) : null,
temps: tempRange(hass, floor),
},
]),
+3
View File
@@ -11,6 +11,7 @@ function linked(): Building {
floor.furniture = [{ id: "tv", type: "tv", x: 1, z: 1, rotation: 0, w: 1, d: 0.1, h: 0.6, variant: null, entity: "media_player.tv", power: "sensor.tv_power", pictures: [{ entity: "", state: "", image: "abc123" }, { entity: "", state: "", image: "https://example.org/a.png" }, { entity: "", state: "", image: "camera:front" }] }];
floor.background = { image_id: "bg1", x: 0, z: 0, width: 10, rotation: 0, opacity: 0.5 } as never;
b.floors = [floor];
floor.utility_meters = { gas: { power: "sensor.gas_rate", energy: "sensor.gas_total" } };
b.presence = [{ person: "person.a", sensor: "sensor.a" }];
b.energy = { ...b.energy, grid: "sensor.grid", solar: "sensor.solar" };
return b;
@@ -24,6 +25,8 @@ test("a shareable copy has no entity, area, person or background left", () => {
assert.equal(copy.floors[0].furniture[0].entity, null);
assert.equal(copy.floors[0].furniture[0].power, null);
assert.equal(copy.floors[0].background, null);
assert.equal(copy.floors[0].utility_meters, null);
assert.equal(original.floors[0].utility_meters?.gas?.energy, "sensor.gas_total");
assert.deepEqual([copy.presence, copy.energy.grid, copy.energy.solar], [[], null, null]);
// the original stays as it was
assert.equal(original.floors[0].rooms[0].area_id, "living");
+1
View File
@@ -83,6 +83,7 @@ export function withoutEntities(source: Building): Building {
floor.background = null;
floor.placements = [];
floor.power_entity = null;
floor.utility_meters = null;
floor.ha_floor = null;
for (const room of floor.rooms) {
Object.assign(room, { area_id: null, sub_areas: null, panel: [], hidden: [], no_state: [] });
+1
View File
@@ -61,6 +61,7 @@ export interface SymconObject {
icon: string;
/** Native module type of an instance (0 core, 1 IO, 2 splitter, 3 device, 4–6 system). */
module_type?: number;
module_id?: string;
/** Display-only grouping node; never an actual Symcon object. */
virtual?: boolean;
/** Present on variables and links to variables. */
+145
View File
@@ -0,0 +1,145 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { box, entity, floorWith, hassOf } from "./entities/fixtures.ts";
import type { HomeAssistant, SymconObject } from "./types.ts";
import { emptyBuilding, UTILITY_KINDS } from "./model.ts";
import { floorMeter, floorUtilityReadings, roomUtilityReadings, utilityText, utilityWatched } from "./utilities.ts";
import { roomPower, roomPowerSensors } from "./heatmap.ts";
import { floorCounts } from "./presence.ts";
import { watchedEntities } from "./components/view3d/watch-list.ts";
const DUMMY = "{485D0419-BE97-4548-AA9C-C083EB82E61E}";
function fixture() {
const objects: SymconObject[] = [];
const states: ReturnType<typeof entity>[] = [];
const node = (id: number, parent: number, name: string, type = 0, extra: Partial<SymconObject> = {}) => objects.push({ object_id: id, parent_id: parent, name, path: `Haus / ${name}`, object_type: type, hidden: true, position: 0, icon: "", ...extra });
const variable = (id: number, parent: number, name: string, value: number, unit: string, domain = "sensor") => {
const eid = `${domain}.${id}`;
node(id, parent, name, 2, { entity_id: eid });
states.push(entity(eid, domain === "sensor" ? String(value) : "on", { symcon_id: id, symcon_variable_type: 2, symcon_value: value, unit_of_measurement: unit, friendly_name: name }));
return eid;
};
const hass = () => hassOf(states, {}, { symconObjects: [...objects], language: "de" });
const room = (id = 10) => box(String(id), 0, 0, 5, 4, `symcon-category-${id}`);
return { objects, states, node, variable, hass, room };
}
test("hidden native categories and real dummy modules discover all five media, scoped to the room", () => {
const f = fixture(); f.node(10, 0, "Raum / Nord"); f.node(20, 0, "Fremder Raum");
for (const [i, name] of ["Elektro/Strom", "Wasser", "Gas", "Heizen", "Kühlen"].entries()) {
const id = 100 + i * 10;
f.node(id, 10, name, i % 2 ? 1 : 0, { module_id: DUMMY });
f.variable(id + 1, id, "Leistung", i + 1, i === 1 ? "m³/h" : "kW");
f.variable(id + 2, id, "Verbrauch", i + 10, i === 1 ? "m³" : "kWh");
}
f.node(200, 20, "Strom"); f.variable(201, 200, "Leistung", 9999, "kW");
f.node(300, 10, "Strom", 1, { module_id: "{OTHER}" }); f.variable(301, 300, "Leistung", 9999, "kW");
const rows = roomUtilityReadings(f.hass(), f.room());
assert.equal(rows.length, 10);
assert.deepEqual(new Set(rows.map((r) => r.kind)), new Set(UTILITY_KINDS));
assert.equal(rows.find((r) => r.kind === "electricity" && r.metric === "power")?.value, 1000);
assert.equal(rows.find((r) => r.kind === "cooling" && r.metric === "energy")?.value, 14);
});
test("native raw numeric values, compatible units and floor sums are used without counting aliases or links twice", () => {
const f = fixture(); f.node(10, 0, "A"); f.node(20, 0, "B");
f.node(11, 10, "Elektro"); f.node(21, 20, "Strom");
const id = f.variable(12, 11, "Leistung", 1.5, "kW", "light");
f.node(13, 11, "Leistung-Link", 6, { entity_id: id });
f.variable(14, 11, "Verbrauch", 2500, "Wh");
f.variable(22, 21, "Leistung", 500, "W"); f.variable(24, 21, "Verbrauch", 3, "kWh");
const h = f.hass(), a = f.room(), b = f.room(20), floor = floorWith([a, b]);
const rows = floorUtilityReadings(h, floor);
assert.deepEqual(rows.map((r) => [r.metric, r.unit, r.value]), [["power", "W", 2000], ["energy", "kWh", 5.5]]);
assert.equal(roomPower(h, emptyBuilding(), floor, a), 1500);
assert.deepEqual(roomPowerSensors(h, emptyBuilding(), floor, a), [id]);
const building = { ...emptyBuilding(), floors: [floor] };
assert.equal(floorCounts(h, building, new Map(), []).get(floor.id)?.power, 2000);
assert.deepEqual(utilityWatched(h, [floor]).sort(), [id, "sensor.14", "sensor.22", "sensor.24"].sort());
});
test("a parent's total replaces submeter totals while separate periods and physical quantities remain separate", () => {
const f = fixture(); f.node(10, 0, "A"); f.node(11, 10, "Gas");
f.variable(12, 11, "Verbrauch", 100, "m³");
f.variable(13, 11, "Energie", 1200, "kWh");
f.variable(14, 11, "Verbrauch heute", 3, "m³");
f.variable(15, 11, "Verbrauch Monat", 20, "m³");
f.variable(16, 11, "Verbrauch Jahr", 70, "m³");
f.node(20, 11, "Unterzähler", 1); f.variable(21, 20, "Verbrauch", 999, "m³");
const rows = roomUtilityReadings(f.hass(), f.room());
assert.equal(rows.length, 5);
assert.deepEqual(rows.filter((r) => r.unit === "m³").map((r) => [r.period, r.value]), [["total", 100], ["day", 3], ["month", 20], ["year", 70]]);
assert.equal(rows.find((r) => r.unit === "kWh")?.value, 1200);
});
test("water flow and consumption convert litres without mixing flow into cumulative consumption", () => {
const f = fixture(); f.node(10, 0, "A"); f.node(11, 10, "Wasser");
f.variable(12, 11, "Durchfluss", 10, "l/min"); f.variable(13, 11, "Verbrauch", 2500, "l");
const rows = roomUtilityReadings(f.hass(), f.room());
assert.deepEqual(rows.map((r) => [r.metric, r.unit, r.value]), [["power", "m³/h", 0.6], ["energy", "m³", 2.5]]);
assert.equal(utilityText(f.hass(), { ...rows[0], value: 0.001 }), "0,001 m³/h");
});
test("explicit totals beat phase readings and synonymous total variables are not added twice", () => {
const f = fixture(); f.node(10, 0, "A"); f.node(11, 10, "Strom");
f.variable(12, 11, "Leistung", 100, "W"); f.variable(13, 11, "Gesamtleistung", 250, "W");
f.variable(14, 11, "Leistung L1", 75, "W");
f.variable(15, 11, "Verbrauch", 10, "kWh"); f.variable(16, 11, "Energie", 10, "kWh");
assert.deepEqual(roomUtilityReadings(f.hass(), f.room()).map((r) => r.value), [250, 10]);
});
test("shared categories count once per floor and a nested room's area is excluded from its parent's room", () => {
const f = fixture(); f.node(10, 0, "A"); f.node(11, 10, "Strom"); f.variable(12, 11, "Leistung", 100, "W");
f.node(20, 10, "B"); f.node(21, 20, "Strom"); f.variable(22, 21, "Leistung", 200, "W");
const a = f.room(), b = f.room(20), h = f.hass();
assert.equal(roomUtilityReadings(h, a, [a, b])[0].value, 100);
assert.equal(floorUtilityReadings(h, floorWith([a, b]))[0].value, 300);
assert.equal(floorUtilityReadings(h, floorWith([a, { ...a, id: "shared" }]))[0].value, 300);
});
test("manual floor meters override only their matching metric, zero is valid, clearing returns to automatic", () => {
const f = fixture(); f.node(10, 0, "A"); f.node(11, 10, "Heizen");
f.variable(12, 11, "Leistung", 100, "W"); f.variable(13, 11, "Verbrauch", 5, "kWh");
const manual = f.variable(90, 0, "Stockwerksverbrauch", 0, "MWh", "cover");
const floor = floorWith([f.room()], { utility_meters: { heating: { energy: manual } } }), h = f.hass();
let rows = floorUtilityReadings(h, floor);
assert.deepEqual(rows.map((r) => [r.metric, r.value, r.manual]), [["power", 100, false], ["energy", 0, true]]);
assert.equal(utilityText(h, rows[1]), "0 kWh");
floor.utility_meters!.heating!.energy = null;
rows = floorUtilityReadings(h, floor);
assert.equal(rows[1].value, 5); assert.equal(rows[1].manual, false);
});
test("legacy floor power remains selected and an explicit automatic choice overrides it", () => {
const f = fixture(); const id = f.variable(90, 0, "Alt", 640, "W"); const h = f.hass();
const floor = floorWith([], { power_entity: id });
assert.equal(floorMeter(h, floor, "electricity", "power"), id);
assert.equal(floorUtilityReadings(h, floor)[0].value, 640);
floor.utility_meters = { electricity: { power: null } };
assert.equal(floorMeter(h, floor, "electricity", "power"), null);
assert.deepEqual(floorUtilityReadings(h, floor), []);
});
test("an unavailable meter makes its sum unavailable instead of reporting a partial total; live values update", () => {
const f = fixture(); f.node(10, 0, "A"); f.node(11, 10, "Strom"); f.variable(12, 11, "Leistung", 1, "W");
f.node(20, 0, "B"); f.node(21, 20, "Strom"); const id = f.variable(22, 21, "Leistung", 2, "W");
const floor = floorWith([f.room(), f.room(20)]), h = f.hass();
assert.equal(floorUtilityReadings(h, floor)[0].value, 3);
const next = { ...h, states: { ...h.states, [id]: { ...h.states[id], state: "unavailable" } } } as HomeAssistant;
assert.equal(floorUtilityReadings(next, floor)[0].value, null);
assert.equal(floorUtilityReadings(next, floor)[0].incomplete, true);
const live = { ...h, states: { ...h.states, [id]: { ...h.states[id], attributes: { ...h.states[id].attributes, symcon_value: 5 } } } };
assert.equal(floorUtilityReadings(live, floor)[0].value, 6);
});
test("the view watches automatic and all five manual floor meters even without heatmap or climate cards", () => {
const f = fixture(); f.node(10, 0, "A"); f.node(11, 10, "Strom"); const auto = f.variable(12, 11, "Leistung", 1, "W");
const manual = UTILITY_KINDS.map((kind, i) => [kind, { energy: f.variable(100 + i, 0, "Stockwerksverbrauch", 5, "kWh") }] as const);
const floor = floorWith([f.room()], { utility_meters: Object.fromEntries(manual) });
const ids = watchedEntities({ hass: f.hass(), building: { ...emptyBuilding(), floors: [floor] }, openingLinks: new Map(), furnitureLinks: new Map(), needsRoomSensors: false, alertSources: null, weatherEntityId: null });
for (const id of [auto, ...manual.map(([, r]) => r.energy)]) assert.ok(ids.includes(id), id);
});
test("HA rooms do not gain guessed native utility readings", () => {
assert.deepEqual(roomUtilityReadings(hassOf([]), box("r", 0, 0, 4, 3, "living")), []);
});
+160
View File
@@ -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}` : ""}`;
}
+104
View File
@@ -0,0 +1,104 @@
// Native hierarchical meters, floor override picker, room/floor reports and live updates in the built UI.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { extname, join, relative, resolve } from "node:path";
import puppeteer from "puppeteer-core";
const root = resolve(import.meta.dirname, "..");
const server = createServer((req, res) => {
const file = resolve(root, `.${decodeURIComponent(new URL(req.url, "http://localhost").pathname)}`);
if (relative(root, file).startsWith("..") || !existsSync(file)) return res.writeHead(404).end();
res.writeHead(200, { "content-type": ({ ".html": "text/html", ".js": "text/javascript", ".json": "application/json" })[extname(file)] ?? "application/octet-stream" }).end(readFileSync(file));
});
await new Promise((done) => server.listen(0, "127.0.0.1", done));
let browser;
try {
const executablePath = [process.env.CHROME_PATH, "C:/Program Files/Google/Chrome/Application/chrome.exe", "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"].find((p) => p && existsSync(p));
browser = await puppeteer.launch({ executablePath, headless: true, args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"] });
const page = await browser.newPage();
const errors = []; page.on("pageerror", (e) => errors.push(String(e)));
await page.setViewport({ width: 1440, height: 1000 });
await page.goto(`http://127.0.0.1:${server.address().port}/preview/index.html`, { waitUntil: "networkidle0" });
await page.waitForFunction(() => window.nfPanel?.data.building?.floors.length);
await page.evaluate(async () => {
const p = window.nfPanel, objects = [], states = { ...p.hass.states };
const node = (id, parent, name, type = 0, extra = {}) => objects.push({ object_id: id, parent_id: parent, name, path: `Haus / ${name}`, object_type: type, hidden: true, position: 0, icon: "", ...extra });
const variable = (id, parent, name, value, unit, domain = "sensor") => {
const entity_id = `${domain}.${id}`;
node(id, parent, name, 2, { entity_id });
states[entity_id] = { entity_id, state: domain === "sensor" ? String(value) : "open", attributes: { symcon_id: id, symcon_variable_type: 2, symcon_value: value, unit_of_measurement: unit, symcon_path: `Haus / ${name}`, friendly_name: name } };
};
node(9000, 0, "Haus"); node(9010, 9000, "Büro"); node(9020, 9000, "Küche");
for (const [index, name] of ["Elektro/Strom", "Wasser", "Gas", "Heizen", "Kühlen"].entries()) {
const id = 9100 + 10 * index;
node(id, 9010, name, index % 2 ? 1 : 0, { module_id: "{485D0419-BE97-4548-AA9C-C083EB82E61E}" });
variable(id + 1, id, "Leistung", index + 1, index === 1 ? "m³/h" : "kW");
variable(id + 2, id, "Verbrauch", 10 + index, index === 1 ? "m³" : "kWh");
}
node(9200, 9020, "Strom"); variable(9201, 9200, "Leistung", 500, "W"); variable(9202, 9200, "Verbrauch", 5, "kWh");
variable(9900, 9000, "Eigener Stockwerksverbrauch", 75, "kWh", "cover");
const b = structuredClone(p.data.building), floor = b.floors[0];
floor.rooms[0].area_id = "symcon-category-9010"; floor.rooms[1].area_id = "symcon-category-9020";
floor.power_entity = null; floor.utility_meters = null;
window.utilityFloorId = floor.id;
p.data.edit(b);
p.hass = { ...p.hass, language: "de", states, symconObjects: objects };
await p.updateComplete;
[...p.shadowRoot.querySelectorAll("[role=tab]")].find((b) => b.textContent.includes("Editor")).click();
});
await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector("nf-editor")?.shadowRoot);
await page.evaluate(async () => {
const e = window.nfPanel.shadowRoot.querySelector("nf-editor"); window.utilityEditor = e;
e._floorId = window.utilityFloorId; e.selectItem("room", null); await e.updateComplete;
const details = e.shadowRoot.querySelector(".nf-utility-meters");
details.open = true;
if (details.querySelectorAll("nf-entity-picker").length !== 10) throw new Error("Every medium needs power and consumption pickers");
const report = details.querySelector("nf-utility-report"); await report.updateComplete;
if (!/1,5 kW/.test(report.shadowRoot.textContent) || !/15 kWh/.test(report.shadowRoot.textContent)) throw new Error("Floor room totals missing");
const picker = details.querySelectorAll("nf-entity-picker")[1]; await picker.updateComplete;
const native = picker.shadowRoot.querySelector("nf-symcon-object-picker"); await native.updateComplete;
native.shadowRoot.querySelector(".trigger").click(); await native.updateComplete;
const input = native.shadowRoot.querySelector(".search"); input.value = "Eigener Stockwerksverbrauch"; input.dispatchEvent(new Event("input", { bubbles: true })); await native.updateComplete;
const row = native.shadowRoot.querySelector("#object-9900");
if (!row?.classList.contains("selectable")) throw new Error("Float consumption must be selectable regardless of inferred cover domain");
row.click(); await native.updateComplete; native.shadowRoot.querySelector(".apply").click();
await e.updateComplete; await window.nfPanel.updateComplete; await e.updateComplete;
});
assert.equal(await page.evaluate(() => window.utilityEditor._doc.floors[0].utility_meters.electricity.energy), "cover.9900");
assert.match(await page.evaluate(async () => { const r = window.utilityEditor.shadowRoot.querySelector(".nf-utility-meters nf-utility-report"); await r.updateComplete; return r.shadowRoot.textContent; }), /75 kWh/);
await page.evaluate(async () => {
const e = window.utilityEditor, picker = e.shadowRoot.querySelectorAll(".nf-utility-meters nf-entity-picker")[1]; await picker.updateComplete;
const native = picker.shadowRoot.querySelector("nf-symcon-object-picker"); await native.updateComplete; native.shadowRoot.querySelector(".clear").click();
await e.updateComplete; await window.nfPanel.updateComplete; await e.updateComplete;
const rp = document.createElement("nf-room-panel");
Object.assign(rp, { hass: e.hass, building: e._doc, floor: e._doc.floors[0], room: e._doc.floors[0].rooms[0] });
document.body.append(rp); await rp.updateComplete;
const report = rp.shadowRoot.querySelector("nf-utility-report"); await report.updateComplete;
if (report.shadowRoot.querySelectorAll("section").length !== 5) throw new Error("Room report missing a medium");
if (!/10 kWh/.test(report.shadowRoot.textContent)) throw new Error("Room consumption missing");
rp.remove();
[...window.nfPanel.shadowRoot.querySelectorAll("[role=tab]")].find((b) => b.textContent.trim() === "3D").click();
});
assert.equal(await page.evaluate(() => window.nfPanel.data.building.floors[0].utility_meters.electricity.energy), null);
await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector("nf-view3d")?.shadowRoot.querySelector(".nf-utility-toggle"));
await page.evaluate(() => { window.utilityView = window.nfPanel.shadowRoot.querySelector("nf-view3d"); window.utilityView.shadowRoot.querySelector(".nf-utility-toggle").click(); });
assert.equal(await page.evaluate(() => window.utilityView.shadowRoot.querySelector(".nf-utility-dialog").open), true);
assert.match(await page.evaluate(async () => { const r = window.utilityView.shadowRoot.querySelector(".nf-utility-dialog nf-utility-report"); await r.updateComplete; return r.shadowRoot.textContent; }), /15 kWh/);
await page.evaluate(async () => {
const p = window.nfPanel, st = p.hass.states["sensor.9202"];
p.hass = { ...p.hass, states: { ...p.hass.states, "sensor.9202": { ...st, state: "8", attributes: { ...st.attributes, symcon_value: 8 } } } };
await p.updateComplete;
});
await page.waitForFunction(() => window.utilityView.shadowRoot.querySelector(".nf-utility-dialog nf-utility-report").shadowRoot.textContent.includes("18 kWh"));
const out = join(root, "preview/screenshots"); mkdirSync(out, { recursive: true });
await page.screenshot({ path: join(out, "symcon-utility-floor-desktop.png") });
await page.setViewport({ width: 390, height: 844 });
const bounds = await page.evaluate(() => { const r = window.utilityView.shadowRoot.querySelector(".nf-utility-dialog").getBoundingClientRect(); return { left: r.left, right: r.right, width: innerWidth }; });
assert.ok(bounds.left >= 0 && bounds.right <= bounds.width, "meter overview fits mobile viewport");
await page.screenshot({ path: join(out, "symcon-utility-floor-mobile.png") });
assert.deepEqual(errors, []);
console.log("OK: hidden category/dummy discovery, room and floor totals, ten native meter selectors, numeric cover-domain override, clear-to-automatic, live consumption update and desktop/mobile floor dialog");
} finally {
await browser?.close(); await new Promise((done) => server.close(done));
}