feat: improve Symcon controls, device readings and designer help

This commit is contained in:
jhartworks committed 2026-11-10 09:19:13 +01:00
1 parent ff54f4461a
commit 00fca890de
50 files changed
+2447 -1840

No files matched your search

+3 -2
View File
@@ -18,6 +18,7 @@ import type { Building } from "./model.ts";
import { roomsOnly } from "./rooms-only.ts";
import { colorSchemeOf, controls, readableStyles, tokens } from "./styles.ts";
import type { HomeAssistant } from "./types.ts";
import { withCoverControls } from "./entities/cover-controls.ts";
import type { WallMode } from "./viewer/viewer3d.ts";
import { lookNow } from "./themes.ts";
@@ -313,7 +314,7 @@ export class NextFloorCard extends LitElement {
};
const eye = c?.controls_hidden !== undefined || (c?.controls_hide_after ?? 0) > 0;
return html`<nf-view3d
.hass=${this.hass}
.hass=${withCoverControls(this.hass, b.floors)}
.building=${b}
.packs=${this.data.packs}
.floorId=${s.floorId}
@@ -392,7 +393,7 @@ export class NextFloorCard extends LitElement {
return html`<nf-room-panel
.building=${this.plan() ?? null}
class="nf-card-panel"
.hass=${this.hass}
.hass=${withCoverControls(this.hass, b.floors)}
.room=${b.floors.flatMap((f) => f.rooms).find((r) => r.id === this._roomId) ?? null}
.floor=${b.floors.find((f) => f.rooms.some((r) => r.id === this._roomId)) ?? null}
.outside=${this._roomId === OUTSIDE ? outsideEntities(this.hass, b.floors) : null}
+4 -2
View File
@@ -1,6 +1,8 @@
// 2D editor: floors, rooms (rectangles and free shapes), snapping, undo, background template.
import { html, LitElement, nothing, svg, type PropertyValues, type TemplateResult } from "lit";
import { withCoverControls } from "../entities/cover-controls.ts";
import { hint } from "./editor/fields.ts";
import { fetchImage, importPack, storeImage } from "../api.ts";
import { defaultHeight, entityName, kindOf, roomEntities } from "../devices.ts";
import { closeGaps, suggestedThickness } from "../geometry/gaps.ts";
@@ -1043,7 +1045,7 @@ export class NfEditor extends LitElement {
</div>`}
${this.render3dBar()}
<nf-view3d
.hass=${this.hass}
.hass=${this.hass ? withCoverControls(this.hass, this._doc3d.floors) : undefined}
.building=${this._doc3d}
.floorId=${this.houseTool ? null : this._floorId}
.roomId=${null}
@@ -3210,7 +3212,7 @@ export class NfEditor extends LitElement {
${this.planLayers(floor, walls?.walls ?? null)}
</svg>
${this.renderContext()}
<p class="nf-hint ${this._fixedHint ? "nf-hint-fixed" : ""}">${this._pick ? this.t("robot_cal_doing") : !floor ? this.t("hint_empty") : this._fixedHint ? this.t("fixed_drag_hint") : this.t(`hint_${this._tool}` as I18nKey)}</p>
${this._pick || this._fixedHint ? html`<p class="nf-hint ${this._fixedHint ? "nf-hint-fixed" : ""}">${this._pick ? this.t("robot_cal_doing") : this.t("fixed_drag_hint")}</p>` : html`<div class="nf-hint">${hint(!floor ? this.t("hint_empty") : this.t(`hint_${this._tool}` as I18nKey))}</div>`}
<button class="nf-keys-open" title=${this.t("keys_title")} aria-label=${this.t("keys_title")} @click=${() => (this._keys = true)}>?</button>
${this.isAdmin
? renderTour((k, vars) => this.t(k, vars), this._tour, (step) => {
+4 -3
View File
@@ -7,6 +7,7 @@ import { LitElement, html, nothing, type PropertyValues } from "lit";
import { uid, type BleFingerprint, type BleTag } from "../../model.ts";
import { fingerprintsOf, locate, RECORD_SECONDS, replaceRoom, signalLevel, type Reading } from "./ops/ble.ts";
import type { EditorHost } from "./host.ts";
import { hint } from "./fields.ts";
interface Scan {
address: string | null;
@@ -187,7 +188,7 @@ export class NfBleLocate extends LitElement {
<span class="nf-ble-track"><span class="nf-ble-fill" style="width:${Math.round(signalLevel(r.rssi) * 100)}%"></span></span>
<span class="nf-ble-db">${Math.round(r.rssi)}</span>
</div>`)}
${entries.length === 1 ? html`<p class="nf-sub">${t("ble_one_scanner")}</p>` : nothing}
${entries.length === 1 ? hint(t("ble_one_scanner")) : nothing}
</div>`;
}
@@ -215,7 +216,7 @@ export class NfBleLocate extends LitElement {
</button>
${this._room && count(this._room) ? html`<button class="nf-btn" ?disabled=${recording} @click=${() => this.update2(tag.id, (x) => (x.prints = x.prints.filter((p) => p.room !== this._room)))}>${t("ble_forget_room")}</button>` : nothing}
</div>
<p class="nf-sub">${t("ble_learn_hint")}</p>`;
${hint(t("ble_learn_hint"))}`;
}
protected render() {
@@ -238,7 +239,7 @@ export class NfBleLocate extends LitElement {
<button class="nf-btn" title=${t("delete")} @click=${() => this.removeTag(x.id)}>✕</button>
</div>`,
)}
${tag ? html`<div class="nf-ble-learn">${this.learn(tag)}<p class="nf-sub">${t("ble_sensor_hint", { name: tag.name })}</p></div>` : nothing}
${tag ? html`<div class="nf-ble-learn">${this.learn(tag)}${hint(t("ble_sensor_hint", { name: tag.name }))}</div>` : nothing}
<div class="nf-form">
<label class="nf-field nf-wide">${t("ble_add")}
<select .value=${this._pick} @change=${(e: Event) => (this._pick = (e.target as HTMLSelectElement).value)}>
@@ -0,0 +1,21 @@
import { html, type TemplateResult } from "lit";
import { uid, type DeviceValueLink } from "../../model.ts";
import { valueSymbol } from "../../entities/device-values.ts";
import { entityOptions } from "./entities.ts";
import { entityField, hint, textField } from "./fields.ts";
import type { EditorHost } from "./host.ts";
export function renderDeviceValues(host: EditorHost, links: readonly DeviceValueLink[] = [], set: (next: DeviceValueLink[] | undefined) => void): TemplateResult {
const options = entityOptions(host.hass, (id) => !host.hass?.states[id]?.attributes.symcon_source_entity || links.some((l) => l.entity === id));
const patch = (id: string, change: Partial<DeviceValueLink>) => set(links.map((l) => l.id === id ? { ...l, ...change } : l));
return html`<div class="nf-value-links nf-wide">
<div class="nf-h3row"><h4>${host.t("device_values")}</h4><button class="nf-btn nf-value-add" title=${host.t("device_value_add")} aria-label=${host.t("device_value_add")} ?disabled=${!host.admin} @click=${() => set([...links, { id: uid("value"), entity: null }])}>+</button></div>
${links.map((l, i) => html`<div class="nf-form nf-value-link" data-value=${l.id}>
${entityField(host, `${host.t("device_value")} ${i + 1}`, l.entity, undefined, options, (v) => patch(l.id, { entity: v === "none" ? null : v }))}
${textField(host, host.t("device_value_icon"), l.icon ?? "", (icon) => patch(l.id, { icon: icon || null }), { maxlength: 16, placeholder: valueSymbol(l.entity ? host.hass?.states[l.entity] : undefined) })}
${textField(host, host.t("device_value_label"), l.label ?? "", (label) => patch(l.id, { label: label || null }), { maxlength: 60 })}
<button class="nf-link nf-value-remove nf-wide" ?disabled=${!host.admin} @click=${() => { const next = links.filter((v) => v.id !== l.id); set(next.length ? next : undefined); }}>× ${host.t("device_value_remove")}</button>
</div>`)}
${hint(host.t("device_values_hint"))}
</div>`;
}
+4 -3
View File
@@ -10,6 +10,7 @@ import type { EntityOption } from "./entities.ts";
import type { EditorHost } from "./host.ts";
import { pluginMdiIcon } from "../../plugins/registry.ts";
import "../entity-picker.ts";
import "../help-popup.ts";
const valueOf = (e: Event) => (e.target as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement).value;
@@ -150,7 +151,7 @@ export function pinShiftField(host: EditorHost, value: PinOffset | null | undefi
<div class="nf-form">
${numberField(host, "↔ x", v.x ?? 0, set("x"), 0.05)} ${numberField(host, "↕ z", v.z ?? 0, set("z"), 0.05)} ${numberField(host, host.t("pin_shift_up"), v.y ?? 0, set("y"), 0.05)}
${value ? html`<button class="nf-btn nf-field-btn" ?disabled=${!host.admin} @click=${() => onChange(null)}>${host.t("height_auto")}</button>` : nothing}
<p class="nf-sub nf-wide">${host.t("pin_shift_hint")}</p>
${hint(host.t("pin_shift_hint"), "nf-wide")}
</div>
</details>`;
}
@@ -158,8 +159,8 @@ export function pinShiftField(host: EditorHost, value: PinOffset | null | undefi
/** A row of buttons at the bottom of a form. */
export const actions = (...buttons: (TemplateResult | typeof nothing)[]): TemplateResult => html`<div class="nf-actions">${buttons}</div>`;
/** A help line under a form. */
export const hint = (text: string, extraClass = ""): TemplateResult => html`<p class="nf-sub ${extraClass}">${text}</p>`;
/** A compact information button that opens the explanation in a dialog. */
export const hint = (text: string, extraClass = ""): TemplateResult => html`<nf-help-popup class=${extraClass} .text=${text}></nf-help-popup>`;
/** A percentage between 10 and 150 for how strongly a lamp glows. 100 % is stored as "no value of its own". */
export function glowField(host: EditorHost, value: number | null | undefined, onChange: (v: number | null) => void, o: { label?: I18nKey; hint?: I18nKey; lowest?: number } = {}): TemplateResult {
@@ -2,7 +2,7 @@
// fields or the furniture; only what depends on the compass follows (the sun's light, wind, the compass labels of roof faces).
import { html, svg, type TemplateResult } from "lit";
import { numberField } from "../fields.ts";
import { hint, numberField } from "../fields.ts";
import type { EditorHost } from "../host.ts";
import { turnedNorth } from "../ops/settings.ts";
@@ -29,7 +29,7 @@ export function renderCompass(host: EditorHost, north: number, set: (north: numb
<button class="nf-btn" ?disabled=${!host.admin} @click=${turn(-90)}>↺ 90°</button>
<button class="nf-btn" ?disabled=${!host.admin} @click=${turn(90)}>↻ 90°</button>
</div>
<span class="nf-sub">${t("compass_hint")}</span>
${hint(t("compass_hint"))}
</div>
</div>`;
}
@@ -148,7 +148,7 @@ export function renderRoomClimate(host: EditorHost, room: Room, patch: (patch: P
};
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>
<div class="nf-form">${field("temperature", host.t("climate_temperature"))} ${field("humidity", host.t("climate_humidity"))} ${field("co2", host.t("climate_co2"))} ${field("illuminance", host.t("climate_illuminance"))}</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"))}
@@ -9,6 +9,8 @@ import { packItemLabel, packLabel } from "../../../furniture-names.ts";
import { isClimateFurniture, isElectric, isPackType, packType, type FurniturePack } from "../../../packs.ts";
import { checkField, deviceIcon, entityField, glowField, iconField, markerField, pinShiftField, numberField, selectField, textField } from "../fields.ts";
import { entityOptions } from "../entities.ts";
import { isPositionVariable } from "../../../entities/position-value.ts";
import { renderDeviceValues } from "../device-values.ts";
import type { EditorHost } from "../host.ts";
import { lightEffectFields } from "../light-effect-fields.ts";
import { pluginDeviceSettings, pluginText, settingsWithDefaults } from "../../../plugins/registry.ts";
@@ -98,6 +100,11 @@ export function renderDeviceForm(host: EditorHost, placed: Placement, actions: D
</p>
<div class="nf-form">
${kind === "cover" ? entityField(host, t("cover_tilt_entity"), placed.cover_tilt ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("cover.")), (v) => set({ cover_tilt: v && v !== "none" ? v : null })) : nothing}
${kind === "cover" ? html`
${checkField(host, t("cover_direction_invert"), !!placed.cover_inverted, (on) => set({ cover_inverted: on || undefined }))}
${checkField(host, t("cover_tilt_direction_invert"), !!placed.cover_tilt_inverted, (on) => set({ cover_tilt_inverted: on || undefined }))}
${entityField(host, t("cover_position_entity"), placed.position ?? null, undefined, entityOptions(host.hass, (id) => isPositionVariable(host.hass, id)), (v) => set({ position: v && v !== "none" ? v : null }))}
${placed.position ? checkField(host, t("cover_position_invert"), !!placed.position_inverted, (on) => set({ position_inverted: on || undefined })) : nothing}` : nothing}
${light ? html`${selectField(host, t("lamp_mount"), mount, lampMounts, mountChange, { wide: true })}${glowField(host, placed.glow_scale, (v) => set({ glow_scale: v }))}` : nothing}
${light ? lightEffectFields(host, placed, host.hass?.states[placed.entity_id]?.attributes.effect_list, set) : nothing}
${placed.entity_id.startsWith("media_player.") ? glowField(host, placed.sound_rings, (v) => set({ sound_rings: v }), { label: "sound_rings", hint: "sound_rings_hint", lowest: 0 }) : nothing}
@@ -113,6 +120,7 @@ export function renderDeviceForm(host: EditorHost, placed: Placement, actions: D
${placed.name ? checkField(host, t("show_name"), !!placed.show_name, (on) => set({ show_name: on || undefined })) : nothing}
${iconField(host, placed.icon, (v) => set({ icon: v }))}
${pluginFields(host, placed, set)}
${renderDeviceValues(host, placed.values, (values) => set({ values }))}
</div>
${host.admin
? html`<div class="nf-actions">
@@ -11,6 +11,7 @@ import { checkField, entityField, glowField, hint, iconField, markerField, pinSh
import type { EditorHost } from "../host.ts";
import { lightEffectFields } from "../light-effect-fields.ts";
import { lightEffectSource } from "../../../light-effects.ts";
import { renderDeviceValues } from "../device-values.ts";
import { calibrationFrom, calibrationFromRooms, gridPlaces, gridRooms, mapCamera, nudgeCalibration, type CalibrationNudge, type Place } from "../../../live/vacuum-map.ts";
/** What the forms of a piece of furniture make the editor do. */
@@ -313,5 +314,6 @@ export function furnitureLinks(host: EditorHost, item: Furniture, actions: Furni
? html`${linkBlock(entityField(host, t("furn_door_left"), item.door_left ?? null, undefined, doors, (v) => actions.update({ door_left: v })), entityField(host, t("furn_door_right"), item.door_right ?? null, undefined, doors, (v) => actions.update({ door_right: v })))}
${hint(t("fridge_hint"))}`
: nothing}
${renderDeviceValues(host, item.values, (values) => actions.update({ values }))}
${hint(t(hintKey))}`;
}
@@ -6,6 +6,7 @@ import { entityName, openingEntities, windowPosition } from "../../../devices.ts
import type { I18nKey } from "../../../i18n.ts";
import { DOOR_STYLES, OPENING_PRESETS, openingPreset, openingStyle, WINDOW_OPENINGS, WINDOW_STYLES, type Opening, type OpeningPreset, type OpeningStyle } from "../../../model.ts";
import { entityOptions, isNumeric } from "../entities.ts";
import { isPositionVariable } from "../../../entities/position-value.ts";
import { checkField, entityField, hint, numberField, selectField } from "../fields.ts";
import type { EditorHost } from "../host.ts";
@@ -41,7 +42,7 @@ function choices(host: EditorHost) {
return {
covers: entityOptions(hass, (id) => id.startsWith("cover.")),
// numbers that can report where a blind is
positions: entityOptions(hass, (id) => /^(sensor|number|input_number)\./.test(id) && Number.isFinite(Number(stateOf(id)?.state))),
positions: entityOptions(hass, (id) => isPositionVariable(hass, id)),
// plain contacts, and handle sensors with three states (open, tilted, closed)
contacts: entityOptions(hass, (id) => isContact(id) || (isNumeric(id) && windowPosition(stateOf(id)) !== null)),
plainContacts: entityOptions(hass, isContact),
@@ -171,7 +172,9 @@ function blindFields(host: EditorHost, o: Opening, actions: OpeningActions, list
return html`${entityField(host, t(symcon ? "symcon_cover_position" : window ? "cover_entity" : "door_cover"), o.cover, automatic, lists.covers, (v) => actions.update({ cover: v }))}
${symcon || (hasBlind && o.blind === "venetian") ? entityField(host, t("cover_tilt_entity"), o.cover_tilt ?? null, undefined, lists.covers, (v) => actions.update({ cover_tilt: noneAsNull(v) })) : nothing}
${hasBlind
? html`${entityField(host, t("cover_position_entity"), o.position ?? null, undefined, lists.positions, (v) => actions.update({ position: noneAsNull(v) }))}
? html`${checkField(host, t("cover_direction_invert"), !!o.cover_inverted, (on) => actions.update({ cover_inverted: on || undefined }))}
${o.cover_tilt || o.blind === "venetian" ? checkField(host, t("cover_tilt_direction_invert"), !!o.cover_tilt_inverted, (on) => actions.update({ cover_tilt_inverted: on || undefined })) : nothing}
${entityField(host, t("cover_position_entity"), o.position ?? null, undefined, lists.positions, (v) => actions.update({ position: noneAsNull(v) }))}
${o.position ? checkField(host, t("cover_position_invert"), !!o.position_inverted, (on) => actions.update({ position_inverted: on })) : nothing}
${checkField(host, t("device_confirm"), !!o.confirm, (on) => actions.update({ confirm: on }), { title: t("cover_confirm_hint") })}
${window
@@ -180,6 +183,7 @@ function blindFields(host: EditorHost, o: Opening, actions: OpeningActions, list
: nothing}
${!window && o.type !== "garage" ? entityField(host, t("cover2_entity"), o.cover2 ?? null, undefined, lists.covers, (v) => actions.update({ cover2: noneAsNull(v) })) : nothing}
${o.cover2 && o.cover2 !== "none" ? entityField(host, t("cover2_tilt_entity"), o.cover2_tilt ?? null, undefined, lists.covers, (v) => actions.update({ cover2_tilt: noneAsNull(v) })) : nothing}
${o.cover2 && o.cover2 !== "none" ? html`${checkField(host, t("cover2_direction_invert"), !!o.cover2_inverted, (on) => actions.update({ cover2_inverted: on || undefined }))}${checkField(host, t("cover2_tilt_direction_invert"), !!o.cover2_tilt_inverted, (on) => actions.update({ cover2_tilt_inverted: on || undefined }))}` : nothing}
${numberField(host, t("cover_my"), o.my_position ?? 0, (v) => actions.update({ my_position: v > 0 ? Math.min(100, Math.round(v)) : null }), 5, 0)}
${hint(t("blind_hint"), "nf-wide")}`
: nothing}`;
+1 -1
View File
@@ -113,7 +113,7 @@ function ceilingField(host: EditorHost, room: Room, floor: Floor, actions: RoomA
${room.ceiling != null ? html`<button class="nf-btn nf-field-btn" ?disabled=${!host.admin} @click=${() => actions.patch({ ceiling: null })}>${t("height_auto")}</button>` : nothing}
${hint(t("room_ceiling_tip"), "nf-wide")}
${room.ceiling != null && room.ceiling > floor.height + 0.005
? html`<p class="nf-sub nf-wide">${t("room_ceiling_through", { ceiling: formatNumber(host.hass, room.ceiling, 2), floor: formatNumber(host.hass, floor.height, 2) })}</p>`
? hint(t("room_ceiling_through", { ceiling: formatNumber(host.hass, room.ceiling, 2), floor: formatNumber(host.hass, floor.height, 2) }), "nf-wide")
: nothing}`;
}
@@ -2,6 +2,7 @@ import { html, nothing, type TemplateResult } from "lit";
import { LIGHT_ANIMATIONS, type LightEffectConfig } from "../../light-effects.ts";
import { pluginLightAnimationNames } from "../../plugins/registry.ts";
import type { EditorHost } from "./host.ts";
import { hint } from "./fields.ts";
/** A small local-only mapping editor. Unknown stored identifiers remain untouched until edited. */
export function lightEffectFields(host: EditorHost, config: LightEffectConfig, effects: unknown, update: (patch: LightEffectConfig) => void): TemplateResult {
@@ -32,7 +33,7 @@ export function lightEffectFields(host: EditorHost, config: LightEffectConfig, e
};
return html`<details class="nf-wide">
<summary>${host.t("light_effects")}</summary>
<p class="nf-sub">${host.t("light_effects_hint")}</p>
${hint(host.t("light_effects_hint"))}
<label class="nf-check"><input type="checkbox" .checked=${config.animations_enabled !== false} ?disabled=${!host.admin}
@change=${(e: Event) => update({ animations_enabled: (e.target as HTMLInputElement).checked })} />${host.t("light_effects_enabled")}</label>
${names.map((name) => html`<label class="nf-field nf-wide">${name}
@@ -46,6 +47,7 @@ export function lightEffectFields(host: EditorHost, config: LightEffectConfig, e
<label class="nf-field nf-wide">${host.t("light_effect_add")}<input type="text" ?disabled=${!host.admin} placeholder="Regenbogen"
@input=${(e: Event) => (e.target as HTMLInputElement).setCustomValidity("")}
@change=${(e: Event) => { const input = e.target as HTMLInputElement; if (set(input.value, "none", input, true)) input.value = ""; }} /></label>
<p class="nf-sub" data-effect-feedback role="status" aria-live="polite">${host.t("light_effect_name_limit")} ${host.t("light_effect_count_limit")}</p>
${hint(`${host.t("light_effect_name_limit")} ${host.t("light_effect_count_limit")}`)}
<p class="nf-sub" data-effect-feedback role="status" aria-live="polite"></p>
</details>`;
}
+3
View File
@@ -2,6 +2,9 @@ import { css } from "lit";
/** The editor's own styles: the plan canvas, the side panel with its forms and libraries, the 3D pane and the phone layout. */
export const editorStyles = css`
.nf-value-links h4 { margin: 12px 0; }
.nf-value-add { min-width: 30px; font-size: 18px; padding: 3px 8px; }
.nf-value-link { padding: 8px 0; border-bottom: 1px solid var(--nf-line); }
:host {
display: block;
height: 100%;
+2 -1
View File
@@ -9,6 +9,7 @@ import { openingPreset } from "../../model.ts";
import type { EditorHost } from "./host.ts";
import { furnitureAt, openingAt, wallElevation, wallFrame, type ElevationBox } from "./ops/wall-view.ts";
import { formatLength } from "../../units.ts";
import { hint } from "./fields.ts";
const SNAP = 0.01;
const snap = (v: number) => Math.round(v / SNAP) * SNAP;
@@ -172,7 +173,7 @@ export class NfWallView extends LitElement {
<input type="number" step="0.01" min="0" .value=${sel.y0.toFixed(2)} ?disabled=${!this.host.admin} @change=${(e: Event) => this.place(sel, sel.x0, Number((e.target as HTMLInputElement).value))}
/></label>`
: nothing}`
: html`<span class="muted">${t("wall_view_hint")}</span>`}
: hint(t("wall_view_hint"))}
</footer>
</div>
</div>`;
+34
View File
@@ -0,0 +1,34 @@
import { css, html, LitElement } from "lit";
import { tokens } from "../styles.ts";
/** Explanations stay reachable by keyboard without taking space in the form. */
export class NfHelpPopup extends LitElement {
static properties = { text: { attribute: false } };
declare text: string;
constructor() { super(); this.text = ""; }
private get dialog() { return this.renderRoot.querySelector<HTMLDialogElement>("dialog"); }
render() {
return html`<button class="info" type="button" aria-label="Information anzeigen" aria-haspopup="dialog" title="Information" @click=${() => this.dialog?.showModal()}>ⓘ</button>
<dialog aria-label="Information" @keydown=${(event: KeyboardEvent) => event.stopPropagation()} @click=${(event: MouseEvent) => {
if (event.target !== event.currentTarget) return;
const r = this.dialog!.getBoundingClientRect();
if (event.clientX < r.left || event.clientX > r.right || event.clientY < r.top || event.clientY > r.bottom) this.dialog?.close();
}}>
<header><b>Information</b><button class="close" type="button" aria-label="Schließen" @click=${() => this.dialog?.close()}>×</button></header>
<p>${this.text}</p>
</dialog>`;
}
static styles = [tokens, css`
:host { display:inline-block; margin:4px 0; vertical-align:middle; }
button { font:inherit; cursor:pointer; color:var(--nf-muted); background:transparent; border:1px solid var(--nf-line); border-radius:50%; pointer-events:auto; }
.info { width:26px; height:26px; padding:0; font-size:18px; line-height:24px; }
button:hover { color:var(--nf-accent); }
button:focus-visible { outline:2px solid var(--nf-accent); outline-offset:2px; }
dialog { box-sizing:border-box; width:min(560px,calc(100vw - 32px)); max-height:80vh; max-height:80dvh; overflow:auto; padding:18px 22px; border:1px solid var(--nf-line); border-radius:14px; background:var(--nf-chrome-solid); color:var(--nf-text); font:14px/1.5 system-ui,sans-serif; box-shadow:var(--nf-shadow); pointer-events:auto; }
dialog::backdrop { background:#050b16a6; }
header { display:flex; align-items:center; justify-content:space-between; gap:20px; font-size:16px; }
.close { width:30px; height:30px; padding:0; font-size:23px; }
p { white-space:pre-wrap; overflow-wrap:anywhere; margin:16px 0 4px; }
`];
}
if (!customElements.get("nf-help-popup")) customElements.define("nf-help-popup", NfHelpPopup);
+4 -3
View File
@@ -9,6 +9,7 @@ import type { FurniturePack } from "../packs.ts";
import { controls, tokens } from "../styles.ts";
import type { HomeAssistant } from "../types.ts";
import type { ModelInfo } from "../viewer/viewer3d.ts";
import { hint } from "./editor/fields.ts";
type Present = "unknown" | "yes" | "no";
@@ -214,7 +215,7 @@ export class NfModelUpload extends LitElement {
<button class="nf-btn" @click=${() => this.turn(-1)}>↺ 90°</button>
<button class="nf-btn" @click=${() => this.turn(1)}>↻ 90°</button>
</div>
<small class="nf-sub">${this.t("model_front_hint")}</small>
${hint(this.t("model_front_hint"))}
</div>
<div class="nf-field">
<span>${this.t("model_paint")}</span>
@@ -242,12 +243,12 @@ export class NfModelUpload extends LitElement {
if (slots.length === 0 || !(this.hass?.user?.is_admin ?? false)) return nothing;
return html`<section class="nf-ext-card">
<h3>${this.t("models")}</h3>
<p class="nf-sub">${this.t("models_hint")}</p>
${hint(this.t("models_hint"))}
${slots.map((slot) => this.row(slot))}
${this._draft ? this.editor(this._draft) : nothing}
${this._busy && !this._draft ? html`<p class="nf-sub">${this.t("loading")}</p>` : nothing}
${this._message ? html`<p class="nf-sub ${this._message.ok ? "nf-notice" : "nf-pack-error"}">${this._message.text}</p>` : nothing}
<p class="nf-sub">${this.t("models_licence")}</p>
${hint(this.t("models_licence"))}
</section>`;
}
+2 -2
View File
@@ -162,7 +162,7 @@ export class NfQuickMenu extends LitElement {
@click=${() => (moving ? this.call("cover", "stop_cover") : this.ask() && this.call("cover", closed > 50 ? "open_cover" : "close_cover"))}
>
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 4h16M5 4v15M19 4v15M7 8h10M7 12h10M7 16h10" /></svg>
<b>${pos !== null ? `${pos} %` : stateText(this.hass, st)}</b>
<b>${pos !== null ? `${Math.round(pos)} %` : stateText(this.hass, st)}</b>
</button>
</div>
${setPos
@@ -193,7 +193,7 @@ export class NfQuickMenu extends LitElement {
max="100"
.value=${String(tilt)}
aria-label=${this.t("cover_tilt")}
@change=${(e: Event) => this.call("cover", "set_cover_tilt_position", { entity_id: this.tiltEntity || this.entity, tilt_position: Number((e.target as HTMLInputElement).value) })}
@change=${(e: Event) => this.call("cover", "set_cover_tilt_position", { entity_id: st.attributes.nf_cover_control ? this.entity : this.tiltEntity || this.entity, tilt_position: Number((e.target as HTMLInputElement).value) })}
/></label>`;
if (features & (COVER_OPEN_TILT | COVER_CLOSE_TILT))
return html`<div class="qm-tilt-buttons">
+13 -1
View File
@@ -22,6 +22,8 @@ import { curvePath } from "../live/day-curves.ts";
import { controls, tokens } from "../styles.ts";
import type { HassEntity, HomeAssistant } from "../types.ts";
import { coverTiltEntity, coverWithTilt } from "../entities/covers.ts";
import { deviceValueReadouts } from "../entities/device-values.ts";
import { pointInPolygon } from "../model.ts";
const COVER_SET_POSITION = 4;
const COVER_STOP = 8;
@@ -533,6 +535,7 @@ export class NfRoomPanel extends LitElement {
${media.length ? this.section("panel_media", media.map((st) => this.mediaRow(st))) : nothing}
${switches.length ? this.section("panel_switches", switches.map((st) => this.switchRow(st))) : nothing}
${sensors.length ? this.section("panel_sensors", sensors.map((st) => this.sensorRow(st))) : nothing}
${this.extraValues(room)}
${canAnnounce(this.hass) && roomHasSpeaker(this.hass, this.floor, room) ? this.announceSection(room) : nothing}
${this.pluginSections(room, ids)}
${hiddenCount
@@ -545,6 +548,13 @@ export class NfRoomPanel extends LitElement {
}
/** Header facts: the room's temperature and humidity from its climate sensors (chosen or automatic). */
private extraValues(room: Room) {
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;
}
private facts(climates: HassEntity[]): string[] {
const out: string[] = [];
const room = this.room;
@@ -564,6 +574,8 @@ export class NfRoomPanel extends LitElement {
else if (climateTemp && room.climate?.temperature !== "none") out.push(`${formatNumber(this.hass, climateTemp.attributes.current_temperature as number, 1)} ${tempUnit(this.hass)}`);
const hum = value("humidity", "%");
if (hum) out.push(hum);
const lux = roomClimateValue(this.hass, this.floor ?? null, room, "illuminance");
if (lux !== null) out.push(`☀ ${formatNumber(this.hass, lux, 0)} lx`);
// what the room's devices draw now
const power = this.floor && this.building ? roomPower(this.hass, this.building, this.floor, room) : null;
if (power !== null) out.push(`⚡ ${powerText(this.hass, power)}`);
@@ -755,7 +767,7 @@ export class NfRoomPanel extends LitElement {
max="100"
?disabled=${na}
.value=${String(a.current_tilt_position)}
@change=${(e: Event) => this.call("cover", "set_cover_tilt_position", { entity_id: tiltEntity ?? id, tilt_position: Number((e.target as HTMLInputElement).value) })}
@change=${(e: Event) => this.call("cover", "set_cover_tilt_position", { entity_id: a.nf_cover_control ? id : tiltEntity ?? id, tilt_position: Number((e.target as HTMLInputElement).value) })}
/></label>`
: features & 48
? html`<div class="nf-rp-buttons">
+8 -5
View File
@@ -50,6 +50,7 @@ import { scaleGlow, buildMarkers, openMoreInfo, stateText, toggleEntity, withPlu
import { fanSpin } from "../entities/fans.ts";
import { fixtureGlow } from "../entities/kinds.ts";
import { coverTiltEntity } from "../entities/covers.ts";
import { deviceValuesText } from "../entities/device-values.ts";
import { furnitureShown, hiddenFurniture, withoutHidden } from "../entities/visibility.ts";
import { pictureUrl } from "../entities/pictures.ts";
import { fetchImage } from "../api.ts";
@@ -1236,7 +1237,7 @@ export class NfView3d extends LitElement {
const deviceTemp = !isCooling(f.type) ? deviceTempOf(hass, f.temp_entity) : null;
const deviceTempText = deviceTemp === null ? "" : `🌡 ${formatNumber(hass, fromCelsius(hass, deviceTemp), 1)} ${tempUnit(hass)}`;
const extraRef = f.type === "home_battery" ? f.soc : f.type === "wallbox" ? f.status : temps ? (f.temp_entity && f.temp_entity !== "none" ? f.temp_entity : f.temp_entity2) : deviceTemp !== null ? f.temp_entity : null;
const extra = extraRef && extraRef !== "none" ? extraRef : null;
const extra = extraRef && extraRef !== "none" ? extraRef : (f.values ?? []).find((v) => v.entity && v.entity !== "none")?.entity ?? null;
const link = linked ?? (extra ? { entity: null, power: null } : undefined);
if (!link) continue;
// a battery goes by its charge first: its power sensor is often placed on its own as well
@@ -1330,6 +1331,7 @@ export class NfView3d extends LitElement {
? formatPower(hass, Math.max(0, power))
: "",
deviceTempText,
deviceValuesText(hass, f.values),
]
.filter(Boolean)
.join(" · "),
@@ -1341,7 +1343,7 @@ export class NfView3d extends LitElement {
// inverter, battery, wallbox: their own text (watts, charge, status) is always worth a pin
energyDevice: f.type === "inverter" || f.type === "home_battery" || f.type === "wallbox" || f.type === "meter",
// a fridge's temperatures are worth a pin, like an energy device's values
readout: !!temps || undefined,
readout: !!temps || !!f.values?.some((v) => v.entity && v.entity !== "none") || undefined,
show: f.marker ?? undefined,
fromFurniture: true,
});
@@ -1563,7 +1565,7 @@ export class NfView3d extends LitElement {
}
/** A lamp: its 3D model glows with the linked light and is tapped directly. */
private lampMarker(hass: HomeAssistant, floor: Building["floors"][number], f: Furniture, entity: string | null): DeviceMarker & { fromFurniture: boolean } {
private lampMarker(hass: HomeAssistant, floor: Building["floors"][number], f: Furniture, entity: string | null): DeviceMarker & { fromFurniture: boolean; readout?: boolean } {
const st = entity ? hass.states[entity] : undefined;
// further bulbs of the same fixture (a night light, an ambient ring): the lamp glows with them while its main light is off
const others = (f.extra_lights ?? []).map((id) => hass.states[id]).filter((s): s is HassEntity => !!s);
@@ -1607,7 +1609,7 @@ export class NfView3d extends LitElement {
bollard: base + f.h + 0.25,
garden: base + f.h + 0.25,
}[model];
const marker: DeviceMarker & { fromFurniture: boolean } = {
const marker: DeviceMarker & { fromFurniture: boolean; readout?: boolean } = {
// a lamp without a light keeps a key of its own (it is drawn, but not tappable)
id: entity ?? `lamp:${f.id}`,
floorId: floor.id,
@@ -1617,7 +1619,8 @@ export class NfView3d extends LitElement {
y,
icon: iconSvg("light"),
name: f.name || (entity ? entityName(hass, entity) : furnitureName(hass, f.type)),
text: st && (isActive(st) || !otherOn) ? stateText(hass, st) : otherOn ? entityName(hass, otherOn.entity_id) : "",
text: [st && (isActive(st) || !otherOn) ? stateText(hass, st) : otherOn ? entityName(hass, otherOn.entity_id) : "", deviceValuesText(hass, f.values)].filter(Boolean).join(" · "),
readout: !!f.values?.some((v) => v.entity && v.entity !== "none"),
active: (st ? isActive(st) : false) || !!otherOn,
unavailable: st ? isUnavailable(st) : false,
glow: st || others.length ? scaleGlow(fixtureGlow(st, others, f.color_entity && f.color_entity !== "none" ? hass.states[f.color_entity] : undefined), f.glow_scale) : null,
@@ -48,6 +48,14 @@ test("a standalone blind's separate slat position is watched", () => {
assert.ok(watchedEntities(inputs({ building: b })).includes("cover.slats"));
});
test("all custom device and furniture readings are watched", () => {
const b = building();
b.floors[0].placements[0].values = [{ id: "a", entity: "sensor.inside" }, { id: "b", entity: "sensor.outside" }];
b.floors[0].furniture[0].values = [{ id: "c", entity: "sensor.lux" }];
const ids = watchedEntities(inputs({ building: b, needsRoomSensors: false }));
for (const id of ["sensor.inside", "sensor.outside", "sensor.lux"]) assert.ok(ids.includes(id));
});
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" } });
+3 -3
View File
@@ -42,7 +42,7 @@ function furnitureIds(inputs: WatchInputs): MaybeId[] {
...pieces.flatMap((m) => [m.state_entity, m.state_entity2, m.color_entity, ...(m.gang_entities ?? []), ...(m.extra_lights ?? []), m.cover_entity, m.care_entity, m.room_sensor, m.show_when?.entity, m.picture && /^[a-z_]+\.[a-z0-9_]+$/.test(m.picture) ? m.picture : null]),
// a washer's, dryer's or dishwasher's time left comes from a sensor next to its switch
...pieces.filter((m) => m.type === "washer" || m.type === "dryer" || m.type === "dishwasher").flatMap((m) => deviceSiblings(hass, furnitureLinks.get(m.id)?.entity ?? furnitureLinks.get(m.id)?.power).filter((id) => id.startsWith("sensor."))),
...pieces.flatMap((m) => [m.door_left, m.door_right, m.soc, m.status, m.charge, m.export, m.temp_entity, m.temp_entity2]),
...pieces.flatMap((m) => [m.door_left, m.door_right, m.soc, m.status, m.charge, m.export, m.temp_entity, m.temp_entity2, ...(m.values ?? []).map((v) => v.entity)]),
...pieces.filter((m) => m.type === "robot_vacuum").map((m) => robotRoomSensor(hass, furnitureLinks.get(m.id)?.entity ?? null, m.room_sensor)),
...pieces.flatMap((m) => (m.pictures ?? []).flatMap((rule) => [rule.entity, ...(rule.image.startsWith("camera:") ? [rule.image.slice("camera:".length)] : [])])),
];
@@ -60,11 +60,11 @@ export function watchedEntities(inputs: WatchInputs): string[] {
const energy = b.energy;
const lightsOfRooms = roomsOf(b).flatMap((r) => roomEntities(hass, r).filter((id) => kindOf(id) === "light"));
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))]
? [...roomEntities(hass, r).filter((id) => id.startsWith("sensor.") || id.startsWith("climate.")), ...Object.values(r.climate ?? {}).flat(), ...(["temperature", "humidity", "co2", "illuminance"] as const).flatMap((key) => roomClimateSensors(hass, f, r, key))]
: []));
const ids: MaybeId[] = [
...placed,
...b.floors.flatMap((f) => f.placements.map((p) => p.cover_tilt)),
...b.floors.flatMap((f) => f.placements.flatMap((p) => [p.cover_tilt, p.position, ...(p.values ?? []).map((v) => v.entity)])),
...openingIds(inputs.openingLinks),
...placed.map((id) => powerSensorFor(hass, id)),
// what plugins draw for a device may follow further entities (a camera's motion sensor)
@@ -0,0 +1,58 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { box, entity, floorWith, hassOf, opening } from "./fixtures.ts";
import { openingEntities, openingState } from "./openings.ts";
import { isPositionVariable, positionPercent } from "./position-value.ts";
import { withCoverControls } from "./cover-controls.ts";
test("Symcon position feedback accepts numeric actuator domains and respects native integer/float ranges", () => {
const h = hassOf([
entity("cover.feedback", "open", { symcon_id: 1, symcon_variable_type: 1, symcon_numeric_value: 128, symcon_min: 0, symcon_max: 255 }),
entity("light.fraction", "on", { symcon_id: 2, symcon_variable_type: 2, symcon_numeric_value: 0.4, symcon_min: 0, symcon_max: 1 }),
entity("cover.one", "open", { symcon_id: 3, symcon_variable_type: 1, symcon_numeric_value: 1, symcon_min: 0, symcon_max: 100 }),
entity("sensor.text", "50", { symcon_id: 4, symcon_variable_type: 3 }),
]);
assert.equal(isPositionVariable(h, "cover.feedback"), true);
assert.equal(isPositionVariable(h, "light.fraction"), true);
assert.equal(isPositionVariable(h, "sensor.text"), false);
assert.equal(positionPercent(h, "cover.feedback"), 128 / 255 * 100);
assert.equal(positionPercent(h, "light.fraction"), 40);
assert.equal(positionPercent(h, "cover.one"), 1, "integer 1 is one percent, not a normalized float at full travel");
});
test("blind and slat inversions act independently on feedback, 3D, sliders, buttons and grouped commands", async () => {
for (const inverted of [false, true]) for (const tiltInverted of [false, true]) {
const calls: unknown[] = [];
const raw = hassOf([entity("cover.height", "open", { current_position: 5 }), entity("cover.slats", "open", { current_position: 30, symcon_id: 9 }), entity("cover.feedback", "open", { symcon_numeric_value: 40, symcon_min: 0, symcon_max: 100 }), entity("cover.normal", "open", { current_position: 90 })], {}, { callService: async (domain: string, service: string, data: unknown) => { calls.push([domain, service, data]); } });
const floor = floorWith([box("r", 0, 0, 4, 4)], { openings: [opening("w", "r", "window", { cover: "cover.height", cover_tilt: "cover.slats", position: "cover.feedback", cover_inverted: inverted, cover_tilt_inverted: tiltInverted })] });
const view = withCoverControls(raw, [floor]);
assert.equal(view.states["cover.height"].attributes.current_position, inverted ? 60 : 40);
assert.equal(view.states["cover.height"].attributes.current_tilt_position, tiltInverted ? 70 : 30);
const links = openingEntities(raw, [floor]).get("w")!;
const fromRaw = openingState(raw, links), fromView = openingState(view, links);
assert.equal(fromRaw.cover, fromView.cover, "3D feedback cannot be inverted twice");
assert.equal(fromRaw.slats, fromView.slats);
await view.callService("cover", "set_cover_position", { entity_id: "cover.height", position: 75 });
await view.callService("cover", "set_cover_tilt_position", { entity_id: "cover.height", tilt_position: 20 });
await view.callService("cover", "open_cover", { entity_id: ["cover.height", "cover.normal"] });
assert.deepEqual(calls, [
["cover", "set_cover_position", { entity_id: "cover.height", position: inverted ? 25 : 75 }],
["cover", "set_cover_tilt_position", { entity_id: "cover.slats", tilt_position: tiltInverted ? 80 : 20 }],
["cover", inverted ? "close_cover" : "open_cover", { entity_id: "cover.height" }],
["cover", "open_cover", { entity_id: "cover.normal" }],
]);
assert.equal(raw.states["cover.height"].attributes.current_position, 5, "the native state remains unchanged");
}
});
test("standalone covers, feedback-only inversion, facade reuse and changed settings remain consistent", async () => {
const raw = hassOf([entity("cover.height", "closed", { current_position: 0, current_tilt_position: 20 }), entity("sensor.feedback", "25", { unit_of_measurement: "%" })]);
const floor = floorWith([], { placements: [{ entity_id: "cover.height", x: 1, z: 1, y: null, position: "sensor.feedback", position_inverted: true, cover_tilt_inverted: true }] });
const floors = [floor];
const first = withCoverControls(raw, floors);
assert.equal(first.states["cover.height"].attributes.current_position, 75);
assert.equal(first.states["cover.height"].attributes.current_tilt_position, 80);
assert.equal(withCoverControls(first, floors), first, "nested views cannot invert an already adapted facade again");
const next = withCoverControls(first, [{ ...floor, placements: [{ ...floor.placements[0], cover_inverted: true }] }]);
assert.equal(next.states["cover.height"].attributes.current_position, 25);
});
+84
View File
@@ -0,0 +1,84 @@
// Present a plan's cover wiring as one consistent logical direction to every view and command.
import type { Floor } from "../model.ts";
import type { HassEntity, HomeAssistant } from "../types.ts";
import { openingEntities } from "./openings.ts";
import { positionPercent } from "./position-value.ts";
interface Binding {
inverted?: boolean;
tiltInverted?: boolean;
tilt?: string | null;
position?: string | null;
positionInverted?: boolean;
}
const cache = new WeakMap<HomeAssistant, WeakMap<readonly Floor[], HomeAssistant>>();
const sources = new WeakMap<HomeAssistant, HomeAssistant>();
const swapped: Record<string, string> = { open_cover: "close_cover", close_cover: "open_cover", open_cover_tilt: "close_cover_tilt", close_cover_tilt: "open_cover_tilt" };
export function withCoverControls(hass: HomeAssistant, floors: readonly Floor[]): HomeAssistant {
const raw = sources.get(hass) ?? hass;
const memo = cache.get(raw) ?? new WeakMap<readonly Floor[], HomeAssistant>();
cache.set(raw, memo);
const existing = memo.get(floors);
if (existing) return existing;
const bindings = new Map<string, Binding>();
for (const f of floors) for (const p of f.placements) if (p.entity_id.startsWith("cover.")) {
bindings.set(p.entity_id, { inverted: p.cover_inverted, tiltInverted: p.cover_tilt_inverted, tilt: p.cover_tilt === "none" ? null : p.cover_tilt, position: p.position, positionInverted: p.position_inverted });
}
for (const e of openingEntities(raw, floors).values()) {
if (e.cover && !bindings.has(e.cover)) bindings.set(e.cover, { inverted: e.coverInverted, tiltInverted: e.coverTiltInverted, tilt: e.coverTilt, position: e.position, positionInverted: e.positionInverted });
if (e.cover2 && !bindings.has(e.cover2)) bindings.set(e.cover2, { inverted: e.cover2Inverted, tiltInverted: e.cover2TiltInverted, tilt: e.cover2Tilt });
}
const states = { ...raw.states };
for (const [id, b] of bindings) {
const st = raw.states[id];
if (!st) continue;
const a: Record<string, unknown> = { ...st.attributes, nf_cover_control: true };
let position = positionPercent(raw, b.position);
if (position !== null && b.positionInverted) position = 100 - position;
if (position === null) position = typeof st.attributes.current_position === "number" ? st.attributes.current_position : null;
if (position !== null) a.current_position = b.inverted ? 100 - position : position;
const tiltState = b.tilt ? raw.states[b.tilt] : st;
let tilt = typeof tiltState?.attributes.current_tilt_position === "number" ? tiltState.attributes.current_tilt_position : b.tilt ? positionPercent(raw, b.tilt) : null;
if (tilt !== null) {
if (b.tiltInverted) tilt = 100 - tilt;
a.current_tilt_position = tilt;
a.supported_features = Number(a.supported_features ?? 0) | 128;
}
let state = st.state;
if (b.inverted) state = ({ open: "closed", closed: "open", opening: "closing", closing: "opening" } as Record<string, string>)[state] ?? state;
if (typeof a.current_position === "number" && state !== "unavailable" && state !== "unknown" && state !== "opening" && state !== "closing") state = a.current_position > 0 ? "open" : "closed";
states[id] = { ...st, state, attributes: a } satisfies HassEntity;
}
const result: HomeAssistant = { ...raw, states, callService: async (domain, service, data = {}) => {
if (domain !== "cover") return raw.callService(domain, service, data);
const ids = Array.isArray(data.entity_id) ? data.entity_id : [data.entity_id];
const send = async (id: unknown) => {
const b = typeof id === "string" ? bindings.get(id) : undefined;
if (!b) return raw.callService(domain, service, { ...data, entity_id: id });
const payload: Record<string, unknown> = { ...data, entity_id: id };
let command = service;
if (command === "toggle" || command === "toggle_cover") command = states[String(id)]?.state === "closed" ? "open_cover" : "close_cover";
const tilt = command.includes("tilt");
if (tilt && b.tilt) payload.entity_id = b.tilt;
if (tilt ? b.tiltInverted : b.inverted) {
command = swapped[command] ?? command;
const key = tilt ? "tilt_position" : "position";
if (typeof payload[key] === "number") payload[key] = 100 - payload[key];
}
// A separate HA position-only cover controls its slats through its position service.
const target = b.tilt ? raw.states[b.tilt] : undefined;
if (tilt && b.tilt && !target?.attributes.symcon_id && typeof target?.attributes.current_tilt_position !== "number") {
if (command === "set_cover_tilt_position") { command = "set_cover_position"; payload.position = payload.tilt_position; delete payload.tilt_position; }
else if (command === "open_cover_tilt") command = "open_cover";
else if (command === "close_cover_tilt") command = "close_cover";
}
return raw.callService(domain, command, payload);
};
return Array.isArray(data.entity_id) ? Promise.all(ids.map(send)) : send(ids[0]);
} };
sources.set(result, raw);
memo.set(floors, result);
return result;
}
+1
View File
@@ -17,6 +17,7 @@ export function coverTiltEntity(hass: HomeAssistant, floors: readonly Floor[], i
}
export function coverWithTilt(hass: HomeAssistant, st: HassEntity, tilt: string | null | undefined): HassEntity {
if (st.attributes.nf_cover_control) return st;
if (!tilt) return st;
const a = hass.states[tilt]?.attributes;
const position = a?.current_tilt_position ?? a?.current_position;
@@ -0,0 +1,27 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { entity, hassOf } from "./fixtures.ts";
import { deviceValueReadouts, deviceValuesText } from "./device-values.ts";
test("several temperatures and other device values keep independent symbols, labels and native readings", () => {
const h = hassOf([
entity("cover.temp", "open", { symcon_numeric_value: 22.7, unit_of_measurement: "°C", device_class: "temperature" }),
entity("sensor.out", "48.5", { unit_of_measurement: "°C", friendly_name: "Ausgang", device_class: "temperature" }),
entity("sensor.humidity", "55", { unit_of_measurement: "%", device_class: "humidity" }),
entity("sensor.status", "normal", {}),
]);
const links = [{ id: "a", entity: "cover.temp", icon: "❄", label: "Innen" }, { id: "b", entity: "sensor.out", icon: "🔥" }, { id: "c", entity: "sensor.humidity" }, { id: "d", entity: "sensor.status", icon: "✓" }];
const rows = deviceValueReadouts(h, links);
assert.deepEqual(rows.map((v) => v.icon), ["❄", "🔥", "💧", "✓"]);
assert.equal(rows[0].text, "22.7 °C", "an inferred actuator domain cannot replace the numeric reading with an on/off state");
assert.equal(rows[1].label, "Ausgang");
assert.equal(rows[3].text, "normal");
assert.match(deviceValuesText(h, links), /❄ Innen: 22.7 °C.*🔥 48.5 °C.*💧 55 %/);
assert.equal(deviceValueReadouts(h, [links[1]])[0].id, "b", "removing one link keeps the others intact");
});
test("unassigned values stay hidden and linked unavailable readings retain a dash", () => {
const h = hassOf([entity("sensor.offline", "unavailable"), entity("sensor.native", "on", { symcon_formatted: "Ein" })]);
const rows = deviceValueReadouts(h, [{ id: "empty", entity: null }, { id: "none", entity: "none" }, { id: "offline", entity: "sensor.offline" }, { id: "native", entity: "sensor.native" }]);
assert.deepEqual(rows.map((v) => v.text), ["–", "Ein"]);
});
+31
View File
@@ -0,0 +1,31 @@
import type { DeviceValueLink } from "../model.ts";
import type { HassEntity, HomeAssistant } from "../types.ts";
import { formatNumber } from "../i18n.ts";
import { entityName, isUnavailable } from "./kinds.ts";
export function valueSymbol(st: HassEntity | undefined): string {
const a = st?.attributes;
return ({ temperature: "🌡", humidity: "💧", carbon_dioxide: "☁", illuminance: "☀", power: "⚡", energy: "⚡" } as Record<string, string>)[String(a?.device_class)] ?? (a?.unit_of_measurement === "°C" ? "🌡" : "◉");
}
export function deviceValueReadouts(hass: HomeAssistant, links: readonly DeviceValueLink[] = []): { id: string; entity: string; icon: string; label: string; text: string }[] {
return links.flatMap((link) => {
if (!link.entity || link.entity === "none") return [];
const st = hass.states[link.entity];
let text = "–";
if (st && !isUnavailable(st)) {
const a = st.attributes;
if (typeof a.symcon_formatted === "string" && a.symcon_formatted.trim()) text = a.symcon_formatted;
else {
const raw = a.symcon_numeric_value ?? st.state;
const n = typeof raw === "number" || (typeof raw === "string" && raw.trim()) ? Number(raw) : NaN;
text = Number.isFinite(n) ? `${formatNumber(hass, n, hass.entities?.[link.entity]?.display_precision ?? (a.symcon_variable_type === 1 ? 0 : 1))}${a.unit_of_measurement ? ` ${a.unit_of_measurement}` : ""}` : String(raw ?? "–");
}
}
return [{ id: link.id, entity: link.entity, icon: link.icon?.trim() || valueSymbol(st), label: link.label?.trim() || entityName(hass, link.entity), text }];
});
}
export function deviceValuesText(hass: HomeAssistant, links: readonly DeviceValueLink[] = []): string {
return deviceValueReadouts(hass, links).map((v) => `${v.icon} ${v.label && links.find((l) => l.id === v.id)?.label ? `${v.label}: ` : ""}${v.text}`).join(" · ");
}
+28 -16
View File
@@ -4,10 +4,13 @@ import type { Floor, Opening } from "../model.ts";
import type { HassEntity, HomeAssistant } from "../types.ts";
import { isUnavailable, kindOf } from "./kinds.ts";
import { roomEntities } from "./registry.ts";
import { positionPercent } from "./position-value.ts";
export interface OpeningEntities {
cover: string | null;
coverTilt?: string | null;
coverInverted?: boolean;
coverTiltInverted?: boolean;
contact: string | null;
tilt: string | null;
/** Contact and tilt sensor of the second leaf of a double door or window. */
@@ -30,6 +33,8 @@ export interface OpeningEntities {
/** A second blind of a wide window (its right half, seen from the room). */
cover2?: string | null;
cover2Tilt?: string | null;
cover2Inverted?: boolean;
cover2TiltInverted?: boolean;
}
const BLIND_CLASSES = new Set([undefined, "shutter", "blind", "awning", "shade", "curtain", "window"]);
@@ -95,6 +100,10 @@ export function openingEntities(hass: HomeAssistant, floors: readonly Floor[]):
cover2: o.type === "garage" ? null : unlessNone(o.cover2),
coverTilt: unlessNone(o.cover_tilt),
cover2Tilt: unlessNone(o.cover2_tilt),
coverInverted: !!o.cover_inverted,
coverTiltInverted: !!o.cover_tilt_inverted,
cover2Inverted: !!o.cover2_inverted,
cover2TiltInverted: !!o.cover2_tilt_inverted,
});
}
}
@@ -131,39 +140,42 @@ export const DOOR_DEFAULT_OPEN = 0.5;
/** How far a blind is open according to a position sensor: a percentage or a 0-1 fraction. Null when unknown. */
function reportedPosition(hass: HomeAssistant, id: string | null | undefined): number | null {
const st = id ? hass.states[id] : undefined;
const value = st && !isUnavailable(st) ? Number(st.state) : NaN;
if (!Number.isFinite(value)) return null;
const isPercent = st!.attributes.unit_of_measurement === "%" || value > 1;
return Math.min(1, Math.max(0, isPercent ? value / 100 : value));
const value = positionPercent(hass, id);
return value === null ? null : value / 100;
}
/** How closed the blind is (0 open, 1 closed) from the position sensor, else from the cover entity. Null without cover data. */
/** How far a cover entity is closed (0 up, 1 down), or null without one. */
function coverClosed(hass: HomeAssistant, id: string | null | undefined): number | null {
function coverClosed(hass: HomeAssistant, id: string | null | undefined, inverted = false): number | null {
const cover = id ? hass.states[id] : undefined;
if (!cover || isUnavailable(cover)) return id ? 0 : null;
const percent = cover.attributes.current_position;
if (typeof percent === "number") return 1 - Math.min(100, Math.max(0, percent)) / 100;
if (cover.state === "closed") return 1;
if (typeof percent === "number") { const closed = 1 - Math.min(100, Math.max(0, percent)) / 100; return inverted && !cover.attributes.nf_cover_control ? 1 - closed : closed; }
if (cover.state === "closed") return inverted && !cover.attributes.nf_cover_control ? 0 : 1;
if (cover.state === "open") return inverted && !cover.attributes.nf_cover_control ? 1 : 0;
return cover.state === "opening" || cover.state === "closing" ? 0.5 : 0;
}
/** How far the slats of a venetian blind are open (0 shut, 1 level), from its tilt position; null when it reports none. */
function slatsOpen(hass: HomeAssistant, id: string | null | undefined, separate?: string | null): number | null {
function slatsOpen(hass: HomeAssistant, id: string | null | undefined, separate?: string | null, inverted = false): number | null {
const main = hass.states[id || ""];
if (main?.attributes.nf_cover_control) return typeof main.attributes.current_tilt_position === "number" ? main.attributes.current_tilt_position / 100 : null;
const a = hass.states[separate || id || ""]?.attributes;
const tilt = a?.current_tilt_position ?? (separate ? a?.current_position : undefined);
return typeof tilt === "number" ? Math.min(100, Math.max(0, tilt)) / 100 : null;
const value = typeof tilt === "number" ? Math.min(100, Math.max(0, tilt)) : separate ? positionPercent(hass, separate) : null;
return value === null ? null : (inverted ? 100 - value : value) / 100;
}
function blindClosedFraction(hass: HomeAssistant, e: OpeningEntities): number | null {
if (hass.states[e.cover || ""]?.attributes.nf_cover_control) return coverClosed(hass, e.cover);
const reported = reportedPosition(hass, e.position);
if (reported !== null) return e.positionInverted ? reported : 1 - reported;
if (reported !== null) { const closed = e.positionInverted ? reported : 1 - reported; return e.coverInverted ? 1 - closed : closed; }
const cover = e.cover ? hass.states[e.cover] : undefined;
if (cover && !isUnavailable(cover)) {
const percent = cover.attributes.current_position;
if (typeof percent === "number") return 1 - Math.min(100, Math.max(0, percent)) / 100;
if (cover.state === "closed") return 1;
if (typeof percent === "number") return coverClosed(hass, e.cover, e.coverInverted);
if (cover.state === "closed") return e.coverInverted ? 0 : 1;
if (cover.state === "open") return e.coverInverted ? 1 : 0;
return cover.state === "opening" || cover.state === "closing" ? 0.5 : 0;
}
return e.cover ? 0 : null;
@@ -202,10 +214,10 @@ export function openingState(hass: HomeAssistant, e: OpeningEntities, type: Open
const isKnown = (id: string | null | undefined) => !!id && !!hass.states[id] && !isUnavailable(hass.states[id]);
const positionOf = (id: string | null | undefined) => (id ? windowPosition(hass.states[id]) : null);
const cover = blindClosedFraction(hass, e);
const slats = slatsOpen(hass, e.cover, e.coverTilt);
const slats2 = slatsOpen(hass, e.cover2, e.cover2Tilt);
const slats = slatsOpen(hass, e.cover, e.coverTilt, e.coverTiltInverted);
const slats2 = slatsOpen(hass, e.cover2, e.cover2Tilt, e.cover2TiltInverted);
const blindState = {
...(e.cover2 ? { cover2: coverClosed(hass, e.cover2) } : {}),
...(e.cover2 ? { cover2: coverClosed(hass, e.cover2, e.cover2Inverted) } : {}),
...(slats !== null ? { slats } : {}),
...(slats2 !== null ? { slats2 } : {}),
};
+28
View File
@@ -0,0 +1,28 @@
import type { HomeAssistant } from "../types.ts";
import { symconPercent } from "../symcon-controls.ts";
import { isUnavailable } from "./kinds.ts";
/** A feedback variable can be numeric even when its inferred entity domain is an actuator. */
export function isPositionVariable(hass: HomeAssistant | undefined, id: string): boolean {
const st = hass?.states[id];
if (!st) return false;
const a = st.attributes;
if (typeof a.symcon_id === "number") return a.symcon_variable_type === 1 || a.symcon_variable_type === 2;
return typeof a.current_position === "number" || (/^(sensor|number|input_number)\./.test(id) && !!st.state.trim() && Number.isFinite(Number(st.state)));
}
/** Percent open, using native Symcon ranges before considering plain 0–100 or 0–1 sensors. */
export function positionPercent(hass: HomeAssistant, id: string | null | undefined): number | null {
const st = id ? hass.states[id] : undefined;
if (!st || isUnavailable(st)) return null;
const a = st.attributes;
if (a.nf_cover_control && typeof a.current_position === "number") return a.current_position;
const native = symconPercent(st);
if (native !== null) return native;
if (typeof a.current_position === "number") return Math.max(0, Math.min(100, a.current_position));
if (!st.state.trim()) return null;
const value = Number(st.state);
if (!Number.isFinite(value)) return null;
const percent = a.unit_of_measurement === "%" || value > 1 || value < 0 ? value : value * 100;
return Math.max(0, Math.min(100, percent));
}
+3 -2
View File
@@ -206,7 +206,7 @@ export const primaryEntities = (hass: HomeAssistant, ids: readonly string[]): st
// ---------------------------------------------------------------- room climate
/** Device classes of the three room values. */
export const CLIMATE_CLASSES = { temperature: "temperature", humidity: "humidity", co2: "carbon_dioxide" } as const;
export const CLIMATE_CLASSES = { temperature: "temperature", humidity: "humidity", co2: "carbon_dioxide", illuminance: "illuminance" } as const;
export type ClimateKey = keyof typeof CLIMATE_CLASSES;
/** Numeric room values, including Symcon readings whose legacy domain was inferred from a parent name. */
@@ -222,6 +222,7 @@ export function isClimateValueSensor(hass: HomeAssistant, id: string, key: Clima
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;
if (key === "illuminance" && ["lx", "lux"].includes(unit)) return true;
return a.device_class === CLIMATE_CLASSES[key];
}
@@ -277,7 +278,7 @@ export function roomClimateValue(hass: HomeAssistant, floor: Floor | null, room:
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;
if ((key !== "temperature" && key !== "humidity") || room.climate?.[key] === "none") return null;
const attr = key === "temperature" ? "current_temperature" : "current_humidity";
const climates = roomEntities(hass, room)
.filter((id) => id.startsWith("climate."))
+24
View File
@@ -28,7 +28,19 @@ const DE = {
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",
climate_illuminance: "Helligkeit",
device_values: "Zusätzliche Werte",
device_value: "Datenpunkt",
device_value_add: "Wert hinzufügen",
device_value_remove: "Wert entfernen",
device_value_icon: "Symbol",
device_value_label: "Bezeichnung (optional)",
device_values_hint: "Über + weitere Datenpunkte auswählen, zum Beispiel mehrere Temperaturen oder andere Messwerte. Als Symbol eignen sich Emojis oder kurze Zeichen wie 🌡, 💧, ☁ oder ⚡. Die Werte erscheinen am Gerät und im Raumfenster.",
cover_tilt_entity: "Lamellenposition",
cover_direction_invert: "Wirksinn Behang umkehren",
cover_tilt_direction_invert: "Wirksinn Lamellen umkehren",
cover2_direction_invert: "Wirksinn zweiter Behang umkehren",
cover2_tilt_direction_invert: "Wirksinn Lamellen des zweiten Behangs umkehren",
cover2_tilt_entity: "Lamellenposition (zweiter Behang)",
symcon_variables_loading: "Variablen werden geladen …",
symcon_variables_loaded: "Variablen und Objektbaum wurden neu geladen.",
@@ -2057,7 +2069,19 @@ const EN: Record<Key, string> = {
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",
climate_illuminance: "Illuminance",
device_values: "Additional values",
device_value: "Data point",
device_value_add: "Add value",
device_value_remove: "Remove value",
device_value_icon: "Symbol",
device_value_label: "Label (optional)",
device_values_hint: "Use + to select additional data points, such as several temperatures or other readings. Symbols can be emoji or short characters such as 🌡, 💧, ☁ or ⚡. Values appear on the device and in the room panel.",
cover_tilt_entity: "Slat position",
cover_direction_invert: "Reverse blind direction",
cover_tilt_direction_invert: "Reverse slat direction",
cover2_direction_invert: "Reverse second blind direction",
cover2_tilt_direction_invert: "Reverse second blind slat direction",
cover2_tilt_entity: "Slat position (second blind)",
symcon_variables_loading: "Loading variables …",
symcon_variables_loaded: "Variables and object tree reloaded.",
+9 -11
View File
@@ -316,12 +316,11 @@ 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}>
<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}
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}
</div>`;
}
@@ -434,18 +433,17 @@ export const liveCardStyles = css`
.live-card-roomclimate {
display: grid;
gap: 4px;
min-width: 190px;
min-width: 96px;
max-width: calc(100vw - 24px);
box-sizing: border-box;
}
.live-card-roomclimate .live-title {
overflow: hidden;
text-overflow: ellipsis;
max-width: 220px;
.live-card-roomclimate .live-row {
gap: 12px;
}
.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-climate-illuminance b { color: color-mix(in srgb, #fde68a 80%, var(--nf-text)); }
.live-row {
display: flex;
justify-content: space-between;
+15 -4
View File
@@ -6,16 +6,18 @@ 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" } };
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", illuminance: "sensor.lux" } };
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"),
entity("cover.knx", "open", { symcon_numeric_value: 48.5 }), entity("sensor.co2", "780"), entity("sensor.lux", "320", { unit_of_measurement: "lx" }),
]);
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.equal(cards[0].illuminance, 320);
assert.equal(cards[0].showIlluminance, true);
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");
@@ -23,8 +25,8 @@ test("enabled room cards use explicit numeric sensors, averages and temperature
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" };
const room = { ...box("u", 0, 0, 6, 6), climate_card: true, climate: { temperature: "sensor.pending" }, 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, climate: { temperature: "sensor.pending" } }]), id: "upper" };
b.floors = [floorWith([room]), upper];
const h = hassOf([]);
const all = roomClimateCards(h, b, null, null);
@@ -40,4 +42,13 @@ test("missing, unavailable and disabled readings stay missing rather than becomi
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]);
assert.deepEqual([card.showTemperature, card.showHumidity, card.showCo2], [true, true, false]);
});
test("unlinked metrics are hidden and an entirely unlinked room has no empty card", () => {
const b = emptyBuilding();
b.floors = [floorWith([{ ...box("r", 0, 0, 4, 4), climate_card: true, climate: { temperature: "sensor.t", humidity: "none", co2: "none" } }, { ...box("empty", 5, 0, 9, 4), climate_card: true }])];
const [card, ...rest] = roomClimateCards(hassOf([entity("sensor.t", "22.7", { unit_of_measurement: "°C" })]), b, null, null);
assert.equal(rest.length, 0);
assert.deepEqual([card.showTemperature, card.showHumidity, card.showCo2], [true, false, false]);
});
+19 -4
View File
@@ -1,4 +1,4 @@
import { roomClimateValue } from "../devices.ts";
import { roomClimateSensors, roomClimateValue, type ClimateKey } 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";
@@ -12,6 +12,11 @@ export interface RoomClimateCard {
temperature: number | null;
humidity: number | null;
co2: number | null;
showTemperature: boolean;
showHumidity: boolean;
showCo2: boolean;
illuminance: number | null;
showIlluminance: boolean;
}
/** One opt-in card per room, using the exact same sensor assignments and averaging as the room panel. */
@@ -21,13 +26,23 @@ export function roomClimateCards(hass: HomeAssistant, building: Building, floorI
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 temperature = roomClimateValue(hass, floor, room, "temperature");
const humidity = roomClimateValue(hass, floor, room, "humidity");
const co2 = roomClimateValue(hass, floor, room, "co2");
const illuminance = roomClimateValue(hass, floor, room, "illuminance");
const linked = (key: ClimateKey, value: number | null) => {
const chosen = room.climate?.[key];
if (chosen === "none") return false;
return (chosen ? [chosen].flat().some((id) => !!id && id !== "none") : false) || roomClimateSensors(hass, floor, room, key).length > 0 || value !== null;
};
const showTemperature = linked("temperature", temperature), showHumidity = linked("humidity", humidity), showCo2 = linked("co2", co2);
const showIlluminance = linked("illuminance", illuminance);
if (!showTemperature && !showHumidity && !showCo2 && !showIlluminance) 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"),
temperature, humidity, co2, illuminance, showTemperature, showHumidity, showCo2, showIlluminance,
});
}
}
+2 -1
View File
@@ -6,6 +6,7 @@ import { formatNumber, translate, type I18nKey } from "./i18n.ts";
import { iconSvg, mdiIcon } from "./icons.ts";
import { ceilingAt, offsetAt, pointInPolygon, type Building, type Floor, type Placement, type Room } from "./model.ts";
import type { HassEntity, HomeAssistant } from "./types.ts";
import { deviceValuesText } from "./entities/device-values.ts";
import type { DeviceMarker } from "./viewer/viewer3d.ts";
import { lightAnimation } from "./light-effects.ts";
import { pluginFloorWedge, pluginKind, pluginMarkerPatch } from "./plugins/registry.ts";
@@ -135,7 +136,7 @@ function markerFor(hass: HomeAssistant, floor: Floor, placed: Placement): Device
name: placed.name || entityName(hass, placed.entity_id, areaName),
ownName: placed.name || undefined,
showName: !!placed.show_name,
text: stateText(hass, st),
text: [stateText(hass, st), deviceValuesText(hass, placed.values)].filter(Boolean).join(" · "),
active: isActive(st),
unavailable: isUnavailable(st),
glow: kind === "light" ? scaleGlow(lightGlow(st), placed.glow_scale) : null,
+19
View File
@@ -16,6 +16,15 @@ export interface RoomClimate {
temperature?: string | string[] | null;
humidity?: string | string[] | null;
co2?: string | string[] | null;
illuminance?: string | string[] | null;
}
/** Additional readouts attached to a device; entity references always come from the picker. */
export interface DeviceValueLink {
id: string;
entity: EntityRef;
icon?: string | null;
label?: string | null;
}
/** A wall height on a room edge, or one per part of a split edge. */
@@ -162,9 +171,13 @@ export interface Opening {
cover: EntityRef;
/** Separate numeric control for the venetian blind's slat position. */
cover_tilt?: EntityRef;
cover_inverted?: boolean;
cover_tilt_inverted?: boolean;
/** Windows and doors: a second blind for the right half (seen from the room) of a wide window. */
cover2?: string | null;
cover2_tilt?: EntityRef;
cover2_inverted?: boolean;
cover2_tilt_inverted?: boolean;
/** The kind of blind: a roller shutter outside (null, default), a venetian blind (Raffstore) outside with slats, or a roller blind inside. */
blind?: "roller" | "venetian" | "inside" | null;
/** The favourite position of the blind (%, open = 100) – Somfy's "My": a button in its menu moves it there. */
@@ -234,6 +247,7 @@ export interface Furniture extends LightEffectConfig {
/** Fridges and freezers: a temperature sensor of the fridge (temp_entity) and one of the freezer compartment; the marker shows them and warns when too warm. Any other device: its own thermometer, shown on its pin (#112). */
temp_entity?: string | null;
temp_entity2?: string | null;
values?: DeviceValueLink[];
/** Smart fridge: door sensors of the left (freezer) and right (fridge) door; the doors open in 3D while they report open. */
door_left?: EntityRef;
door_right?: EntityRef;
@@ -343,6 +357,11 @@ export interface Placement extends LightEffectConfig {
simple?: boolean;
/** A placed blind's separate slat position control. */
cover_tilt?: EntityRef;
values?: DeviceValueLink[];
cover_inverted?: boolean;
cover_tilt_inverted?: boolean;
position?: EntityRef;
position_inverted?: boolean;
/** Its marker in 3D: automatic (null), always shown, shown without watts, or hidden. */
marker?: MarkerShow | null;
/** An own symbol for the marker: a Material Design icon name without "mdi:" (null = by kind). */
+4 -3
View File
@@ -21,6 +21,7 @@ import { panelStyles } from "./panel/styles.ts";
import { colorSchemeOf, controls, readableStyles, tokens } from "./styles.ts";
import { LOOKS, lookNow, type Look } from "./themes.ts";
import type { HomeAssistant } from "./types.ts";
import { withCoverControls } from "./entities/cover-controls.ts";
import { allOffPlan, floorSwitchables, type ServiceCall } from "./live/all-off.ts";
import type { FloorStack, Quality, WallMode } from "./viewer/viewer3d.ts";
@@ -580,7 +581,7 @@ export class NextFloorPanel extends LitElement {
<div class="nf-stage-wrap ${this._roomId ? "nf-room-open" : ""}">
<nf-view3d
class="nf-body"
.hass=${this.hass}
.hass=${withCoverControls(this.hass, building.floors)}
.building=${building}
.packs=${this.data.packs}
.floorStack=${p.floorStack}
@@ -631,7 +632,7 @@ export class NextFloorPanel extends LitElement {
? html`<nf-room-panel
.building=${this.data.building ?? null}
class="nf-room-panel"
.hass=${this.hass}
.hass=${withCoverControls(this.hass, building.floors)}
.room=${room}
.floor=${building.floors.find((f) => f.rooms.some((r) => r.id === this._roomId)) ?? null}
.confirmEntities=${confirmEntities(this.hass, building.floors)}
@@ -644,7 +645,7 @@ export class NextFloorPanel extends LitElement {
? html`<nf-room-panel
.building=${this.data.building ?? null}
class="nf-room-panel"
.hass=${this.hass}
.hass=${withCoverControls(this.hass, building.floors)}
.room=${null}
.outside=${this.outsideIds(building)}
.confirmEntities=${confirmEntities(this.hass, building.floors)}