feat: add native Symcon archive trends and explicit room naming

This commit is contained in:
jhartworks committed 2026-11-11 12:00:51 +01:00
1 parent bb153490b0
commit cfc77787a0
28 files changed
+2449 -1250

No files matched your search

+3 -2
View File
@@ -100,6 +100,7 @@ import { EditHistory } from "./editor/history.ts";
import { copyOfFurniture, copyOfOutdoorArea, deviceForFurniture, furnitureForDevice, newFloorOpening, newFreeWall, newFurniture, newOutdoorArea, offsetOnEdge, openingKindPatch, parkingSpotFor, placeInRoom, removeDevice, roomCentre, turnedBy } from "./editor/ops/items.ts";
import { NO_CHANGE, NOTHING_TO_MOVE, nudge, type NudgeTarget } from "./editor/ops/nudge.ts";
import { areaChoice, copyOfRoom, cornerMoved, evenCeilingLights, newRoom, rectangleAfter, removeCorner, removeRoom, type RectField } from "./editor/ops/rooms.ts";
import { isSymcon } from "../entities/symcon-values.ts";
import { translate as moveScope, turnQuarterClockwise, type Scope } from "./editor/ops/transform.ts";
import { Selection, type ItemKind } from "./editor/selection.ts";
import { SideState } from "./editor/side-state.ts";
@@ -545,7 +546,7 @@ export class NfEditor extends LitElement {
case "set_area":
return this.change((doc) => {
const room = onFloor(doc)?.rooms.find((r) => r.id === fix.roomId);
if (room) Object.assign(room, areaChoice(room, fix.areaId, this.hass?.areas ?? {}));
if (room) Object.assign(room, areaChoice(room, fix.areaId, this.hass?.areas ?? {}, !isSymcon(this.hass)));
});
case "add_area_rooms": {
const floor = onFloor(this._doc);
@@ -2636,7 +2637,7 @@ export class NfEditor extends LitElement {
private setArea(areaId: string): void {
const room = this.room;
if (room) this.updateRoom(areaChoice(room, areaId, this.hass?.areas ?? {}));
if (room) this.updateRoom(areaChoice(room, areaId, this.hass?.areas ?? {}, !isSymcon(this.hass)));
}
private setRect(field: RectField, value: number): void {
+2 -1
View File
@@ -7,7 +7,7 @@ import { PACKAGES, type PackageId } from "../../../packages.ts";
import { entityOptions } from "../entities.ts";
import { checkField, colorField, entityField, hint, numberField, selectField, textField } from "../fields.ts";
import type { EditorHost } from "../host.ts";
import type { RectField } from "../ops/rooms.ts";
import { areaLeafName, type RectField } from "../ops/rooms.ts";
import { SPOT_TYPES, spotCount, spotItems } from "../ops/spots.ts";
import type { SideState } from "../side-state.ts";
import { formatArea, formatLength } from "../../../units.ts";
@@ -161,6 +161,7 @@ export function renderRoomForm(host: EditorHost, state: SideState, room: Room, a
<div class="nf-form">
${textField(host, t("room_name"), room.name, (v) => actions.patch({ name: v }), { wide: true })}
${selectField(host, t("area"), room.area_id ?? "", areaChoices, (id) => actions.setArea(id), { wide: true })}
${isSymcon(host.hass) && room.area_id ? html`<button type="button" class="nf-btn nf-wide nf-take-area-name" ?disabled=${!host.admin || !areaLeafName(host.hass, room.area_id)} @click=${() => actions.patch({ name: areaLeafName(host.hass, room.area_id!) })}>Bereichsnamen übernehmen</button>` : nothing}
${(room.sub_areas ?? []).map((a) => html`<span class="nf-chip nf-wide">${host.hass?.areas?.[a]?.name ?? a} <button class="nf-btn nf-field-btn" ?disabled=${!host.admin} title=${t("delete")} @click=${() => actions.patch({ sub_areas: (room.sub_areas ?? []).filter((x) => x !== a).length ? (room.sub_areas ?? []).filter((x) => x !== a) : null })}>✕</button></span>`)}
${room.area_id
? selectField(host, t("sub_area_add"), "", areaChoices.filter(([id]) => id !== room.area_id && !(room.sub_areas ?? []).includes(id)), (id) => id && actions.patch({ sub_areas: [...(room.sub_areas ?? []), id] }), { wide: true, title: t("sub_area_hint") })
@@ -1,9 +1,9 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { box, floorWith, opening } from "../../../entities/fixtures.ts";
import { box, floorWith, opening, hassOf } from "../../../entities/fixtures.ts";
import type { Placement } from "../../../model.ts";
import { setWallSlope } from "./edges.ts";
import { insertCorner, areaChoice, copyOfRoom, cornerMoved, evenCeilingLights, newRoom, rectangleAfter, removeCorner, removeRoom } from "./rooms.ts";
import { insertCorner, areaChoice, areaLeafName, copyOfRoom, cornerMoved, evenCeilingLights, newRoom, rectangleAfter, removeCorner, removeRoom } from "./rooms.ts";
const lamp = (id: string, x: number, z: number, extra: Partial<Placement> = {}): Placement => ({ entity_id: id, x, z, y: null, ...extra });
@@ -73,6 +73,14 @@ test("choosing an area names a room that only had a placeholder name", () => {
assert.deepEqual(areaChoice({ ...box("r", 0, 0, 1, 1), name: "Lounge" }, "", areas), { area_id: null });
});
test("Symcon area selection preserves the name and explicit adoption uses the real leaf category", () => {
const h = hassOf([], {}, { areas: { "symcon-category-10": { area_id: "symcon-category-10", name: "Haus / OG / Büro" } }, symconObjects: [{ object_id: 10, parent_id: 2, name: "Büro / Nord", path: "Haus / OG / Büro / Nord", object_type: 0, position: 0, hidden: true, icon: "" }] });
assert.deepEqual(areaChoice({ ...box("r", 0, 0, 1, 1), name: "Room 3" }, "symcon-category-10", h.areas!, false), { area_id: "symcon-category-10" });
assert.equal(areaLeafName(h, "symcon-category-10"), "Büro / Nord");
assert.equal(areaLeafName({ ...h, symconObjects: [] }, "symcon-category-10"), "Büro");
assert.equal(areaLeafName(h, "missing"), "");
});
test("ceiling lights spread over the room in a grid, a short last row over the full width", () => {
const room = box("r", 0, 0, 6, 4);
const lights = [lamp("light.a", 1, 1), lamp("light.b", 1.1, 1), lamp("light.c", 1.2, 1), lamp("light.d", 1.3, 1), lamp("light.e", 1.4, 1)];
+10 -2
View File
@@ -3,6 +3,7 @@
import { bounds, pointInPolygon, uid, type Floor, type Opening, type Placement, type Room, type Vec2 } from "../../../model.ts";
import { arcPoints, pieceAt, polylineLength } from "../../../geometry/arcs.ts";
import { kindOf } from "../../../devices.ts";
import type { HomeAssistant } from "../../../types.ts";
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
const rounded = (points: readonly Vec2[]): Vec2[] => points.map(([x, z]) => [thousandths(x), thousandths(z)]);
@@ -73,10 +74,17 @@ const GENERIC_NAME = /^(Raum|Room) \d+$/;
* What choosing a Home Assistant area does to a room: it gets the area, and a name that was only a placeholder ("Room 3", or the
* name of some area) takes the area's name.
*/
export function areaChoice(room: Room, areaId: string, areas: Readonly<Record<string, { name: string }>>): Partial<Room> {
export function areaChoice(room: Room, areaId: string, areas: Readonly<Record<string, { name: string }>>, takeName = true): Partial<Room> {
const area = areaId ? areas[areaId] : undefined;
const placeholder = !room.name || GENERIC_NAME.test(room.name) || Object.values(areas).some((a) => a.name === room.name);
return { area_id: areaId || null, ...(area && placeholder ? { name: area.name } : {}) };
return { area_id: areaId || null, ...(takeName && area && placeholder ? { name: area.name } : {}) };
}
/** Use the actual leaf category, even when its native name contains a slash. */
export function areaLeafName(hass: HomeAssistant | undefined, areaId: string): string {
const id = /^symcon-category-(\d+)$/.exec(areaId)?.[1];
return (id ? hass?.symconObjects?.find((n) => n.object_id === Number(id))?.name : undefined)
?? hass?.areas?.[areaId]?.name.split(" / ").at(-1)?.trim() ?? "";
}
/**
+2 -1
View File
@@ -4,6 +4,7 @@ import type { HomeAssistant } from "../types.ts";
import { ROOM_HVAC_FIELDS } from "../entities/room-hvac.ts";
import { nativeBool, nativeNumber, nativeText, nativeValue } from "../entities/symcon-values.ts";
import { controls, tokens } from "../styles.ts";
import { trendButton } from "./trend-button.ts";
interface SchedulePoint { hour: number; minute: number; second: number; action: number }
interface ScheduleGroup { id: number; days: number; points: SchedulePoint[] }
@@ -29,7 +30,7 @@ export class NfRoomHvac extends LitElement {
private value(label: string, id: string, control: boolean) {
const st = this.hass.states[id], value = nativeValue(st), a = st?.attributes;
const writable = control && !!a?.symcon_has_action && value !== null && !this._pending.has(id);
return html`<div class="value"><span>${label}</span><b>${nativeText(st)}</b>
return html`<div class="value"><span>${label}</span><b>${nativeText(st)}${trendButton(this.hass, [id], label)}</b>
${control && a?.symcon_has_action && a.symcon_variable_type === 0 ? html`<button class="nf-chip" aria-pressed=${nativeBool(st) === true} ?disabled=${!writable} @click=${() => void this.send(id, "symcon", "set_value", { value: !nativeBool(st) })}>${nativeBool(st) ? "Ein" : "Aus"}</button>`
: control && a?.symcon_has_action && [1, 2].includes(Number(a.symcon_variable_type)) ? html`<input type="number" aria-label=${label} .value=${String(nativeNumber(st) ?? "")} min=${String(a.symcon_min ?? 0)} max=${String(a.symcon_max ?? 100)} step=${String(a.symcon_step || (a.symcon_variable_type === 1 ? 1 : 0.1))} ?disabled=${!writable}
@change=${(event: Event) => { const input = event.target as HTMLInputElement; if (input.value.trim() && input.checkValidity()) void this.send(id, "symcon", "set_value", { value: Number(input.value) }); }} />` : nothing}
+17 -16
View File
@@ -12,6 +12,7 @@ import { isSymcon, nativeText } from "../entities/symcon-values.ts";
import "./room-hvac.ts";
import "./utility-report.ts";
import { roomUtilityReadings, utilityText } from "../utilities.ts";
import { trendButton } from "./trend-button.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";
@@ -473,7 +474,7 @@ export class NfRoomPanel extends LitElement {
<header class="nf-rp-head">
<div>
<h2>${room.name}</h2>
${facts.length ? html`<p class="nf-rp-facts">${facts.join(" · ")}</p>` : nothing} ${this.renderEnergy()} ${this.renderSunYear()} ${this.renderShade()}
${facts.length ? html`<p class="nf-rp-facts">${facts.map((fact, i) => html`${i ? " · " : nothing}${fact}`)}</p>` : nothing} ${this.renderEnergy()} ${this.renderSunYear()} ${this.renderShade()}
${this.renderOpenWhileHeating(climates)} ${this.renderEmptyLights(room, lightsOn)}
${this.renderCurve()}
</div>
@@ -561,11 +562,11 @@ export class NfRoomPanel extends LitElement {
if (!this.floor) return nothing;
const groups = [...this.floor.placements.filter((p) => !p.outside && pointInPolygon([p.x, p.z], room.points)).map((p) => ({ name: p.name || entityName(this.hass, p.entity_id), rows: deviceValueReadouts(this.hass, p.values) })),
...this.floor.furniture.filter((f) => pointInPolygon([f.x, f.z], room.points)).map((f) => ({ name: f.name || (f.entity && f.entity !== "none" ? entityName(this.hass, f.entity) : this.t("device")), rows: deviceValueReadouts(this.hass, f.values) }))].filter((g) => g.rows.length);
return groups.length ? this.section("device_values", groups.map((g) => html`<div class="nf-extra-values"><b>${g.name}</b>${g.rows.map((v) => html`<div class="nf-rp-row"><span class="nf-rp-icon">${v.icon}</span><span class="nf-rp-name">${v.label}</span><b class="nf-rp-state">${v.text}</b></div>`)}</div>`)) : nothing;
return groups.length ? this.section("device_values", groups.map((g) => html`<div class="nf-extra-values"><b>${g.name}</b>${g.rows.map((v) => html`<div class="nf-rp-row"><span class="nf-rp-icon">${v.icon}</span><span class="nf-rp-name">${v.label}</span><b class="nf-rp-state">${v.text}${trendButton(this.hass, [v.entity], v.label)}</b></div>`)}</div>`)) : nothing;
}
private facts(climates: HassEntity[]): string[] {
const out: string[] = [];
private facts(climates: HassEntity[]): (string | TemplateResult)[] {
const out: (string | TemplateResult)[] = [];
const room = this.room;
// Outside has no climate of its own
if (!room) return out;
@@ -579,16 +580,16 @@ export class NfRoomPanel extends LitElement {
};
const climateTemp = climates.find((c) => typeof c.attributes.current_temperature === "number");
const temp = value("temperature", "°C");
if (temp) out.push(temp);
else if (climateTemp && room.climate?.temperature !== "none") out.push(`${formatNumber(this.hass, climateTemp.attributes.current_temperature as number, 1)} ${tempUnit(this.hass)}`);
if (temp) out.push(html`${temp}${trendButton(this.hass, roomClimateSensors(this.hass, this.floor, room, "temperature"), "Temperatur")}`);
else if (climateTemp && room.climate?.temperature !== "none") out.push(html`${formatNumber(this.hass, climateTemp.attributes.current_temperature as number, 1)} ${tempUnit(this.hass)}${trendButton(this.hass, [climateTemp.entity_id], "Temperatur")}`);
const hum = value("humidity", "%");
if (hum) out.push(hum);
if (hum) out.push(html`${hum}${trendButton(this.hass, roomClimateSensors(this.hass, this.floor, room, "humidity"), "Luftfeuchte")}`);
const lux = roomClimateValue(this.hass, this.floor ?? null, room, "illuminance");
if (lux !== null) out.push(`☀ ${formatNumber(this.hass, lux, 0)} lx`);
if (lux !== null) out.push(html`☀ ${formatNumber(this.hass, lux, 0)} lx${trendButton(this.hass, roomClimateSensors(this.hass, this.floor, room, "illuminance"), "Helligkeit")}`);
// what the room's devices draw now
const meter = roomUtilityReadings(this.hass, room, this.building?.floors.flatMap((f) => f.rooms)).find((r) => r.kind === "electricity" && r.metric === "power" && r.unit === "W");
const power = !meter && this.floor && this.building ? roomPower(this.hass, this.building, this.floor, room) : null;
if (meter) out.push(`⚡ ${utilityText(this.hass, meter)}`);
if (meter) out.push(html`⚡ ${utilityText(this.hass, meter)}${trendButton(this.hass, meter.sources, "Leistung")}`);
else if (power !== null) out.push(`⚡ ${powerText(this.hass, power)}`);
// how long its windows and doors stand open (the one open longest)
const openSince = this.floor
@@ -633,7 +634,7 @@ export class NfRoomPanel extends LitElement {
// how comfortable it is (0 … 100)
const comfort = comfortScore(t, h, roomClimateValue(this.hass, this.floor, room, "co2"), isSummer(new Date(), this.hass.config?.latitude));
const status = room.hvac?.status;
if (status && status !== "none") out.push(nativeText(this.hass.states[status]));
if (status && status !== "none") out.push(html`${nativeText(this.hass.states[status])}${trendButton(this.hass, [status], "Raumstatus")}`);
else if (comfort !== null && (t !== null || h !== null) && !off.includes("comfort")) out.push(`😊 ${this.t("comfort_n", { n: comfort })}`);
return out;
}
@@ -700,7 +701,7 @@ export class NfRoomPanel extends LitElement {
return html`<div class="nf-rp-row">
<span class="nf-rp-icon ${on ? "nf-rp-on" : ""}">${icon("light")}</span>
${this.nameButton(id)}
<span class="nf-rp-state">${this.stateOf(st)}</span>
<span class="nf-rp-state">${this.stateOf(st)}${trendButton(this.hass, [st.entity_id])}</span>
${this.toggle(st, on, () => this.call("light", "toggle", { entity_id: id }))}
${dimmable && !simple
? html`<label class="nf-rp-slider"
@@ -751,7 +752,7 @@ export class NfRoomPanel extends LitElement {
return html`<div class="nf-rp-row">
<span class="nf-rp-icon">${icon("cover")}</span>
${this.nameButton(id)}
<span class="nf-rp-state">${this.stateOf(st)}</span>
<span class="nf-rp-state">${this.stateOf(st)}${trendButton(this.hass, [st.entity_id])}</span>
<div class="nf-rp-buttons">
<button class="nf-btn nf-rp-small" ?disabled=${na} @click=${() => this.askFor(id) && this.call("cover", "open_cover", { entity_id: id })}>${this.t("cover_open")}</button>
${features & COVER_STOP
@@ -803,7 +804,7 @@ export class NfRoomPanel extends LitElement {
return html`<div class="nf-rp-row">
<span class="nf-rp-icon ${a.hvac_action === "heating" ? "nf-rp-on" : ""}">${icon("climate")}</span>
${this.nameButton(id)}
<span class="nf-rp-state">${this.stateOf(st)}</span>
<span class="nf-rp-state">${this.stateOf(st)}${trendButton(this.hass, [st.entity_id])}</span>
${target !== null
? html`<div class="nf-rp-stepper nf-rp-wide">
<button class="nf-btn" aria-label=${this.t("temp_down")} @click=${() => set(target - step)}>−</button>
@@ -852,7 +853,7 @@ export class NfRoomPanel extends LitElement {
return html`<div class="nf-rp-row">
<span class="nf-rp-icon ${st.state === "playing" ? "nf-rp-on" : ""}">${icon("media")}</span>
${this.nameButton(id)}
<span class="nf-rp-state">${this.stateOf(st, this.stateLabel(st.state))}</span>
<span class="nf-rp-state">${this.stateOf(st, this.stateLabel(st.state))}${trendButton(this.hass, [st.entity_id])}</span>
${title ? html`<p class="nf-rp-media nf-rp-wide">${title}</p>` : nothing}
<div class="nf-rp-buttons nf-rp-wide">
<button class="nf-btn nf-rp-small" aria-label=${this.t("previous")} ?disabled=${na} @click=${() => this.call("media_player", "media_previous_track", { entity_id: id })}>
@@ -888,7 +889,7 @@ export class NfRoomPanel extends LitElement {
return html`<div class="nf-rp-row">
<span class="nf-rp-icon ${on ? "nf-rp-on" : ""}">${icon(kind)}</span>
${this.nameButton(id)}
<span class="nf-rp-state">${this.stateOf(st)}</span>
<span class="nf-rp-state">${this.stateOf(st)}${trendButton(this.hass, [st.entity_id])}</span>
${this.toggle(st, on, act)}
</div>`;
}
@@ -899,7 +900,7 @@ export class NfRoomPanel extends LitElement {
return html`<div class="nf-rp-row">
<span class="nf-rp-icon ${warn ? "nf-rp-on" : ""}">${icon(kind)}</span>
${this.nameButton(st.entity_id)}
<span class="nf-rp-state">${this.stateOf(st)}</span>
<span class="nf-rp-state">${this.stateOf(st)}${trendButton(this.hass, [st.entity_id])}</span>
</div>`;
}
+40
View File
@@ -0,0 +1,40 @@
import { css, html, LitElement, nothing } from "lit";
import type { HomeAssistant } from "../types.ts";
import { loggedEntities } from "../trend-data.ts";
declare const __NF_TREND_HASH__: string;
let loaded: Promise<typeof import("./trend-dialog.ts")> | undefined;
/** Small shared trigger; the chart and its controls load only after the first click. */
class NfTrendButton extends LitElement {
static properties = { hass: { attribute: false }, ids: { attribute: false }, label: { attribute: false }, busy: { state: true }, error: { state: true } };
declare hass: HomeAssistant;
declare ids: string[];
declare label: string;
private declare busy: boolean;
private declare error: string;
constructor() { super(); this.ids = []; this.label = ""; this.busy = false; this.error = ""; }
private async open(event: Event) {
event.stopPropagation(); this.busy = true; this.error = "";
try {
const url = new URL(`./nextfloor-trend.js?v=${__NF_TREND_HASH__}`, import.meta.url).href;
const mod = await (loaded ??= import(/* @vite-ignore */ url).catch((error) => { loaded = undefined; throw error; }));
await mod.openTrend(this.hass, this.ids, this.label);
} catch (error) { this.error = error instanceof Error ? error.message : String(error); }
finally { this.busy = false; }
}
render() {
if (!loggedEntities(this.hass, this.ids).length) return nothing;
const title = this.label ? `Trend anzeigen: ${this.label}` : "Trend anzeigen";
return html`<button type="button" title=${title} aria-label=${title} aria-haspopup="dialog" ?disabled=${this.busy} @pointerdown=${(e: Event) => e.stopPropagation()} @click=${(e: Event) => void this.open(e)}>
<svg width="15" height="15" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M3 2v15h15M5 13l4-5 4 2 4-6"/></svg>
</button>${this.error ? html`<span role="alert">${this.error}</span>` : nothing}`;
}
static styles = css`:host{display:inline-flex;vertical-align:middle;margin-left:4px;font-weight:normal}button{display:inline-flex;align-items:center;justify-content:center;width:25px;height:25px;padding:3px;border:1px solid currentColor;border-radius:6px;background:transparent;color:var(--nf-accent,#40c8ff);opacity:.8;cursor:pointer}button:hover,button:focus-visible{opacity:1;background:#40c8ff18}button:disabled{opacity:.4}span{font:12px system-ui;color:#ff9b9b;max-width:180px}`;
}
if (!customElements.get("nf-trend-button")) customElements.define("nf-trend-button", NfTrendButton);
export function trendButton(hass: HomeAssistant | undefined, ids: readonly string[], label = "") {
const logged = loggedEntities(hass, ids);
return logged.length ? html`<nf-trend-button .hass=${hass} .ids=${logged} .label=${label}></nf-trend-button>` : nothing;
}
+179
View File
@@ -0,0 +1,179 @@
import { css, html, LitElement, nothing, svg } from "lit";
import type { HomeAssistant } from "../types.ts";
import { tokens } from "../styles.ts";
import { localDateTime, loggedEntities, TREND_RESOLUTIONS, trendBounds, trendCsv, type TrendPoint, type TrendResolution, type TrendSeries } from "../trend-data.ts";
import "./help-popup.ts";
const COLORS = ["#4ec9ff", "#ffbe69", "#ae9bff", "#72deb0", "#ff87aa", "#ebde72"];
const entityName = (hass: HomeAssistant, id: string) => String(hass.states[id]?.attributes.friendly_name || id);
const errorText = (e: unknown) => ({ variable_not_logged: "Die Variable wird nicht mehr geloggt.", trend_range_too_large_for_resolution: "Bitte für diesen Zeitraum eine gröbere Auflösung wählen.", invalid_trend_range: "Bitte einen gültigen Zeitraum wählen." } as Record<string, string>)[String(e instanceof Error ? e.message : e)] || String(e instanceof Error ? e.message : e);
/** Lazy, read-only archive viewer, shared by designer and tile iframe. */
export class NfTrendDialog extends LitElement {
static properties = {
hass: { attribute: false }, ids: { attribute: false }, label: { attribute: false },
from: { state: true }, to: { state: true }, resolution: { state: true }, chartStyle: { state: true }, field: { state: true },
min: { state: true }, max: { state: true }, zero: { state: true }, band: { state: true }, live: { state: true },
series: { state: true }, hiddenSeries: { state: true }, loading: { state: true }, errors: { state: true }, hover: { state: true }, width: { state: true }, page: { state: true },
};
declare hass: HomeAssistant;
declare ids: string[];
declare label: string;
private declare from: number;
private declare to: number;
private declare resolution: TrendResolution;
private declare chartStyle: "auto" | "line" | "step" | "bar" | "table";
private declare field: "v" | "min" | "max";
private declare min: string;
private declare max: string;
private declare zero: boolean;
private declare band: boolean;
private declare live: boolean;
private declare series: TrendSeries[];
// Avoid HTMLElement.hidden: this collection controls individual chart series only.
private declare hiddenSeries: Set<string>;
private declare loading: boolean;
private declare errors: string[];
private declare hover: number | null;
private declare width: number;
private declare page: number;
private request = 0;
private drag: number | null = null;
private timer?: ReturnType<typeof setInterval>;
private observer?: ResizeObserver;
constructor() {
super(); this.ids = []; this.label = "";
this.to = Math.floor(Date.now() / 1000); this.from = this.to - 86400;
this.resolution = "auto"; this.chartStyle = "auto"; this.field = "v"; this.min = ""; this.max = "";
this.zero = false; this.band = true; this.live = false; this.series = []; this.hiddenSeries = new Set();
this.loading = false; this.errors = []; this.hover = null; this.width = 900; this.page = 0;
}
async open() {
await this.updateComplete;
this.renderRoot.querySelector<HTMLDialogElement>("dialog")!.showModal();
this.observer = new ResizeObserver(([e]) => { this.width = Math.max(280, Math.floor(e.contentRect.width)); });
this.observer.observe(this.renderRoot.querySelector(".body")!);
this.timer = setInterval(() => { if (this.live && !this.loading) { const span = this.to - this.from; this.to = Math.floor(Date.now() / 1000); this.from = this.to - span; void this.load(); } }, 30000);
await this.load();
}
disconnectedCallback() { super.disconnectedCallback(); ++this.request; clearInterval(this.timer); this.observer?.disconnect(); }
private async load() {
const request = ++this.request, start = this.from, end = this.to;
this.errors = []; this.series = []; this.hover = null; this.page = 0;
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 1 || end <= start) { this.errors = ["Das Ende muss nach dem Beginn des Zeitraums liegen."]; this.loading = false; return; }
this.loading = true;
const series: TrendSeries[] = [], errors: string[] = [];
// Keep archive reads bounded even when the value is linked to many variables.
for (let i = 0; i < this.ids.length && request === this.request; i += 3) {
const ids = this.ids.slice(i, i + 3);
const results = await Promise.allSettled(ids.map((entity_id) => this.hass.callWS<TrendSeries>({ type: "nextfloor/archive/trend", entity_id, start, end, aggregation: this.resolution })));
results.forEach((r, index) => r.status === "fulfilled" ? series.push(r.value) : errors.push(`${entityName(this.hass, ids[index])}: ${errorText(r.reason)}`));
}
if (request !== this.request || !this.isConnected) return;
this.series = series; this.errors = errors; this.loading = false;
}
private range(from: number, to: number) { this.from = Math.max(1, Math.floor(from)); this.to = Math.max(this.from + 1, Math.floor(to)); this.live = false; void this.load(); }
private zoom(factor: number, anchor = .5) { const span = Math.max(60, Math.min(315576000, (this.to - this.from) * factor)), at = this.from + (this.to - this.from) * anchor; this.range(at - span * anchor, at + span * (1 - anchor)); }
private stamp(t: number) { return new Date(t * 1000).toLocaleString(this.hass.language, { dateStyle: "short", timeStyle: "medium" }); }
private number(v: number) { return v.toLocaleString(this.hass.language, { maximumFractionDigits: Math.abs(v) < .01 && v !== 0 ? 5 : 2 }); }
private unit(id: string) { return String(this.hass.states[id]?.attributes.unit_of_measurement ?? ""); }
private selected() { return this.series.filter((s) => !this.hiddenSeries.has(s.entity_id)); }
private value(p: TrendPoint) { const value = this.field === "v" ? p.v : p[this.field] ?? p.v; return typeof value === "number" && Number.isFinite(value) ? value : null; }
private color(id: string) { return COLORS[this.ids.indexOf(id) % COLORS.length]; }
private ratio(event: PointerEvent | WheelEvent) { const r = (event.currentTarget as SVGSVGElement).getBoundingClientRect(); return Math.max(0, Math.min(1, ((event.clientX - r.left) / r.width * this.width - 64) / (this.width - 80))); }
private exportCsv() {
const names = Object.fromEntries(this.ids.map((id) => [id, String(this.hass.states[id]?.attributes.symcon_path || entityName(this.hass, id))]));
const url = URL.createObjectURL(new Blob([trendCsv(this.selected(), names)], { type: "text/csv;charset=utf-8" }));
const link = document.createElement("a"); link.href = url; link.download = "Symcon-Trend.csv"; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);
}
private plot(series: TrendSeries[], unit: string) {
const numbers = series.flatMap((s) => s.points.flatMap((p) => { const v = this.value(p); return v === null ? [] : this.band && !s.counter ? [v, p.min ?? v, p.max ?? v] : [v]; }));
if (!numbers.length) return html`<p class="note">Keine numerischen Archivwerte in diesem Zeitraum.</p>`;
let low: number, high: number;
try { [low, high] = trendBounds(numbers, this.min, this.max, this.zero || this.chartStyle === "bar" || series.some((s) => s.type === 0) || (this.chartStyle === "auto" && series.some((s) => s.counter && s.aggregation !== "raw"))); }
catch (e) { return html`<p role="alert">${errorText(e)}</p>`; }
const left = 64, right = this.width - 16, top = 14, bottom = 220;
const x = (t: number) => left + (t - this.from) / (this.to - this.from) * (right - left);
const y = (v: number) => bottom - (v - low) / (high - low) * (bottom - top);
const point = (p: TrendPoint, field = this.field) => Number(field === "v" ? p.v : p[field] ?? p.v);
const path = (s: TrendSeries, field = this.field) => {
const ps = s.points.filter((p) => typeof p.v === "number");
const stepped = this.chartStyle === "step" || (this.chartStyle === "auto" && s.type === 0);
return ps.map((p, i) => `${i ? stepped ? `H${x(p.t).toFixed(1)}V` : "L" : "M"}${stepped && i ? y(point(p, field)).toFixed(1) : `${x(p.t).toFixed(1)},${y(point(p, field)).toFixed(1)}`}`).join("") + (ps.length ? stepped ? `H${right}` : s.aggregation === "raw" ? `L${right},${y(point(ps[ps.length - 1], field)).toFixed(1)}` : "" : "");
};
const ticks = this.width < 480 ? 2 : 5;
return html`<section class="chart-group"><h3>${unit || "Wert"}</h3><svg class="plot" viewBox=${`0 0 ${this.width} 256`} role="img" aria-label=${`Trend ${unit}`} @wheel=${(e: WheelEvent) => { e.preventDefault(); this.zoom(e.deltaY > 0 ? 1.5 : 1 / 1.5, this.ratio(e)); }}
@pointerdown=${(e: PointerEvent) => { this.drag = this.ratio(e); (e.currentTarget as Element).setPointerCapture(e.pointerId); }}
@pointerup=${(e: PointerEvent) => { if (this.drag === null) return; const start = this.drag, end = this.ratio(e); this.drag = null; if (Math.abs(start - end) > .02) { const span = this.to - this.from; this.range(this.from + span * Math.min(start, end), this.from + span * Math.max(start, end)); } }}
@pointercancel=${() => { this.drag = null; }} @pointermove=${(e: PointerEvent) => { this.hover = this.from + (this.to - this.from) * this.ratio(e); }}>
<defs><clipPath id="plot-clip"><rect x=${left} y=${top} width=${right - left} height=${bottom - top}/></clipPath></defs>
${[0, 1, 2, 3, 4].map((i) => { const v = low + (high - low) * i / 4; return svg`<line class="grid" x1=${left} x2=${right} y1=${y(v)} y2=${y(v)}/><text x=${left - 7} y=${y(v) + 4} text-anchor="end">${this.number(v)}</text>`; })}
${Array.from({ length: ticks }, (_, i) => { const t = this.from + (this.to - this.from) * i / (ticks - 1); return svg`<text x=${x(t)} y="244" text-anchor=${i === 0 ? "start" : i === ticks - 1 ? "end" : "middle"}>${new Date(t * 1000).toLocaleString(this.hass.language, { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" })}</text>`; })}
<g clip-path="url(#plot-clip)">${series.map((s) => {
const bars = this.chartStyle === "bar" || (this.chartStyle === "auto" && s.counter && s.aggregation !== "raw");
const color = this.color(s.entity_id);
if (bars) return s.points.filter((p) => this.value(p) !== null).map((p) => svg`<rect fill=${color} opacity=".65" x=${x(p.t)} y=${Math.min(y(this.value(p)!), y(0))} width=${Math.max(1, Math.min(right, x(p.t + Math.max(1, p.d))) - x(p.t) - 1)} height=${Math.max(1, Math.abs(y(this.value(p)!) - y(0)))}/>`);
return svg`${this.band && s.aggregation !== "raw" && !s.counter ? svg`<path d=${path(s, "min")} fill="none" stroke=${color} opacity=".3"/><path d=${path(s, "max")} fill="none" stroke=${color} opacity=".3"/>` : nothing}<path d=${path(s)} fill="none" stroke=${color} stroke-width="2" vector-effect="non-scaling-stroke"/>${s.points.length === 1 ? svg`<circle cx=${x(s.points[0].t)} cy=${y(point(s.points[0]))} r="3" fill=${color}/>` : nothing}`;
})}${this.hover !== null ? svg`<line x1=${x(this.hover)} x2=${x(this.hover)} y1=${top} y2=${bottom} stroke="currentColor" stroke-dasharray="3 4" opacity=".5"/>` : nothing}</g>
</svg></section>`;
}
private table(series: TrendSeries[]) {
const rows = series.flatMap((s) => s.points.map((p) => ({ id: s.entity_id, ...p }))).sort((a, b) => b.t - a.t);
const pages = Math.max(1, Math.ceil(rows.length / 100)), page = Math.min(this.page, pages - 1);
return html`<div class="table"><table><thead><tr><th>Zeit</th><th>Variable</th><th>Wert</th></tr></thead><tbody>${rows.slice(page * 100, (page + 1) * 100).map((p) => html`<tr><td>${this.stamp(p.t)}</td><td>${entityName(this.hass, p.id)}</td><td>${typeof p.v === "number" ? this.number(p.v) : p.v} ${this.unit(p.id)}</td></tr>`)}</tbody></table></div><div class="actions"><button ?disabled=${!page} @click=${() => { this.page = page - 1; }}>Zurück</button><span>${page + 1} / ${pages}</span><button ?disabled=${page >= pages - 1} @click=${() => { this.page = page + 1; }}>Weiter</button></div>`;
}
render() {
const selected = this.selected(), allString = selected.length > 0 && selected.every((s) => s.type === 3);
const text = this.hover === null ? "Letzter Wert" : this.stamp(this.hover);
return html`<dialog aria-label="Variablentrend" @close=${() => this.remove()} @keydown=${(e: KeyboardEvent) => e.stopPropagation()}>
<header><div><h2>${this.label || "Variablentrend"}</h2><span>Symcon Archiv</span></div><button aria-label="Schließen" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>("dialog")?.close()}>×</button></header>
<div class="body"><div class="presets">${[["1 h", 3600], ["6 h", 21600], ["24 h", 86400], ["7 Tage", 604800], ["30 Tage", 2592000], ["1 Jahr", 31536000]].map(([label, seconds]) => html`<button @click=${() => { const end = Math.floor(Date.now() / 1000); this.range(end - Number(seconds), end); }}>${label}</button>`)}</div>
<form @submit=${(e: Event) => { e.preventDefault(); void this.load(); }}><div class="fields">
<label>Von<input type="datetime-local" .value=${localDateTime(this.from)} @change=${(e: Event) => { this.from = Math.floor(new Date((e.target as HTMLInputElement).value).getTime() / 1000); this.live = false; void this.load(); }}/></label>
<label>Bis<input type="datetime-local" .value=${localDateTime(this.to)} @change=${(e: Event) => { this.to = Math.floor(new Date((e.target as HTMLInputElement).value).getTime() / 1000); this.live = false; void this.load(); }}/></label>
<label>Auflösung<select .value=${this.resolution} @change=${(e: Event) => { this.resolution = (e.target as HTMLSelectElement).value as TrendResolution; void this.load(); }}>${Object.entries(TREND_RESOLUTIONS).map(([id, label]) => html`<option value=${id}>${label}</option>`)}</select></label>
<button type="submit" ?disabled=${this.loading}>${this.loading ? "Lädt …" : "Anzeigen"}</button>
</div></form>
<details class="settings"><summary>Darstellung und Wertebereich</summary><div class="fields">
<label>Darstellung<select .value=${this.chartStyle} @change=${(e: Event) => { this.chartStyle = (e.target as HTMLSelectElement).value as typeof this.chartStyle; }}>${Object.entries({ auto: "Automatisch", line: "Linie", step: "Stufen", bar: "Balken", table: "Tabelle" }).map(([id, label]) => html`<option value=${id}>${label}</option>`)}</select></label>
<label>Aggregierter Wert<select .value=${this.field} @change=${(e: Event) => { this.field = (e.target as HTMLSelectElement).value as typeof this.field; }}><option value="v">Mittelwert / Verbrauch</option><option value="min">Minimum</option><option value="max">Maximum</option></select></label>
<label>Y-Minimum<input type="number" step="any" placeholder="Automatisch" .value=${this.min} @input=${(e: Event) => { this.min = (e.target as HTMLInputElement).value; }}/></label>
<label>Y-Maximum<input type="number" step="any" placeholder="Automatisch" .value=${this.max} @input=${(e: Event) => { this.max = (e.target as HTMLInputElement).value; }}/></label>
</div><div class="checks"><label><input type="checkbox" .checked=${this.zero} @change=${(e: Event) => { this.zero = (e.target as HTMLInputElement).checked; }}/> Nullpunkt einbeziehen</label><label><input type="checkbox" .checked=${this.band} @change=${(e: Event) => { this.band = (e.target as HTMLInputElement).checked; }}/> Min/Max anzeigen</label></div></details>
<div class="actions"><button aria-label="Vorheriger Zeitraum" @click=${() => this.range(this.from - (this.to - this.from), this.from)}>←</button><button aria-label="Nächster Zeitraum" @click=${() => this.range(this.to, this.to + (this.to - this.from))}>→</button><button aria-label="Hineinzoomen" @click=${() => this.zoom(.5)}>+</button><button aria-label="Herauszoomen" @click=${() => this.zoom(2)}>−</button><button @click=${() => void this.load()} ?disabled=${this.loading}>Aktualisieren</button><label><input type="checkbox" .checked=${this.live} @change=${(e: Event) => { this.live = (e.target as HTMLInputElement).checked; }}/> Live (30 s)</label><button @click=${() => this.exportCsv()} ?disabled=${!selected.length}>CSV</button>
<nf-help-popup .text=${"Zeitraum und Auflösung lesen die originalen Symcon-Archivdaten. Rohdaten zeigen gespeicherte Änderungen; ein zuvor bekannter Wert wird zum Beginn fortgeführt. Bei Zählern sind aggregierte Werte der Verbrauch pro Intervall, bei Messwerten der Mittelwert. Mehrere Variablen werden einzeln dargestellt; unterschiedliche Einheiten erhalten eigene Diagramme. Zoomen: +/−, Mausrad oder im Diagramm einen Zeitraum ziehen. Eigene Y-Grenzen gelten für alle Diagramme. Begrenzte Rohdatenabfragen werden gekennzeichnet; wähle dann einen kürzeren Zeitraum oder eine Aggregation."}></nf-help-popup>
</div>
<div class="legend">${this.ids.map((id) => html`<label title=${String(this.hass.states[id]?.attributes.symcon_path || entityName(this.hass, id))}><input type="checkbox" .checked=${!this.hiddenSeries.has(id)} @change=${(e: Event) => { const set = new Set(this.hiddenSeries); if ((e.target as HTMLInputElement).checked) set.delete(id); else set.add(id); this.hiddenSeries = set; this.requestUpdate(); }}/><i style=${`background:${this.color(id)}`}></i>${entityName(this.hass, id)}</label>`)}</div>
${this.errors.map((e) => html`<p class="error" role="alert">${e}</p>`)}${this.loading ? html`<p class="note" role="status">Archivwerte werden geladen …</p>` : nothing}
${selected.filter((s) => s.truncated).map((s) => html`<p class="error" role="status">${entityName(this.hass, s.entity_id)}: Die Abfrage ist auf ${(s.limit ?? 10000).toLocaleString(this.hass.language)} Einträge begrenzt. Bitte Zeitraum verkürzen oder Auflösung ändern.</p>`)}
${selected.some((s) => s.counter && s.aggregation !== "raw") ? html`<p class="note">Zähler: Verbrauch pro Intervall</p>` : nothing}
${this.chartStyle === "table" || allString ? this.table(selected) : [...new Set(selected.filter((s) => s.type !== 3).map((s) => this.unit(s.entity_id)))].map((unit) => this.plot(selected.filter((s) => s.type !== 3 && this.unit(s.entity_id) === unit), unit))}
${selected.some((s) => s.type === 3) && !allString && this.chartStyle !== "table" ? this.table(selected.filter((s) => s.type === 3)) : nothing}
${!this.loading && selected.length && selected.every((s) => !s.points.length) ? html`<p class="note">Keine Archivwerte in diesem Zeitraum.</p>` : nothing}
<div class="cursor"><b>${text}</b>${selected.map((s) => { let p = s.points.at(-1); if (this.hover !== null) { let lo = 0, hi = s.points.length; while (lo < hi) { const mid = (lo + hi) >>> 1; if (s.points[mid].t <= this.hover) lo = mid + 1; else hi = mid; } p = s.points[lo - 1]; } return html`<span style=${`color:${this.color(s.entity_id)}`}>${entityName(this.hass, s.entity_id)}: ${p ? typeof p.v === "number" ? `${this.number(this.value(p)!)} ${this.unit(s.entity_id)}` : p.v : "–"}</span>`; })}</div>
</div>
</dialog>`;
}
static styles = [tokens, css`
:host{font:14px/1.45 system-ui,sans-serif;color:var(--nf-text)}dialog{box-sizing:border-box;width:min(1080px,calc(100vw - 24px));max-height:92vh;max-height:92dvh;padding:0;border:1px solid var(--nf-line);border-radius:14px;background:var(--nf-chrome-solid,#1c1c1c);color:inherit;box-shadow:var(--nf-shadow);overflow:auto}dialog::backdrop{background:#050b16a8}header{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:16px 20px;border-bottom:1px solid var(--nf-line)}h2{font-size:18px;margin:0}header span,.note{font-size:12px;color:var(--nf-muted)}header button{font-size:23px;width:36px;height:36px;padding:0}.body{padding:16px 20px}.presets,.actions,.checks,.legend,.cursor{display:flex;align-items:center;flex-wrap:wrap;gap:8px;margin:0 0 14px}.fields{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;align-items:end;margin:12px 0}.fields label{display:grid;gap:5px;color:var(--nf-muted);font-size:12px}button,input,select{font:inherit;box-sizing:border-box;color:var(--nf-text)}button,select,input:not([type=checkbox]){border:1px solid var(--nf-line);border-radius:7px;padding:8px;background:var(--nf-fill,#292929);min-width:0}button{cursor:pointer}button:disabled{opacity:.45}button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid var(--nf-accent);outline-offset:2px}.settings{border:1px solid var(--nf-line);padding:10px 12px;border-radius:9px;margin:12px 0}summary{cursor:pointer}.checks label,.actions label,.legend label{display:flex;align-items:center;gap:6px;font-size:12px}.legend i{display:inline-block;width:10px;height:10px;border-radius:50%;flex-shrink:0}.legend label{max-width:100%;overflow-wrap:anywhere}.plot{display:block;width:100%;touch-action:none;user-select:none}.plot text{fill:var(--nf-muted);font:11px system-ui}.grid{stroke:var(--nf-line)}h3{font-size:12px;color:var(--nf-muted);margin:12px 0 0}.chart-group{margin-bottom:10px}.cursor{font-size:12px;align-items:flex-start}.cursor>b{width:100%;color:var(--nf-muted)}.cursor span{overflow-wrap:anywhere}.error{color:#ffa5a5}.table{overflow:auto;max-height:380px;margin:12px 0}table{width:100%;border-collapse:collapse;font-size:12px}td,th{text-align:left;padding:7px;border-bottom:1px solid var(--nf-line);overflow-wrap:anywhere}td:first-child{white-space:nowrap}th{position:sticky;top:0;background:var(--nf-chrome-solid,#1c1c1c)}@media(max-width:500px){header{padding:12px}.body{padding:10px}.fields{grid-template-columns:repeat(2,minmax(0,1fr))}input[type=datetime-local]{font-size:12px;padding:7px 3px}.actions{gap:6px}.actions button{padding:7px}header h2{font-size:16px}}
header{position:sticky;top:0;z-index:2;background:var(--nf-chrome-solid,#1c1c1c)}
`];
}
// Each lazy bundle has its own Lit copy; use an existing registration when another host loaded it first.
if (!customElements.get("nf-trend-dialog")) customElements.define("nf-trend-dialog", NfTrendDialog);
export async function openTrend(hass: HomeAssistant, ids: string[], label: string) {
const logged = loggedEntities(hass, ids);
if (!logged.length) return;
const dialog = document.createElement("nf-trend-dialog") as NfTrendDialog;
Object.assign(dialog, { hass, ids: logged, label }); document.body.append(dialog);
try { await dialog.open(); } catch (e) { dialog.remove(); throw e; }
}
+2 -1
View File
@@ -2,6 +2,7 @@ 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";
import { trendButton } from "./trend-button.ts";
/** The same metered readings in the room panel and the floor overview. */
class NfUtilityReport extends LitElement {
@@ -15,7 +16,7 @@ class NfUtilityReport extends LitElement {
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")}`}>
<span>${utilityMetricLabel(r)}${r.manual ? html` <small>· Zähler</small>` : ""}</span><b>${utilityText(this.hass, r)}</b>
<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>`)}`;
}
+4 -3
View File
@@ -54,6 +54,7 @@ import { isSymcon, isSymconVariable, nativeBool, nativeText } from "../entities/
import { WEATHER_VARIABLE_LABELS } from "../symcon-weather.ts";
import { floorUtilityReadings, utilityText } from "../utilities.ts";
import "./utility-report.ts";
import { trendButton } from "./trend-button.ts";
import { deviceValuesText } from "../entities/device-values.ts";
import { furnitureShown, hiddenFurniture, withoutHidden } from "../entities/visibility.ts";
import { pictureUrl } from "../entities/pictures.ts";
@@ -2747,11 +2748,11 @@ export class NfView3d extends LitElement {
/** The plan's own sensors at the top (outside temperature, the alarm…): their name and state; a tap opens their details. */
private ownSensors() {
const ids = this.sensorBar && this.hass ? (this.building?.settings.status_entities ?? []) : [];
const people = isSymcon(this.hass) ? (this.building?.presence ?? []).filter((link) => isSymconVariable(this.hass, link.person, [0])).map((link) => html`<div class="nf-energy-item nf-presence-state"><span>${link.name || entityName(this.hass, link.person)}</span><b>${nativeBool(this.hass.states[link.person]) === null ? "–" : nativeBool(this.hass.states[link.person]) ? "Anwesend" : "Abwesend"}</b></div>`) : [];
const people = isSymcon(this.hass) ? (this.building?.presence ?? []).filter((link) => isSymconVariable(this.hass, link.person, [0])).map((link) => html`<div class="nf-energy-item nf-presence-state"><span>${link.name || entityName(this.hass, link.person)}</span><b>${nativeBool(this.hass.states[link.person]) === null ? "–" : nativeBool(this.hass.states[link.person]) ? "Anwesend" : "Abwesend"}${trendButton(this.hass, [link.person], link.name || "Anwesenheit")}</b></div>`) : [];
const weather = isSymcon(this.hass) ? Object.entries(this.building?.settings.weather_variables ?? {}).filter((entry): entry is [keyof typeof WEATHER_VARIABLE_LABELS, string] => !!entry[1] && entry[1] !== "none").map(([key, id]) => [WEATHER_VARIABLE_LABELS[key] || key, id]) : [];
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;
<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])}${trendButton(this.hass, [id], label)}</b></p>`)}</dialog>` : nothing;
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;
@@ -2760,7 +2761,7 @@ export class NfView3d extends LitElement {
.map(
(id) => html`<button class="nf-energy-item nf-own-sensor" title=${entityName(this.hass, id)} @click=${() => openMoreInfo(this, id)}>
<span>${entityName(this.hass, id)}</span><b>${stateText(this.hass, this.hass.states[id])}</b>
</button>`,
</button>${trendButton(this.hass, [id], entityName(this.hass, id))}`,
)];
}
+5 -4
View File
@@ -20,6 +20,7 @@ import type { HeatPumpInfo } from "./heat-pump.ts";
import type { PlanPoint } from "../viewer/live-energy.ts";
import type { RoomClimateCard } from "./room-climate-card.ts";
import { fromCelsius, tempUnit } from "../devices.ts";
import { trendButton } from "../components/trend-button.ts";
export interface HouseCard {
kind: "house";
@@ -317,10 +318,10 @@ function heatPumpCard(hass: HomeAssistant | undefined, c: HeatPumpCard, i: numbe
function roomClimateCard(hass: HomeAssistant | undefined, c: RoomClimateCard, i: number): TemplateResult {
const value = (n: number | null, digits: number, unit: string) => n === null ? "–" : `${formatNumber(hass, n, digits)} ${unit}`;
return html`<div class="live-card live-card-roomclimate" data-i=${i} data-room=${c.roomId} role="group" aria-label=${`${c.name || translate(hass, "room")} · ${translate(hass, "climate")}`}>
${c.showTemperature ? html`<div class="live-row live-climate-temperature"><span title=${translate(hass, "climate_temperature")} aria-label=${translate(hass, "climate_temperature")}>🌡</span><b>${value(c.temperature === null ? null : hass ? fromCelsius(hass, c.temperature) : c.temperature, 1, hass ? tempUnit(hass) : "°C")}</b></div>` : nothing}
${c.showHumidity ? html`<div class="live-row live-climate-humidity"><span title=${translate(hass, "climate_humidity")} aria-label=${translate(hass, "climate_humidity")}>💧</span><b>${value(c.humidity, 0, "%")}</b></div>` : nothing}
${c.showCo2 ? html`<div class="live-row live-climate-co2"><span title=${translate(hass, "climate_co2")} aria-label=${translate(hass, "climate_co2")}>☁</span><b>${value(c.co2, 0, "ppm")}</b></div>` : nothing}
${c.showIlluminance ? html`<div class="live-row live-climate-illuminance"><span title=${translate(hass, "climate_illuminance")} aria-label=${translate(hass, "climate_illuminance")}>☀</span><b>${value(c.illuminance, 0, "lx")}</b></div>` : nothing}
${c.showTemperature ? html`<div class="live-row live-climate-temperature"><span title=${translate(hass, "climate_temperature")} aria-label=${translate(hass, "climate_temperature")}>🌡</span><b>${value(c.temperature === null ? null : hass ? fromCelsius(hass, c.temperature) : c.temperature, 1, hass ? tempUnit(hass) : "°C")}${trendButton(hass, c.sources?.temperature ?? [], translate(hass, "climate_temperature"))}</b></div>` : nothing}
${c.showHumidity ? html`<div class="live-row live-climate-humidity"><span title=${translate(hass, "climate_humidity")} aria-label=${translate(hass, "climate_humidity")}>💧</span><b>${value(c.humidity, 0, "%")}${trendButton(hass, c.sources?.humidity ?? [], translate(hass, "climate_humidity"))}</b></div>` : nothing}
${c.showCo2 ? html`<div class="live-row live-climate-co2"><span title=${translate(hass, "climate_co2")} aria-label=${translate(hass, "climate_co2")}>☁</span><b>${value(c.co2, 0, "ppm")}${trendButton(hass, c.sources?.co2 ?? [], translate(hass, "climate_co2"))}</b></div>` : nothing}
${c.showIlluminance ? html`<div class="live-row live-climate-illuminance"><span title=${translate(hass, "climate_illuminance")} aria-label=${translate(hass, "climate_illuminance")}>☀</span><b>${value(c.illuminance, 0, "lx")}${trendButton(hass, c.sources?.illuminance ?? [], translate(hass, "climate_illuminance"))}</b></div>` : nothing}
</div>`;
}
+2
View File
@@ -17,6 +17,7 @@ export interface RoomClimateCard {
showCo2: boolean;
illuminance: number | null;
showIlluminance: boolean;
sources?: Partial<Record<ClimateKey, string[]>>;
}
/** Opt-in room cards for an opened floor/room; the all-floors overview stays clear. */
@@ -44,6 +45,7 @@ export function roomClimateCards(hass: HomeAssistant, building: Building, floorI
cards.push({ kind: "roomclimate", roomId: room.id, name: room.name,
at: { floorId: floor.id, x, z, y: (room.ceiling ?? floor.height) + 0.4 },
temperature, humidity, co2, illuminance, showTemperature, showHumidity, showCo2, showIlluminance,
sources: Object.fromEntries((["temperature", "humidity", "co2", "illuminance"] as const).map((key) => [key, roomClimateSensors(hass, floor, room, key)])),
});
}
}
+41
View File
@@ -0,0 +1,41 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { entity, hassOf } from "./entities/fixtures.ts";
import { localDateTime, loggedEntities, trendBounds, trendCsv, type TrendSeries } from "./trend-data.ts";
test("only logged native variables are offered, deduplicating role aliases and preserving offline logs", () => {
const h = hassOf([
entity("sensor.1", "unavailable", { symcon_id: 1, symcon_archive: { id: 99 } }),
entity("light.1", "on", { symcon_id: 1, symcon_source_entity: "sensor.1", symcon_archive: { id: 99 } }),
entity("sensor.2", "5", { symcon_id: 2 }),
entity("sensor.ha", "5"),
]);
assert.deepEqual(loggedEntities(h, ["light.1", "sensor.1", "sensor.2", "sensor.ha", "missing"]), ["sensor.1"]);
});
test("graph bounds accept own limits, retain zero and handle large, flat and empty series", () => {
assert.deepEqual(trendBounds([10, 20], "", "", false), [10, 20]);
assert.deepEqual(trendBounds([10, 20], "0", "30,5", false), [0, 30.5]);
assert.deepEqual(trendBounds([0], "", "", true), [0, 1]);
assert.deepEqual(trendBounds([20], "", "", false), [19, 21]);
assert.deepEqual(trendBounds([], "", "", false), [0, 1]);
assert.deepEqual(trendBounds(Array.from({ length: 200000 }, (_, i) => i), "", "", false), [0, 199999]);
assert.throws(() => trendBounds([10], "20", "10", false), /kleiner/);
assert.throws(() => trendBounds([10], "5", "5", false), /kleiner/);
});
test("local datetime input round-trips through the browser timezone and invalid input stays blank", () => {
const date = new Date(2026, 10, 11, 12, 34);
assert.equal(localDateTime(date.getTime() / 1000), "2026-11-11T12:34");
assert.equal(new Date(localDateTime(date.getTime() / 1000)).getTime(), date.getTime());
assert.equal(localDateTime(NaN), "");
});
test("CSV includes original records and safely escapes quotes, delimiters and logged formula text", () => {
const series: TrendSeries = { entity_id: "sensor.1", start: 1, end: 10, type: 3, aggregation: "raw", counter: false, truncated: false, points: [{ t: 2, d: 0, v: '=SUM(1;2)"' }] };
const csv = trendCsv([series], { "sensor.1": "Text;Wert" });
assert.ok(csv.startsWith("\uFEFFVariable;Zeit;Wert"));
assert.ok(csv.includes('"Text;Wert"'));
assert.ok(csv.includes('"\'=SUM(1;2)"""'));
assert.ok(csv.includes("1970-01-01T00:00:02.000Z"));
});
+39
View File
@@ -0,0 +1,39 @@
import type { HomeAssistant } from "./types.ts";
export const TREND_RESOLUTIONS = { auto: "Automatisch", raw: "Rohdaten", minute: "1 Minute", "5minutes": "5 Minuten", "15minutes": "15 Minuten", hour: "Stunde", day: "Tag", week: "Woche", month: "Monat", year: "Jahr" } as const;
export type TrendResolution = keyof typeof TREND_RESOLUTIONS;
export interface TrendPoint { t: number; v: number | string; d: number; min?: number; max?: number }
export interface TrendSeries { entity_id: string; start: number; end: number; aggregation: TrendResolution; counter: boolean; type: number; limit?: number; truncated: boolean; points: TrendPoint[] }
/** Role aliases and object links must open the original native archive only once. */
export function loggedEntities(hass: HomeAssistant | undefined, ids: readonly string[]): string[] {
const seen = new Set<number>();
return ids.flatMap((candidate) => {
const id = String(hass?.states[candidate]?.attributes.symcon_source_entity || candidate);
const a = hass?.states[id]?.attributes, native = Number(a?.symcon_id);
if (!native || !a?.symcon_archive || seen.has(native)) return [];
seen.add(native); return [id];
});
}
export function localDateTime(timestamp: number): string {
if (!Number.isFinite(timestamp)) return "";
const d = new Date(timestamp * 1000);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}T${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
}
export function trendBounds(values: readonly number[], minText: string, maxText: string, zero: boolean): [number, number] {
const manual = (s: string) => s.trim() && Number.isFinite(Number(s.replace(",", "."))) ? Number(s.replace(",", ".")) : null;
const low = manual(minText), high = manual(maxText);
let min = low ?? values.reduce((a, b) => Math.min(a, b), zero || !values.length ? 0 : Infinity);
let max = high ?? values.reduce((a, b) => Math.max(a, b), zero ? 0 : values.length ? -Infinity : 1);
if (min === max) { if (low === null && !zero) min -= Math.max(1, Math.abs(min) * .05); if (high === null) max += Math.max(1, Math.abs(max) * .05); }
if (min >= max) throw new Error("Der untere Wertebereich muss kleiner als der obere sein.");
return [min, max];
}
/** CSV stays spreadsheet-safe even for logged strings beginning with a formula character. */
export function trendCsv(series: readonly TrendSeries[], names: Record<string, string>): string {
const cell = (value: unknown) => { const s = String(value ?? ""); return `"${/^[=+@\-\t\r]/.test(s) ? "'" : ""}${s.replaceAll('"', '""')}"`; };
return "\uFEFF" + [["Variable", "Zeit", "Wert", "Minimum", "Maximum"].join(";"), ...series.flatMap((s) => s.points.map((p) => [names[s.entity_id] || s.entity_id, new Date(p.t * 1000).toISOString(), p.v, p.min ?? "", p.max ?? ""].map(cell).join(";")))].join("\r\n");
}