fix: group utility overview by area and show explicit room meters
This commit is contained in:
1 parent
8c6b23bd22
commit
93c015ec77
17 files changed
+1475
-1253
No files matched your search
@@ -15,6 +15,7 @@ import { generateWalls, innerSize, type Wall } from "../../../geometry/walls.ts"
|
||||
import { countsAsLiving, roomArea } from "../../../geometry/living-area.ts";
|
||||
import { roomSpeaker } from "../../../live/announce.ts";
|
||||
import { isSymcon } from "../../../entities/symcon-values.ts";
|
||||
import { renderSymconRoomMeters } from "../symcon-fields.ts";
|
||||
|
||||
/** What the room form makes the editor do, and the parts of it that the editor still draws itself. */
|
||||
export interface RoomActions {
|
||||
@@ -189,7 +190,7 @@ export function renderRoomForm(host: EditorHost, state: SideState, room: Room, a
|
||||
<button class="nf-btn" title=${t("room_start_view_hint")} ?disabled=${!host.admin} @click=${() => actions.rememberView()}>${t("room_start_view")}</button>
|
||||
${room.start_view ? html`<button class="nf-btn" title=${t("room_start_view_reset")} ?disabled=${!host.admin} @click=${() => actions.patch({ start_view: null })}>↺</button>` : nothing}
|
||||
</div>
|
||||
${actions.wallHeights} ${actions.climate} ${corners(host, room, rectangle, actions)}
|
||||
${actions.wallHeights} ${actions.climate} ${isSymcon(host.hass) ? renderSymconRoomMeters(host, room, (change) => actions.patch(change)) : nothing} ${corners(host, room, rectangle, actions)}
|
||||
${host.admin
|
||||
? html`<div class="nf-actions">
|
||||
<button class="nf-btn nf-primary" @click=${() => (state.packages = !state.packages)}>${t("pkg_open")}</button>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { html, nothing } from "lit";
|
||||
import { WEATHER_VARIABLE_KEYS, type BuildingSettings, type PresenceLink, type Room, type RoomHvac } from "../../model.ts";
|
||||
import { UTILITY_KINDS, WEATHER_VARIABLE_KEYS, type BuildingSettings, type PresenceLink, type Room, type RoomHvac } from "../../model.ts";
|
||||
import { UTILITY_ICONS, UTILITY_LABELS } from "../../utilities.ts";
|
||||
import { WEATHER_VARIABLE_LABELS } from "../../symcon-weather.ts";
|
||||
import { ROOM_HVAC_FIELDS } from "../../entities/room-hvac.ts";
|
||||
import { isSymconVariable } from "../../entities/symcon-values.ts";
|
||||
@@ -8,6 +9,18 @@ import { entityOptions } from "./entities.ts";
|
||||
import { checkField, entityField, hint, textField } from "./fields.ts";
|
||||
import type { EditorHost } from "./host.ts";
|
||||
|
||||
export function renderSymconRoomMeters(host: EditorHost, room: Room, patch: (change: Partial<Room>) => void) {
|
||||
const options = entityOptions(host.hass, (id) => isSymconVariable(host.hass, id, [1, 2]));
|
||||
return html`<details class="nf-room-utility-meters"><summary>Eigene Raumzähler</summary><div class="nf-form">
|
||||
${hint("Nur direkt zugewiesene Raumzähler erscheinen als eingerückte Raumzeile unter dem verknüpften Bereich. Die Bereichswerte stehen einmal beim Bereich; vorhandene Bereichssummen enthalten die Raumwerte bereits. Fehlt dem Bereich ein passender Zähler, werden dafür die eigenen Raumzähler summiert.", "nf-wide")}
|
||||
${UTILITY_KINDS.map((kind) => html`<b class="nf-wide">${UTILITY_ICONS[kind]} ${UTILITY_LABELS[kind]}</b>${(["power", "energy"] as const).map((metric) => entityField(host, metric === "power" ? "Leistung / Durchfluss" : "Energie / Verbrauch", room.utility_meters?.[kind]?.[metric] ?? null, undefined, options, (v) => {
|
||||
const meters = { ...room.utility_meters, [kind]: { ...room.utility_meters?.[kind], [metric]: v === "none" ? null : v } };
|
||||
if (!Object.values(meters[kind]!).some((id) => id && id !== "none")) delete meters[kind];
|
||||
patch({ utility_meters: Object.keys(meters).length ? meters : null });
|
||||
}, { types: [1, 2] }))}`)}
|
||||
</div></details>`;
|
||||
}
|
||||
|
||||
export function renderSymconRoomHvac(host: EditorHost, room: Room, patch: (change: Partial<Room>) => void) {
|
||||
const set = (change: Partial<RoomHvac>) => patch({ hvac: { ...room.hvac, ...change } });
|
||||
const schedules = room.hvac?.schedules ?? [];
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { UTILITY_KINDS, type Floor } from "../model.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { buildingUtilityReadings, floorUtilityReadings, roomUtilityReadings, UTILITY_ICONS, UTILITY_LABELS, utilityMetricLabel, utilityText, type UtilityReading } from "../utilities.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 → rooms: the same native readings in the bar and the quiet side card. */
|
||||
/** Building → floors, floor → native areas → rooms with their own explicit meters. */
|
||||
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;
|
||||
@@ -16,10 +16,17 @@ class NfUtilityOverview extends LitElement {
|
||||
|
||||
constructor() { super(); this.floors = []; this.floorId = null; this.inline = false; this.compact = false; this.folded = null; }
|
||||
private value(row: UtilityReading | undefined) {
|
||||
return row ? html`<span class="value" title=${`${utilityMetricLabel(row)}${row.manual ? " · eigener Stockwerkszähler" : ""}`}><b>${utilityText(this.hass, row)}</b>${row.period !== "total" ? html`<small>${({ day: "heute", month: "Monat", year: "Jahr" })[row.period]}</small>` : nothing}${trendButton(this.hass, row.sources, `${UTILITY_LABELS[row.kind]} · ${utilityMetricLabel(row)}`)}</span>` : nothing;
|
||||
return row ? html`<span class="value" title=${`${utilityMetricLabel(row)}${row.manual ? " · eigener Zähler" : ""}`}><b>${utilityText(this.hass, row)}</b>${row.period !== "total" ? html`<small>${({ day: "heute", month: "Monat", year: "Jahr" })[row.period]}</small>` : nothing}${trendButton(this.hass, row.sources, `${UTILITY_LABELS[row.kind]} · ${utilityMetricLabel(row)}`)}</span>` : nothing;
|
||||
}
|
||||
private open(id: string, room: boolean) { this.dispatchEvent(new CustomEvent("utility-open", { detail: { floorId: room ? this.floorId : id, roomId: room ? id : null }, bubbles: true, composed: true })); }
|
||||
|
||||
private rows(readings: UtilityReading[]) {
|
||||
return UTILITY_KINDS.map((kind) => {
|
||||
const powers = readings.filter((r) => r.kind === kind && r.metric === "power"), energies = readings.filter((r) => r.kind === kind && r.metric === "energy");
|
||||
return Array.from({ length: Math.max(powers.length, energies.length) }, (_, i) => html`<div class="row"><span class="kind" title=${UTILITY_LABELS[kind]}>${i ? "" : `${UTILITY_ICONS[kind]} ${UTILITY_LABELS[kind]}`}</span>${powers[i] ? this.value(powers[i]) : html`<span></span>`}${energies[i] ? this.value(energies[i]) : html`<span></span>`}</div>`);
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
if (!this.hass) return nothing;
|
||||
const rooms = this.floors.flatMap((f) => f.rooms), floor = this.floors.find((f) => f.id === this.floorId);
|
||||
@@ -30,19 +37,18 @@ 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 ? floor.rooms.map((r) => ({ id: r.id, name: r.name, readings: roomUtilityReadings(this.hass, r, rooms) }))
|
||||
: [...this.floors].sort((a, b) => b.elevation - a.elevation).map((f) => ({ id: f.id, name: f.name, readings: floorUtilityReadings(this.hass, f, rooms) }));
|
||||
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);
|
||||
if (!shown.length) return nothing;
|
||||
const folded = this.folded ?? this.compact;
|
||||
return html`<section class="panel" aria-label=${floor ? "Bereichszähler" : "Stockwerkszähler"}>
|
||||
<button class="heading" aria-expanded=${!folded} @click=${() => { this.folded = !folded; }}><span>${floor ? "Bereiche" : "Stockwerke"}<small>${floor?.name || "Gesamtgebäude"}</small></span><span aria-hidden="true">${folded ? "+" : "−"}</span></button>
|
||||
${folded ? nothing : html`<div class="entries"><div class="columns"><span></span><span title="Leistung bzw. Durchfluss">Leistung</span><span>Energie / Verbrauch</span></div>
|
||||
${shown.map((entry) => html`<section class="entry"><button class="entry-name" title=${entry.name} @click=${() => this.open(entry.id, !!floor)}>${entry.name}</button>
|
||||
${UTILITY_KINDS.map((kind) => {
|
||||
const powers = entry.readings.filter((r) => r.kind === kind && r.metric === "power"), energies = entry.readings.filter((r) => r.kind === kind && r.metric === "energy");
|
||||
return Array.from({ length: Math.max(powers.length, energies.length) }, (_, i) => html`<div class="row"><span class="kind" title=${UTILITY_LABELS[kind]}>${i ? "" : `${UTILITY_ICONS[kind]} ${UTILITY_LABELS[kind]}`}</span>${powers[i] ? this.value(powers[i]) : html`<span></span>`}${energies[i] ? this.value(energies[i]) : html`<span></span>`}</div>`);
|
||||
})}
|
||||
${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>`)}
|
||||
</section>`)}
|
||||
</div>`}
|
||||
</section>`;
|
||||
@@ -71,6 +77,9 @@ class NfUtilityOverview extends LitElement {
|
||||
.entry:last-child { padding-bottom:0; }
|
||||
.entry-name { display:block; width:100%; padding:0 0 3px; font-size:11px; font-weight:600; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; }
|
||||
.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; }
|
||||
.row { min-height:20px; }
|
||||
.kind { color:var(--nf-muted); font-size:10px; white-space:nowrap; }
|
||||
.row .value b { font-size:11px; font-weight:normal; }
|
||||
|
||||
@@ -15,7 +15,7 @@ class NfUtilityReport extends LitElement {
|
||||
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 ? " · Err: Mindestens ein Wert fehlt; angezeigt wird die Summe der verfügbaren Werte." : ""}\n${r.sources.map((id) => this.hass.states[id]?.attributes.symcon_path || this.hass.states[id]?.attributes.friendly_name || id).join("\n")}`}>
|
||||
${this.readings.filter((r) => r.kind === kind).map((r) => html`<div class="reading" title=${`${r.manual ? "Eigener Zähler" : "Bereichszähler"}${r.incomplete ? " · Err: Mindestens ein Wert fehlt; angezeigt wird die Summe der verfügbaren Werte." : ""}\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)}${trendButton(this.hass, r.sources, `${UTILITY_LABELS[r.kind]} · ${utilityMetricLabel(r)}`)}</b>
|
||||
</div>`)}
|
||||
</section>`)}`;
|
||||
|
||||
@@ -53,6 +53,8 @@ export interface Room {
|
||||
/** Show temperature, humidity and CO2 in a floating glass card over this room. */
|
||||
climate_card?: boolean;
|
||||
hvac?: RoomHvac | null;
|
||||
/** Explicit room meters; area meters are shown once for their linked native category. */
|
||||
utility_meters?: Partial<Record<UtilityKind, UtilityMeterRefs>> | null;
|
||||
id: string;
|
||||
name: string;
|
||||
area_id: string | null;
|
||||
|
||||
@@ -3,7 +3,7 @@ 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 { buildingUtilityReadings, floorMeter, floorUtilityReadings, roomUtilityReadings, utilityText, utilityWatched } from "./utilities.ts";
|
||||
import { buildingUtilityReadings, floorMeter, floorUtilityAreas, floorUtilityReadings, ownRoomUtilityReadings, roomUtilityReadings, utilityText, utilityWatched } from "./utilities.ts";
|
||||
import { roomPower, roomPowerSensors } from "./heatmap.ts";
|
||||
import { floorCounts, floorInfoText } from "./presence.ts";
|
||||
import { watchedEntities } from "./components/view3d/watch-list.ts";
|
||||
@@ -184,3 +184,61 @@ test("building totals use effective floor meters, deduplicate shared sources and
|
||||
assert.equal(rows[0].value, 500, "one shared native meter must not count twice in the building");
|
||||
assert.deepEqual(rows[0].sources, [manual]);
|
||||
});
|
||||
|
||||
test("the floor overview groups by native area ID and name; plan rooms without their own meters never become children", () => {
|
||||
const f = fixture(); f.node(10, 0, "Bereich Büro"); f.node(11, 10, "Strom"); f.variable(12, 11, "Leistung", 320, "W");
|
||||
f.node(20, 0, "Bereich Büro"); f.node(21, 20, "Strom"); f.variable(22, 21, "Leistung", 430, "W");
|
||||
const floor = floorWith([{ ...f.room(), id: "a", name: "SE Inno" }, { ...f.room(), id: "b", name: "WC Damen" }, { ...f.room(20), name: "Archiv" }]);
|
||||
const h = f.hass(), groups = floorUtilityAreas(h, floor);
|
||||
assert.deepEqual(groups.map((g) => [g.id, g.name, g.readings[0].value, g.rooms]), [["symcon-category-10", "Bereich Büro", 320, []], ["symcon-category-20", "Bereich Büro", 430, []]]);
|
||||
assert.equal(floorUtilityReadings(h, floor)[0].value, 750, "sharing an area never repeats its meter");
|
||||
});
|
||||
|
||||
test("explicit room meters are shown under their primary area without adding them to an existing area total", () => {
|
||||
const f = fixture(); f.node(10, 0, "Büro"); f.node(11, 10, "Strom"); f.variable(12, 11, "Leistung", 320, "W"); f.variable(13, 11, "Verbrauch", 100, "kWh");
|
||||
const power = f.variable(90, 0, "beliebiger Raumwert", 0, "W", "cover"), energy = f.variable(91, 0, "Raumzähler", 3, "kWh");
|
||||
const room = { ...f.room(), name: "IT Chef", utility_meters: { electricity: { power, energy } } };
|
||||
const other = { ...f.room(), id: "other", name: "Küche", utility_meters: { electricity: { power: "none", energy: null } } };
|
||||
const floor = floorWith([room, other]), h = f.hass(), [area] = floorUtilityAreas(h, floor);
|
||||
assert.deepEqual(area.readings.map((r) => r.value), [320, 100]);
|
||||
assert.deepEqual(area.rooms.map((r) => [r.id, r.name, r.readings.map((v) => v.value)]), [[room.id, "IT Chef", [0, 3]]]);
|
||||
assert.deepEqual(floorUtilityReadings(h, floor).map((r) => r.value), [320, 100]);
|
||||
assert.deepEqual(roomUtilityReadings(h, room).map((r) => r.value), [0, 3]);
|
||||
assert.ok(utilityWatched(h, [floor]).includes(power), "room readings stay watched even when their parent total covers them");
|
||||
h.states[power] = { ...h.states[power], state: "unavailable" };
|
||||
assert.equal(utilityText(h, floorUtilityAreas(h, floor)[0].rooms[0].readings[0]), "Err: –");
|
||||
assert.equal(utilityText(h, floorUtilityReadings(h, floor)[0]), "320 W");
|
||||
});
|
||||
|
||||
test("missing area quantities are summed from explicit room meters while units and periods remain separate", () => {
|
||||
const f = fixture(); f.node(10, 0, "Büro"); f.node(11, 10, "Strom"); f.variable(12, 11, "Leistung", 320, "W");
|
||||
const a = { ...f.room(), utility_meters: { electricity: { energy: f.variable(90, 0, "Raumzähler", 2000, "Wh") }, water: { energy: f.variable(91, 0, "Wasser heute", 20, "l") } } };
|
||||
const b = { ...f.room(), id: "b", utility_meters: { electricity: { energy: f.variable(92, 0, "Raumzähler", 3, "kWh") }, water: { energy: f.variable(93, 0, "Wasser", 4, "m³") } } };
|
||||
const floor = floorWith([a, b]), h = f.hass(), [area] = floorUtilityAreas(h, floor);
|
||||
assert.deepEqual(area.readings.map((r) => [r.kind, r.metric, r.unit, r.period, r.value]), [["electricity", "power", "W", "total", 320], ["electricity", "energy", "kWh", "total", 5], ["water", "energy", "m³", "day", .02], ["water", "energy", "m³", "total", 4]]);
|
||||
assert.equal(ownRoomUtilityReadings(h, a).length, 2, "an unassigned room power field never inherits the area's power into the child row");
|
||||
assert.equal(floorUtilityReadings(h, floor).find((r) => r.metric === "energy")?.value, 5);
|
||||
});
|
||||
|
||||
test("subareas are listed once and a room's own counters appear only below its primary area", () => {
|
||||
const f = fixture(); f.node(10, 0, "Büro"); f.node(11, 10, "Strom"); f.variable(12, 11, "Leistung", 100, "W");
|
||||
f.node(20, 0, "Nebenbereich"); f.node(21, 20, "Strom"); f.variable(22, 21, "Leistung", 200, "W");
|
||||
const meter = f.variable(90, 0, "Raumzähler", 10, "W");
|
||||
const room = { ...f.room(), sub_areas: ["symcon-category-20", "symcon-category-20"], utility_meters: { electricity: { power: meter } } };
|
||||
const floor = floorWith([room]), groups = floorUtilityAreas(f.hass(), floor);
|
||||
assert.deepEqual(groups.map((g) => [g.name, g.rooms.map((r) => r.id)]), [["Büro", [room.id]], ["Nebenbereich", []]]);
|
||||
assert.equal(floorUtilityReadings(f.hass(), floor)[0].value, 300);
|
||||
});
|
||||
|
||||
test("room meters without an area have a quiet unassigned group and participate in effective floor/building totals", () => {
|
||||
const f = fixture(), id = f.variable(90, 0, "Raumzähler", 12, "W");
|
||||
const room = { ...f.room(), area_id: null, utility_meters: { electricity: { power: id } } };
|
||||
const floor = floorWith([room]), h = f.hass();
|
||||
assert.equal(floorUtilityAreas(h, floor)[0].name, "Nicht zugeordnet");
|
||||
assert.deepEqual(floorUtilityReadings(h, floor)[0].sources, [id]);
|
||||
assert.equal(buildingUtilityReadings(h, [floor])[0].value, 12);
|
||||
floor.utility_meters = { electricity: { power: id } };
|
||||
assert.equal(buildingUtilityReadings(h, [floor])[0].value, 12, "the explicit floor meter still wins without double counting");
|
||||
room.utility_meters.electricity.power = "none";
|
||||
assert.deepEqual(floorUtilityAreas(h, floor), []);
|
||||
});
|
||||
@@ -13,6 +13,11 @@ export interface UtilityReading {
|
||||
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[] }[];
|
||||
}
|
||||
|
||||
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 => {
|
||||
@@ -119,8 +124,48 @@ function readings(hass: HomeAssistant, sources: Source[], manual = false): Utili
|
||||
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[] {
|
||||
return readings(hass, roomSources(hass, room, rooms));
|
||||
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): UtilityArea[] {
|
||||
if (!isSymcon(hass)) return [];
|
||||
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");
|
||||
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) })).filter((r) => r.readings.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 {
|
||||
@@ -130,7 +175,7 @@ export function floorMeter(hass: HomeAssistant, floor: Floor, kind: UtilityKind,
|
||||
}
|
||||
|
||||
export function floorUtilityReadings(hass: HomeAssistant, floor: Floor, rooms: readonly Room[] = floor.rooms): UtilityReading[] {
|
||||
const all = floor.rooms.flatMap((r) => roomSources(hass, r, rooms));
|
||||
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);
|
||||
@@ -150,6 +195,7 @@ export function utilityWatched(hass: HomeAssistant, floors: readonly Floor[]): s
|
||||
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)),
|
||||
...UTILITY_KINDS.flatMap((kind) => [floorMeter(hass, f, kind, "power"), floorMeter(hass, f, kind, "energy")]).filter((id): id is string => !!id),
|
||||
]))];
|
||||
}
|
||||
|
||||
@@ -39,8 +39,12 @@ try {
|
||||
node(9200, 9020, "Strom"); variable(9201, 9200, "Leistung", 500, "W"); variable(9202, 9200, "Verbrauch", 5, "kWh");
|
||||
node(9030, 9000, "Serverraum"); node(9300, 9030, "Strom"); variable(9301, 9300, "Leistung", 2, "kW"); variable(9302, 9300, "Verbrauch", 20, "kWh");
|
||||
variable(9900, 9000, "Eigener Stockwerksverbrauch", 75, "kWh", "cover");
|
||||
variable(9801, 9000, "Direkte Raumleistung", 0, "W", "cover"); variable(9802, 9000, "Direkter Raumverbrauch", 2, "kWh");
|
||||
states["cover.9801"].attributes.symcon_archive = { id: 999, counter: false };
|
||||
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.rooms[0].name = "IT Chef"; floor.rooms[2].name = "IT Werkstatt"; floor.rooms[3].name = "WC Damen";
|
||||
floor.rooms[2].area_id = floor.rooms[3].area_id = "symcon-category-9010";
|
||||
floor.power_entity = null; floor.utility_meters = null;
|
||||
b.floors[1].rooms[0].area_id = "symcon-category-9030";
|
||||
b.floors[1].power_entity = null; b.floors[1].utility_meters = null;
|
||||
@@ -81,6 +85,21 @@ try {
|
||||
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();
|
||||
const chooseRoomMeter = async (roomId, index, objectId, search) => {
|
||||
e.selectItem("room", roomId); await e.updateComplete;
|
||||
const details = e.shadowRoot.querySelector(".nf-room-utility-meters"); details.open = true;
|
||||
if (details.querySelectorAll("nf-entity-picker").length !== 10) throw new Error("Every room medium needs power and consumption selectors");
|
||||
const picker = details.querySelectorAll("nf-entity-picker")[index]; 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 = search; input.dispatchEvent(new Event("input", { bubbles: true })); await native.updateComplete;
|
||||
const row = native.shadowRoot.querySelector(`#object-${objectId}`);
|
||||
if (!row?.classList.contains("selectable")) throw new Error("Native numeric room meter was excluded by an inferred actuator domain");
|
||||
row.click(); await native.updateComplete; native.shadowRoot.querySelector(".apply").click();
|
||||
await e.updateComplete; await window.nfPanel.updateComplete; await e.updateComplete;
|
||||
};
|
||||
await chooseRoomMeter(e._doc.floors[0].rooms[0].id, 0, 9801, "Direkte Raumleistung");
|
||||
await chooseRoomMeter(e._doc.floors[0].rooms[2].id, 1, 9802, "Direkter Raumverbrauch");
|
||||
[...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);
|
||||
@@ -110,7 +129,17 @@ try {
|
||||
});
|
||||
await page.waitForFunction(() => window.utilityView.floorId === window.utilityFloorId && window.utilityView.shadowRoot.querySelector('nf-utility-overview[inline]').shadowRoot.textContent.includes("15 kWh"));
|
||||
assert.match(await page.evaluate(() => window.utilityView.shadowRoot.querySelector('nf-utility-overview[inline]').shadowRoot.textContent), /1,5 kW/);
|
||||
assert.equal(await page.evaluate(() => window.utilityView.shadowRoot.querySelector('.nf-utility-right nf-utility-overview').shadowRoot.querySelectorAll('.entry').length), 2, "floor view lists its two metered rooms");
|
||||
assert.equal(await page.evaluate(() => window.utilityView.shadowRoot.querySelector('.nf-utility-right nf-utility-overview').shadowRoot.querySelectorAll('.entry').length), 2, "floor view lists its two native areas, despite multiple plan rooms sharing one area");
|
||||
assert.deepEqual(await page.evaluate(() => {
|
||||
const root = window.utilityView.shadowRoot.querySelector('.nf-utility-right nf-utility-overview').shadowRoot;
|
||||
return [...root.querySelectorAll('.entry')].map((entry) => ({ name: entry.querySelector('.area-name').textContent, rooms: [...entry.querySelectorAll('.room-entry')].map((room) => ({ name: room.querySelector('.entry-name').textContent.trim(), values: [...room.querySelectorAll('.value b')].map((b) => b.textContent), indent: Number.parseFloat(getComputedStyle(room.querySelector('.entry-name')).paddingLeft), trend: !!room.querySelector('nf-trend-button') })) }));
|
||||
}), [{ name: "Büro", rooms: [{ name: "↳ IT Chef", values: ["0 W"], indent: 12, trend: true }, { name: "↳ IT Werkstatt", values: ["2 kWh"], indent: 12, trend: false }] }, { name: "Küche", rooms: [] }], "only directly metered rooms are indented under the actual area; unassigned room values do not inherit area totals");
|
||||
await page.evaluate(async () => {
|
||||
const p = window.nfPanel, st = p.hass.states["cover.9801"];
|
||||
p.hass = { ...p.hass, states: { ...p.hass.states, "cover.9801": { ...st, attributes: { ...st.attributes, symcon_value: 37 } } } }; await p.updateComplete;
|
||||
});
|
||||
await page.waitForFunction(() => window.utilityView.shadowRoot.querySelector('.nf-utility-right nf-utility-overview').shadowRoot.querySelector('.room-entry .value b').textContent === "37 W");
|
||||
assert.match(await page.evaluate(() => window.utilityView.shadowRoot.querySelector('nf-utility-overview[inline]').shadowRoot.textContent), /1,5 kW/, "a room's detail never increases an existing area total");
|
||||
await page.evaluate(() => window.utilityView.shadowRoot.querySelector('.nf-utility-overview-toggle').click());
|
||||
await page.waitForFunction(() => !window.utilityView.shadowRoot.querySelector('.nf-utility-right'));
|
||||
assert.match(await page.evaluate(() => window.utilityView.shadowRoot.querySelector('nf-utility-overview[inline]').shadowRoot.textContent), /15 kWh/);
|
||||
@@ -177,11 +206,25 @@ try {
|
||||
assert.equal(await page.evaluate(() => window.utilityView.shadowRoot.querySelector('.nf-utility-right nf-utility-overview').shadowRoot.querySelectorAll('.entry').length), 2);
|
||||
await page.evaluate(() => { const p = window.nfPanel, card = window.utilityView.shadowRoot.querySelector('.nf-utility-right nf-utility-overview'); [...card.shadowRoot.querySelectorAll('.entry-name')].find((b) => b.textContent === p.data.building.floors[0].name).click(); });
|
||||
await page.waitForFunction(() => window.utilityView.floorId === window.utilityFloorId);
|
||||
await page.evaluate(() => window.utilityView.shadowRoot.querySelector('.nf-utility-right nf-utility-overview').shadowRoot.querySelector('.entry-name').click());
|
||||
await page.evaluate(() => window.utilityView.shadowRoot.querySelector('.nf-utility-right nf-utility-overview').shadowRoot.querySelector('.room-entry .entry-name').click());
|
||||
await page.waitForFunction(() => window.utilityView.roomId === window.nfPanel.data.building.floors[0].rooms[0].id && window.utilityView.panelOpen);
|
||||
assert.equal(await page.evaluate(() => !!window.utilityView.shadowRoot.querySelector('.nf-utility-right')), false, "the overview leaves space for the opened room menu");
|
||||
await page.evaluate(() => [...window.nfPanel.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'); e._floorId = window.utilityFloorId;
|
||||
e.selectItem('room', e._doc.floors[0].rooms[0].id); await e.updateComplete;
|
||||
const picker = e.shadowRoot.querySelector('.nf-room-utility-meters nf-entity-picker'); 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;
|
||||
if (e._doc.floors[0].rooms[0].utility_meters !== null) throw new Error('Clearing the last room meter must clear the direct assignment');
|
||||
window.nfPanel._roomId = null;
|
||||
[...window.nfPanel.shadowRoot.querySelectorAll('[role=tab]')].find((b) => b.textContent.trim() === '3D').click();
|
||||
});
|
||||
await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector('nf-view3d')?.shadowRoot.querySelector('.nf-utility-right nf-utility-overview')?.shadowRoot.querySelectorAll('.room-entry').length === 1);
|
||||
assert.equal(await page.evaluate(() => window.nfPanel.shadowRoot.querySelector('nf-view3d').shadowRoot.querySelector('.nf-utility-right nf-utility-overview').shadowRoot.querySelector('.room-entry .entry-name').textContent.trim()), '↳ IT Werkstatt', 'clearing a room meter removes only its child row and retains its area');
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("OK: hidden category/dummy discovery, room/floor totals and headers, native meter selectors, clear-to-automatic, live updates, Err: partial sums, missing readings, recovery and desktop/mobile dialog");
|
||||
console.log("OK: native area groups, repeated-area deduplication, explicit indented room meters, power/energy-only children, trends/live updates/clear, unchanged totals, floor overrides, Err and desktop/mobile overview");
|
||||
} finally {
|
||||
await browser?.close(); await new Promise((done) => server.close(done));
|
||||
}
|
||||
Reference in new issue
Block a user