feat: add fresh-water cascades with independent stations and buffer links

This commit is contained in:
jhartworks committed 2026-11-12 16:16:01 +01:00
1 parent a2a119d3ee
commit 992c3e18f2
30 files changed
+2199 -1578

No files matched your search

@@ -0,0 +1,46 @@
import { html, nothing } from "lit";
import { repeat } from "lit/directives/repeat.js";
import { uid, type Furniture } from "../../../model.ts";
import { hydronicConfig, type HydronicControl } from "../../../hydronic-model.ts";
import { freshwaterStations, MAX_FRESHWATER_STATIONS, newFreshwaterStation, stationHasValve, withFreshwaterStations, type FreshwaterStation } from "../../../freshwater-model.ts";
import { entityOptions } from "../entities.ts";
import { checkField, entityField, hint, selectField, textField } from "../fields.ts";
import type { EditorHost } from "../host.ts";
export function renderFreshwaterForm(host: EditorHost, item: Furniture, update: (patch: Partial<Furniture>) => void) {
const h=hydronicConfig(item),stations=freshwaterStations(item),options=entityOptions(host.hass,()=>true);
const save=(next:FreshwaterStation[],resize=false)=>update({hydronic:withFreshwaterStations(h,next),...(resize?{w:Math.round(item.w/stations.length*next.length*1000)/1000}:{})});
const ref=(label:string,value:string|null|undefined,types:number[],set:(id:string|null)=>void)=>entityField(host,label,value??null,undefined,options,(v)=>set(v==="none"?null:v),{types});
const numeric=(label:string,value:string|null|undefined,set:(id:string|null)=>void)=>ref(label,value,[1,2],set);
const control=(label:string,value:HydronicControl|undefined,set:(c:HydronicControl)=>void)=>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)=>set({...value,feedback}))}
${ref("Befehl / Sollwert (optional)",value?.command,[0,1,2],(command)=>set({...value,command}))}
${hint("Eine zugewiesene Rückmeldung bestimmt die Anzeige auch bei Ausfall. Nur ohne Rückmeldung wird der Sollwert verwendet. Bedienbare Variablen verwenden ihre native Symcon-Schaltaktion und ihren unveränderten Wertebereich.","nf-wide")}
</div></details>`;
const floor=host.doc.floors.find((f)=>f.furniture.some((m)=>m.id===item.id));
const buffers=(floor?.furniture??[]).filter((m)=>m.type==="buffer_tank");
const choices:[string,string][]=[["","Keiner"],...buffers.map((m,i):[string,string]=>[m.id,m.name||`Pufferspeicher ${i+1}`])];
if(h.buffer_id&&!buffers.some((b)=>b.id===h.buffer_id))choices.push([h.buffer_id,"Verknüpfter Puffer nicht im Stockwerk vorhanden"]);
return html`<section class="nf-freshwater-form">
<div class="nf-form">${selectField(host,"Pufferspeicher im Plan",h.buffer_id??"",choices,(id)=>update({hydronic:{...h,buffer_id:id||null}}),{wide:true})}
${hint("Die Zuordnung zeichnet Vorlauf und Rücklauf zum platzierten Puffer im selben Stockwerk. Datenpunkte werden für jede Station separat aus dem Objektbaum gewählt. Eine Kaskade teilt sich die Sammelleitungen; die Zirkulationspumpe gehört zur gemeinsamen Leitung. Das Hinzufügen einer Station verbreitert das Bauteil, neue Stationen starten ohne Datenpunkt-Verknüpfungen.","nf-wide")}
</div>
${repeat(stations,(s)=>s.id,(s,i)=>{
const patch=(p:Partial<FreshwaterStation>)=>save(stations.map((old)=>old.id===s.id?{...old,...p}:old));
return html`<details class="nf-freshwater-station" data-station=${s.id} ?open=${i===0}><summary>K${i+1} · ${s.name||`Station ${i+1}`}</summary><div class="nf-form">
${textField(host,"Name",s.name,(name)=>patch({name}),{wide:true,maxlength:100})}
${numeric("Vorlauf",s.flow,(flow)=>patch({flow}))}${numeric("Rücklauf",s.return,(back)=>patch({return:back}))}
${numeric("Trinkwarmwasser",s.hot_water,(hot_water)=>patch({hot_water}))}${numeric("Kaltwasser",s.cold_water,(cold_water)=>patch({cold_water}))}
${control("Ladepumpe",s.pump,(pump)=>patch({pump}))}
${numeric("Pumpenleistung (optional)",s.power,(power)=>patch({power}))}
${checkField(host,"Kaskadenventil vorhanden",stationHasValve(s),(has_valve)=>patch({has_valve}))}
${stationHasValve(s)?control("Kaskadenventil (Kaltwasser)",s.valve,(valve)=>patch({valve})):nothing}
${stations.length>1?html`<button class="nf-link nf-wide nf-freshwater-remove" ?disabled=${!host.admin} @click=${()=>save(stations.filter((old)=>old.id!==s.id),true)}>× Station entfernen</button>`:nothing}
</div></details>`;
})}
<button class="nf-btn nf-freshwater-add" ?disabled=${!host.admin||stations.length>=MAX_FRESHWATER_STATIONS} @click=${()=>save([...stations,newFreshwaterStation(uid("station"),`Station ${stations.length+1}`)],true)}>+ Station hinzufügen</button>
<div class="nf-form">${numeric("Zirkulationstemperatur",h.circulation_temperature,(circulation_temperature)=>update({hydronic:{...h,circulation_temperature}}))}
${control("Zirkulationspumpe",h.circulation,(circulation)=>update({hydronic:{...h,circulation}}))}
</div>
</section>`;
}
@@ -6,6 +6,7 @@ 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";
import { renderFreshwaterForm } from "./freshwater.ts";
export function renderHydronicForm(host: EditorHost, item: Furniture, update: (patch: Partial<Furniture>) => void) {
const h = hydronicConfig(item), options = entityOptions(host.hass, () => true);
@@ -46,7 +47,7 @@ export function renderHydronicForm(host: EditorHost, item: Furniture, update: (p
<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}
${item.type === "freshwater_station" ? renderFreshwaterForm(host,item,update) : nothing}
${renderDeviceValues(host, item.values, (values) => update({ values }))}
</section>`;
}
+23 -15
View File
@@ -6,6 +6,7 @@ import { hydronicReading, readControl, temperatureC, type HydronicReading } from
import { nativeBool, nativeNumber, nativeText, nativeValue } from "../entities/symcon-values.ts";
import { tokens } from "../styles.ts";
import { trendButton } from "./trend-button.ts";
import { freshwaterStations, stationHasValve, type FreshwaterStation } from "../freshwater-model.ts";
export { hydronicVisual } from "../hydronic-values.ts";
const names: Record<string, string> = { heating_manifold: "Heiz-/Kühlkreisverteiler", buffer_tank: "Pufferspeicher", freshwater_station: "Frischwasserstation" };
@@ -19,12 +20,16 @@ const delta = (hass: HomeAssistant, flow?: string | null, back?: string | null)
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);
const h = hydronicConfig(item), rows = item.type === "freshwater_station" ? [] : 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); }
if (item.type === "freshwater_station") { const row=hydronicReading(hass,"Zirkulation",h.circulation_temperature);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;
}
function stationRows(hass:HomeAssistant,station:FreshwaterStation):HydronicReading[] {
return [...parts(hass,station.flow,station.return),...[ ["Kaltwasser",station.cold_water],["Trinkwarmwasser",station.hot_water],["Pumpenleistung",station.power] ].flatMap(([label,id])=>{const row=hydronicReading(hass,label!,id);return row?[row]:[];})];
}
const stationName=(station:FreshwaterStation,i:number)=>`K${i+1} · ${station.name||`Station ${i+1}`}`;
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);
@@ -45,22 +50,24 @@ class HydronicCard extends LitElement {
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);
const h = hydronicConfig(this.item), rows = rootRows(this.hass, this.item),stations=this.item.type==="freshwater_station"?freshwaterStations(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}
${stations.length>1?html`<small class="cascade-count">Kaskade · ${stations.length} Stationen</small>${stations.map((s,i)=>{const pump=readControl(this.hass,s.pump),row=hydronicReading(this.hass,"Trinkwarmwasser",s.hot_water)||hydronicReading(this.hass,"Vorlauf",s.flow);return html`<div class="station-summary" data-station=${s.id}><button class="station-name" @click=${()=>openHydronic(this.hass,this.item,this.readOnly,s.id)}><i class="lamp" title=${`Pumpe: ${pump.id?nativeText(this.hass.states[pump.id]):"–"}`} style=${`background:${pump.running===null?"#888":pump.running?"#6fe1a2":"#a82638"}`}></i>${stationName(s,i)}</button><b>${row?.text||"–"}</b>${row?trendButton(this.hass,[row.id],`${stationName(s,i)} · ${row.label}`):nothing}</div>`;})}`:stations.map((s)=>html`<section class="circuit">${stationRows(this.hass,s).map((r)=>rowTemplate(this.hass,r))}${controlRow(this.hass,"Ladepumpe",s.pump)}${stationHasValve(s)?controlRow(this.hass,"Kaskadenventil",s.valve):nothing}</section>`)}
${rows.map((r) => rowTemplate(this.hass, r))}${this.item.type === "freshwater_station" ? controlRow(this.hass, "Zirkulationspumpe", h.circulation) : nothing}
${this.item.type !== "heating_manifold" && this.item.type!=="freshwater_station" && !rows.length ? html`<p class="empty">Noch keine Fühler verknüpft</p>` : nothing}
</div>`;
}
static styles = [tokens, styles];
static styles = [tokens, styles,css`.cascade-count{color:var(--nf-muted)}.station-summary{display:grid;grid-template-columns:minmax(0,1fr) auto 18px;align-items:center;gap:6px;width:100%;padding:5px 0;font-size:11px}.station-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:0;background:none;border:0;text-align:left}.station-summary b{white-space:nowrap;font-variant-numeric:tabular-nums}`];
}
class HydronicDialog extends LitElement {
static properties = { hass: { attribute: false }, item: { attribute: false }, readOnly: { type: Boolean }, pending: { state: true }, error: { state: true } };
static properties = { hass: { attribute: false }, item: { attribute: false }, readOnly: { type: Boolean }, focusStation: { attribute:false }, pending: { state: true }, error: { state: true } };
declare hass: HomeAssistant; declare item: Furniture; declare readOnly: boolean;
declare focusStation: string | undefined;
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(); }
async show() { await this.updateComplete; this.shadowRoot!.querySelector("dialog")!.showModal();if(this.focusStation)this.shadowRoot!.querySelector(`[data-station="${CSS.escape(this.focusStation)}"]`)?.scrollIntoView({block:"start"}); }
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;
@@ -85,23 +92,24 @@ class HydronicDialog extends LitElement {
}
render() {
if (!this.hass || !this.item) return nothing;
const h = hydronicConfig(this.item), rows = rootRows(this.hass, this.item);
const h = hydronicConfig(this.item), rows = rootRows(this.hass, this.item),stations=this.item.type==="freshwater_station"?freshwaterStations(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}
${stations.map((s,i)=>html`<details class="freshwater-unit" data-station=${s.id} ?open=${i===0||this.focusStation===s.id}><summary>${stationName(s,i)}</summary>${stationRows(this.hass,s).map((r)=>rowTemplate(this.hass,r))}${delta(this.hass,s.flow,s.return)}${this.control("Ladepumpe",s.pump)}${stationHasValve(s)?this.control("Kaskadenventil",s.valve):nothing}</details>`)}
${rows.map((r) => rowTemplate(this.hass, r))}${this.item.type === "buffer_tank" ? delta(this.hass, h.flow, h.return) : nothing}
${this.item.type === "freshwater_station" ? this.control("Zirkulationspumpe", h.circulation) : nothing}
${!rows.length && this.item.type !== "heating_manifold" && this.item.type!=="freshwater_station" ? 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}`];
static styles = [tokens, styles, css`:host{max-width:none;min-width:0}.freshwater-unit{border-bottom:1px solid var(--nf-line);padding:8px 0}.freshwater-unit>summary{cursor:pointer;font-weight:600;padding:4px 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> {
export async function openHydronic(hass: HomeAssistant, item: Furniture, readOnly = false, focusStation?:string): 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();
activeDialog = dialog; Object.assign(dialog, { hass, item, readOnly,focusStation }); document.body.append(dialog); await dialog.show();
}
export function refreshHydronic(hass: HomeAssistant, building: Building, readOnly = false): void {
if (!activeDialog) return;
+59
View File
@@ -0,0 +1,59 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { freshwaterStations,newFreshwaterStation,withFreshwaterStations } from "./freshwater-model.ts";
import { hydronicRefs } from "./hydronic-model.ts";
import { bufferTemperatureLayers,hydronicVisual } from "./hydronic-values.ts";
import { emptyBuilding,normalizeBuilding,type Furniture } from "./model.ts";
import { entity,floorWith,hassOf,box } from "./entities/fixtures.ts";
import { watchedEntities } from "./components/view3d/watch-list.ts";
import { floorUtilityAreas,floorUtilityReadings } from "./utilities.ts";
const item=(extra:Partial<Furniture>={}):Furniture=>({id:"fws",type:"freshwater_station",name:"Frischwasser",x:0,z:0,w:.65,d:.28,h:.9,rotation:0,variant:null,...extra});
const point=(id:string,value:number|boolean)=>entity(id,"open",{symcon_id:123,symcon_variable_type:typeof value==="boolean"?0:2,symcon_value:value});
test("promoting an old single station preserves every link and leaves no phantom shared bindings",()=>{
const original={flow:"cover.1",return:"light.2",hot_water:"climate.3",pump:{command:"cover.4",feedback:"lock.5"},circulation:{feedback:"sensor.6"},circulation_temperature:"sensor.7",buffer_id:"buffer"};
const f=item({hydronic:original}),legacy=freshwaterStations(f);
assert.equal(legacy.length,1);assert.equal(legacy[0].flow,"cover.1");assert.deepEqual(legacy[0].pump,original.pump);
const converted=withFreshwaterStations(original,[...legacy,newFreshwaterStation("s2","Zweite")]);
assert.equal(converted.flow,undefined);assert.equal(converted.pump,undefined);assert.equal(converted.buffer_id,"buffer");
assert.deepEqual(converted.circulation,original.circulation);assert.equal(converted.stations![0].return,"light.2");assert.equal(converted.stations![1].pump,undefined);
assert.equal(original.flow,"cover.1","conversion must not mutate a saved single-station object");
});
test("independent station feedback keeps zero/offline values and never falls back to a different module",()=>{
const f=item({hydronic:{stations:[{id:"a",name:"A",pump:{feedback:"cover.p1",command:"cover.cmd"},valve:{feedback:"sensor.v1"},hot_water:"sensor.t1"},{id:"b",name:"B",pump:{feedback:"cover.p2"},hot_water:"sensor.t2"}]}});
const h=hassOf([point("cover.p1",false),point("cover.cmd",true),point("cover.p2",true),point("sensor.v1",0),point("sensor.t1",0),point("sensor.t2",52)]);
let visual=hydronicVisual(h,f,"g",.7);
assert.deepEqual(visual.stations?.map((s)=>[s.pump,s.valve,s.temperatures[3]]),[[false,0,0],[true,null,52]]);
h.states["cover.p1"].state="unavailable";h.states["sensor.t1"].state="unavailable";
visual=hydronicVisual(h,f,"g",.7);assert.equal(visual.stations?.[0].pump,null);assert.equal(visual.stations?.[0].temperatures[3],null);assert.equal(visual.stations?.[1].pump,true);
});
test("all cascade and common circulation links are watched; removed stations and disabled valves release their refs",()=>{
const f=item({hydronic:{buffer_id:"buffer-object",stations:[{id:"a",name:"A",flow:"cover.1",pump:{command:"light.2",feedback:"lock.3"},valve:{command:"cover.4",feedback:"light.5"},power:"climate.6"},{id:"b",name:"B",hot_water:"sensor.7",cold_water:"sensor.8"}],circulation:{feedback:"sensor.9"}}});
const b={...emptyBuilding(),floors:[floorWith([],{furniture:[f]})]},h=hassOf([],{}, {symconObjects:[]});
assert.deepEqual(hydronicRefs(f).sort(),["cover.1","light.2","lock.3","cover.4","light.5","climate.6","sensor.7","sensor.8","sensor.9"].sort());
const watched=watchedEntities({hass:h,building:b,openingLinks:new Map(),furnitureLinks:new Map(),needsRoomSensors:false,alertSources:null,weatherEntityId:null});
assert.ok(hydronicRefs(f).every((id)=>watched.includes(id)));assert.ok(!watched.includes("buffer-object"));
f.hydronic!.stations=f.hydronic!.stations!.slice(0,1);f.hydronic!.stations[0].has_valve=false;
assert.ok(!hydronicRefs(f).some((id)=>["cover.4","light.5","sensor.7","sensor.8"].includes(id)));
});
test("cascade bindings and the buffer association survive persistence; unit power is detail only",()=>{
const f=item({hydronic:{buffer_id:"buffer",stations:[{id:"a",name:"K1",power:"cover.1"},{id:"b",name:"K2",power:"cover.2"}]}});
const b=normalizeBuilding(JSON.parse(JSON.stringify({...emptyBuilding(),floors:[floorWith([box("r",-3,-3,3,3)],{furniture:[f]})]})));
assert.deepEqual(b.floors[0].furniture[0].hydronic,f.hydronic);
const h=hassOf([point("cover.1",0),point("cover.2",48)],{}, {symconObjects:[]});
const details=floorUtilityAreas(h,b.floors[0],b.floors[0].rooms,true)[0].rooms[0].devices;
assert.deepEqual(details.map((d)=>[d.name,d.readings[0].value]),[["Frischwasser · K1",0],["Frischwasser · K2",48]]);
assert.deepEqual(floorUtilityReadings(h,b.floors[0]),[]);
});
test("storage colour interpolation follows measured probe height, retains zero and invents no data for empty probes",()=>{
assert.ok(bufferTemperatureLayers([{level:1,value:null}]).every((v)=>v===null));
assert.ok(bufferTemperatureLayers([{level:.4,value:0}]).every((v)=>v===0));
const probes=[{level:1,value:60},{level:0,value:20}];
const layers=bufferTemperatureLayers(probes,4);assert.deepEqual(layers,[25,35,45,55]);assert.deepEqual(probes,[{level:1,value:60},{level:0,value:20}]);
assert.ok(bufferTemperatureLayers([{level:1,value:Infinity},{level:0,value:null}]).every((v)=>v===null));
});
+24
View File
@@ -0,0 +1,24 @@
import type { Furniture } from "./model.ts";
import type { HydronicConfig, HydronicControl } from "./hydronic-model.ts";
export const MAX_FRESHWATER_STATIONS = 16;
export interface FreshwaterStation {
id: string; name: string;
flow?: string | null; return?: string | null; hot_water?: string | null; cold_water?: string | null; power?: string | null;
pump?: HydronicControl; valve?: HydronicControl; has_valve?: boolean;
}
export const newFreshwaterStation = (id: string, name = "Station 1"): FreshwaterStation => ({ id, name, has_valve: true });
export const stationHasValve = (station: FreshwaterStation): boolean => station.has_valve !== false;
/** Legacy single stations retain their exact links until the next edit promotes them to the station list. */
export function freshwaterStations(item: Pick<Furniture, "hydronic">): readonly FreshwaterStation[] {
const h = item.hydronic ?? {};
if (h.stations?.length) return h.stations.slice(0, MAX_FRESHWATER_STATIONS);
return [{ ...newFreshwaterStation("station-1"), flow: h.flow, return: h.return, hot_water: h.hot_water, cold_water: h.cold_water, pump: h.pump }];
}
export function withFreshwaterStations(h: HydronicConfig, stations: FreshwaterStation[]): HydronicConfig {
const next = { ...h, stations };
// These used to belong to the single station. They must not survive as phantom shared sensors.
for (const key of ["flow", "return", "hot_water", "cold_water", "pump"] as const) delete next[key];
return next;
}
+7 -2
View File
@@ -1,4 +1,5 @@
import type { EntityRef, Furniture } from "./model.ts";
import { freshwaterStations, stationHasValve, type FreshwaterStation } from "./freshwater-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);
@@ -20,6 +21,10 @@ export interface HydronicConfig {
flow?: EntityRef; return?: EntityRef;
pump?: HydronicControl; circulation?: HydronicControl;
circulation_temperature?: EntityRef; hot_water?: EntityRef;
cold_water?: EntityRef;
stations?: FreshwaterStation[];
/** A placed buffer on the same floor; this is a plan object, never a Symcon variable. */
buffer_id?: string | null;
}
export const newCircuit = (id: string, name = "Heizkreis"): HydronicCircuit => ({ id, name, kind: "heating", has_pump: true, has_valve: true });
@@ -36,9 +41,9 @@ 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,
return [...new Set([...(item.type === "freshwater_station" ? [] : [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)] : []),
...(item.type === "freshwater_station" ? [h.circulation_temperature, ...controlRefs(h.circulation), ...freshwaterStations(item).flatMap((s) => [s.flow, s.return, s.hot_water, s.cold_water, s.power, ...controlRefs(s.pump), ...(stationHasValve(s) ? controlRefs(s.valve) : [])])] : []),
].filter(realRef))];
}
+16
View File
@@ -2,14 +2,29 @@ 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";
import { freshwaterStations, stationHasValve } from "./freshwater-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 }
/** Colour layers interpolate measured storage probes only; no linked temperature means no coloured skin. */
export function bufferTemperatureLayers(probes: readonly {level:number;value:number|null}[],count=24):(number|null)[] {
const points=probes.filter((p):p is {level:number;value:number}=>p.value!==null&&Number.isFinite(p.value)&&Number.isFinite(p.level)).slice().sort((a,b)=>a.level-b.level);
return Array.from({length:count},(_,i)=>{
if(!points.length)return null;
const level=(i+.5)/count;
if(level<=points[0].level)return points[0].value;
const high=points.findIndex((p)=>p.level>=level);
if(high<0)return points.at(-1)!.value;
const a=points[high-1],b=points[high],span=b.level-a.level;
return span>0?a.value+(b.value-a.value)*(level-a.level)/span:b.value;
});
}
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)[];
stations?: { id: string; pump: boolean | null; valve: number | null; temperatures: (number | null)[] }[];
animate?: boolean;
pump: boolean | null; circulation: boolean | null;
}
@@ -50,6 +65,7 @@ export function hydronicVisual(hass: HomeAssistant, item: Furniture, floorId: st
}),
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)),
stations: item.type === "freshwater_station" ? freshwaterStations(item).map((s) => ({ id:s.id, pump:readControl(hass,s.pump).running, valve:stationHasValve(s)?readControl(hass,s.valve).percent:null, temperatures:[s.flow,s.return,s.cold_water,s.hot_water].map((id)=>temperatureC(hass,id)) })) : [],
pump: readControl(hass, h.pump).running, circulation: readControl(hass, h.circulation).running,
};
}
+2
View File
@@ -7,6 +7,7 @@ import { furnitureName } from "./furniture-names.ts";
import { powerSensorFor } from "./energy.ts";
import { hasPump, hydronicConfig, isHydronic, realRef } from "./hydronic-model.ts";
import { isSymcon } from "./entities/symcon-values.ts";
import { freshwaterStations } from "./freshwater-model.ts";
export interface DevicePowerLink { id: string; name: string; source: string }
const sourceOf = (hass: HomeAssistant, id: string) => String(hass.states[id]?.attributes.symcon_source_entity || id);
@@ -48,6 +49,7 @@ export function roomDevicePowerLinks(hass: HomeAssistant, floor: Floor): Map<str
if (isHydronic(item.type)) for (const c of hydronicConfig(item).circuits ?? []) {
if (hasPump(c)) add(`furniture:${item.id}:${c.id}`, `${name} · ${c.name || "Pumpe"}`, item.x, item.z, c.power);
}
if(item.type==="freshwater_station")for(const s of freshwaterStations(item))add(`furniture:${item.id}:station:${s.id}`,`${name} · ${s.name}`,item.x,item.z,s.power);
}
for (const item of floor.placements) {
if (item.outside) continue;
@@ -0,0 +1,50 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import type { Furniture } from "../model.ts";
import { freshwaterLayout } from "./freshwater-layout.ts";
import { newFreshwaterStation } from "../freshwater-model.ts";
import { hydronicPoint,freshwaterConnectionPaths,HydronicConnections } from "./hydronic-connections.ts";
import { hydronicVisual } from "../hydronic-values.ts";
import { hassOf } from "../entities/fixtures.ts";
import { Group } from "three";
const item=(type:string,extra:Partial<Furniture>={}):Furniture=>({id:type,type,x:0,z:0,w:type==="buffer_tank"?.85:.65,d:type==="buffer_tank"?.85:.28,h:type==="buffer_tank"?1.85:.9,rotation:0,variant:null,...extra});
test("single and parallel stations have separate primary and drinking-water paths with physically separated crossings",()=>{
for(const count of [1,4,16]){
const f=item("freshwater_station",{w:.65*count,hydronic:{stations:Array.from({length:count},(_,i)=>newFreshwaterStation(String(i)))}}),layout=freshwaterLayout(f);
assert.equal(layout.units.length,count);assert.equal(layout.headers.length,4);
for(const u of layout.units){
const primary=new Set(u.pipes.filter((p)=>p.medium.startsWith("primary")).flatMap((p)=>[p.from.join(","),p.to.join(",")]));
assert.ok(u.pipes.filter((p)=>["hot_water","cold_water"].includes(p.medium)).every((p)=>!primary.has(p.from.join(","))&&!primary.has(p.to.join(","))),"drinking water must never tee into the primary water circuit");
assert.ok(u.pump.y<u.plate.y0&&u.valve!.y<u.pump.y);assert.ok(u.x>=-f.w/2&&u.x<=f.w/2);
assert.ok(u.pipes.every((p)=>[...p.from,...p.to].every(Number.isFinite)));
}
assert.ok(layout.front-layout.blueZ>layout.headerR+layout.pipeR,"cold-water/primary-return crossings need depth clearance");
}
});
test("circulation is common and conditional; its return port does not short-circuit the hot-water outlet",()=>{
const plain=item("freshwater_station");assert.equal(freshwaterLayout(plain).circulationPipes.length,0);
const linked=freshwaterLayout({...plain,hydronic:{circulation:{feedback:"cover.1"}}});
assert.equal(linked.circulationPipes.length,2);
assert.notEqual(linked.circulationPipes[0].from[1],linked.ys.hot);
assert.equal(linked.circulationPipes.at(-1)!.to[1],linked.ys.cold);
});
test("buffer links carry primary water only and follow placement, tilt, mirror and mount transforms",()=>{
const h=hassOf([]),fresh=hydronicVisual(h,item("freshwater_station",{id:"f",x:-2,z:1,rotation:90,mirror:true,tilt_x:10,hydronic:{buffer_id:"b"}}),"g",.7),buffer=hydronicVisual(h,item("buffer_tank",{id:"b",x:1,z:-1,rotation:25}),"g",0);
const paths=freshwaterConnectionPaths(fresh,buffer);
assert.deepEqual(paths.map((p)=>p.medium),["primary_flow","primary_return"]);
assert.ok(paths.every((p)=>p.points.every((v)=>v.toArray().every(Number.isFinite))));
assert.notDeepEqual(paths[0].points[0].toArray(),paths[1].points[0].toArray());
const port=hydronicPoint(fresh,[.2,.4,0]);assert.ok(port.y>.7);assert.notEqual(port.z,1);
});
test("connection groups follow floor lifts and are removed when a buffer disappears or lies on a different floor",()=>{
let visible=true;const root=new Group(),links=new HydronicConnections(root,(id)=>({y:id==="other"?6:3,dy:0,visible})),h=hassOf([]);
const f=hydronicVisual(h,item("freshwater_station",{id:"f",x:-2,hydronic:{buffer_id:"b"}}),"g",.8),b=hydronicVisual(h,item("buffer_tank",{id:"b",x:1}),"g",0);
links.set([f,b]);assert.equal(root.children.length,1);links.step();assert.equal(root.children[0].position.y,3);
const oldGroup=root.children[0];f.item.x-=.5;links.set([f,b]);assert.notEqual(root.children[0],oldGroup,"dragging an existing plan object must rebuild its pipe endpoints even if the item reference is reused");
visible=false;links.step();assert.equal(root.children[0].visible,false);
links.set([f]);assert.equal(root.children.length,0);
links.set([f,{...b,floorId:"other"}]);assert.equal(root.children.length,0);
links.set([{...f,floorId:"other"},{...b,floorId:"other"}]);links.step();assert.equal(root.children[0].position.y,6);
links.set([f,b]);links.dispose();assert.equal(root.children.length,0);
});
+44
View File
@@ -0,0 +1,44 @@
import type { Furniture } from "../model.ts";
import { freshwaterStations, stationHasValve } from "../freshwater-model.ts";
import { realRef } from "../hydronic-model.ts";
import type { PipePoint } from "./hydronic-layout.ts";
export type WaterMedium="primary_flow"|"primary_return"|"hot_water"|"cold_water"|"circulation";
export interface WaterPipe {from:PipePoint;to:PipePoint;medium:WaterMedium}
export interface WaterInstrument {x:number;y:number;z:number;front:number;r:number}
export function freshwaterLayout(item:Pick<Furniture,"w"|"d"|"h"|"hydronic">) {
const {w,d,h}=item,stations=freshwaterStations(item),service=Math.min(w*.2,h*.25),pitch=(w-service)/stations.length;
const front=d*.24,redZ=-d*.03,blueZ=-d*.25;
const ys={flow:h*.98,back:h*.9,hot:h*.82,cold:h*.06};
const headerR=Math.min(h*.012,d*.065,pitch*.04),pipeR=Math.min(h*.009,d*.045,pitch*.025);
const headers:WaterPipe[]=[
{from:[-w*.49,ys.flow,redZ],to:[w*.49,ys.flow,redZ],medium:"primary_flow"},
{from:[-w*.49,ys.back,blueZ],to:[w*.49,ys.back,blueZ],medium:"primary_return"},
{from:[-w*.49,ys.hot,front],to:[w*.49,ys.hot,front],medium:"hot_water"},
{from:[-w*.49,ys.cold,front],to:[w*.49,ys.cold,front],medium:"cold_water"},
];
const instrument=(x:number,y:number,r:number):WaterInstrument=>({x,y,z:front,front:front+Math.min(d*.22,r*.85),r});
const units=stations.map((station,i)=>{
const x=-w/2+service+pitch*(i+.5),left=x-pitch*.33,back=x+pitch*.4,water=x+pitch*.23,plate=pitch*.18;
const pipes:WaterPipe[]=[];
const path=(medium:WaterMedium,points:PipePoint[])=>{for(let j=1;j<points.length;j++)pipes.push({from:points[j-1],to:points[j],medium});};
path("primary_flow",[[left,ys.flow,redZ],[left,h*.78,redZ],[left,h*.78,front],[left,h*.64,front],[x-plate,h*.64,front]]);
// Primary return stays behind the drinking-water inlet at the lower crossing.
path("primary_return",[[x-plate,h*.42,front],[left,h*.42,front],[left,h*.24,front],[left,h*.24,blueZ],[back,h*.24,blueZ],[back,ys.back,blueZ]]);
path("hot_water",[[x+plate,h*.64,front],[water,h*.64,front],[water,ys.hot,front]]);
path("cold_water",[[water,ys.cold,front],[water,h*.42,front],[x+plate,h*.42,front]]);
const pump=instrument(left,h*.33,Math.min(pitch*.09,h*.04,d*.25));
const valve=stationHasValve(station)?instrument(water,h*.145,Math.min(pitch*.055,h*.025,d*.16)):null;
const gaugeR=Math.min(pitch*.025,h*.015,d*.07);
const probes=[instrument(left,h*.72,gaugeR),{...instrument(back,h*.72,gaugeR),z:blueZ,front:blueZ+gaugeR*.85},instrument(water,h*.29,gaugeR),instrument(water,h*.72,gaugeR)];
return{id:station.id,x,pitch,pipes,pump,valve,probes,plate:{x0:x-plate,x1:x+plate,y0:h*.38,y1:h*.68,back:front-d*.13,front:front+d*.16}};
});
const cfg=item.hydronic;
const circulation=[cfg?.circulation?.command,cfg?.circulation?.feedback,cfg?.circulation_temperature].some(realRef);
const circX=-w/2+service*.5,circPump=instrument(circX,h*.49,Math.min(service*.28,h*.035,d*.22));
const circulationPipes:WaterPipe[]=circulation?[
{from:[-w*.49,h*.75,front],to:[circX,h*.75,front],medium:"circulation"},
{from:[circX,h*.75,front],to:[circX,ys.cold,front],medium:"circulation"},
]:[];
return{units,headers,circulationPipes,circPump,circProbe:instrument(circX,h*.65,Math.min(service*.12,h*.014)),pipeR,headerR,front,redZ,blueZ,ys,service,pitch};
}
@@ -0,0 +1,35 @@
import { Color } from "three";
import type { Furniture } from "../../model.ts";
import { freshwaterLayout,type WaterMedium } from "../freshwater-layout.ts";
import type { Builder } from "./builder.ts";
import { EDGE_FAINT,M,material } from "./palette.ts";
import { hydronicBody,hydronicPipe,HYDRONIC_METAL } from "./hydronic-parts.ts";
export const WATER_MATERIALS={primary_flow:material(0xa93235,0xd74c42),primary_return:material(0x245e9c,0x4c98d5),hot_water:material(0xb67425,0xeea54c),cold_water:material(0x31794e,0x6dbf78),circulation:material(0x79519c,0xb582d1)} satisfies Record<WaterMedium,ReturnType<typeof material>>;
const brass=material(0x92724b,0xc9a56a),plate=material(0x7e8d94,0xb0bdc0),ink=new Color(0xa5b4c0);
export function freshwaterModel(b:Builder,f:Furniture) {
const p=freshwaterLayout(f);
for(const pipe of p.headers)hydronicPipe(b,pipe.from,pipe.to,p.headerR,WATER_MATERIALS[pipe.medium]);
for(const pipe of p.circulationPipes)hydronicPipe(b,pipe.from,pipe.to,p.pipeR,WATER_MATERIALS[pipe.medium]);
if(p.circulationPipes.length){const a=p.circPump;hydronicBody(b,a.x,a.y,a.r,a.z-p.pipeR,a.front,M.darkBody);const g=p.circProbe;hydronicBody(b,g.x,g.y,g.r,g.z,g.front,HYDRONIC_METAL);}
p.units.forEach((s,i)=>{
const half=s.pitch*.45;
b.block({x:[s.x-half,s.x+half],y:[f.h*.18,f.h*.76],z:[-f.d*.46,-f.d*.34]},M.darkBody,EDGE_FAINT);
for(const pipe of s.pipes)hydronicPipe(b,pipe.from,pipe.to,p.pipeR,WATER_MATERIALS[pipe.medium]);
b.block({x:[s.plate.x0,s.plate.x1],y:[s.plate.y0,s.plate.y1],z:[s.plate.back,s.plate.front]},plate,EDGE_FAINT);
// Two physically separate channels share the plate exchanger, never a pipe junction.
for(let k=1;k<7;k++) {
const x=s.plate.x0+(s.plate.x1-s.plate.x0)*k/7;
b.seg(x,s.plate.y0+f.h*.015,s.plate.front+.001,x+s.pitch*.045,s.plate.y1-f.h*.015,s.plate.front+.001,EDGE_FAINT);
}
for(const[xx,m]of[[s.plate.x0,WATER_MATERIALS.primary_flow],[s.plate.x1,WATER_MATERIALS.hot_water]] as const)b.block({x:[xx-s.pitch*.016,xx+s.pitch*.016],y:[s.plate.y0,s.plate.y1],z:[s.plate.front,s.plate.front+f.d*.015]},m);
for(const a of [s.pump,...(s.valve?[s.valve]:[])])hydronicBody(b,a.x,a.y,a.r,a.z-p.pipeR,a.front,a===s.valve?brass:M.darkBody);
for(const g of s.probes)hydronicBody(b,g.x,g.y,g.r,g.z,g.front,HYDRONIC_METAL);
// Small, code-native K1…K16 labels identify the modules without another floating card per unit.
const scale=Math.min(s.pitch*.055,f.h*.022),x=s.x-half+scale*.6,y=f.h*.72,z=f.d*.31;
b.seg(x,y-scale,z,x,y+scale,z,ink);b.seg(x,y,z,x+scale,y+scale,z,ink);b.seg(x,y,z,x+scale,y-scale,z,ink);
const digits=String(i+1),map=["abcdef","bc","abdeg","abcdg","bcfg","acdfg","acdefg","abc","abcdefg","abcdfg"];
const lines={a:[0,1,1,1],b:[1,1,1,0],c:[1,0,1,-1],d:[0,-1,1,-1],e:[0,0,0,-1],f:[0,1,0,0],g:[0,0,1,0]} as const;
for(let j=0;j<digits.length;j++)for(const key of map[Number(digits[j])]){const[a,aa,c,cc]=lines[key as keyof typeof lines],dx=x+scale*(1.7+j*1.4);b.seg(dx+a*scale,y+aa*scale,z,dx+c*scale,y+cc*scale,z,ink);}
});
}
@@ -0,0 +1,14 @@
import type { PipePoint } from "../hydronic-layout.ts";
import type { Builder } from "./builder.ts";
import { EDGE_FAINT,material,type Material } from "./palette.ts";
export const HYDRONIC_METAL=material(0x696f70,0x929794);
export function hydronicPipe(b:Builder,a:PipePoint,end:PipePoint,r:number,m:Material) {
const[x0,y0,z0]=a,[x1,y1,z1]=end;
if(Math.abs(x1-x0)>1e-6)b.lyingCylinder("x",(x0+x1)/2,z0,y0-r,y0+r,Math.abs(x1-x0),r*2,m,12,EDGE_FAINT);
else if(Math.abs(z1-z0)>1e-6)b.lyingCylinder("z",x0,(z0+z1)/2,y0-r,y0+r,Math.abs(z1-z0),r*2,m,12,EDGE_FAINT);
else b.cylinder(x0,z0,r,Math.min(y0,y1),Math.max(y0,y1),m,12,EDGE_FAINT);
}
export function hydronicBody(b:Builder,x:number,y:number,r:number,back:number,front:number,m=HYDRONIC_METAL) {
b.lyingCylinder("z",x,(back+front)/2,y-r,y+r,front-back,r*2,m,24,EDGE_FAINT);
}
+8 -15
View File
@@ -3,19 +3,21 @@ import { hasPump, hasValve, hydronicConfig } from "../../hydronic-model.ts";
import { circuitLayout, type PipePoint } from "../hydronic-layout.ts";
import { Builder } from "./builder.ts";
import { EDGE_FAINT, EDGE_FURN, M, material } from "./palette.ts";
import { freshwaterModel } from "./freshwater.ts";
import { bufferPort } from "../hydronic-ports.ts";
const hot = material(0x9d413e, 0xc86b56), cold = material(0x285f85, 0x4e99bd), brass = material(0x92724b, 0xc9a56a);
const steel = material(0x696f70, 0x929794), load = material(0x343c3e, 0x50595b), faceplate = material(0xa4aca8, 0xc9cebf);
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);
const cfg = hydronicConfig(f);
if(f.type==="freshwater_station"){freshwaterModel(b,f);return;}
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, h * .06, h * .9, M.darkBody, 32, EDGE_FURN);
for(let i=0;i<7;i++)b.cylinder(0,0,r*Math.sqrt(1-(i/7)**2),h*(.9+i*.012),h*(.9+(i+1)*.012),M.darkBody,32);
b.cylinder(0,0,r*.08,h*.984,h,M.metal,12,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 side of [-1,1])for(const level of [.12,.38,.62,.88]){const p=bufferPort(f,side,level);b.lyingCylinder("x",p.x,p.z,p.y-p.r,p.y+p.r,p.length,p.r*2,level>.5?hot:cold,12,EDGE_FAINT);}
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);
@@ -64,14 +66,5 @@ export function hydronicModel(b: Builder, f: Furniture, w: number, d: number, h:
b.ring(xx,p.temperatureY,p.gaugeR*.8,p.gaugeFront+.001,16,EDGE_FAINT);
}
});
} 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,64 @@
import { CylinderGeometry,Euler,Group,Mesh,MeshBasicMaterial,SphereGeometry,Vector3,type Material } from "three";
import type { HydronicVisual } from "../hydronic-values.ts";
import type { FloorLift } from "./live-energy.ts";
import type { PipePoint } from "./hydronic-layout.ts";
import { freshwaterLayout } from "./freshwater-layout.ts";
import { bufferPort } from "./hydronic-ports.ts";
export function hydronicPoint(spot:HydronicVisual,point:PipePoint):Vector3 {
const f=spot.item;
return new Vector3(point[0]*(f.mirror?-1:1),point[1],point[2]).applyEuler(new Euler((f.tilt_x??0)*Math.PI/180,-f.rotation*Math.PI/180,(f.tilt_z??0)*Math.PI/180,"YZX")).add(new Vector3(f.x,spot.base,f.z));
}
const axis=(spot:HydronicVisual)=>hydronicPoint(spot,[1,0,0]).sub(hydronicPoint(spot,[0,0,0]));
/** Only primary-water paths are joined to storage. The drinking-water circuits never enter the buffer. */
export function freshwaterConnectionPaths(station:HydronicVisual,buffer:HydronicVisual) {
const f=station.item,b=buffer.item,layout=freshwaterLayout(f);
const fCentre=hydronicPoint(station,[0,f.h/2,0]),bCentre=hydronicPoint(buffer,[0,b.h/2,0]);
const fAxis=axis(station),bAxis=axis(buffer),fSide=bCentre.clone().sub(fCentre).dot(fAxis)>=0?1:-1,bSide=fCentre.clone().sub(bCentre).dot(bAxis)>=0?1:-1;
let front=-Infinity;
for(const spot of [station,buffer])for(const x of [-spot.item.w/2,spot.item.w/2])for(const z of [-spot.item.d/2,spot.item.d/2])for(const y of [0,spot.item.h])front=Math.max(front,hydronicPoint(spot,[x,y,z]).z);
return (["primary_flow","primary_return"] as const).map((medium,i)=>{
const a=hydronicPoint(station,[fSide*f.w*.49,i?layout.ys.back:layout.ys.flow,i?layout.blueZ:layout.redZ]);
const end=hydronicPoint(buffer,bufferPort(b,bSide,i ? .12 : .88).end),exit=a.clone().addScaledVector(fAxis,fSide*.15),approach=end.clone().addScaledVector(bAxis,bSide*.15),z=front+.24+i*.07;
return{medium,points:[a,exit,new Vector3(exit.x,exit.y,z),new Vector3(approach.x,exit.y,z),new Vector3(approach.x,approach.y,z),approach,end]};
});
}
interface Connection {station:HydronicVisual;buffer:HydronicVisual;group:Group;key:string}
const placementKey=(spot:HydronicVisual)=>{const f=spot.item;return[spot.floorId,spot.base,f.id,f.x,f.z,f.w,f.d,f.h,f.rotation,f.tilt_x??0,f.tilt_z??0,!!f.mirror].join("|");};
export class HydronicConnections {
private views=new Map<string,Connection>();
private readonly parent:Group;
private readonly lift:FloorLift;
constructor(parent:Group,lift:FloorLift){this.parent=parent;this.lift=lift;}
private remove(view:Connection) {
const materials=new Set<Material>();
view.group.traverse((o)=>{if(o instanceof Mesh){o.geometry.dispose();if(Array.isArray(o.material))o.material.forEach((m)=>materials.add(m));else materials.add(o.material);}});
materials.forEach((m)=>m.dispose());this.parent.remove(view.group);
}
set(spots:HydronicVisual[]) {
const keep=new Set<string>();
for(const station of spots){
if(station.item.type!=="freshwater_station"||!station.item.hydronic?.buffer_id)continue;
const buffer=spots.find((s)=>s.id===station.item.hydronic!.buffer_id&&s.floorId===station.floorId&&s.item.type==="buffer_tank");
if(!buffer)continue;keep.add(station.id);
const old=this.views.get(station.id);
const key=placementKey(station)+"/"+placementKey(buffer);
if(old?.key===key){old.station=station;old.buffer=buffer;continue;}
if(old)this.remove(old);
const group=new Group();group.name=`hydronic-connection-${station.id}`;
const r=Math.min(station.item.d*.05,.018),up=new Vector3(0,1,0);
for(const path of freshwaterConnectionPaths(station,buffer)){
const material=new MeshBasicMaterial({color:path.medium==="primary_flow"?0xb93e38:0x327cae});
for(let i=1;i<path.points.length;i++){
const a=path.points[i-1],b=path.points[i],delta=b.clone().sub(a),length=delta.length();if(length<1e-5)continue;
const mesh=new Mesh(new CylinderGeometry(r,r,length,10),material);mesh.position.copy(a).add(b).multiplyScalar(.5);mesh.quaternion.setFromUnitVectors(up,delta.normalize());mesh.name=path.medium;group.add(mesh);
}
for(const point of path.points.slice(1,-1)){const joint=new Mesh(new SphereGeometry(r,8,6),material);joint.position.copy(point);group.add(joint);}
}
this.parent.add(group);this.views.set(station.id,{station,buffer,group,key});
}
for(const[id,view]of this.views)if(!keep.has(id)){this.remove(view);this.views.delete(id);}
}
step(){for(const view of this.views.values()){const l=this.lift(view.station.floorId);view.group.visible=l.visible;view.group.position.y=l.y;}}
dispose(){for(const view of this.views.values())this.remove(view);this.views.clear();}
}
+5
View File
@@ -0,0 +1,5 @@
import type { Furniture } from "../model.ts";
export function bufferPort(f:Pick<Furniture,"w"|"d"|"h">,side:number,level:number) {
const r=Math.min(f.w,f.d)*.46,length=Math.min(f.w,f.d)*.14;
return{x:side*r*.95,y:f.h*level,z:0,length,r:Math.min(Math.min(f.w,f.d)*.03,f.h*.015),end:[side*(r*.95+length/2),f.h*level,0] as const};
}
+45 -27
View File
@@ -1,12 +1,15 @@
import { BoxGeometry, BufferGeometry, CircleGeometry, Color, Float32BufferAttribute, Group, Mesh, MeshBasicMaterial, SphereGeometry, type Scene } from "three";
import { BoxGeometry, BufferGeometry, CircleGeometry, Color, CylinderGeometry, Float32BufferAttribute, Group, Mesh, MeshBasicMaterial, SphereGeometry, type Scene } from "three";
import { hasPump, hasValve, hydronicConfig } from "../hydronic-model.ts";
import type { HydronicVisual } from "../hydronic-values.ts";
import { bufferTemperatureLayers,type HydronicVisual } from "../hydronic-values.ts";
import type { FloorLift } from "./live-energy.ts";
import { circuitLayout } from "./hydronic-layout.ts";
import { freshwaterLayout } from "./freshwater-layout.ts";
import { HydronicConnections } from "./hydronic-connections.ts";
interface Part { mesh: Mesh<BufferGeometry, MeshBasicMaterial>; kind: "pump" | "pumpState" | "valve" | "temperature"; circuit?: number; probe?: number; temp?: number; circulation?: boolean }
interface View { spot: HydronicVisual; group: Group; parts: Part[] }
interface Part { mesh: Mesh<BufferGeometry, MeshBasicMaterial>; kind: "pump" | "pumpState" | "valve" | "temperature" | "bufferBand"; circuit?: number; station?:number; probe?: number; temp?: number; circulation?: boolean; band?:number }
interface View { spot: HydronicVisual; group: Group; parts: Part[]; bands:(number|null)[] }
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);
const storageCold=new Color(0x147cba),storageMiddle=new Color(0xbce5e9),storageHot=new Color(0xd02b38);
/** Moving pump faces, valve pointers and actual probe colours, independent of the static furniture mesh. */
export class HydronicLayer {
@@ -14,7 +17,8 @@ export class HydronicLayer {
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 readonly connections:HydronicConnections;
constructor(scene: Scene, lift: FloorLift) { this.scene = scene; this.lift = lift; this.connections=new HydronicConnections(this.group,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);
@@ -25,67 +29,81 @@ export class HydronicLayer {
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;
view.spot = spot;view.bands=spot.item.type==="buffer_tank"?bufferTemperatureLayers(spot.probes):[];
}
this.connections.set(spots);
}
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> = {}, geometry?: BufferGeometry) => {
const mesh = new Mesh(geometry ?? (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.name = `hydronic-${kind}-${data.circulation ? "circulation" : data.station!==undefined?`station-${data.station}${kind==="temperature"?`-${data.temp??0}`:""}`:data.circuit ?? data.probe ?? data.temp ?? 0}`;
mesh.position.set(x, y, z); group.add(mesh); parts.push({ mesh, kind, ...data });
};
const pumpFace=(x:number,y:number,z:number,r:number,data:Partial<Part>)=>{
add(x,y,z+.001,r*.84,"pumpState",data,new CircleGeometry(r*.84,24));
const vertices:number[]=[];
for(let j=0;j<3;j++)for(const[xx,yy]of[[0,.1],[.28,.18],[0,.73]]){const a=j*Math.PI*2/3;vertices.push(r*(xx*Math.cos(a)-yy*Math.sin(a)),r*(xx*Math.sin(a)+yy*Math.cos(a)),0);}
add(x,y,z+.002,r,"pump",data,new BufferGeometry().setAttribute("position",new Float32BufferAttribute(vertices,3)));
};
if (f.type === "heating_manifold") {
const circuits = h.circuits ?? [];
circuits.forEach((c, i) => {
const p = circuitLayout(f,c,i,circuits.length);
if (hasPump(c)) {
add(p.flowX,p.pumpY,p.pumpFront+.001,p.pumpR*.84,"pumpState",{circuit:i},new CircleGeometry(p.pumpR*.84,24));
const vertices: number[] = [];
for (let j=0;j<3;j++) for (const [xx,yy] of [[0,.1],[.28,.18],[0,.73]]) {
const a=j*Math.PI*2/3;vertices.push(p.pumpR*(xx*Math.cos(a)-yy*Math.sin(a)),p.pumpR*(xx*Math.sin(a)+yy*Math.cos(a)),0);
}
add(p.flowX,p.pumpY,p.pumpFront+.002,p.pumpR,"pump",{circuit:i},new BufferGeometry().setAttribute("position",new Float32BufferAttribute(vertices,3)));
}
if (hasPump(c)) pumpFace(p.flowX,p.pumpY,p.pumpFront,p.pumpR,{circuit:i});
if (hasValve(c)) add(p.flowX,p.valveY,p.valveFront+.003,p.valveR*.8,"valve",{circuit:i});
add(p.flowGaugeX,p.temperatureY,p.gaugeFront+.001,p.gaugeR*.45,"temperature",{circuit:i,temp:0});
add(p.returnGaugeX,p.temperatureY,p.gaugeFront+.001,p.gaugeR*.45,"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; }
for(let i=0;i<24;i++){
const r=Math.min(f.w,f.d)*.464;
add(0,f.h*(.1+.8*(i+.5)/24),0,r,"bufferBand",{band:i},new CylinderGeometry(r,r,f.h*.8/24,32,1,true));
const material=parts.at(-1)!.mesh.material;material.transparent=true;material.opacity=.8;material.depthWrite=false;
}
} else {
const layout=freshwaterLayout(f);
layout.units.forEach((unit,i)=>{
const a=unit.pump;pumpFace(a.x,a.y,a.front,a.r,{station:i});
if(unit.valve){const v=unit.valve;add(v.x,v.y,v.front+.003,v.r*.8,"valve",{station:i});}
unit.probes.forEach((p,temp)=>add(p.x,p.y,p.front+.001,p.r*.5,"temperature",{station:i,temp}));
});
if(layout.circulationPipes.length){const a=layout.circPump;pumpFace(a.x,a.y,a.front,a.r,{circulation:true});const p=layout.circProbe;add(p.x,p.y,p.front+.001,p.r*.5,"temperature",{temp:2});}
}
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 };
group.name = `hydronic-${f.id}`; this.group.add(group); return { spot, group, parts,bands:[] };
}
step(now: number): boolean {
let moving = false;
this.connections.step();
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];
const station=p.station===undefined?undefined:spot.stations?.[p.station];
if(p.kind==="bufferBand"){
const value=v.bands[p.band??0];p.mesh.visible=value!==null&&value!==undefined;
if(value!==null&&value!==undefined){const mix=Math.max(0,Math.min(1,(value-20)/45));p.mesh.material.color.copy(mix<.5?storageCold:storageMiddle).lerp(mix<.5?storageMiddle:storageHot,mix<.5?mix*2:(mix-.5)*2);}
} else if (p.kind === "temperature") {
const value = p.station!==undefined?station?.temperatures[p.temp??0]: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" || p.kind === "pumpState") {
const running = c ? c.pump : p.circulation ? spot.circulation : spot.pump;
const running = p.station!==undefined?station?.pump??null:c ? c.pump : p.circulation ? spot.circulation : spot.pump;
if (p.kind === "pumpState") { p.mesh.material.color.set(running === null ? 0x72787e : running ? 0x4b9639 : 0xa82638); continue; }
p.mesh.material.color.set(c ? running === null ? 0xb2b7b9 : 0xe0e7d9 : running === null ? 0x89909a : running ? 0x6fe1a2 : 0x465361);
p.mesh.material.color.set(running === null ? 0xb2b7b9 : 0xe0e7d9);
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 : 0x8ec96a);
const valve=p.station!==undefined?station?.valve:c?.valve;
p.mesh.rotation.z = valve === null || valve === undefined ? 0 : valve / 100 * Math.PI / 2;
p.mesh.material.color.set(valve == null ? 0x89909a : c?.cooling ? 0x50b8ff : 0x8ec96a);
}
}
}
return moving;
}
dispose() { for (const v of this.views.values()) this.remove(v); this.views.clear(); this.scene.remove(this.group); }
dispose() { this.connections.dispose();for (const v of this.views.values()) this.remove(v); this.views.clear(); this.scene.remove(this.group); }
}