feat: add 3D hydronic manifolds buffer tanks and fresh water stations
This commit is contained in:
1 parent
93c015ec77
commit
173d02e3cc
37 files changed
+3253
-1815
No files matched your search
@@ -17,6 +17,8 @@ import { dataField, TARGET_EXAMPLES } from "./house.ts";
|
||||
import { parkingForm } from "./parking.ts";
|
||||
import { stairForm } from "./stairs.ts";
|
||||
import { DEFAULT_STAIR } from "../../../geometry/stairs.ts";
|
||||
import { isHydronic } from "../../../hydronic-model.ts";
|
||||
import { renderHydronicForm } from "./hydronic.ts";
|
||||
|
||||
export interface FurnitureActions extends FurnitureLinkActions {
|
||||
rotate(delta: number): void;
|
||||
@@ -239,7 +241,7 @@ export function renderFurnitureForm(host: EditorHost, item: Furniture, actions:
|
||||
<div class="nf-h3row"><h3>${item.name || host.t("furniture")}</h3>${actions.lockButton}</div>
|
||||
<div class="nf-form">${nameFields(host, item, actions)} ${kindField(host, item, actions.packs, actions)} ${geometryFields(host, item, actions)}</div>
|
||||
${typeNotes(host, item, actions)} ${item.type === "stairs" && item.stair ? stairForm(host, item, actions) : nothing} ${variantField(host, item, actions)} ${paintField(host, item, actions)}
|
||||
${links} ${item.type.endsWith(":sprinkler") ? html`<div class="nf-form">${numberField(host, host.t("spray_reach"), item.spray ?? 3, (v) => actions.update({ spray: Math.min(15, Math.max(0.5, v)) }), 0.5, 0.5)}${hint(host.t("spray_hint"), "nf-wide")}</div>` : nothing}
|
||||
${isHydronic(item.type) ? renderHydronicForm(host, item, (patch) => actions.update(patch)) : links} ${item.type.endsWith(":sprinkler") ? html`<div class="nf-form">${numberField(host, host.t("spray_reach"), item.spray ?? 3, (v) => actions.update({ spray: Math.min(15, Math.max(0.5, v)) }), 0.5, 0.5)}${hint(host.t("spray_hint"), "nf-wide")}</div>` : nothing}
|
||||
${hasPicture(item.type) ? pictureFields(host, item, actions) : nothing}
|
||||
${packItem(item.type)?.pet
|
||||
? html`<div class="nf-form nf-links">${entityField(host, host.t("pet_room_sensor"), item.room_sensor ?? null, undefined, entityOptions(host.hass, (id) => /^(sensor|device_tracker|input_select|select)\./.test(id)), (v) => actions.update({ room_sensor: v && v !== "none" ? v : null }))}${hint(host.t("pet_room_hint"), "nf-wide")}</div>`
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { html, nothing } from "lit";
|
||||
import { repeat } from "lit/directives/repeat.js";
|
||||
import { uid, type Furniture } from "../../../model.ts";
|
||||
import { hasPump, hasValve, hydronicConfig, newCircuit, type HydronicConfig, type HydronicControl, type HydronicCircuit } from "../../../hydronic-model.ts";
|
||||
import { entityOptions } from "../entities.ts";
|
||||
import { checkField, entityField, hint, numberField, pinShiftField, selectField, textField } from "../fields.ts";
|
||||
import { renderDeviceValues } from "../device-values.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
|
||||
export function renderHydronicForm(host: EditorHost, item: Furniture, update: (patch: Partial<Furniture>) => void) {
|
||||
const h = hydronicConfig(item), options = entityOptions(host.hass, () => true);
|
||||
const set = (patch: Partial<HydronicConfig>) => update({ hydronic: { ...h, ...patch } });
|
||||
const ref = (label: string, value: string | null | undefined, types: number[], save: (id: string | null) => void) => entityField(host, label, value ?? null, undefined, options, (v) => save(v === "none" ? null : v), { types });
|
||||
const numeric = (label: string, value: string | null | undefined, save: (id: string | null) => void) => ref(label, value, [1, 2], save);
|
||||
const control = (label: string, value: HydronicControl | undefined, save: (c: HydronicControl) => void, valve = false) => html`<details class="nf-wide nf-hydronic-control"><summary>${label}</summary><div class="nf-form">
|
||||
${ref("Rückmeldung / Istwert", value?.feedback, [0, 1, 2], (feedback) => save({ ...value, feedback }))}
|
||||
${ref("Befehl / Sollwert (optional)", value?.command, [0, 1, 2], (command) => save({ ...value, command }))}
|
||||
${valve ? checkField(host, "Ventil nur in 3D umkehren", !!value?.inverted, (inverted) => save({ ...value, inverted })) : nothing}
|
||||
${hint("Eine zugewiesene Rückmeldung bestimmt die 3D-Anzeige, auch wenn sie gerade nicht verfügbar ist. Ohne Rückmeldung wird der verknüpfte Sollwert verwendet. Befehle werden über die Symcon-Schaltaktion in ihrem nativen Wertebereich gesendet. Die 3D-Umkehrung verändert weder Anzeige- noch Schreibwerte.", "nf-wide")}
|
||||
</div></details>`;
|
||||
const temperatures = html`${numeric("Vorlauf", h.flow, (flow) => set({ flow }))}${numeric("Rücklauf", h.return, (back) => set({ return: back }))}`;
|
||||
const circuit = (c: HydronicCircuit, i: number) => {
|
||||
const patch = (p: Partial<HydronicCircuit>) => set({ circuits: (h.circuits ?? []).map((old) => old.id === c.id ? { ...old, ...p } : old) });
|
||||
return html`<details class="nf-hydronic-circuit" data-circuit=${c.id} ?open=${i === 0}><summary>${c.name || `Kreis ${i + 1}`}</summary><div class="nf-form">
|
||||
${textField(host, "Name", c.name, (name) => patch({ name }), { wide: true, maxlength: 100 })}
|
||||
${selectField(host, "Kreisart", c.kind, [["heating", "Heizkreis"], ["cooling", "Kühlkreis"], ["changeover", "Heizen / Kühlen"], ["pump", "Einspeise- / Vorschubpumpe (ohne Ventil)"]], (kind) => patch({ kind, ...(kind === "pump" ? { has_pump: true, has_valve: false } : {}) }), { wide: true })}
|
||||
${c.kind !== "pump" ? html`${checkField(host, "Pumpe vorhanden", hasPump(c), (has_pump) => patch({ has_pump }))}${checkField(host, "Ventil vorhanden", hasValve(c), (has_valve) => patch({ has_valve }))}` : nothing}
|
||||
${hasPump(c) ? control("Pumpe", c.pump, (pump) => patch({ pump })) : nothing}
|
||||
${hasValve(c) ? control("Ventil", c.valve, (valve) => patch({ valve }), true) : nothing}
|
||||
${numeric("Vorlauf", c.flow, (flow) => patch({ flow }))}${numeric("Rücklauf", c.return, (back) => patch({ return: back }))}
|
||||
${hasPump(c) ? numeric("Pumpenleistung (optional)", c.power, (power) => patch({ power })) : nothing}
|
||||
${c.kind === "changeover" ? html`${ref("Umschaltung Heizen / Kühlen", c.mode_entity, [0, 1], (mode_entity) => patch({ mode_entity }))}${numberField(host, "Kühlbetrieb bei Wert", c.cooling_value ?? 1, (cooling_value) => patch({ cooling_value: Math.round(cooling_value) }), 1)}` : nothing}
|
||||
<button class="nf-link nf-wide nf-hydronic-remove" ?disabled=${!host.admin} @click=${() => set({ circuits: (h.circuits ?? []).filter((old) => old.id !== c.id) })}>× Kreis entfernen</button>
|
||||
</div></details>`;
|
||||
};
|
||||
return html`<section class="nf-hydronic-form">
|
||||
<div class="nf-form">${checkField(host, "Schwebende 3D-Kachel", h.card !== false, (card) => set({ card }))}${pinShiftField(host, item.pin_offset, (pin_offset) => update({ pin_offset }))}${hint("Verknüpfe jeden Datenpunkt über den Objektbaum. Namen und Pfade schränken die Auswahl nicht ein. Nicht verknüpfte Werte bleiben in der 3D-Kachel ausgeblendet. Das Bauteil öffnet beim Antippen seine Werte und Bedienung.", "nf-wide")}</div>
|
||||
${item.type === "heating_manifold" ? html`${repeat(h.circuits ?? [], (c) => c.id, circuit)}<button class="nf-btn nf-hydronic-add" title="Bis zu 32 Kreise" ?disabled=${!host.admin || (h.circuits?.length ?? 0) >= 32} @click=${() => set({ circuits: [...(h.circuits ?? []), newCircuit(uid("circuit"), `Kreis ${(h.circuits?.length ?? 0) + 1}`)] })}>+ Kreis hinzufügen</button>` : nothing}
|
||||
${item.type === "buffer_tank" ? html`<div class="nf-form">${temperatures}${hint("Die sieben Startplätze liegen von oben nach unten. Höhe 100 % liegt oben, 0 % unten. Fühlerplätze können ergänzt, entfernt und frei in der Höhe positioniert werden; die Anzeige sortiert sie von oben nach unten.", "nf-wide")}</div>
|
||||
${repeat([...(h.sensors ?? [])].sort((a, b) => b.level - a.level), (probe) => probe.id, (probe) => {
|
||||
const patch = (change: Partial<typeof probe>) => set({ sensors: (h.sensors ?? []).map((s) => s.id === probe.id ? { ...s, ...change } : s) });
|
||||
return html`<details class="nf-hydronic-probe" data-probe=${probe.id}><summary>${probe.name || "Fühler"} · ${Math.round(probe.level * 100)} %</summary><div class="nf-form">
|
||||
${textField(host, "Bezeichnung", probe.name, (name) => patch({ name }), { wide: true, maxlength: 100 })}${numeric("Temperatur", probe.entity, (entity) => patch({ entity }))}
|
||||
${numberField(host, "Höhe (%) · 100 = oben", Math.round(probe.level * 1000) / 10, (v) => patch({ level: Math.max(0, Math.min(1, v / 100)) }), .1, 0)}
|
||||
<button class="nf-link nf-wide" ?disabled=${!host.admin} @click=${() => set({ sensors: (h.sensors ?? []).filter((s) => s.id !== probe.id) })}>× Fühlerplatz entfernen</button>
|
||||
</div></details>`;
|
||||
})}<button class="nf-btn nf-hydronic-add-probe" title="Bis zu 64 Fühlerplätze" ?disabled=${!host.admin || (h.sensors?.length ?? 0) >= 64} @click=${() => set({ sensors: [...(h.sensors ?? []), { id: uid("probe"), name: `Fühler ${(h.sensors?.length ?? 0) + 1}`, entity: null, level: .5 }] })}>+ Fühlerplatz hinzufügen</button>` : nothing}
|
||||
${item.type === "freshwater_station" ? html`<div class="nf-form">${temperatures}${numeric("Zirkulationstemperatur", h.circulation_temperature, (circulation_temperature) => set({ circulation_temperature }))}${numeric("Trinkwarmwasser", h.hot_water, (hot_water) => set({ hot_water }))}${control("Ladepumpe", h.pump, (pump) => set({ pump }))}${control("Zirkulationspumpe", h.circulation, (circulation) => set({ circulation }))}</div>` : nothing}
|
||||
${renderDeviceValues(host, item.values, (values) => update({ values }))}
|
||||
</section>`;
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
type Vec2,
|
||||
} from "../../../model.ts";
|
||||
import { furnitureSize } from "../../../packs.ts";
|
||||
import { defaultHydronic, isHydronic } from "../../../hydronic-model.ts";
|
||||
|
||||
const thousandths = (v: number) => Math.round(v * 1000) / 1000;
|
||||
const quarterTurns = (degrees: number, by: number) => (((degrees + by) % 360) + 360) % 360;
|
||||
@@ -74,6 +75,7 @@ export function newFurniture(type: string, doc: Building, floor: Floor, at: Vec2
|
||||
const above = doc.floors.filter((f) => f.elevation > floor.elevation).sort((p, q) => p.elevation - q.elevation)[0];
|
||||
const h = type === "stairs" ? thousandths(above ? above.elevation - floor.elevation : floor.height + 0.25) : height;
|
||||
const item: Furniture = { id: uid("furniture"), type, x: thousandths(at[0]), z: thousandths(at[1]), rotation: 0, w, d, h, variant: null };
|
||||
if (isHydronic(type)) item.hydronic = defaultHydronic(type);
|
||||
// new stairs are shaped stairs: shape, turn and steps are set in the form, and they open only the floor they need
|
||||
if (type === "stairs") item.stair = { ...DEFAULT_STAIR };
|
||||
return item;
|
||||
|
||||
@@ -2003,4 +2003,8 @@ export const editorStyles = css`
|
||||
font-size: 12.5px;
|
||||
color: var(--nf-warm);
|
||||
}
|
||||
.nf-hydronic-form>details { border:1px solid var(--nf-line); border-radius:10px; padding:10px; margin:8px 0; }
|
||||
.nf-hydronic-form summary { cursor:pointer; font-weight:500; }
|
||||
.nf-hydronic-form details[open]>.nf-form { margin-top:9px; }
|
||||
.nf-hydronic-control { border-top:1px solid var(--nf-line); padding-top:7px; }
|
||||
`;
|
||||
@@ -0,0 +1,113 @@
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import type { Building, Furniture } from "../model.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { hasPump, hasValve, hydronicConfig, isHydronic, realRef, type HydronicCircuit, type HydronicControl } from "../hydronic-model.ts";
|
||||
import { hydronicReading, readControl, temperatureC, type HydronicReading } from "../hydronic-values.ts";
|
||||
import { nativeBool, nativeNumber, nativeText, nativeValue } from "../entities/symcon-values.ts";
|
||||
import { tokens } from "../styles.ts";
|
||||
import { trendButton } from "./trend-button.ts";
|
||||
export { hydronicVisual } from "../hydronic-values.ts";
|
||||
|
||||
const names: Record<string, string> = { heating_manifold: "Heiz-/Kühlkreisverteiler", buffer_tank: "Pufferspeicher", freshwater_station: "Frischwasserstation" };
|
||||
const nameOf = (item: Furniture) => item.name || names[item.type];
|
||||
const titleOf = (c: HydronicCircuit) => c.name || ({ heating: "Heizkreis", cooling: "Kühlkreis", changeover: "Heizen / Kühlen", pump: "Vorschubpumpe" })[c.kind];
|
||||
const modeOf = (hass: HomeAssistant, c: HydronicCircuit) => c.kind === "pump" ? "Pumpenkreis" : c.kind === "cooling" ? "Kühlen" : c.kind === "heating" ? "Heizen"
|
||||
: realRef(c.mode_entity) && nativeValue(hass.states[c.mode_entity]) === null ? "Betriebsart –" : Number(realRef(c.mode_entity) ? nativeValue(hass.states[c.mode_entity]) : 0) === (c.cooling_value ?? 1) ? "Kühlen" : "Heizen";
|
||||
const parts = (hass: HomeAssistant, flow?: string | null, back?: string | null): HydronicReading[] => [hydronicReading(hass, "Vorlauf", flow), hydronicReading(hass, "Rücklauf", back)].filter((r): r is HydronicReading => r !== null);
|
||||
const delta = (hass: HomeAssistant, flow?: string | null, back?: string | null) => {
|
||||
const a = temperatureC(hass, flow), b = temperatureC(hass, back);
|
||||
return a === null || b === null ? nothing : html`<div class="reading delta"><span>ΔT · VL − RL</span><b>${(a - b).toLocaleString(hass.language, { maximumFractionDigits: 1 })} K</b></div>`;
|
||||
};
|
||||
function rootRows(hass: HomeAssistant, item: Furniture): HydronicReading[] {
|
||||
const h = hydronicConfig(item), rows = parts(hass, h.flow, h.return);
|
||||
if (item.type === "buffer_tank") rows.unshift(...[...(h.sensors ?? [])].sort((a, b) => b.level - a.level).flatMap((s) => { const row = hydronicReading(hass, s.name || "Fühler", s.entity); return row ? [row] : []; }));
|
||||
if (item.type === "freshwater_station") for (const [label, id] of [["Zirkulation", h.circulation_temperature], ["Trinkwarmwasser", h.hot_water]] as const) { const row = hydronicReading(hass, label, id); if (row) rows.push(row); }
|
||||
for (const v of item.values ?? []) { const row = hydronicReading(hass, v.label || String(v.entity && hass.states[v.entity]?.attributes.friendly_name || "Wert"), v.entity); if (row) rows.push({ ...row, icon: v.icon }); }
|
||||
return rows;
|
||||
}
|
||||
const rowTemplate = (hass: HomeAssistant, row: HydronicReading) => html`<div class="reading" data-source=${row.id}><span>${row.icon?.startsWith("mdi:") ? html`<ha-icon icon=${row.icon}></ha-icon>` : row.icon || nothing} ${row.label}</span><b>${row.text}${trendButton(hass, [row.id], row.label)}</b></div>`;
|
||||
function controlRow(hass: HomeAssistant, label: string, binding?: HydronicControl) {
|
||||
const state = readControl(hass, binding);
|
||||
return state.id ? html`<div class="reading" data-source=${state.id}><span>${label}<small>${state.feedback ? "Ist" : "Soll"}</small></span><b><i class="lamp" style=${`background:${state.running === null ? "#888" : state.running ? "#6fe1a2" : "#465361"}`}></i>${nativeText(hass.states[state.id])}${trendButton(hass, [state.id], label)}</b></div>` : nothing;
|
||||
}
|
||||
|
||||
const styles = css`
|
||||
:host{display:block;color:var(--nf-text);font:12px/1.4 system-ui,sans-serif;min-width:170px;max-width:300px}
|
||||
button{font:inherit;color:inherit;background:var(--nf-fill,#ffffff10);border:1px solid var(--nf-line);border-radius:7px;padding:5px 8px;cursor:pointer}button:disabled,input:disabled{opacity:.45;cursor:default}button:focus-visible,input:focus-visible{outline:2px solid var(--nf-accent);outline-offset:2px}
|
||||
.title{display:block;width:100%;padding:0 0 5px;border:0;background:none;font-weight:600;text-align:left;white-space:normal}.content{max-height:250px;overflow:auto;overscroll-behavior:contain}.circuit{border-top:1px solid var(--nf-line);padding:5px 0}.circuit-name{font-size:11px;font-weight:600;margin-bottom:3px}.reading{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:center;min-height:22px}.reading>span{color:var(--nf-muted);white-space:normal}.reading b{display:flex;align-items:center;justify-content:flex-end;white-space:nowrap;font-variant-numeric:tabular-nums;font-weight:500}.reading small{font-size:9px;margin-left:5px;opacity:.75}.delta{font-size:10px}.lamp{display:inline-block;flex:none;width:6px;height:6px;border-radius:50%;margin-right:5px}.empty{color:var(--nf-muted);font-size:11px;white-space:normal;margin:5px 0}nf-trend-button{margin-left:3px}
|
||||
.circuit-name small,h3 small{font-size:10px;color:var(--nf-muted);font-weight:normal;margin-left:5px}
|
||||
ha-icon{--mdc-icon-size:13px;width:13px;height:13px;vertical-align:middle}
|
||||
dialog{box-sizing:border-box;width:min(620px,calc(100vw - 24px));max-width:none;max-height:calc(100dvh - 24px);padding:0;color:var(--nf-text);background:var(--nf-chrome-solid,#1c1c1c);border:1px solid var(--nf-line);border-radius:14px;box-shadow:0 20px 70px #0008;font:13px/1.4 system-ui,sans-serif}dialog::backdrop{background:#050b16a6;backdrop-filter:blur(3px)}header{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px 18px;border-bottom:1px solid var(--nf-line)}h2{font-size:17px;margin:0}.body{padding:12px 18px;max-height:calc(100dvh - 120px);overflow:auto;overscroll-behavior:contain}h3{font-size:13px;margin:12px 0 7px}fieldset{min-width:0;margin:8px 0;padding:10px;border:1px solid var(--nf-line);border-radius:9px}legend{font-size:12px;color:var(--nf-muted)}.command{display:flex;align-items:center;gap:12px;margin-top:8px}.command input[type=range]{flex:1;min-width:0;accent-color:var(--nf-accent)}.command input[type=number]{width:90px;box-sizing:border-box;background:var(--nf-fill,#ffffff10);border:1px solid var(--nf-line);border-radius:6px;color:inherit;padding:5px}.command output{font-variant-numeric:tabular-nums;min-width:45px;text-align:right}.error{color:#ff9b9b}.readonly{color:var(--nf-muted);font-size:11px;margin:4px 0}.body .reading{padding:4px 0}.body .circuit{padding-bottom:12px}
|
||||
`;
|
||||
|
||||
class HydronicCard extends LitElement {
|
||||
static properties = { hass: { attribute: false }, item: { attribute: false }, readOnly: { type: Boolean } };
|
||||
declare hass: HomeAssistant; declare item: Furniture; declare readOnly: boolean;
|
||||
render() {
|
||||
if (!this.hass || !this.item) return nothing;
|
||||
const h = hydronicConfig(this.item), rows = rootRows(this.hass, this.item);
|
||||
return html`<button class="title" @click=${() => openHydronic(this.hass, this.item, this.readOnly)} aria-haspopup="dialog">${nameOf(this.item)} ⚙</button><div class="content">
|
||||
${this.item.type === "heating_manifold" ? (h.circuits ?? []).map((c) => html`<section class="circuit"><div class="circuit-name">${titleOf(c)} <small>${modeOf(this.hass, c)}</small></div>${hasPump(c) ? controlRow(this.hass, "Pumpe", c.pump) : nothing}${hasValve(c) ? controlRow(this.hass, "Ventil", c.valve) : nothing}${parts(this.hass, c.flow, c.return).map((r) => rowTemplate(this.hass, r))}${hydronicReading(this.hass, "Leistung", c.power) ? rowTemplate(this.hass, hydronicReading(this.hass, "Leistung", c.power)!) : nothing}</section>`) : nothing}
|
||||
${rows.map((r) => rowTemplate(this.hass, r))}${this.item.type === "freshwater_station" ? html`${controlRow(this.hass, "Ladepumpe", h.pump)}${controlRow(this.hass, "Zirkulationspumpe", h.circulation)}` : nothing}
|
||||
${this.item.type !== "heating_manifold" && !rows.length ? html`<p class="empty">Noch keine Fühler verknüpft</p>` : nothing}
|
||||
</div>`;
|
||||
}
|
||||
static styles = [tokens, styles];
|
||||
}
|
||||
|
||||
class HydronicDialog extends LitElement {
|
||||
static properties = { hass: { attribute: false }, item: { attribute: false }, readOnly: { type: Boolean }, pending: { state: true }, error: { state: true } };
|
||||
declare hass: HomeAssistant; declare item: Furniture; declare readOnly: boolean;
|
||||
private declare pending: Set<string>; private declare error: string;
|
||||
constructor() { super(); this.pending = new Set(); this.error = ""; this.readOnly = false; }
|
||||
async show() { await this.updateComplete; this.shadowRoot!.querySelector("dialog")!.showModal(); }
|
||||
private async send(id: string, value: number | boolean) {
|
||||
const st = this.hass.states[id];
|
||||
if (this.readOnly || !st?.attributes.symcon_has_action || nativeValue(st) === null || this.pending.has(id)) return;
|
||||
this.pending = new Set([...this.pending, id]); this.error = "";
|
||||
try { await this.hass.callService("symcon", "set_value", { entity_id: id, value }); }
|
||||
catch (error) { this.error = error instanceof Error ? error.message : String(error); }
|
||||
finally { this.pending = new Set([...this.pending].filter((v) => v !== id)); }
|
||||
}
|
||||
private control(label: string, binding?: HydronicControl) {
|
||||
if (!realRef(binding?.command) && !realRef(binding?.feedback)) return nothing;
|
||||
const id = realRef(binding?.command) ? binding.command : null, st = id ? this.hass.states[id] : undefined;
|
||||
const a = st?.attributes, value = nativeValue(st), writable = !!id && !!a?.symcon_has_action && value !== null && !this.readOnly && !this.pending.has(id);
|
||||
const min = Number(a?.symcon_min ?? 0), max = Number(a?.symcon_max ?? 100), step = Number(a?.symcon_step || (a?.symcon_variable_type === 1 ? 1 : .1));
|
||||
const number = nativeNumber(st);
|
||||
const writeNumber = (event: Event) => { const input = event.target as HTMLInputElement; if (id && input.value.trim() && input.checkValidity() && Number.isFinite(input.valueAsNumber)) void this.send(id, input.valueAsNumber); };
|
||||
return html`<fieldset data-control=${label}><legend>${label}</legend>${controlRow(this.hass, label, binding)}
|
||||
${id ? html`<div class="reading"><span>Befehl / Sollwert</span><b>${nativeText(st)}${trendButton(this.hass, [id], `${label} · Sollwert`)}</b></div>
|
||||
${a?.symcon_variable_type === 0 ? html`<div class="command"><button data-command=${id} ?disabled=${!writable} @click=${() => void this.send(id, !nativeBool(st))}>${nativeBool(st) ? "Ausschalten / Schließen" : "Einschalten / Öffnen"}</button></div>`
|
||||
: [1, 2].includes(Number(a?.symcon_variable_type)) ? html`<div class="command"><input type="range" aria-label=${`${label} Sollwert`} data-command=${id} min=${min} max=${max} step=${step} .value=${String(number ?? min)} ?disabled=${!writable} @change=${writeNumber}/><input type="number" aria-label=${`${label} nativer Sollwert`} min=${min} max=${max} step=${step} .value=${number === null ? "" : String(number)} ?disabled=${!writable} @change=${writeNumber}/></div>` : nothing}
|
||||
${this.readOnly ? html`<p class="readonly">Historische Ansicht · nur Anzeige</p>` : !a?.symcon_has_action ? html`<p class="readonly">Nur Anzeige · keine Symcon-Schaltaktion hinterlegt</p>` : nothing}` : nothing}
|
||||
</fieldset>`;
|
||||
}
|
||||
render() {
|
||||
if (!this.hass || !this.item) return nothing;
|
||||
const h = hydronicConfig(this.item), rows = rootRows(this.hass, this.item);
|
||||
return html`<dialog @close=${() => { this.remove(); if (activeDialog === this) activeDialog = null; }} @keydown=${(e: Event) => e.stopPropagation()}><header><h2>${nameOf(this.item)}</h2><button aria-label="Schließen" @click=${() => this.shadowRoot!.querySelector("dialog")!.close()}>×</button></header><div class="body">
|
||||
${this.item.type === "heating_manifold" ? (h.circuits ?? []).map((c) => html`<section class="circuit" data-circuit=${c.id}><h3>${titleOf(c)} <small>${modeOf(this.hass, c)}</small></h3>${hasPump(c) ? this.control("Pumpe", c.pump) : nothing}${hasValve(c) ? this.control("Ventil", c.valve) : nothing}${parts(this.hass, c.flow, c.return).map((r) => rowTemplate(this.hass, r))}${delta(this.hass, c.flow, c.return)}${hydronicReading(this.hass, "Pumpenleistung", c.power) ? rowTemplate(this.hass, hydronicReading(this.hass, "Pumpenleistung", c.power)!) : nothing}</section>`) : nothing}
|
||||
${rows.map((r) => rowTemplate(this.hass, r))}${this.item.type !== "heating_manifold" ? delta(this.hass, h.flow, h.return) : nothing}
|
||||
${this.item.type === "freshwater_station" ? html`${this.control("Ladepumpe", h.pump)}${this.control("Zirkulationspumpe", h.circulation)}` : nothing}
|
||||
${!rows.length && this.item.type !== "heating_manifold" ? html`<p class="empty">Die Fühler lassen sich im Editor über den Objektbaum zuweisen.</p>` : nothing}
|
||||
${this.error ? html`<p class="error" role="alert">${this.error}</p>` : nothing}
|
||||
</div></dialog>`;
|
||||
}
|
||||
static styles = [tokens, styles, css`:host{max-width:none;min-width:0}`];
|
||||
}
|
||||
let activeDialog: HydronicDialog | null = null;
|
||||
export function closeHydronic() { activeDialog?.remove(); activeDialog = null; }
|
||||
export async function openHydronic(hass: HomeAssistant, item: Furniture, readOnly = false): Promise<void> {
|
||||
activeDialog?.remove();
|
||||
const dialog = document.createElement("nf-hydronic-dialog") as HydronicDialog;
|
||||
activeDialog = dialog; Object.assign(dialog, { hass, item, readOnly }); document.body.append(dialog); await dialog.show();
|
||||
}
|
||||
export function refreshHydronic(hass: HomeAssistant, building: Building, readOnly = false): void {
|
||||
if (!activeDialog) return;
|
||||
const item = building.floors.flatMap((f) => f.furniture).find((f) => f.id === activeDialog!.item.id);
|
||||
if (!item || !isHydronic(item.type)) { activeDialog.remove(); activeDialog = null; return; }
|
||||
Object.assign(activeDialog, { hass, item, readOnly });
|
||||
}
|
||||
if (!customElements.get("nf-hydronic-card")) customElements.define("nf-hydronic-card", HydronicCard);
|
||||
if (!customElements.get("nf-hydronic-dialog")) customElements.define("nf-hydronic-dialog", HydronicDialog);
|
||||
@@ -32,6 +32,8 @@ import { chosenEffects, readSkyWeather, withDensity } from "../live/sky-weather.
|
||||
import { energyPicture, houseHub, type EnergyPicture } from "../live/energy-flow.ts";
|
||||
import { roomClimateCards } from "../live/room-climate-card.ts";
|
||||
import { furniturePowerCards } from "../live/furniture-power-card.ts";
|
||||
import { isHydronic } from "../hydronic-model.ts";
|
||||
import { loadHydronics } from "../load-hydronics.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";
|
||||
@@ -413,6 +415,8 @@ export class NfView3d extends LitElement {
|
||||
private declare _utilityOverviewVisible: boolean;
|
||||
|
||||
private viewer: NextFloorViewer | null = null;
|
||||
private hydronicModule: Awaited<ReturnType<typeof loadHydronics>> | null = null;
|
||||
private hydronicGeneration = 0;
|
||||
private starting = false;
|
||||
/** States of the placed entities as last sent to the viewer. */
|
||||
private shownStates = new Map<string, HassEntity | undefined>();
|
||||
@@ -549,6 +553,7 @@ export class NfView3d extends LitElement {
|
||||
|
||||
disconnectedCallback(): void {
|
||||
super.disconnectedCallback();
|
||||
this.hydronicGeneration++; this.hydronicModule?.closeHydronic();
|
||||
this.stopPlugins?.();
|
||||
this.stopPlugins = null;
|
||||
this.listenToAnnouncements(false);
|
||||
@@ -859,6 +864,7 @@ export class NfView3d extends LitElement {
|
||||
// a piece shown only while a helper is on (seasonal decoration) comes and goes with it
|
||||
if (hiddenFurniture(hass, b).join(",") !== this.shownFor?.key) v.setBuilding(this.shownBuilding(hass));
|
||||
this.shownStates = new Map(this.watched.map((id) => [id, hass.states[id]]));
|
||||
this.syncHydronics(v, b, hass);
|
||||
this.refreshToday(b);
|
||||
this.refreshForecast(b);
|
||||
|
||||
@@ -1380,6 +1386,7 @@ export class NfView3d extends LitElement {
|
||||
}
|
||||
// an item with its own tap action shows what it shows as usual; a tap on it or on its pin runs the action
|
||||
const own = ownTaps(b, markers);
|
||||
for (const f of b.floors.flatMap((fl) => fl.furniture)) if (isHydronic(f.type)) targets.set(f.id, `hydronic:${f.id}`);
|
||||
this.tapPins = own.pins;
|
||||
for (const f of b.floors.flatMap((fl) => fl.furniture)) if (f.tap?.action) targets.set(f.id, `tap:${f.id}`);
|
||||
// one without a pin of its own gets one above it, like a device's, that does the same
|
||||
@@ -2323,6 +2330,11 @@ export class NfView3d extends LitElement {
|
||||
if (entityId.startsWith("lamp:")) return;
|
||||
// in the past nothing is switched
|
||||
if (this._travel) return;
|
||||
if (entityId.startsWith("hydronic:")) {
|
||||
const item = this.building?.floors.flatMap((f) => f.furniture).find((f) => f.id === entityId.slice(9));
|
||||
if (item && this.hass) void loadHydronics().then((mod) => { if (this.isConnected && this.hass) { this.hydronicModule = mod; return mod.openHydronic(this.hass, item); } }).catch((err) => { this._error = String(err); });
|
||||
return;
|
||||
}
|
||||
const ownTap = entityId.startsWith("tap:") ? entityId.slice(4) : this.tapPins.get(entityId);
|
||||
if (ownTap) {
|
||||
const f = this.building?.floors.flatMap((fl) => fl.furniture).find((it) => it.id === ownTap);
|
||||
@@ -2639,6 +2651,18 @@ export class NfView3d extends LitElement {
|
||||
.catch(() => (this.dayCurves = null));
|
||||
}
|
||||
|
||||
private syncHydronics(v: NextFloorViewer, b: Building, hass: HomeAssistant): void {
|
||||
const generation = ++this.hydronicGeneration;
|
||||
const items = this.shownBuilding(hass).floors.filter((floor) => !this.floorId || floor.id === this.floorId).flatMap((floor) => floor.furniture.filter((item) => isHydronic(item.type)).map((item) => ({ floor, item })));
|
||||
if (!items.length) { v.setHydronics([]); this.hydronicModule?.refreshHydronic(hass, b, !!this._travel); return; }
|
||||
void loadHydronics().then((mod) => {
|
||||
if (generation !== this.hydronicGeneration || this.viewer !== v || !this.isConnected) return;
|
||||
this.hydronicModule = mod;
|
||||
v.setHydronics(items.map(({ floor, item }) => ({ ...mod.hydronicVisual(hass, item, floor.id, mountBase(floor, item)), animate: !this.dimmed && !this._travel })));
|
||||
mod.refreshHydronic(hass, b, !!this._travel);
|
||||
}).catch((err) => { this._error = String(err); });
|
||||
}
|
||||
|
||||
private syncLhCards(v: NextFloorViewer, b: Building, pic: EnergyPicture, cars: ReturnType<NfView3d["liveCars"]>, media: MediaNow[], hass: HomeAssistant): void {
|
||||
const cards: LiveCard[] = [];
|
||||
const s = pic.summary;
|
||||
@@ -2663,6 +2687,12 @@ export class NfView3d extends LitElement {
|
||||
if (this.liveCardsOn && !this.dimmed) {
|
||||
cards.push(...roomClimateCards(hass, b, this.floorId, this.roomId));
|
||||
cards.push(...furniturePowerCards(hass, b, this.furnitureLinks ?? new Map(), this.floorId, this.roomId));
|
||||
for (const floor of b.floors) for (const item of floor.furniture) {
|
||||
if (!isHydronic(item.type) || item.hydronic?.card === false || (this.floorId && floor.id !== this.floorId) || !furnitureShown(hass, item)) continue;
|
||||
const room = this.roomId ? floor.rooms.find((r) => r.id === this.roomId) : null;
|
||||
if (this.roomId && (!room || !pointInPolygon([item.x, item.z], room.points))) continue;
|
||||
cards.push({ kind: "hydronic", item, readOnly: !!this._travel, at: { floorId: floor.id, x: item.x + (item.pin_offset?.x ?? 0), z: item.z + (item.pin_offset?.z ?? 0), y: mountBase(floor, item) + item.h + .3 + (item.pin_offset?.y ?? 0) } });
|
||||
}
|
||||
}
|
||||
if (JSON.stringify(cards) !== JSON.stringify(this._liveCards)) this._liveCards = cards;
|
||||
v.setLiveAnchors(
|
||||
@@ -2714,7 +2744,7 @@ 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);
|
||||
const climate = this.building?.floors.some((f) => f.rooms.some((r) => r.climate_card) || f.furniture.some((m) => m.power_card));
|
||||
const climate = this.building?.floors.some((f) => f.rooms.some((r) => r.climate_card) || f.furniture.some((m) => m.power_card || (isHydronic(m.type) && m.hydronic?.card !== false)));
|
||||
const climateToggle = climate ? this.renderCardToggle() : nothing;
|
||||
const roomNames = this.roomNamesButton ? html`<button class="nf-energy-item nf-flow-toggle nf-room-names-toggle" aria-pressed=${this.roomLabels} title=${translate(this.hass, "room_names_toggle_hint")} @click=${() => {
|
||||
this.roomLabels = !this.roomLabels;
|
||||
|
||||
@@ -11,6 +11,7 @@ import { pluginWatched } from "../../plugins/registry.ts";
|
||||
import type { HomeAssistant } from "../../types.ts";
|
||||
import { weatherEntity } from "../../weather.ts";
|
||||
import { utilityWatched } from "../../utilities.ts";
|
||||
import { hydronicRefs } from "../../hydronic-model.ts";
|
||||
|
||||
export interface WatchInputs {
|
||||
hass: HomeAssistant;
|
||||
@@ -44,6 +45,7 @@ function furnitureIds(inputs: WatchInputs): MaybeId[] {
|
||||
// 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, ...(m.values ?? []).map((v) => v.entity)]),
|
||||
...pieces.flatMap(hydronicRefs),
|
||||
...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)] : [])])),
|
||||
];
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { EntityRef, Furniture } from "./model.ts";
|
||||
|
||||
export const HYDRONIC_TYPES = ["heating_manifold", "buffer_tank", "freshwater_station"] as const;
|
||||
export const isHydronic = (type: string): boolean => (HYDRONIC_TYPES as readonly string[]).includes(type);
|
||||
export interface HydronicControl { command?: EntityRef; feedback?: EntityRef; inverted?: boolean }
|
||||
export interface HydronicCircuit {
|
||||
id: string; name: string; kind: "heating" | "cooling" | "changeover" | "pump";
|
||||
has_pump?: boolean; has_valve?: boolean;
|
||||
pump?: HydronicControl; valve?: HydronicControl;
|
||||
flow?: EntityRef; return?: EntityRef; power?: EntityRef;
|
||||
mode_entity?: EntityRef; cooling_value?: number;
|
||||
}
|
||||
export interface HydronicProbe { id: string; name: string; entity: EntityRef; level: number }
|
||||
export interface HydronicConfig {
|
||||
card?: boolean;
|
||||
circuits?: HydronicCircuit[];
|
||||
sensors?: HydronicProbe[];
|
||||
flow?: EntityRef; return?: EntityRef;
|
||||
pump?: HydronicControl; circulation?: HydronicControl;
|
||||
circulation_temperature?: EntityRef; hot_water?: EntityRef;
|
||||
}
|
||||
|
||||
export const newCircuit = (id: string, name = "Heizkreis"): HydronicCircuit => ({ id, name, kind: "heating", has_pump: true, has_valve: true });
|
||||
export function defaultHydronic(type: string): HydronicConfig {
|
||||
return { card: true, ...(type === "heating_manifold" ? { circuits: [newCircuit("c1", "Heizkreis 1")] } : {}),
|
||||
...(type === "buffer_tank" ? { sensors: Array.from({ length: 7 }, (_, i) => ({ id: `s${i + 1}`, name: `Fühler ${i + 1}`, entity: null, level: 1 - i / 6 })) } : {}) };
|
||||
}
|
||||
export function hydronicConfig(item: Pick<Furniture, "type" | "hydronic">): HydronicConfig { return { ...defaultHydronic(item.type), ...item.hydronic }; }
|
||||
export const hasPump = (c: HydronicCircuit): boolean => c.has_pump !== false;
|
||||
export const hasValve = (c: HydronicCircuit): boolean => c.kind !== "pump" && c.has_valve !== false;
|
||||
export const circuitX = (i: number, count: number): number => -.4 + .8 * (i + .5) / Math.max(1, count);
|
||||
export const realRef = (id: EntityRef | undefined): id is string => !!id && id !== "none";
|
||||
const controlRefs = (c: HydronicControl | undefined) => [c?.command, c?.feedback];
|
||||
export function hydronicRefs(item: Pick<Furniture, "type" | "hydronic">): string[] {
|
||||
if (!isHydronic(item.type)) return [];
|
||||
const h = hydronicConfig(item);
|
||||
return [...new Set([h.flow, h.return,
|
||||
...(item.type === "heating_manifold" ? (h.circuits ?? []).flatMap((c) => [c.flow, c.return, c.power, c.mode_entity, ...(hasPump(c) ? controlRefs(c.pump) : []), ...(hasValve(c) ? controlRefs(c.valve) : [])]) : []),
|
||||
...(item.type === "buffer_tank" ? (h.sensors ?? []).map((s) => s.entity) : []),
|
||||
...(item.type === "freshwater_station" ? [h.circulation_temperature, h.hot_water, ...controlRefs(h.pump), ...controlRefs(h.circulation)] : []),
|
||||
].filter(realRef))];
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { entity, floorWith, hassOf } from "./entities/fixtures.ts";
|
||||
import { emptyBuilding, FURNITURE_SIZE, normalizeBuilding, type Furniture } from "./model.ts";
|
||||
import { defaultHydronic, hasValve, hydronicConfig, hydronicRefs, isHydronic, newCircuit } from "./hydronic-model.ts";
|
||||
import { hydronicReading, hydronicVisual, readControl, temperatureC } from "./hydronic-values.ts";
|
||||
import { watchedEntities } from "./components/view3d/watch-list.ts";
|
||||
|
||||
const piece = (type: string, extra: Partial<Furniture> = {}): Furniture => { const [w,d,h] = FURNITURE_SIZE[type as keyof typeof FURNITURE_SIZE]; return { id: "hyd", type, x: 0, z: 0, w,d,h,rotation:0,variant:null, ...extra }; };
|
||||
const native = (id: string, value: number | boolean, extra: Record<string, unknown> = {}) => entity(id, "open", { symcon_id: 123, symcon_variable_type: typeof value === "boolean" ? 0 : 2, symcon_value: value, symcon_min: 0, symcon_max: 100, ...extra });
|
||||
|
||||
test("a buffer starts with seven unique probes from top to bottom and remains freely configurable after persistence", () => {
|
||||
const item = piece("buffer_tank", { hydronic: defaultHydronic("buffer_tank") });
|
||||
item.hydronic!.sensors!.forEach((s, i) => assert.ok(Math.abs(s.level - (6 - i) / 6) < 1e-10));
|
||||
assert.equal(new Set(item.hydronic!.sensors!.map((s) => s.id)).size, 7);
|
||||
item.hydronic!.sensors!.push({ id:"extra",name:"Frei",level:.73,entity:"cover.temperature" });
|
||||
const b = { ...emptyBuilding(), floors: [floorWith([], { furniture:[item] })] };
|
||||
assert.equal(hydronicConfig(normalizeBuilding(JSON.parse(JSON.stringify(b))).floors[0].furniture[0]).sensors!.at(-1)!.level, .73);
|
||||
assert.equal(hydronicConfig(piece("buffer_tank", { hydronic: { sensors: [] } })).sensors!.length, 0, "an explicitly empty list is not replaced by the defaults");
|
||||
});
|
||||
|
||||
test("feedback wins even at zero or offline; the command is used only when no feedback is assigned", () => {
|
||||
const h = hassOf([native("cover.cmd", true), native("lock.feedback", false)]);
|
||||
assert.equal(readControl(h, { command:"cover.cmd",feedback:"lock.feedback" }).running, false);
|
||||
h.states["lock.feedback"] = { ...h.states["lock.feedback"],state:"unavailable" };
|
||||
assert.equal(readControl(h, { command:"cover.cmd",feedback:"lock.feedback" }).running, null);
|
||||
assert.equal(readControl(h, { command:"cover.cmd" }).running, true);
|
||||
assert.equal(readControl(h, { command:"cover.cmd", feedback:"none" }).running, true);
|
||||
assert.equal(readControl(h, {}).id, null);
|
||||
});
|
||||
|
||||
test("native integer and float ranges drive visuals, while inversion leaves raw readings untouched", () => {
|
||||
const h = hassOf([native("climate.valve",128,{symcon_variable_type:1,symcon_max:255,symcon_formatted:"128"})]);
|
||||
const valve = { feedback:"climate.valve",inverted:true };
|
||||
const item = piece("heating_manifold",{hydronic:{circuits:[{...newCircuit("c"),valve}]}});
|
||||
const raw = readControl(h,valve), visual = hydronicVisual(h,item,"floor",0);
|
||||
assert.equal(raw.value,128); assert.equal(raw.percent,128/255*100);
|
||||
assert.equal(visual.circuits[0].valve,100-128/255*100);
|
||||
assert.equal(hydronicReading(h,"Ventil","climate.valve")!.text,"128");
|
||||
h.states["climate.valve"] = native("climate.valve",.4,{symcon_max:1});
|
||||
assert.equal(readControl(h,valve).percent,40);
|
||||
});
|
||||
|
||||
test("a pure feed pump has no valve, and changing operating mode uses raw Boolean/Integer values without name guesses", () => {
|
||||
const h = hassOf([native("cover.Garage",true),native("lock.mode",false)]);
|
||||
const c = { ...newCircuit("feed"),kind:"pump" as const,pump:{feedback:"cover.Garage"},valve:{feedback:"unused"} };
|
||||
const switched = { ...newCircuit("mixed"),kind:"changeover" as const,mode_entity:"lock.mode",cooling_value:0 };
|
||||
const item=piece("heating_manifold",{hydronic:{circuits:[c,switched]}});
|
||||
assert.equal(hasValve(c),false); assert.ok(!hydronicRefs(item).includes("unused"));
|
||||
assert.equal(hydronicVisual(h,item,"floor",0).circuits[0].valve,null);
|
||||
assert.equal(hydronicVisual(h,item,"floor",0).circuits[1].cooling,true);
|
||||
h.states["lock.mode"] = native("lock.mode",7,{symcon_variable_type:1}); switched.cooling_value=7;
|
||||
assert.equal(hydronicVisual(h,item,"floor",0).circuits[1].cooling,true);
|
||||
});
|
||||
|
||||
test("zero/negative temperatures and units are retained, and missing values never turn into fake readings", () => {
|
||||
const h=hassOf([native("cover.c",0,{unit_of_measurement:"°C"}),native("sensor.f",32,{unit_of_measurement:"°F"}),native("sensor.k",273.15,{unit_of_measurement:"K"}),native("sensor.neg",-5,{unit_of_measurement:"°C"})]);
|
||||
assert.equal(temperatureC(h,"cover.c"),0); assert.equal(temperatureC(h,"sensor.f"),0); assert.equal(temperatureC(h,"sensor.k"),0);
|
||||
assert.equal(temperatureC(h,"sensor.neg"),-5); assert.equal(hydronicReading(h,"VL","sensor.neg")!.text,"-5 °C");
|
||||
assert.equal(hydronicReading(h,"RL","none"),null); assert.equal(hydronicReading(h,"RL","missing")!.text,"–");
|
||||
h.states["sensor.neg"] = {...h.states["sensor.neg"],state:"unavailable"}; assert.equal(temperatureC(h,"sensor.neg"),null);
|
||||
});
|
||||
|
||||
test("the view watches every circuit, buffer probe and fresh-water datapoint, independent of climate cards or heatmaps", () => {
|
||||
const manifold=piece("heating_manifold",{hydronic:{circuits:[{...newCircuit("c"),flow:"a",return:"b",power:"c",pump:{command:"d",feedback:"e"},valve:{command:"f",feedback:"g"},mode_entity:"h"}]}});
|
||||
const buffer=piece("buffer_tank",{id:"buffer",hydronic:{flow:"i",return:"j",sensors:[{id:"s",name:"s",entity:"k",level:.7}]}});
|
||||
const fresh=piece("freshwater_station",{id:"fresh",hydronic:{flow:"l",return:"m",hot_water:"n",circulation_temperature:"o",pump:{feedback:"p",command:"q"},circulation:{command:"r",feedback:"s"}}});
|
||||
const b={...emptyBuilding(),floors:[floorWith([],{furniture:[manifold,buffer,fresh]})]};
|
||||
const ids=watchedEntities({hass:hassOf([]),building:b,openingLinks:new Map(),furnitureLinks:new Map(),needsRoomSensors:false,alertSources:null,weatherEntityId:null});
|
||||
for(const id of "abcdefghijklmnopqrs") assert.ok(ids.includes(id),id);
|
||||
assert.equal(isHydronic("buffer_tank"),true); assert.equal(isHydronic("radiator"),false);
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { Furniture } from "./model.ts";
|
||||
import type { HomeAssistant } from "./types.ts";
|
||||
import { nativeBool, nativeNumber, nativeText, nativeValue } from "./entities/symcon-values.ts";
|
||||
import { hasPump, hasValve, hydronicConfig, realRef, type HydronicControl } from "./hydronic-model.ts";
|
||||
|
||||
export interface HydronicReading { id: string; label: string; text: string; value: number | null; icon?: string | null }
|
||||
export interface ControlState { id: string | null; value: number | boolean | null; percent: number | null; running: boolean | null; feedback: boolean }
|
||||
export interface HydronicVisual {
|
||||
id: string; floorId: string; item: Furniture; base: number;
|
||||
circuits: { id: string; pump: boolean | null; valve: number | null; cooling: boolean; flow: number | null; return: number | null }[];
|
||||
probes: { level: number; value: number | null }[];
|
||||
temperatures: (number | null)[];
|
||||
animate?: boolean;
|
||||
pump: boolean | null; circulation: boolean | null;
|
||||
}
|
||||
|
||||
/** Readback always wins, including an unavailable readback; never substitute the command in that case. */
|
||||
export function readControl(hass: HomeAssistant, binding: HydronicControl | undefined): ControlState {
|
||||
const feedback = realRef(binding?.feedback), id = feedback ? binding!.feedback! : realRef(binding?.command) ? binding!.command! : null;
|
||||
const st = id ? hass.states[id] : undefined, raw = nativeValue(st);
|
||||
if (!st || raw === null) return { id, value: null, percent: null, running: null, feedback };
|
||||
if (st.attributes.symcon_variable_type === 0 || typeof raw === "boolean") {
|
||||
const value = nativeBool(st);
|
||||
return { id, value, percent: value === null ? null : value ? 100 : 0, running: value, feedback };
|
||||
}
|
||||
const value = nativeNumber(st), min = Number(st.attributes.symcon_min ?? 0), max = Number(st.attributes.symcon_max ?? 100);
|
||||
const percent = value === null ? null : Math.max(0, Math.min(100, 100 * (value - min) / (max > min ? max - min : 100)));
|
||||
return { id, value, percent, running: percent === null ? null : percent > 0, feedback };
|
||||
}
|
||||
export function temperatureC(hass: HomeAssistant, id: string | null | undefined): number | null {
|
||||
if (!realRef(id)) return null;
|
||||
const st = hass.states[id], n = nativeNumber(st);
|
||||
if (n === null) return null;
|
||||
const unit = String(st?.attributes.unit_of_measurement ?? "°C").trim();
|
||||
return unit === "°F" || unit === "℉" ? (n - 32) * 5 / 9 : unit === "K" ? n - 273.15 : n;
|
||||
}
|
||||
export function hydronicReading(hass: HomeAssistant, label: string, id: string | null | undefined): HydronicReading | null {
|
||||
if (!realRef(id)) return null;
|
||||
const st = hass.states[id], value = nativeNumber(st), text = nativeText(st), unit = st?.attributes.unit_of_measurement;
|
||||
return { id, label, value, text: value !== null && unit && typeof st?.attributes.symcon_formatted !== "string" ? `${text} ${unit}` : text };
|
||||
}
|
||||
export function hydronicVisual(hass: HomeAssistant, item: Furniture, floorId: string, base: number): HydronicVisual {
|
||||
const h = hydronicConfig(item);
|
||||
return { id: item.id, floorId, item, base,
|
||||
circuits: (h.circuits ?? []).map((c) => {
|
||||
const valve = hasValve(c) ? readControl(hass, c.valve).percent : null;
|
||||
const mode = realRef(c.mode_entity) ? nativeValue(hass.states[c.mode_entity]) : null;
|
||||
return { id: c.id, pump: hasPump(c) ? readControl(hass, c.pump).running : null, valve: valve === null ? null : c.valve?.inverted ? 100 - valve : valve,
|
||||
cooling: c.kind === "cooling" || (c.kind === "changeover" && mode !== null && Number(mode) === (c.cooling_value ?? 1)), flow: temperatureC(hass, c.flow), return: temperatureC(hass, c.return) };
|
||||
}),
|
||||
probes: (h.sensors ?? []).map((s) => ({ level: s.level, value: temperatureC(hass, s.entity) })),
|
||||
temperatures: [h.flow, h.return, h.circulation_temperature, h.hot_water].map((id) => temperatureC(hass, id)),
|
||||
pump: readControl(hass, h.pump).running, circulation: readControl(hass, h.circulation).running,
|
||||
};
|
||||
}
|
||||
@@ -1834,6 +1834,9 @@ const DE = {
|
||||
furn_inverter: "Wechselrichter",
|
||||
furn_home_battery: "Stromspeicher",
|
||||
furn_wallbox: "Wallbox",
|
||||
furn_heating_manifold: "Heiz-/Kühlkreisverteiler",
|
||||
furn_buffer_tank: "Pufferspeicher",
|
||||
furn_freshwater_station: "Frischwasserstation",
|
||||
furn_entity: "Gerät (Schalter, Steckdose …)",
|
||||
furn_state_entity: "Zustand von (optional)",
|
||||
furn_state_entity2: "Zweiter Zustand (andere Hälfte)",
|
||||
@@ -3875,6 +3878,9 @@ const EN: Record<Key, string> = {
|
||||
furn_inverter: "Solar inverter",
|
||||
furn_home_battery: "Home battery",
|
||||
furn_wallbox: "Wallbox",
|
||||
furn_heating_manifold: "Heating/cooling manifold",
|
||||
furn_buffer_tank: "Buffer tank",
|
||||
furn_freshwater_station: "Fresh water station",
|
||||
furn_group_kitchen: "Kitchen",
|
||||
furn_group_sleeping: "Sleeping",
|
||||
furn_group_bath: "Bath & laundry",
|
||||
|
||||
@@ -164,7 +164,7 @@ test("one shared effect timer stops for no participants, hidden views/document,
|
||||
assert.equal(lamps, 2);
|
||||
viewer.scheduleEffects();
|
||||
const noop = { dispose() {}, disconnect() {}, remove() {} };
|
||||
for (const key of ["weatherLayer", "mapLayer", "energyLayer", "soundLayer", "screenLayer", "pictureLayer", "waterLayer", "resizeObserver", "controls", "patternTexture", "blindTexture", "haloTexture", "labels"]) viewer[key] = noop;
|
||||
for (const key of ["weatherLayer", "mapLayer", "energyLayer", "soundLayer", "screenLayer", "pictureLayer", "waterLayer", "hydronicLayer", "resizeObserver", "controls", "patternTexture", "blindTexture", "haloTexture", "labels"]) viewer[key] = noop;
|
||||
viewer.ground = { geometry: noop, material: noop }; viewer.robots = new Map(); viewer.robotTrails = new Map(); viewer.trailTimers = new Map(); viewer.clear = () => {}; viewer.buildRoofMesh = () => {};
|
||||
viewer.renderer = { dispose() {}, forceContextLoss() {}, domElement: noop };
|
||||
const previousCancel = globalThis.cancelAnimationFrame;
|
||||
|
||||
@@ -23,6 +23,7 @@ import { fromCelsius, tempUnit } from "../devices.ts";
|
||||
import { trendButton } from "../components/trend-button.ts";
|
||||
import { loggedEntities } from "../trend-data.ts";
|
||||
import type { FurniturePowerCard } from "./furniture-power-card.ts";
|
||||
import type { Furniture } from "../model.ts";
|
||||
|
||||
export interface HouseCard {
|
||||
kind: "house";
|
||||
@@ -65,7 +66,8 @@ export interface HeatPumpCard {
|
||||
pump: HeatPumpInfo;
|
||||
}
|
||||
|
||||
export type LiveCard = HouseCard | CarCard | MediaCard | PrinterCard | HeatPumpCard | RoomClimateCard | FurniturePowerCard;
|
||||
export interface HydronicCard { kind: "hydronic"; item: Furniture; readOnly: boolean; at: PlanPoint }
|
||||
export type LiveCard = HouseCard | CarCard | MediaCard | PrinterCard | HeatPumpCard | RoomClimateCard | FurniturePowerCard | HydronicCard;
|
||||
|
||||
/** 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;
|
||||
@@ -248,6 +250,7 @@ export function unstackLhCards(root: ParentNode): void {
|
||||
const placed: { x0: number; x1: number; y0: number; y1: number }[] = [];
|
||||
// a card near the edge slides back into the view (on a phone it was cut off); its thread still points home
|
||||
const width = cards[0]?.parentElement?.clientWidth ?? 0;
|
||||
const height = cards[0]?.parentElement?.clientHeight ?? 0;
|
||||
const items = cards
|
||||
.map((el) => {
|
||||
const [anchor, w] = [Number(el.dataset.x), el.offsetWidth];
|
||||
@@ -258,6 +261,17 @@ export function unstackLhCards(root: ParentNode): void {
|
||||
.sort((a, b) => b.y - a.y);
|
||||
for (const it of items) {
|
||||
let bottom = it.y;
|
||||
// Hydraulic cards contain several readings: use nearby free columns before stacking them out of view.
|
||||
if (it.el.classList.contains("live-card-hydronic") && width > it.w + 16 && height > it.h + 16) {
|
||||
const xs = [it.x, it.w / 2 + 8, width - it.w / 2 - 8, ...placed.flatMap((p) => [p.x0 - it.w / 2 - 8, p.x1 + it.w / 2 + 8])]
|
||||
.filter((x) => x >= it.w / 2 + 8 && x <= width - it.w / 2 - 8).sort((a, b) => Math.abs(a - it.x) - Math.abs(b - it.x));
|
||||
const ys = [Math.max(it.h + 8, Math.min(height - 8, bottom)), ...placed.flatMap((p) => [p.y0 - 8, p.y1 + it.h + 8])].filter((y) => y >= it.h + 8 && y <= height - 8);
|
||||
let position: { x: number; y: number } | undefined;
|
||||
for (const y of ys) { for (const x of xs) {
|
||||
if (!placed.some((p) => x - it.w / 2 < p.x1 + 6 && x + it.w / 2 > p.x0 - 6 && y - it.h < p.y1 + 6 && y > p.y0 - 6)) { position = { x, y }; break; }
|
||||
} if (position) break; }
|
||||
if (position) { it.x = position.x; bottom = position.y; }
|
||||
}
|
||||
for (let guard = 0; guard < 12; guard++) {
|
||||
const r = { x0: it.x - it.w / 2, x1: it.x + it.w / 2, y0: bottom - it.h, y1: bottom };
|
||||
const hit = placed.find((p) => r.x0 < p.x1 + 6 && r.x1 > p.x0 - 6 && r.y0 < p.y1 + 6 && r.y1 > p.y0 - 6);
|
||||
@@ -266,6 +280,7 @@ export function unstackLhCards(root: ParentNode): void {
|
||||
}
|
||||
placed.push({ x0: it.x - it.w / 2, x1: it.x + it.w / 2, y0: bottom - it.h, y1: bottom });
|
||||
const lift = it.y - bottom;
|
||||
it.el.style.setProperty("--live-dx", `${Math.round(Number(it.el.dataset.x) - it.x)}px`);
|
||||
it.el.style.transform = `translate(${Math.round(it.x)}px, ${Math.round(bottom)}px) translate(-50%, -100%)`;
|
||||
it.el.style.setProperty("--live-thread", `${Math.round(18 + lift)}px`);
|
||||
}
|
||||
@@ -338,7 +353,7 @@ function furniturePowerCard(hass: HomeAssistant | undefined, c: FurniturePowerCa
|
||||
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 === "roomclimate" ? roomClimateCard(hass, c, i) : c.kind === "power" ? furniturePowerCard(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)))}
|
||||
${cards.map((c, i) => (c.kind === "roomclimate" ? roomClimateCard(hass, c, i) : c.kind === "power" ? furniturePowerCard(hass, c, i) : c.kind === "hydronic" ? html`<div class="live-card live-card-hydronic" data-i=${i} data-furniture=${c.item.id}><nf-hydronic-card .hass=${hass} .item=${c.item} .readOnly=${c.readOnly}></nf-hydronic-card></div>` : 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>`;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
declare const __NF_HYDRONIC_HASH__: string;
|
||||
let loaded: Promise<typeof import("./components/hydronic-card.ts")> | undefined;
|
||||
export function loadHydronics() {
|
||||
const url = new URL(`./nextfloor-hydronics.js?v=${__NF_HYDRONIC_HASH__}`, import.meta.url).href;
|
||||
return loaded ??= import(/* @vite-ignore */ url).catch((error) => { loaded = undefined; throw error; });
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import type { StairConfig } from "./geometry/stairs.ts";
|
||||
import type { LampModel } from "./viewer/viewer3d.ts";
|
||||
import type { FurnitureColors } from "./furniture-colors.ts";
|
||||
import type { ShowWhen } from "./entities/visibility.ts";
|
||||
import type { HydronicConfig } from "./hydronic-model.ts";
|
||||
|
||||
export type Vec2 = [number, number];
|
||||
|
||||
@@ -229,6 +230,7 @@ export interface ScreenPicture {
|
||||
}
|
||||
|
||||
export interface Furniture extends LightEffectConfig {
|
||||
hydronic?: HydronicConfig | null;
|
||||
/** A tap on the item runs this own action (open a path, an entity's details, a service, a browser_mod popup); null = the item's usual tap. */
|
||||
tap?: Pick<CustomButton, "action" | "target" | "data"> | null;
|
||||
/** Fixed against moving by accident. */
|
||||
@@ -1256,6 +1258,9 @@ export const FURNITURE_TYPES = [
|
||||
"grid_point",
|
||||
"parking",
|
||||
"fridge_smart",
|
||||
"heating_manifold",
|
||||
"buffer_tank",
|
||||
"freshwater_station",
|
||||
"stairwell",
|
||||
] as const;
|
||||
|
||||
@@ -1267,7 +1272,7 @@ export const FURNITURE_GROUPS: Record<string, FurnitureType[]> = {
|
||||
kitchen: ["kitchen", "kitchen_wall", "kitchen_tall", "island", "worktop", "sink", "stove", "dishwasher", "fridge"],
|
||||
sleeping: ["bed", "bunk_bed", "nightstand", "wardrobe", "dresser"],
|
||||
bath: ["bathtub", "shower", "wc", "washbasin", "washer", "dryer"],
|
||||
work: ["desk", "worktop", "office_chair", "tall_cabinet", "coat_rack", "radiator", "stairs", "robot_vacuum"],
|
||||
work: ["desk", "worktop", "office_chair", "tall_cabinet", "coat_rack", "radiator", "stairs", "robot_vacuum", "heating_manifold", "buffer_tank", "freshwater_station"],
|
||||
vehicles: ["parking"],
|
||||
};
|
||||
|
||||
@@ -1459,6 +1464,9 @@ export const FURNITURE_SIZE: Record<FurnitureType, [number, number, number]> = {
|
||||
inverter: [0.5, 0.2, 0.65],
|
||||
home_battery: [0.6, 0.25, 1.1],
|
||||
wallbox: [0.3, 0.15, 0.42],
|
||||
heating_manifold: [1.5, 0.35, 1.1],
|
||||
buffer_tank: [0.85, 0.85, 1.85],
|
||||
freshwater_station: [0.65, 0.28, 0.9],
|
||||
// the meter cabinet hangs on the wall as well
|
||||
meter: [0.55, 0.21, 1.1],
|
||||
// the grid connection: a small street cabinet at the edge of the plot
|
||||
|
||||
@@ -15,6 +15,7 @@ import { packModel, placement } from "./packs.ts";
|
||||
import { shapedStairs } from "./stairs.ts";
|
||||
import { cabinet } from "./parts.ts";
|
||||
import { EDGE_FAINT, EDGE_FURN, M } from "./palette.ts";
|
||||
import { hydronicModel } from "./hydronic.ts";
|
||||
|
||||
/** What a model returns to say whether it casts a contact shadow on the floor. */
|
||||
type Shadow = "yes" | "no";
|
||||
@@ -22,6 +23,11 @@ type Shadow = "yes" | "no";
|
||||
/** Draws one built-in model. Returns "no" for items that hang on a wall or lie flat, "yes" for those standing on the floor. */
|
||||
function drawBuiltIn(b: Builder, f: Furniture, w: number, d: number, h: number, base: number): Shadow {
|
||||
switch (f.type) {
|
||||
case "heating_manifold":
|
||||
case "buffer_tank":
|
||||
case "freshwater_station":
|
||||
hydronicModel(b, f, w, d, h);
|
||||
return "yes";
|
||||
case "sofa":
|
||||
if (f.variant === "l" || f.variant === "u") shapedSofa(b, w, d, h, f.variant);
|
||||
else sofa(b, w, d, h, Math.max(1, Math.round((w - 0.4) / 0.62)));
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { Furniture } from "../../model.ts";
|
||||
import { circuitX, hasPump, hasValve, hydronicConfig } from "../../hydronic-model.ts";
|
||||
import { Builder } from "./builder.ts";
|
||||
import { EDGE_FAINT, EDGE_FURN, M, material } from "./palette.ts";
|
||||
|
||||
const hot = material(0x9d413e, 0xc86b56), cold = material(0x285f85, 0x4e99bd), brass = material(0x92724b, 0xc9a56a);
|
||||
export function hydronicModel(b: Builder, f: Furniture, w: number, d: number, h: number): void {
|
||||
const cfg = hydronicConfig(f), z = d * .3;
|
||||
const pipe = (x: number, y0: number, y1: number, r: number, m = hot) => b.cylinder(x, z, r, y0, y1, m, 10, EDGE_FAINT);
|
||||
const face = (x: number, y: number, r: number, m = M.dark) => b.lyingCylinder("z", x, z, y - r, y + r, d * .5, r * 2, m, 16, EDGE_FURN);
|
||||
if (f.type === "buffer_tank") {
|
||||
const r = Math.min(w, d) * .46;
|
||||
b.cylinder(0, 0, r, h * .06, h * .94, M.darkBody, 24, EDGE_FURN);
|
||||
b.cylinder(0, 0, r * .96, h * .94, h * .99, M.metal, 24, EDGE_FAINT);
|
||||
b.cylinder(0, 0, r * .98, h * .035, h * .06, M.metal, 24, EDGE_FAINT);
|
||||
for (const y of [.12, .88]) b.lyingCylinder("x", r * .95, 0, h * y - .025, h * y + .025, w * .14, .05, y > .5 ? hot : cold, 12, EDGE_FURN);
|
||||
for (const s of cfg.sensors ?? []) {
|
||||
const y = h * (.1 + .8 * s.level);
|
||||
b.lyingCylinder("z", 0, r, y - .018, y + .018, .035, .036, brass, 10, EDGE_FAINT);
|
||||
b.ring(0, y, .025, r + .022, 12, EDGE_FAINT);
|
||||
}
|
||||
for (const x of [-1, 1]) for (const zz of [-1, 1]) b.cylinder(x * r * .52, zz * r * .52, .025, 0, h * .05, M.metal);
|
||||
return;
|
||||
}
|
||||
b.block({ x: [-w * .49, w * .49], y: [h * .02, h * .98], z: [-d * .48, -d * .35] }, M.darkBody, EDGE_FURN);
|
||||
if (f.type === "heating_manifold") {
|
||||
for (const [y, m] of [[.83, hot], [.18, cold]] as const) b.lyingCylinder("x", 0, z, h * y - .027, h * y + .027, w * .92, .054, m, 12, EDGE_FURN);
|
||||
const circuits = cfg.circuits ?? [], column = w * .8 / Math.max(1, circuits.length);
|
||||
circuits.forEach((c, i) => {
|
||||
const x = w * circuitX(i, circuits.length), r = Math.min(column * .35, h * .075);
|
||||
pipe(x - column * .22, h * .18, h * .83, Math.min(.018, column * .09));
|
||||
pipe(x + column * .22, h * .18, h * .83, Math.min(.018, column * .09), cold);
|
||||
if (hasPump(c)) face(x, h * .6, r, M.dark);
|
||||
if (hasValve(c)) {
|
||||
b.block({ x: [x - r * .7, x + r * .7], y: [h * .38, h * .48], z: [0, d * .57] }, brass, EDGE_FAINT);
|
||||
face(x, h * .43, r * .65, M.white);
|
||||
}
|
||||
for (const [y, xx] of [[.76, x - column * .22], [.25, x + column * .22]]) face(xx, h * y, Math.min(r * .4, .025), M.white);
|
||||
});
|
||||
} else {
|
||||
b.block({ x: [-w * .24, w * .24], y: [h * .35, h * .84], z: [-d * .2, d * .12] }, brass, EDGE_FURN);
|
||||
for (let i = 0; i < 9; i++) b.seg(-w * .22 + i * w * .055, h * .38, d * .13, -w * .22 + i * w * .055, h * .81, d * .13, EDGE_FAINT);
|
||||
for (const [i, x] of [-.36, -.12, .12, .36].entries()) {
|
||||
pipe(w * x, 0, h * (i < 2 ? .9 : .35), .018, i === 1 ? cold : hot);
|
||||
face(w * x, h * .28, .028, M.white);
|
||||
}
|
||||
face(-w * .3, h * .55, Math.min(w, h) * .085, M.dark);
|
||||
face(w * .3, h * .55, Math.min(w, h) * .085, M.dark);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { Scene } from "three";
|
||||
import type { Furniture } from "../model.ts";
|
||||
import { newCircuit } from "../hydronic-model.ts";
|
||||
import { hydronicVisual } from "../hydronic-values.ts";
|
||||
import { entity, hassOf } from "../entities/fixtures.ts";
|
||||
import { HydronicLayer } from "./live-hydronics.ts";
|
||||
|
||||
test("live pumps animate reported operation, valve pointers follow visual inversion and floor/mount transforms stay attached", () => {
|
||||
let visible=true;
|
||||
const scene=new Scene(),layer=new HydronicLayer(scene,()=>({y:3,dy:0,visible}));
|
||||
const h=hassOf([entity("sensor.pump","on",{symcon_id:1,symcon_variable_type:0,symcon_value:true}),entity("sensor.valve","25",{symcon_id:2,symcon_variable_type:1,symcon_value:25,symcon_min:0,symcon_max:100})]);
|
||||
const item: Furniture={id:"test",type:"heating_manifold",x:2,z:4,w:1.5,d:.35,h:1.1,rotation:90,variant:null,hydronic:{circuits:[{...newCircuit("c"),pump:{feedback:"sensor.pump"},valve:{feedback:"sensor.valve",inverted:true}}]}};
|
||||
const spot=hydronicVisual(h,item,"f",.9); layer.set([spot]);
|
||||
assert.equal(layer.step(350),true);
|
||||
const group=layer.group.getObjectByName("hydronic-test")!,rotor=group.getObjectByName("hydronic-pump-0")!,valve=group.getObjectByName("hydronic-valve-0")!;
|
||||
assert.deepEqual(group.position.toArray(),[2,3.9,4]); assert.equal(rotor.rotation.z,1); assert.equal(valve.rotation.z,.75*Math.PI/2);
|
||||
visible=false; assert.equal(layer.step(700),false); assert.equal(group.visible,false);
|
||||
visible=true; layer.set([{...spot,animate:false}]); assert.equal(layer.step(1050),false); assert.equal(rotor.rotation.z,0);
|
||||
layer.set([]); assert.equal(layer.group.children.length,0); layer.dispose(); assert.equal(scene.children.length,0);
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
import { BoxGeometry, Color, Group, Mesh, MeshBasicMaterial, SphereGeometry, type Scene } from "three";
|
||||
import { circuitX, hasPump, hasValve, hydronicConfig } from "../hydronic-model.ts";
|
||||
import type { HydronicVisual } from "../hydronic-values.ts";
|
||||
import type { FloorLift } from "./live-energy.ts";
|
||||
|
||||
interface Part { mesh: Mesh<BoxGeometry | SphereGeometry, MeshBasicMaterial>; kind: "pump" | "valve" | "temperature"; circuit?: number; probe?: number; temp?: number; circulation?: boolean }
|
||||
interface View { spot: HydronicVisual; group: Group; parts: Part[] }
|
||||
const heatColor = (value: number | null) => value === null ? new Color(0x69717c) : new Color().setHSL((1 - Math.max(0, Math.min(1, value / 85))) * .62, .8, .55);
|
||||
|
||||
/** Moving pump faces, valve pointers and actual probe colours, independent of the static furniture mesh. */
|
||||
export class HydronicLayer {
|
||||
readonly group = new Group();
|
||||
private views = new Map<string, View>();
|
||||
private readonly scene: Scene;
|
||||
private readonly lift: FloorLift;
|
||||
constructor(scene: Scene, lift: FloorLift) { this.scene = scene; this.lift = lift; this.group.name = "live-hydronics"; scene.add(this.group); }
|
||||
private remove(view: View) {
|
||||
view.group.traverse((o) => { if (o instanceof Mesh) { o.geometry.dispose(); (o.material as MeshBasicMaterial).dispose(); } });
|
||||
this.group.remove(view.group);
|
||||
}
|
||||
set(spots: HydronicVisual[]) {
|
||||
const keep = new Set(spots.map((s) => s.id));
|
||||
for (const [id, v] of this.views) if (!keep.has(id)) { this.remove(v); this.views.delete(id); }
|
||||
for (const spot of spots) {
|
||||
let view = this.views.get(spot.id);
|
||||
if (view?.spot.item !== spot.item) { if (view) this.remove(view); view = this.build(spot); this.views.set(spot.id, view); }
|
||||
view.spot = spot;
|
||||
}
|
||||
}
|
||||
private build(spot: HydronicVisual): View {
|
||||
const group = new Group(), parts: Part[] = [], f = spot.item, h = hydronicConfig(f);
|
||||
const add = (x: number, y: number, z: number, r: number, kind: Part["kind"], data: Partial<Part> = {}) => {
|
||||
const mesh = new Mesh(kind === "temperature" ? new SphereGeometry(r, 10, 6) : new BoxGeometry(r * 1.6, r * .3, .012), new MeshBasicMaterial({ color: 0x69717c, depthWrite: true }));
|
||||
mesh.name = `hydronic-${kind}-${data.circulation ? "circulation" : data.circuit ?? data.probe ?? data.temp ?? 0}`;
|
||||
mesh.position.set(x, y, z); group.add(mesh); parts.push({ mesh, kind, ...data });
|
||||
};
|
||||
if (f.type === "heating_manifold") {
|
||||
const circuits = h.circuits ?? [], column = f.w * .8 / Math.max(1, circuits.length), r = Math.min(column * .35, f.h * .075);
|
||||
circuits.forEach((c, i) => {
|
||||
const x = f.w * circuitX(i, circuits.length);
|
||||
if (hasPump(c)) { add(x, f.h * .6, f.d * .565, r * .8, "pump", { circuit: i }); add(x, f.h * .6, f.d * .57, r * .8, "pump", { circuit: i }); parts.at(-1)!.mesh.userData.angle = Math.PI / 2; }
|
||||
if (hasValve(c)) add(x, f.h * .43, f.d * .58, r * .65, "valve", { circuit: i });
|
||||
add(x - column * .22, f.h * .76, f.d * .57, Math.min(r * .32, .018), "temperature", { circuit: i, temp: 0 });
|
||||
add(x + column * .22, f.h * .25, f.d * .57, Math.min(r * .32, .018), "temperature", { circuit: i, temp: 1 });
|
||||
});
|
||||
} else if (f.type === "buffer_tank") {
|
||||
(h.sensors ?? []).forEach((s, i) => add(0, f.h * (.1 + .8 * s.level), Math.min(f.w, f.d) * .46 + .025, .021, "temperature", { probe: i }));
|
||||
} else {
|
||||
for (const [i, x] of [-.36, -.12, .12, .36].entries()) add(x * f.w, f.h * .28, f.d * .57, .02, "temperature", { temp: i });
|
||||
for (const [i, x] of [-.3, .3].entries()) {
|
||||
for (const angle of [0, Math.PI / 2]) { add(x * f.w, f.h * .55, f.d * .57, Math.min(f.w, f.h) * .065, "pump", { circulation: i === 1 }); parts.at(-1)!.mesh.userData.angle = angle; }
|
||||
}
|
||||
}
|
||||
group.rotation.set((f.tilt_x ?? 0) * Math.PI / 180, -f.rotation * Math.PI / 180, (f.tilt_z ?? 0) * Math.PI / 180, "YZX");
|
||||
group.scale.x = f.mirror ? -1 : 1;
|
||||
group.name = `hydronic-${f.id}`; this.group.add(group); return { spot, group, parts };
|
||||
}
|
||||
step(now: number): boolean {
|
||||
let moving = false;
|
||||
for (const v of this.views.values()) {
|
||||
const { spot } = v, l = this.lift(spot.floorId);
|
||||
v.group.visible = l.visible; v.group.position.set(spot.item.x, l.y + spot.base, spot.item.z);
|
||||
for (const p of v.parts) {
|
||||
const c = p.circuit === undefined ? undefined : spot.circuits[p.circuit];
|
||||
if (p.kind === "temperature") {
|
||||
const value = p.probe !== undefined ? spot.probes[p.probe]?.value : c ? p.temp === 0 ? c.flow : c.return : spot.temperatures[p.temp ?? 0];
|
||||
p.mesh.material.color.copy(heatColor(value ?? null));
|
||||
} else if (p.kind === "pump") {
|
||||
const running = c ? c.pump : p.circulation ? spot.circulation : spot.pump;
|
||||
p.mesh.material.color.set(running === null ? 0x89909a : running ? c?.cooling ? 0x50b8ff : 0x6fe1a2 : 0x465361);
|
||||
p.mesh.rotation.z = Number(p.mesh.userData.angle ?? 0) + (running && spot.animate !== false ? now / 350 : 0);
|
||||
moving ||= l.visible && running === true && spot.animate !== false;
|
||||
} else {
|
||||
p.mesh.rotation.z = c?.valve === null || c?.valve === undefined ? 0 : c.valve / 100 * Math.PI / 2;
|
||||
p.mesh.material.color.set(c?.valve === null ? 0x89909a : c?.cooling ? 0x50b8ff : 0xf6b35b);
|
||||
}
|
||||
}
|
||||
}
|
||||
return moving;
|
||||
}
|
||||
dispose() { for (const v of this.views.values()) this.remove(v); this.views.clear(); this.scene.remove(this.group); }
|
||||
}
|
||||
@@ -84,6 +84,8 @@ import { WeatherLayer, type SkyView } from "./live-weather.ts";
|
||||
import { EnergyLayer, type EnergyArc, type PlanPoint, type SparkField } from "./live-energy.ts";
|
||||
import { SoundLayer, type SoundSpot } from "./live-sound.ts";
|
||||
import { WaterLayer, type SpraySpot } from "./live-water.ts";
|
||||
import { HydronicLayer } from "./live-hydronics.ts";
|
||||
import type { HydronicVisual } from "../hydronic-values.ts";
|
||||
import { ScreenLayer, type LiveScreen } from "./live-screens.ts";
|
||||
import { PictureLayer, type LivePicture } from "./live-pictures.ts";
|
||||
import { addMeshLighting, applyEnvironment, disposeMeshInstance, instantiateMesh, loadMesh } from "./meshes.ts";
|
||||
@@ -585,6 +587,7 @@ export class NextFloorViewer {
|
||||
/** Sound rings around playing speakers and multiroom threads (live-sound.ts). */
|
||||
private readonly soundLayer: SoundLayer;
|
||||
private readonly waterLayer: WaterLayer;
|
||||
private readonly hydronicLayer: HydronicLayer;
|
||||
/** How opaque the glass walls are, shared by every floor's materials (0.2: faint glass). */
|
||||
private readonly glassAlpha = { value: 0.2 };
|
||||
/** Pictures on TVs that play, with an ambilight behind (live-screens.ts). */
|
||||
@@ -624,6 +627,7 @@ export class NextFloorViewer {
|
||||
this.energyLayer = new EnergyLayer(this.scene, this.liftOf);
|
||||
this.soundLayer = new SoundLayer(this.scene, this.liftOf);
|
||||
this.waterLayer = new WaterLayer(this.scene, this.liftOf);
|
||||
this.hydronicLayer = new HydronicLayer(this.scene, this.liftOf);
|
||||
this.screenLayer = new ScreenLayer(this.scene, this.liftOf);
|
||||
this.screenLayer.onChange = () => this.invalidate();
|
||||
this.pictureLayer = new PictureLayer(this.scene, this.liftOf);
|
||||
@@ -1229,6 +1233,8 @@ export class NextFloorViewer {
|
||||
this.invalidate();
|
||||
}
|
||||
|
||||
setHydronics(spots: HydronicVisual[]): void { this.hydronicLayer.set(spots); this.invalidate(); }
|
||||
|
||||
/** TVs and monitors that play: their picture and the ambilight behind them. */
|
||||
setLiveScreens(list: LiveScreenInput[]): void {
|
||||
const out: LiveScreen[] = [];
|
||||
@@ -1484,6 +1490,7 @@ export class NextFloorViewer {
|
||||
this.energyLayer.dispose();
|
||||
this.soundLayer.dispose();
|
||||
this.waterLayer.dispose();
|
||||
this.hydronicLayer.dispose();
|
||||
this.screenLayer.dispose();
|
||||
this.pictureLayer.dispose();
|
||||
this.resizeObserver.disconnect();
|
||||
@@ -3307,7 +3314,7 @@ export class NextFloorViewer {
|
||||
const robotsMoving = this.stepRobots(now);
|
||||
// NextFloor's layers: each one steps every frame (no short-circuit), any of them moving keeps the frames coming
|
||||
this.pictureLayer.step();
|
||||
const liveMoving = [this.weatherLayer, this.energyLayer, this.soundLayer, this.screenLayer, this.waterLayer].map((l) => l.step(now));
|
||||
const liveMoving = [this.weatherLayer, this.energyLayer, this.soundLayer, this.screenLayer, this.waterLayer, this.hydronicLayer].map((l) => l.step(now));
|
||||
const weatherMoving = liveMoving.some(Boolean);
|
||||
const moving = cameraMoving || floorsMoving || openingsMoving || flashing || roofMoving;
|
||||
const busy: string[] = [];
|
||||
|
||||
Reference in new issue
Block a user