feat: add floating room climate cards and fix Symcon humidity selection
This commit is contained in:
1 parent
24188f96f7
commit
ff54f4461a
21 files changed
+764
-398
No files matched your search
@@ -5,7 +5,7 @@ import { entityAreaId, entityKind, entityName, groupByDevice, isClimateValueSens
|
||||
import { iconPath } from "../../../icons.ts";
|
||||
import { pointInPolygon, type Room } from "../../../model.ts";
|
||||
import { entityOptions } from "../entities.ts";
|
||||
import { deviceIcon, entityField, hint } from "../fields.ts";
|
||||
import { checkField, deviceIcon, entityField, hint } from "../fields.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { matchesQuery, placedElsewhere, placedInRoom, rankedBy, takeFirst, withToggled } from "../ops/device-list.ts";
|
||||
import type { SideState } from "../side-state.ts";
|
||||
@@ -133,10 +133,10 @@ export function renderRoomClimate(host: EditorHost, room: Room, patch: (patch: P
|
||||
};
|
||||
const field = (key: ClimateKey, label: string) => {
|
||||
const found = roomClimateSensors(hass, host.floor ?? null, { ...room, climate: null }, key);
|
||||
const wanted = entityOptions(hass, (id) => isClimateValueSensor(hass, id, key));
|
||||
const picked = [room.climate?.[key] ?? null].flat();
|
||||
const wanted = entityOptions(hass, (id) => isClimateValueSensor(hass, id, key, true) && (!hass.states[id]?.attributes.symcon_source_entity || picked.includes(id)));
|
||||
// the room's own sensors first, then the others; device temperatures (a printer, a heat pump) come last
|
||||
const options = rankedBy(wanted, (id) => (entityAreaId(hass, id) === room.area_id ? 0 : 1) + (isRoomClimateSensor(hass, id) ? 0 : 2));
|
||||
const picked = [room.climate?.[key] ?? null].flat();
|
||||
// several sensors are averaged: once one is chosen, another can be added; "none" in a slot drops it
|
||||
const save = (list: (string | null)[]) => {
|
||||
const ids = list.filter((id): id is string => !!id && id !== "none");
|
||||
@@ -146,9 +146,11 @@ export function renderRoomClimate(host: EditorHost, room: Room, patch: (patch: P
|
||||
const slots = real ? [...picked, null] : picked;
|
||||
return slots.map((id, i) => entityField(host, i ? host.t("climate_more") : label, id, i ? undefined : (found[0] ?? null), options, (v) => save(slots.map((x, j) => (j === i ? v : x)))));
|
||||
};
|
||||
return html`<details class="nf-points" ?open=${chosen}>
|
||||
return html`<details class="nf-points" ?open=${chosen || !!room.climate_card}>
|
||||
<summary>${host.t("climate")}</summary>
|
||||
<div class="nf-form">${field("temperature", host.t("climate_temperature"))} ${field("humidity", host.t("climate_humidity"))} ${field("co2", host.t("climate_co2"))}</div>
|
||||
${checkField(host, host.t("climate_card"), !!room.climate_card, (on) => patch({ climate_card: on || undefined }))}
|
||||
${hint(host.t("climate_card_hint"))}
|
||||
${hint(host.t("climate_hint"))}
|
||||
</details>`;
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import { gateStates } from "../entities/gates.ts";
|
||||
import { weatherEntity } from "../weather.ts";
|
||||
import { chosenEffects, readSkyWeather, withDensity } from "../live/sky-weather.ts";
|
||||
import { energyPicture, houseHub, type EnergyPicture } from "../live/energy-flow.ts";
|
||||
import { roomClimateCards } from "../live/room-climate-card.ts";
|
||||
import { loadWeek, type WeekBars } from "../live/week-bars.ts";
|
||||
import { binsDue, loadToday, sortDay, type TodayItem } from "../live/today.ts";
|
||||
import { forecastDays, loadForecast } from "../live/forecast.ts";
|
||||
@@ -690,7 +691,7 @@ export class NfView3d extends LitElement {
|
||||
if (changed.has("building") || changed.has("theme") || changed.has("floorThumbs") || changed.has("packs")) this.scheduleThumbs();
|
||||
// markers shown by kind outside the opened room change with the room
|
||||
const byRoom = this.markersOutside ? ["markersOutside", "floorId", "roomId"] : ["markersOutside"];
|
||||
const forced = this.pluginsDirty || ["building", "markerMode", "heatMode", "flows", "alerts", "dimmed", ...byRoom].some((k) => changed.has(k));
|
||||
const forced = this.pluginsDirty || ["building", "markerMode", "heatMode", "flows", "alerts", "dimmed", "holograms", "roomLabels", "floorId", "roomId", ...byRoom].some((k) => changed.has(k));
|
||||
this.pluginsDirty = false;
|
||||
if (forced || changed.has("hass")) this.syncDevices(forced);
|
||||
if (changed.has("autoOrbit")) v.setAutoOrbit(this.autoOrbit ? 0.06 : 0);
|
||||
@@ -969,7 +970,7 @@ export class NfView3d extends LitElement {
|
||||
playing.filter((m) => m.rings > 0).map((m) => ({ id: m.entity, at: m.at, color: m.color, level: m.volume ?? 0.5, size: m.rings })),
|
||||
multiroom(playing).map(([a, c]) => [a.at, c.at]),
|
||||
);
|
||||
this.syncLhCards(v, b, livePic, liveCars, playing);
|
||||
this.syncLhCards(v, b, livePic, liveCars, playing, hass);
|
||||
// TV screens: a TV or monitor linked to a media player that runs shows what runs
|
||||
v.setLiveScreens(this.dimmed ? [] : liveScreens(hass, b, this.furnitureLinks));
|
||||
v.setPictures(this.framePictures(hass, b));
|
||||
@@ -2618,7 +2619,7 @@ export class NfView3d extends LitElement {
|
||||
.catch(() => (this.dayCurves = null));
|
||||
}
|
||||
|
||||
private syncLhCards(v: NextFloorViewer, b: Building, pic: EnergyPicture, cars: ReturnType<NfView3d["liveCars"]>, media: MediaNow[]): void {
|
||||
private syncLhCards(v: NextFloorViewer, b: Building, pic: EnergyPicture, cars: ReturnType<NfView3d["liveCars"]>, media: MediaNow[], hass: HomeAssistant): void {
|
||||
const cards: LiveCard[] = [];
|
||||
const s = pic.summary;
|
||||
const hasEnergy = s.solar !== null || s.grid !== null || s.battery !== null || s.consumption !== null;
|
||||
@@ -2639,6 +2640,7 @@ export class NfView3d extends LitElement {
|
||||
for (const p of this.liveHeatPumps(b)) cards.push({ kind: "heatpump", at: p.at, name: p.name, pump: p.pump });
|
||||
for (const m of media) cards.push({ kind: "media", at: { ...m.at, y: m.at.y + 0.5 }, media: m });
|
||||
}
|
||||
if (this.liveCardsOn && !this.dimmed) cards.push(...roomClimateCards(hass, b, this.floorId, this.roomId));
|
||||
if (JSON.stringify(cards) !== JSON.stringify(this._liveCards)) this._liveCards = cards;
|
||||
v.setLiveAnchors(
|
||||
cards.map((c) => c.at),
|
||||
@@ -2689,7 +2691,9 @@ export class NfView3d extends LitElement {
|
||||
const own = this.ownSensors();
|
||||
const e = this._liveEnergy?.summary;
|
||||
const energy = !!e && !this.roomId && this.showEnergy && !!this.hass && !(e.consumption === null && e.grid === null && e.solar === null && e.battery === null);
|
||||
if (!energy) return own.length ? html`<div class="nf-energy" aria-live="off">${own}</div>` : nothing;
|
||||
const climate = this.building?.floors.some((f) => f.rooms.some((r) => r.climate_card));
|
||||
const climateToggle = climate ? this.renderCardToggle() : nothing;
|
||||
if (!energy) return own.length || climateToggle !== nothing ? html`<div class="nf-energy" aria-live="off">${own}${climateToggle}</div>` : nothing;
|
||||
const t = (k: Parameters<typeof translate>[1]) => translate(this.hass, k);
|
||||
const items: { cls: string; label: string; value: string }[] = [];
|
||||
if (e.solar !== null) items.push({ cls: "solar", label: t("energy_solar"), value: formatPower(this.hass, e.solar) });
|
||||
@@ -2712,15 +2716,17 @@ export class NfView3d extends LitElement {
|
||||
: html`<button class="nf-energy-item nf-flow-toggle" aria-pressed=${this._flows} title=${t("flows_hint")} aria-label=${t("flows")} @click=${() => this.toggleFlows()}>
|
||||
<span>${t("flows")}</span><b>⚡</b>
|
||||
</button>`}
|
||||
${this.holograms !== null
|
||||
? nothing
|
||||
: html`<button class="nf-energy-item nf-flow-toggle" aria-pressed=${this._liveCardOn} title=${t("holos_hint")} aria-label=${t("holos")} @click=${() => this.toggleLhCards()}>
|
||||
<span>${t("holos")}</span><b>◫</b>
|
||||
</button>`}
|
||||
${this.renderCardToggle()}
|
||||
${own}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private renderCardToggle() {
|
||||
return this.holograms !== null ? nothing : html`<button class="nf-energy-item nf-flow-toggle nf-card-toggle" aria-pressed=${this._liveCardOn} title=${translate(this.hass, "holos_hint")} aria-label=${translate(this.hass, "holos")} @click=${() => this.toggleLhCards()}>
|
||||
<span>${translate(this.hass, "holos")}</span><b>◫</b>
|
||||
</button>`;
|
||||
}
|
||||
|
||||
/** 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 ?? []) : [];
|
||||
@@ -2795,7 +2801,7 @@ export class NfView3d extends LitElement {
|
||||
class="nf-stage ${this.roomLabels ? "" : "nf-no-room-names"} ${this._low ? "nf-low" : ""} ${this.panelOpen ? "nf-panel-open" : ""} ${this._alerts.length ? "nf-has-alerts" : ""} ${this._narrowStage ? "nf-narrow" : ""}"
|
||||
style=${style}
|
||||
>
|
||||
${this._error ? html`<p class="nf-error">${this._error}</p>` : nothing} ${this.renderTopLeft()} ${renderLhCards(this.hass, this.roomId || this.panelOpen ? [] : this._liveCards, (domain, service, entity, data) => this.hass?.callService(domain, service, { entity_id: entity, ...data }), { folded: this._houseFolded, toggle: () => this.toggleHouseFold() })} ${this.clean ? nothing : this.renderLegend()} ${this.renderMapCredit()}
|
||||
${this._error ? html`<p class="nf-error">${this._error}</p>` : nothing} ${this.renderTopLeft()} ${renderLhCards(this.hass, this._liveCards, (domain, service, entity, data) => this.hass?.callService(domain, service, { entity_id: entity, ...data }), { folded: this._houseFolded, toggle: () => this.toggleHouseFold() }, !!this.roomId || this.panelOpen)} ${this.clean ? nothing : this.renderLegend()} ${this.renderMapCredit()}
|
||||
${this.renderAlerts()} ${this.renderAnnouncement()} ${this.clean ? nothing : html`${this.renderThumbs()} ${this.renderScenes()} ${this.renderFind()} ${this.renderCentral()}`} ${this.renderSwipe()}
|
||||
${this.renderMenu()} ${this.renderPlate()} ${this.renderEye()} ${this.renderLock()} ${this.renderWalk()} ${this.renderTravel()} ${this.renderClock()} ${this.renderToday()} ${this.renderLayers()} ${this.renderPluginWindow()}
|
||||
${this.showStats && this._stats
|
||||
|
||||
@@ -47,3 +47,10 @@ test("a standalone blind's separate slat position is watched", () => {
|
||||
b.floors[0].placements.push({ entity_id: "cover.blind", cover_tilt: "cover.slats", x: 2, z: 2, y: null });
|
||||
assert.ok(watchedEntities(inputs({ building: b })).includes("cover.slats"));
|
||||
});
|
||||
|
||||
test("room cards watch explicitly chosen values outside the area, including a source that is temporarily missing", () => {
|
||||
const b = building();
|
||||
Object.assign(b.floors[0].rooms[0], { climate_card: true, climate: { humidity: "cover.knx", temperature: "sensor.missing", co2: "sensor.other_room" } });
|
||||
const ids = watchedEntities(inputs({ building: b, needsRoomSensors: false }));
|
||||
for (const id of ["cover.knx", "sensor.missing", "sensor.other_room"]) assert.ok(ids.includes(id), id);
|
||||
});
|
||||
@@ -2,7 +2,7 @@
|
||||
// everything it shows: devices and their power sensors, openings and their contacts, energy, presence, heat, weather, and so on.
|
||||
|
||||
import { alertEntities, type AlertSources } from "../../alerts.ts";
|
||||
import { carWatched, deviceSiblings, kindOf, robotRoomSensor, type FurnitureLinks, type OpeningEntities, roomEntities } from "../../devices.ts";
|
||||
import { carWatched, deviceSiblings, kindOf, robotRoomSensor, roomClimateSensors, type FurnitureLinks, type OpeningEntities, roomEntities } from "../../devices.ts";
|
||||
import { powerSensorFor } from "../../energy.ts";
|
||||
import { placedEntities } from "../../markers.ts";
|
||||
import type { Building } from "../../model.ts";
|
||||
@@ -59,7 +59,9 @@ export function watchedEntities(inputs: WatchInputs): string[] {
|
||||
const placed = placedEntities(b);
|
||||
const energy = b.energy;
|
||||
const lightsOfRooms = roomsOf(b).flatMap((r) => roomEntities(hass, r).filter((id) => kindOf(id) === "light"));
|
||||
const sensorsOfRooms = inputs.needsRoomSensors ? roomsOf(b).flatMap((r) => roomEntities(hass, r).filter((id) => id.startsWith("sensor.") || id.startsWith("climate."))) : [];
|
||||
const sensorsOfRooms = b.floors.flatMap((f) => f.rooms.flatMap((r) => inputs.needsRoomSensors || r.climate_card
|
||||
? [...roomEntities(hass, r).filter((id) => id.startsWith("sensor.") || id.startsWith("climate.")), ...Object.values(r.climate ?? {}).flat(), ...(["temperature", "humidity", "co2"] as const).flatMap((key) => roomClimateSensors(hass, f, r, key))]
|
||||
: []));
|
||||
const ids: MaybeId[] = [
|
||||
...placed,
|
||||
...b.floors.flatMap((f) => f.placements.map((p) => p.cover_tilt)),
|
||||
|
||||
@@ -21,6 +21,20 @@ test("a KNX numeric temperature remains selectable and readable even with an inf
|
||||
assert.equal(roomClimateValue(hass, null, { ...room, climate: { temperature: "sensor.fahrenheit" } }, "temperature"), 20);
|
||||
});
|
||||
|
||||
test("manual Symcon climate assignment accepts unclassified numeric values without relaxing automatic detection", () => {
|
||||
const h = hassOf([
|
||||
entity("cover.knx", "open", { symcon_id: 12, symcon_variable_type: 2, symcon_numeric_value: 48.5 }),
|
||||
entity("sensor.percent", "50", { unit_of_measurement: "%" }),
|
||||
entity("sensor.soil", "50", { device_class: "moisture", unit_of_measurement: "%" }),
|
||||
entity("sensor.text", "50", { symcon_id: 13, symcon_variable_type: 3, unit_of_measurement: "%" }),
|
||||
]);
|
||||
assert.equal(isClimateValueSensor(h, "cover.knx", "humidity", true), true);
|
||||
assert.equal(isClimateValueSensor(h, "cover.knx", "humidity"), false);
|
||||
assert.equal(isClimateValueSensor(h, "sensor.percent", "humidity"), true);
|
||||
assert.equal(isClimateValueSensor(h, "sensor.soil", "humidity"), false);
|
||||
assert.equal(isClimateValueSensor(h, "sensor.text", "humidity", true), false);
|
||||
});
|
||||
|
||||
const lounge = hassOf(
|
||||
[
|
||||
entity("light.ceiling", "on"),
|
||||
|
||||
@@ -210,13 +210,18 @@ export const CLIMATE_CLASSES = { temperature: "temperature", humidity: "humidity
|
||||
export type ClimateKey = keyof typeof CLIMATE_CLASSES;
|
||||
|
||||
/** Numeric room values, including Symcon readings whose legacy domain was inferred from a parent name. */
|
||||
export function isClimateValueSensor(hass: HomeAssistant, id: string, key: ClimateKey): boolean {
|
||||
export function isClimateValueSensor(hass: HomeAssistant, id: string, key: ClimateKey, manual = false): boolean {
|
||||
const a = hass.states[id]?.attributes;
|
||||
if (!a) return false;
|
||||
const symconNumber = (a.symcon_variable_type === 1 || a.symcon_variable_type === 2) && typeof a.symcon_id === "number";
|
||||
if (typeof a.symcon_id === "number" && !symconNumber) return false;
|
||||
if (!symconNumber && !/^(sensor|input_number|number)\./.test(id)) return false;
|
||||
// An explicit assignment gives an otherwise unclassified Symcon number its meaning.
|
||||
if (manual && symconNumber) return true;
|
||||
const unit = String(a.unit_of_measurement ?? "").replace(/\s/g, "").toLowerCase();
|
||||
if (key === "temperature" && ["°c", "°f", "℃", "℉", "k"].includes(unit)) return true;
|
||||
if (key === "humidity" && !a.device_class && ["%", "%rh", "%r.h.", "%rf", "%r.f."].includes(unit)) return true;
|
||||
if (key === "co2" && unit === "ppm" && /co[₂2]/i.test(String(a.friendly_name ?? ""))) return true;
|
||||
return a.device_class === CLIMATE_CLASSES[key];
|
||||
}
|
||||
|
||||
@@ -264,11 +269,13 @@ export function roomClimateValue(hass: HomeAssistant, floor: Floor | null, room:
|
||||
const readings = roomClimateSensors(hass, floor, room, key)
|
||||
.map((id) => {
|
||||
const state = hass.states[id];
|
||||
if (!state || isUnavailable(state) || (!state.state.trim() && state.attributes.symcon_numeric_value === undefined)) return NaN;
|
||||
const reading = Number(state?.attributes.symcon_numeric_value ?? state?.state);
|
||||
return key === "temperature" ? toCelsius(reading, hass.states[id]?.attributes.unit_of_measurement) : reading;
|
||||
})
|
||||
.filter(Number.isFinite);
|
||||
if (readings.length) return readings.reduce((sum, v) => sum + v, 0) / readings.length;
|
||||
if (room.climate?.[key]) return null;
|
||||
// no room sensor: a thermostat of the room's area tells its temperature and humidity (heating curves, the heat map)
|
||||
if (key === "co2" || room.climate?.[key] === "none") return null;
|
||||
const attr = key === "temperature" ? "current_temperature" : "current_humidity";
|
||||
|
||||
@@ -25,6 +25,9 @@ const DE = {
|
||||
reload_page: "Neu laden",
|
||||
symcon_variables_reload: "Variablen neu laden",
|
||||
symcon_cover_position: "Position (Behang)",
|
||||
climate_card: "Raumklima als schwebende Karte",
|
||||
climate_card_hint: "Zeigt Temperatur, Luftfeuchtigkeit und CO₂ über diesem Raum. In der 3D-Ansicht lassen sie sich über „Karten“ ein- und ausblenden.",
|
||||
climate_card_missing: "Keine aktuellen Messwerte",
|
||||
cover_tilt_entity: "Lamellenposition",
|
||||
cover2_tilt_entity: "Lamellenposition (zweiter Behang)",
|
||||
symcon_variables_loading: "Variablen werden geladen …",
|
||||
@@ -2051,6 +2054,9 @@ const EN: Record<Key, string> = {
|
||||
reload_page: "Reload",
|
||||
symcon_variables_reload: "Reload variables",
|
||||
symcon_cover_position: "Blind position",
|
||||
climate_card: "Room climate as a floating card",
|
||||
climate_card_hint: "Shows temperature, humidity and CO₂ over this room. Toggle them with “Cards” in the 3D view.",
|
||||
climate_card_missing: "No current readings",
|
||||
cover_tilt_entity: "Slat position",
|
||||
cover2_tilt_entity: "Slat position (second blind)",
|
||||
symcon_variables_loading: "Loading variables …",
|
||||
|
||||
@@ -18,6 +18,8 @@ import { curvePath } from "./day-curves.ts";
|
||||
import type { PrinterInfo } from "./printer.ts";
|
||||
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";
|
||||
|
||||
export interface HouseCard {
|
||||
kind: "house";
|
||||
@@ -60,7 +62,7 @@ export interface HeatPumpCard {
|
||||
pump: HeatPumpInfo;
|
||||
}
|
||||
|
||||
export type LiveCard = HouseCard | CarCard | MediaCard | PrinterCard | HeatPumpCard;
|
||||
export type LiveCard = HouseCard | CarCard | MediaCard | PrinterCard | HeatPumpCard | RoomClimateCard;
|
||||
|
||||
/** A button on a card was pressed: the 3D view calls the service (with extra data such as the volume). */
|
||||
export type LiveCardAction = (domain: string, service: string, entity: string, data?: Record<string, unknown>) => void;
|
||||
@@ -312,10 +314,21 @@ function heatPumpCard(hass: HomeAssistant | undefined, c: HeatPumpCard, i: numbe
|
||||
</div>`;
|
||||
}
|
||||
|
||||
export function renderLhCards(hass: HomeAssistant | undefined, cards: readonly LiveCard[], act: LiveCardAction, fold?: LiveCardFold): TemplateResult | typeof nothing {
|
||||
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}>
|
||||
<div class="live-title">${c.name || translate(hass, "room")}</div>
|
||||
<div class="live-row live-climate-temperature"><span>🌡 ${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>
|
||||
<div class="live-row live-climate-humidity"><span>💧 ${translate(hass, "climate_humidity")}</span><b>${value(c.humidity, 0, "%")}</b></div>
|
||||
<div class="live-row live-climate-co2"><span>${translate(hass, "climate_co2")}</span><b>${value(c.co2, 0, "ppm")}</b></div>
|
||||
${c.temperature === null && c.humidity === null && c.co2 === null ? html`<small class="live-status">${translate(hass, "climate_card_missing")}</small>` : nothing}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
export function renderLhCards(hass: HomeAssistant | undefined, cards: readonly LiveCard[], act: LiveCardAction, fold?: LiveCardFold, climateOnly = false): TemplateResult | typeof nothing {
|
||||
if (!cards.length) return nothing;
|
||||
return html`<div class="live-cards">
|
||||
${cards.map((c, i) => (c.kind === "house" ? houseCard(hass, c, i, fold) : c.kind === "car" ? carCard(hass, c, i, act) : c.kind === "printer" ? printerCard(hass, c, i) : c.kind === "heatpump" ? heatPumpCard(hass, c, i) : mediaCard(hass, c, i, act)))}
|
||||
${cards.map((c, i) => (c.kind === "roomclimate" ? roomClimateCard(hass, c, i) : climateOnly ? nothing : c.kind === "house" ? houseCard(hass, c, i, fold) : c.kind === "car" ? carCard(hass, c, i, act) : c.kind === "printer" ? printerCard(hass, c, i) : c.kind === "heatpump" ? heatPumpCard(hass, c, i) : mediaCard(hass, c, i, act)))}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
@@ -418,6 +431,21 @@ export const liveCardStyles = css`
|
||||
gap: 2px;
|
||||
min-width: 150px;
|
||||
}
|
||||
.live-card-roomclimate {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
min-width: 190px;
|
||||
max-width: calc(100vw - 24px);
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.live-card-roomclimate .live-title {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 220px;
|
||||
}
|
||||
.live-climate-temperature b { color: color-mix(in srgb, #ffca8a 80%, var(--nf-text)); }
|
||||
.live-climate-humidity b { color: color-mix(in srgb, #7dd3fc 80%, var(--nf-text)); }
|
||||
.live-climate-co2 b { color: color-mix(in srgb, #c4b5fd 80%, var(--nf-text)); }
|
||||
.live-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { box, entity, floorWith, hassOf } from "../entities/fixtures.ts";
|
||||
import { emptyBuilding, normalizeBuilding, pointInPolygon } from "../model.ts";
|
||||
import { roomClimateCards } from "./room-climate-card.ts";
|
||||
|
||||
test("enabled room cards use explicit numeric sensors, averages and temperature conversion", () => {
|
||||
const b = emptyBuilding();
|
||||
const room = { ...box("living", 0, 0, 4, 4), name: "Wohnzimmer", climate_card: true, climate: { temperature: ["sensor.c", "sensor.f"], humidity: "cover.knx", co2: "sensor.co2" } };
|
||||
b.floors = [floorWith([room, box("disabled", 5, 0, 8, 4)])];
|
||||
const h = hassOf([
|
||||
entity("sensor.c", "20", { unit_of_measurement: "°C" }), entity("sensor.f", "68", { unit_of_measurement: "°F" }),
|
||||
entity("cover.knx", "open", { symcon_numeric_value: 48.5 }), entity("sensor.co2", "780"),
|
||||
]);
|
||||
const cards = roomClimateCards(h, normalizeBuilding(b), null, null);
|
||||
assert.equal(cards.length, 1);
|
||||
assert.deepEqual([cards[0].temperature, cards[0].humidity, cards[0].co2], [20, 48.5, 780]);
|
||||
assert.equal(cards[0].name, "Wohnzimmer");
|
||||
assert.ok(pointInPolygon([cards[0].at.x, cards[0].at.z], room.points));
|
||||
h.states["cover.knx"] = entity("cover.knx", "open", { symcon_numeric_value: 55 });
|
||||
assert.equal(roomClimateCards(h, b, null, null)[0].humidity, 55, "a fresh state updates the card values");
|
||||
});
|
||||
|
||||
test("floor/room navigation filters cards and concave rooms keep their anchor inside", () => {
|
||||
const b = emptyBuilding();
|
||||
const room = { ...box("u", 0, 0, 6, 6), climate_card: true, points: [[0, 0], [6, 0], [6, 6], [4, 6], [4, 2], [2, 2], [2, 6], [0, 6]] as [number, number][] };
|
||||
const upper = { ...floorWith([{ ...box("upper", 0, 0, 4, 4), climate_card: true }]), id: "upper" };
|
||||
b.floors = [floorWith([room]), upper];
|
||||
const h = hassOf([]);
|
||||
const all = roomClimateCards(h, b, null, null);
|
||||
assert.equal(all.length, 2);
|
||||
assert.ok(pointInPolygon([all[0].at.x, all[0].at.z], room.points));
|
||||
assert.deepEqual(roomClimateCards(h, b, "upper", null).map((c) => c.roomId), ["upper"]);
|
||||
assert.deepEqual(roomClimateCards(h, b, null, "u").map((c) => c.roomId), ["u"]);
|
||||
});
|
||||
|
||||
test("missing, unavailable and disabled readings stay missing rather than becoming zero or another thermostat", () => {
|
||||
const b = emptyBuilding();
|
||||
b.floors = [floorWith([{ ...box("r", 0, 0, 4, 4, "a"), climate_card: true, climate: { temperature: "sensor.offline", humidity: "sensor.empty", co2: "none" } }])];
|
||||
const h = hassOf([entity("sensor.offline", "unavailable"), entity("sensor.empty", ""), entity("climate.other", "heat", { current_temperature: 30 })], { "climate.other": { area_id: "a" } });
|
||||
const [card] = roomClimateCards(h, b, null, null);
|
||||
assert.deepEqual([card.temperature, card.humidity, card.co2], [null, null, null]);
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { roomClimateValue } from "../devices.ts";
|
||||
import { centroid, pointInPolygon, spotGrid, type Building } from "../model.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import type { PlanPoint } from "../viewer/live-energy.ts";
|
||||
|
||||
export interface RoomClimateCard {
|
||||
kind: "roomclimate";
|
||||
at: PlanPoint;
|
||||
roomId: string;
|
||||
name: string;
|
||||
/** Celsius internally, converted to the display unit when rendered. */
|
||||
temperature: number | null;
|
||||
humidity: number | null;
|
||||
co2: number | null;
|
||||
}
|
||||
|
||||
/** One opt-in card per room, using the exact same sensor assignments and averaging as the room panel. */
|
||||
export function roomClimateCards(hass: HomeAssistant, building: Building, floorId: string | null, roomId: string | null): RoomClimateCard[] {
|
||||
const cards: RoomClimateCard[] = [];
|
||||
for (const floor of building.floors) {
|
||||
if (floorId && floor.id !== floorId) continue;
|
||||
for (const room of floor.rooms) {
|
||||
if (!room.climate_card || room.points.length < 3 || (roomId && room.id !== roomId)) continue;
|
||||
const middle = centroid(room.points);
|
||||
const [x, z] = pointInPolygon(middle, room.points) ? middle : spotGrid(room, 9, 9).sort((a, b) => Math.hypot(a[0] - middle[0], a[1] - middle[1]) - Math.hypot(b[0] - middle[0], b[1] - middle[1]))[0] ?? room.points[0];
|
||||
cards.push({ kind: "roomclimate", roomId: room.id, name: room.name,
|
||||
at: { floorId: floor.id, x, z, y: (room.ceiling ?? floor.height) + 0.4 },
|
||||
temperature: roomClimateValue(hass, floor, room, "temperature"),
|
||||
humidity: roomClimateValue(hass, floor, room, "humidity"),
|
||||
co2: roomClimateValue(hass, floor, room, "co2"),
|
||||
});
|
||||
}
|
||||
}
|
||||
return cards;
|
||||
}
|
||||
@@ -24,6 +24,8 @@ export type WallHeight = number | null | (number | null)[];
|
||||
export interface Room {
|
||||
/** Room temperature, humidity and CO2: chosen sensors instead of the automatic pick. */
|
||||
climate?: RoomClimate | null;
|
||||
/** Show temperature, humidity and CO2 in a floating glass card over this room. */
|
||||
climate_card?: boolean;
|
||||
id: string;
|
||||
name: string;
|
||||
area_id: string | null;
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
// Complete climate-card flow against the built UI and an invented Symcon object tree.
|
||||
import assert from "node:assert/strict";
|
||||
import { createServer } from "node:http";
|
||||
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
||||
import { extname, join, relative, resolve } from "node:path";
|
||||
import { build } from "esbuild";
|
||||
import puppeteer from "puppeteer-core";
|
||||
|
||||
const root = resolve(import.meta.dirname, "..");
|
||||
const types = { ".html": "text/html", ".js": "text/javascript", ".json": "application/json", ".png": "image/png" };
|
||||
const server = createServer((req, res) => {
|
||||
const file = resolve(root, `.${decodeURIComponent(new URL(req.url, "http://localhost").pathname)}`);
|
||||
if (relative(root, file).startsWith("..") || !existsSync(file)) return res.writeHead(404).end();
|
||||
res.writeHead(200, { "content-type": types[extname(file)] ?? "application/octet-stream" }).end(readFileSync(file));
|
||||
});
|
||||
await new Promise((done) => server.listen(0, "127.0.0.1", done));
|
||||
const executablePath = [process.env.CHROME_PATH, "C:/Program Files/Google/Chrome/Application/chrome.exe", "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"].find((p) => p && existsSync(p));
|
||||
let browser;
|
||||
try {
|
||||
browser = await puppeteer.launch({ executablePath, headless: true, args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"] });
|
||||
const page = await browser.newPage();
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(String(e)));
|
||||
await page.evaluateOnNewDocument(() => localStorage.setItem("nextfloor.cards", "0"));
|
||||
await page.setViewport({ width: 1440, height: 1000 });
|
||||
await page.goto(`http://127.0.0.1:${server.address().port}/preview/index.html`, { waitUntil: "networkidle0" });
|
||||
await page.waitForFunction(() => window.nfPanel?.data.building?.floors.length);
|
||||
const adapter = await build({ entryPoints: [join(root, "frontend/src/symcon-bridge.ts")], bundle: true, write: false, format: "iife", globalName: "SymconAdapter", logLevel: "silent" });
|
||||
await page.addScriptTag({ content: adapter.outputFiles[0].text });
|
||||
await page.evaluate(async () => {
|
||||
window.humidityValue = 51.6;
|
||||
window.bootstrapCalls = 0;
|
||||
const raw = (id, name, type, value, unit, domain = "sensor") => ({ entity_id: `${domain}.${id}`, name, path: `Haus / Messwerte / ${name}`, state: domain === "cover" ? "open" : String(value), attributes: { symcon_id: id, symcon_variable_type: type, symcon_numeric_value: value, unit_of_measurement: unit } });
|
||||
const originalFetch = window.fetch;
|
||||
window.fetch = async (url, init) => {
|
||||
if (!String(url).includes("/hook/climate-fixture/")) return originalFetch(url, init);
|
||||
window.bootstrapCalls++;
|
||||
const variables = [raw(201, "Raumtemperatur", 2, 21.5, "°C"), raw(202, "Messwert Raumfeuchtigkeit", 2, window.humidityValue, "%", "cover"), raw(203, "CO₂", 1, 780, "ppm")];
|
||||
const objects = [{ object_id: 100, parent_id: 0, name: "Haus", path: "Haus", object_type: 0, position: 0, hidden: true, icon: "" },
|
||||
...variables.map((v) => ({ object_id: v.attributes.symcon_id, parent_id: 100, entity_id: v.entity_id, name: v.name, path: v.path, object_type: 2, position: 0, hidden: false, icon: "" }))];
|
||||
return new Response(JSON.stringify({ state_revision: window.bootstrapCalls, building_revision: 1, variables, objects, areas: [] }));
|
||||
};
|
||||
window.__NEXTFLOOR_SYMCON__ = { endpoint: "/hook/climate-fixture", token: "fixture-only" };
|
||||
const bridge = new window.SymconAdapter.SymconBridge();
|
||||
await bridge.start();
|
||||
bridge.stop();
|
||||
const p = window.nfPanel;
|
||||
const apply = () => {
|
||||
const h = bridge.snapshot();
|
||||
p.hass = { ...p.hass, language: "de", states: h.states, entities: h.entities, symconObjects: h.symconObjects, symconRefresh: h.symconRefresh };
|
||||
};
|
||||
apply();
|
||||
bridge.onChange(apply);
|
||||
await p.updateComplete;
|
||||
[...p.shadowRoot.querySelectorAll("[role=tab]")].find((b) => b.textContent.includes("Editor")).click();
|
||||
});
|
||||
await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector("nf-editor")?.shadowRoot);
|
||||
await page.evaluate(async () => {
|
||||
const e = window.nfPanel.shadowRoot.querySelector("nf-editor");
|
||||
window.climateEditor = e;
|
||||
e._floorId = e._doc.floors[0].id;
|
||||
window.climateRoomId = e._doc.floors[0].rooms[0].id;
|
||||
window.climateFloorId = e._floorId;
|
||||
e.selectItem("room", window.climateRoomId);
|
||||
await e.updateComplete;
|
||||
const section = [...e.shadowRoot.querySelectorAll("details.nf-points")].find((d) => d.querySelector("summary").textContent === "Raumklima");
|
||||
section.open = true;
|
||||
window.climateSection = section;
|
||||
window.pickClimate = async (label, id, name) => {
|
||||
const field = [...window.climateSection.querySelectorAll("label.nf-field")].find((el) => el.textContent.trim().startsWith(label));
|
||||
const picker = field.querySelector("nf-entity-picker");
|
||||
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 = name;
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await native.updateComplete;
|
||||
const row = native.shadowRoot.querySelector(`#object-${id}`);
|
||||
if (!row?.classList.contains("selectable")) throw new Error(`${name} must be selectable despite its inferred domain`);
|
||||
row.click();
|
||||
await native.updateComplete;
|
||||
native.shadowRoot.querySelector(".apply").click();
|
||||
await e.updateComplete;
|
||||
};
|
||||
await window.pickClimate("Temperatur", 201, "Raumtemperatur");
|
||||
await window.pickClimate("Luftfeuchte", 202, "Messwert Raumfeuchtigkeit");
|
||||
await window.pickClimate("CO₂", 203, "CO₂");
|
||||
const label = [...window.climateSection.querySelectorAll("label.nf-check")].find((el) => el.textContent.includes("schwebende Karte"));
|
||||
label.querySelector("input").click();
|
||||
await e.updateComplete;
|
||||
const second = e._doc.floors[0].rooms[1];
|
||||
second.climate = { temperature: "none", humidity: "none", co2: "none" };
|
||||
e.selectItem("room", second.id);
|
||||
await e.updateComplete;
|
||||
const section2 = [...e.shadowRoot.querySelectorAll("details.nf-points")].find((d) => d.querySelector("summary").textContent === "Raumklima");
|
||||
section2.open = true;
|
||||
[...section2.querySelectorAll("label.nf-check")].find((el) => el.textContent.includes("schwebende Karte")).querySelector("input").click();
|
||||
await e.updateComplete;
|
||||
[...window.nfPanel.shadowRoot.querySelectorAll("[role=tab]")].find((b) => b.textContent.trim() === "3D").click();
|
||||
});
|
||||
await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector("nf-view3d")?.viewer);
|
||||
await page.evaluate(() => { window.climateView = window.nfPanel.shadowRoot.querySelector("nf-view3d"); });
|
||||
await page.waitForFunction(() => window.climateView.shadowRoot.querySelector(".nf-card-toggle"));
|
||||
assert.equal(await page.evaluate(() => window.climateView.shadowRoot.querySelector(".nf-card-toggle").getAttribute("aria-pressed")), "false");
|
||||
await page.evaluate(() => window.climateView.shadowRoot.querySelector(".nf-card-toggle").click());
|
||||
await page.waitForFunction(() => window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate").length === 2);
|
||||
const text = () => page.evaluate(() => window.climateView.shadowRoot.querySelector(`.live-card[data-room="${window.climateRoomId}"]`).textContent);
|
||||
assert.match(await text(), /21,5\s*°C/);
|
||||
assert.match(await text(), /52\s*%/);
|
||||
assert.match(await text(), /780\s*ppm/);
|
||||
assert.equal(await page.evaluate(() => !!window.climateView.shadowRoot.querySelector(".live-card-house")), false, "climate cards do not require an energy meter");
|
||||
assert.equal(await page.evaluate(() => window.nfPanel.data.building.floors[0].rooms[0].climate.humidity), "cover.202");
|
||||
assert.equal(await page.evaluate(() => [...window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate")].some((c) => c.textContent.includes("Keine aktuellen Messwerte"))), true);
|
||||
await page.evaluate(() => { window.humidityValue = 62.4; window.nfPanel.shadowRoot.querySelector(".nf-reload-variables").click(); });
|
||||
await page.waitForFunction(() => window.climateView.shadowRoot.querySelector(`.live-card[data-room="${window.climateRoomId}"]`).textContent.includes("62 %"));
|
||||
const out = join(root, "preview/screenshots");
|
||||
mkdirSync(out, { recursive: true });
|
||||
await page.waitForFunction(() => [...window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate")].every((c) => c.style.visibility === "visible"));
|
||||
await page.screenshot({ path: join(out, "symcon-climate-desktop.png") });
|
||||
await page.setViewport({ width: 390, height: 844 });
|
||||
await page.evaluate(() => { window.nfPanel.narrow = true; });
|
||||
await page.waitForFunction(() => [...window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate")].every((c) => { const r = c.getBoundingClientRect(); return r.left >= 0 && r.right <= innerWidth; }));
|
||||
await page.screenshot({ path: join(out, "symcon-climate-mobile.png") });
|
||||
await page.evaluate(() => { const p = window.nfPanel; p._floorId = window.climateFloorId; p._roomId = window.climateRoomId; });
|
||||
await page.waitForFunction(() => window.climateView.panelOpen && window.climateView.shadowRoot.querySelectorAll(".live-card-roomclimate").length === 1);
|
||||
assert.match(await text(), /62\s*%/);
|
||||
await page.evaluate(() => window.climateView.shadowRoot.querySelector(".nf-card-toggle").click());
|
||||
await page.waitForFunction(() => !window.climateView.shadowRoot.querySelector(".live-card-roomclimate"));
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("OK: native float humidity picker, saved per-room card setting, temperature/humidity/CO2 values, missing data, live reload, no-energy toggle, desktop/mobile and opened-room cards");
|
||||
} finally {
|
||||
await browser?.close();
|
||||
await new Promise((done) => server.close(done));
|
||||
}
|
||||
Reference in new issue
Block a user