Compare commits

..
29 Commits
Author SHA1 Message Date
jhartworks d8cf076019 feat: add outdoor snapping, terrain types and procedural textures 2026-11-16 13:02:18 +01:00
jhartworks 992c3e18f2 feat: add fresh-water cascades with independent stations and buffer links 2026-11-12 16:16:01 +01:00
jhartworks a2a119d3ee feat: reveal device cards progressively with camera zoom 2026-11-12 15:41:35 +01:00
jhartworks e62f987563 fix: rebuild hydronic circuits around correct inline pipework 2026-11-12 15:27:17 +01:00
jhartworks 59292517b7 feat: add native charging station telemetry and aliased lock status 2026-11-12 14:55:18 +01:00
jhartworks df4a6f36a3 feat: show metered devices below rooms in utility overview 2026-11-12 14:44:02 +01:00
jhartworks 173d02e3cc feat: add 3D hydronic manifolds buffer tanks and fresh water stations 2026-11-12 14:28:30 +01:00
jhartworks 93c015ec77 fix: group utility overview by area and show explicit room meters 2026-11-12 12:09:21 +01:00
jhartworks 8c6b23bd22 fix: select native variables by datatype and explain rejected links 2026-11-12 10:14:19 +01:00
jhartworks 4967dd7950 feat: add floating power cards for all powered furniture 2026-11-11 16:24:52 +01:00
jhartworks 6bd3598779 feat: toggle and remember right utility overview visibility 2026-11-11 13:00:36 +01:00
jhartworks 5fd674bb00 feat: show scoped utility overviews and compact trend controls 2026-11-11 12:33:54 +01:00
jhartworks 2bf5f4a60a fix: keep compact trend icons aligned beside room values 2026-11-11 12:15:37 +01:00
jhartworks cfc77787a0 feat: add native Symcon archive trends and explicit room naming 2026-11-11 12:00:51 +01:00
jhartworks bb153490b0 fix: show incomplete Symcon utility sums with Err prefix 2026-11-11 10:08:20 +01:00
jhartworks a804fc8e15 feat: discover Symcon room utility meters and sum floor consumption 2026-11-11 09:55:26 +01:00
jhartworks 18e73194e0 feat: add native Symcon room climate, schedules, weather and presence 2026-11-11 09:34:26 +01:00
jhartworks 510aece983 fix: retain Symcon webhook registration and show configured view title 2026-11-10 12:39:30 +01:00
jhartworks 8845efdc23 fix: hide room climate cards in all-floors overview 2026-11-10 12:32:59 +01:00
jhartworks 3f6cca056c feat: add room name switches to 3D view and editor toolbars 2026-11-10 10:41:07 +01:00
jhartworks 7a9b2c0a38 fix: restrict blind direction reversal to 3D appearance 2026-11-10 10:31:41 +01:00
jhartworks b9a095bc6e fix: keep Symcon binding paths compact and allow direct unlinking 2026-11-10 10:00:01 +01:00
jhartworks 00fca890de feat: improve Symcon controls, device readings and designer help 2026-11-10 09:19:13 +01:00
jhartworks ff54f4461a feat: add floating room climate cards and fix Symcon humidity selection 2026-11-09 17:04:46 +01:00
jhartworks 24188f96f7 fix: support Symcon numeric dimmers and independent blind slat controls 2026-11-09 15:24:59 +01:00
jhartworks b934f78b9a feat: improve Symcon designer controls and KNX temperature selection 2026-11-09 15:01:54 +01:00
jhartworks 804f2d0494 fix: bound Symcon API responses below the kernel output limit 2026-11-09 14:37:21 +01:00
jhartworks eff9eb83d7 feat: release Symcon 0.2.2 with object tree selection and hook recovery 2026-11-09 12:50:45 +01:00
jhartworks 4a875aa8ea fix: restore Symcon instance discovery 2026-11-09 11:00:00 +01:00
180 changed files with 15499 additions and 3705 deletions

No files matched your search

+86
View File
@@ -4,6 +4,92 @@ All notable changes to NextFloor, newest first. Every release lists what is **Ad
## [Unreleased] ## [Unreleased]
### Added
- **Outdoor snapping and surface textures (Symcon 0.2.29):** Snap outdoor outlines to nearby corners and edges when drawing, moving or resizing, preserving whole-area geometry and Alt bypass. Add street, sidewalk, gravel, river and stream surfaces with schema persistence; river/stream areas default to cutting through surrounding surfaces. All outdoor materials use local metre-scaled procedural textures with distance filtering, including paving joints, asphalt grain, pebbles, vegetation, earth, wood and water ripples. Textures compose with floor fading, slopes, transparency and scene themes without external assets.
- **Fresh-water cascades with storage links (Symcon 0.2.28):** Rebuild the 3D station around separate primary and potable-water paths and a plate exchanger. Add up to 16 named parallel units with independent native temperature, power, pump and isolation-valve links; preserve legacy single-station bindings on edit. Share the supply/return, hot/cold-water and optional circulation headers, keep one compact cascade overlay, and open per-station readouts/commands with archive trends and existing read-only guards. Link a placed same-floor buffer through two primary-only pipes that follow placement and floor transforms; removal releases connections and subscriptions. Buffer colour layers interpolate measured probes only. Adding/removing units adjusts width and never sends device commands or invents parent utility totals.
- **Charging station telemetry (Symcon 0.2.25):** Built-in and pack wallboxes expose native object-tree links for SoC, start/end time, charging duration, charged energy and Integer lock status with unchanged Symcon associations. Optional floating cards and room readouts work without a power/switch link, hide unlinked rows, retain zero/live/offline values and offer archive trends. Time/duration formats support native display and explicit numeric units. All telemetry is read-only.
- **Metered device hierarchy (Symcon 0.2.24):** Show placed devices and furniture with linked power below their plan room and native area in the right overview. Rooms without their own meter act as value-free headings; existing room counters remain separate. Device readings, including manifold pump power, retain zero/offline/live values and archive icons without changing parent totals. The hierarchy stays accessible on device-only floors.
- **Hydronic 3D equipment (Symcon 0.2.23):** Place configurable heating/cooling manifolds, buffer tanks and fresh-water stations from the furniture library. Manifolds support separate valve/pump circuits and valve-free feed pumps, independent command/readback bindings, raw-value changeover selection and visual-only valve inversion. Buffers start with seven height-configurable probe slots and support up to 64 plus flow/return; fresh-water stations expose flow, return, circulation and domestic hot water with independent charging/circulation pumps. Live pump rotors, valve pointers and probe colours accompany lazy floating cards/dialogs, archive trends and native action controls with read-only guards. Feedback stays authoritative even offline; native values and write ranges remain unchanged. Multi-reading hydraulic cards use nearby free columns to stay on screen.
- **Native area and room utility hierarchy (Symcon 0.2.22):** Floor overviews group by the linked native area ID and display its category name and readings once. Only rooms with explicitly assigned power/flow or consumption meters appear as indented children. The room editor provides native numeric meter selectors for all five media; children retain live values, archive access and navigation. Existing area totals cover room details; explicit room meters supply missing quantities without double counting and floor meters retain precedence.
- **Native picker feedback (Symcon 0.2.21):** Rejected selections explain native datatype requirements, instances/categories, missing variables or already linked schedules/presence variables inside the popup. Confirmation cannot apply an older pending choice after a rejection. Manual native variable selection uses actual datatypes instead of name/path/profile/domain heuristics; Boolean garage and staircase lights both support an explicit on/off light role without a dimmer, retaining saved references.
- **Furniture power cards (Symcon 0.2.20):** Every furniture item with a power link can opt into a floating 3D power card, including pack wallboxes with only a power variable. Cards retain zero/export readings, show missing readings as a dash, expose native archive trends and follow floor/room navigation and the global Cards switch. Native integer/float power variables remain selectable regardless of inferred device domain; power-only pack lights also offer marker settings.
- **Utility overview visibility switch:** The top bar can completely hide or restore the right floor/room overview independently of the top totals, with the choice remembered in the browser.
- **Native utility overview by scope:** The top bar shows building totals in all-floors view and the selected floor's totals otherwise. A quiet, foldable side card lists floors or rooms with power/flow and consumption, trend access, live updates and navigation. Building totals respect floor overrides and deduplicate shared native meters.
- **Native Symcon archive trends:** Logged values expose a compact trend icon in floating room cards and room/HVAC/weather/meter readouts. A lazy dialog reads original archive data with custom time/resolution and Y limits, time navigation, wheel/drag zoom, line/step/bar/table views, min/max, live refresh and CSV export. Counter aggregation uses native interval consumption; Boolean/string logs, empty/error/limited responses and different units are handled explicitly.
- **Native Symcon utility meters:** Discover electricity, water, gas, heating and cooling meters in a room's linked area hierarchy, including hidden categories and dummy modules. Display instantaneous power/flow and cumulative energy/consumption separately, sum compatible room readings per floor, and allow independent floor meter overrides for every medium through the object-tree picker. Preserve periods and units, deduplicate links, prefer parent totals over sub-meters, watch live updates, and expose room and floor reports.
- **Native Symcon room climate and clocks:** Select underfloor heating, supply/extract VSRs and temperatures, reheater and an aliased Integer room status from the object tree. The room menu displays and controls native writable values and shows multiple classic weekly schedules with day groups, switch points, action labels and activation controls.
- **Native Symcon weather and presence:** Link individual weather variables and arbitrary Boolean presence variables; weather data drives the 3D sky and rain warnings, while named people appear in the status bar and optionally in a chosen room.
- **Room-name toolbar switches:** The 3D view and editor expose a direct room-name switch at the top, sharing the remembered designer preference. Cards expose the same switch in their 3D top bar. Hiding room names keeps notes, devices and climate cards visible.
- **Room illuminance and multiple device readings:** Rooms can link a brightness sensor and show lux with a sun symbol; CO₂ uses a cloud. A small + button adds device/furniture values with independent object-tree choices, custom symbols and optional labels, shown on device markers and in the room panel.
- **Floating room climate cards:** Each room can show temperature, humidity and CO₂ in a glass card above its own position, using its selected sensors. Cards follow live values and room/floor navigation and can be toggled without configuring an energy meter.
- **IP-Symcon variable reload:** A button in the designer title bar reloads the complete object tree, variables and current presentation metadata without closing the plan, with progress, success and error feedback.
- **IP-Symcon object-tree picker:** Data point fields open a modal dialog with the real Symcon hierarchy, including instances, links, hidden objects and empty categories, ordered as in the console. Search keeps matching objects in their original branches; confirmation, cancellation and keyboard navigation are supported.
### Changed
- **Zoom-dependent device cards (Symcon 0.2.27):** Use actual perspective pixels per plan metre to reveal room, equipment and device details progressively. Active consumption/export appears before idle zero-W cards, with hysteresis around zoom boundaries. Keep summaries/totals independent, prioritise useful readings, preserve focused controls, and hide overflowing or excessively displaced device cards instead of creating long towers. Zooming/panning back into the group restores its detail cards without changing data or bindings.
- **Corrected hydronic 3D circuits (Symcon 0.2.26):** Match the supplied mixed-circuit reference with separate lower supply/return headers, depth-separated crossings, inline flow-side pump and valve, upper temperature probes and a consumer symbol. Three-way mixers connect to the return; two-way valves and valve-free feed groups omit that bypass. Static pipework and live instruments share their layout. Pump faces distinguish running/stopped/unknown feedback, while bindings, native values and visual-only inversion remain unchanged. Correct outward winding on lying cylinder walls and both end caps, including mirrored models.
- **Compact trend popup:** Move custom time/resolution, display options, Y limits and CSV behind a settings button, keep a compact quick toolbar, and give the responsive chart most of the popup height. The settings overlay preserves chart size.
- **Explicit Symcon area names:** Selecting a room area preserves the room name. A dedicated button adopts only the actual leaf category name.
- **Incomplete Symcon utility sums:** Keep the sum of available meter values and prefix it with `Err:` in room/floor reports and power labels. Show `Err: –` when every source is unavailable and remove the marker automatically after recovery.
- **Symcon interface:** Underfloor heating moves into room climate. The linked room-status alias replaces the calculated comfort value. Announcement, speaker, quiet-time and Bluetooth-location controls are removed from the Symcon interface.
- **Symcon view title and form:** The configured visualization name replaces the NextFloor header text; the explanatory paragraph in the instance form is removed.
- **Room climate cards in floor views:** The all-floors overview hides the floating room climate cards. Opening a floor or room shows its enabled cards again.
- **Designer help popups:** Explanations are opened through compact information symbols instead of occupying the forms. Keyboard and touch users can open and dismiss the dialogs.
- **Compact room climate cards:** Floating cards show symbols and values without repeating the room name or labels. Unlinked metrics and entirely empty cards are hidden; linked unavailable sensors retain a dash.
- **Foldable wall menu:** The wall settings in the room sidebar can be collapsed using their heading.
- **IP-Symcon picker main category:** Hidden categories and their variables always remain visible. I/O, splitter, core, configurator, discovery and visualization instances are grouped under a collapsed virtual “System” folder, with searchable/selectable descendants and no changes to the actual Symcon object tree.
### Fixed
- **Compact trend icons and stable climate rows:** Shrink the chart glyph to 12 px with a frameless 18 px button. Floating room cards give icons their own aligned column so logged and unlogged readings retain the same value alignment and row height.
- **Symcon WebHook lifecycle:** Register already during Create, on kernel ready/start and after updates. Ongoing registration maintenance restores delayed route loss even after a previous success, while preserving the instance URL, token and project.
- **Symcon picker width and unlinking:** Long selected object names and paths are truncated within the form, with the full path in a tooltip. A dedicated clear button removes the binding directly and preserves other room-climate sensors.
- **IP-Symcon blind feedback and visual directions:** Numeric position feedback can be selected independently of inferred domains and is read using its native range. Blind and slat directions can be reversed separately in 3D only. Displayed readings, sliders, buttons, swipes and grouped commands keep their original values, including zero; feedback variables are never written.
- **IP-Symcon room humidity selection:** Manual room-climate fields accept numeric Integer/Float variables even without inferred classes or profiles. German “Feuchtigkeit” and subscript “CO₂” names are recognized, and parent category names no longer override measurement classes.
- **IP-Symcon dimmers and venetian blinds:** Numeric variables can be explicitly linked as dimmers or blind controls independently of inferred names. Native integer/float ranges and steps are respected in both directions. Separate blind-height and slat-position variables can be selected in the object tree and controlled independently in the room panel and quick menu; dimmer sliders stay available while off.
- **IP-Symcon KNX room temperatures:** Current Symcon presentation units are read alongside legacy profiles. Numeric temperature variables remain selectable and readable even when a parent name caused an actuator classification; saved mappings stay intact.
- **IP-Symcon “HTTP 200” / output-buffer overflow:** Large API responses use bounded response chunks instead of exceeding the kernel's 1 MiB output limit. The full variable/object tree, packs, plans, images and backups are reassembled without data loss, polling cannot overlap, and malformed responses receive a useful error message.
- **IP-Symcon “Hook not found”:** The module restores its internal WebHook after kernel startup and before opening the designer or tile, reports registration failures instead of showing “ready”, retries failed registrations and offers a “Repair WebHook” button without replacing the instance or its saved project.
- **IP-Symcon module discovery:** NextFloor is registered as a regular device instance with complete module metadata, so it is available in “Add instance”. The independent HTML-SDK tile remains enabled. A package check now rejects invalid module types, missing manifest fields and an incorrect installation directory layout before building.
- **IP-Symcon designer version check:** The frontend uses the Symcon library version rather than the Home Assistant integration version, preventing an incorrect Home Assistant restart prompt.
## [0.26.6] ## [0.26.6]
### Added ### Added
File diff suppressed because it is too large. Load diff
@@ -1,28 +1,28 @@
/*! NextFloor, MIT licence. Includes three.js (MIT) and Lit (BSD-3-Clause); see LICENSE and THIRD_PARTY_NOTICES.md */ /*! NextFloor, MIT licence. Includes three.js (MIT) and Lit (BSD-3-Clause); see LICENSE and THIRD_PARTY_NOTICES.md */
var p={cs:"4be67fcd522e",da:"0fe66a82bf2a",es:"bd89dffd1355",fi:"9a17bc084f56",fr:"6312d0f61ebf",hu:"27ba348531dc",it:"1b705e76dd00",nb:"c5ea24fb9ef6",nl:"b64142c67c2e",pl:"8527a4930402",pt:"31857a2d2277",ro:"e3cb5f449f0f",sk:"320611594db0",sl:"8071691ceda3",sv:"711b911ec8da",tr:"7c83ce1c3372",zh:"50518d9f494e"};var M=globalThis,N=M.ShadowRoot&&(M.ShadyCSS===void 0||M.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,U=Symbol(),me=new WeakMap,R=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==U)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(N&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=me.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&me.set(t,e))}return e}toString(){return this.cssText}},pe=i=>new R(typeof i=="string"?i:i+"",void 0,U),V=(i,...e)=>{let t=i.length===1?i[0]:e.reduce((n,r,o)=>n+(a=>{if(a._$cssResult$===!0)return a.cssText;if(typeof a=="number")return a;throw Error("Value passed to 'css' function must be a 'css' function result: "+a+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+i[o+1],i[0]);return new R(t,i,U)},fe=(i,e)=>{if(N)i.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(let t of e){let n=document.createElement("style"),r=M.litNonce;r!==void 0&&n.setAttribute("nonce",r),n.textContent=t.cssText,i.appendChild(n)}},j=N?i=>i:i=>i instanceof CSSStyleSheet?(e=>{let t="";for(let n of e.cssRules)t+=n.cssText;return pe(t)})(i):i;var{is:Ke,defineProperty:Ge,getOwnPropertyDescriptor:Oe,getOwnPropertyNames:Ie,getOwnPropertySymbols:Ze,getPrototypeOf:Ue}=Object,C=globalThis,ge=C.trustedTypes,Ve=ge?ge.emptyScript:"",je=C.reactiveElementPolyfillSupport,F=(i,e)=>i,q={toAttribute(i,e){switch(e){case Boolean:i=i?Ve:null;break;case Object:case Array:i=i==null?i:JSON.stringify(i)}return i},fromAttribute(i,e){let t=i;switch(e){case Boolean:t=i!==null;break;case Number:t=i===null?null:Number(i);break;case Object:case Array:try{t=JSON.parse(i)}catch{t=null}}return t}},we=(i,e)=>!Ke(i,e),be={attribute:!0,type:String,converter:q,reflect:!1,useDefault:!1,hasChanged:we};Symbol.metadata??=Symbol("metadata"),C.litPropertyMetadata??=new WeakMap;var b=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=be){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&Ge(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:o}=Oe(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:r,set(a){let s=r?.call(this);o?.call(this,a),this.requestUpdate(e,s,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??be}static _$Ei(){if(this.hasOwnProperty(F("elementProperties")))return;let e=Ue(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(F("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(F("properties"))){let t=this.properties,n=[...Ie(t),...Ze(t)];for(let r of n)this.createProperty(r,t[r])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[n,r]of t)this.elementProperties.set(n,r)}this._$Eh=new Map;for(let[t,n]of this.elementProperties){let r=this._$Eu(t,n);r!==void 0&&this._$Eh.set(r,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let r of n)t.unshift(j(r))}else e!==void 0&&t.push(j(e));return t}static _$Eu(e,t){let n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return fe(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.Line truncated var m={cs:"4be67fcd522e",da:"0fe66a82bf2a",es:"bd89dffd1355",fi:"9a17bc084f56",fr:"6312d0f61ebf",hu:"27ba348531dc",it:"1b705e76dd00",nb:"c5ea24fb9ef6",nl:"b64142c67c2e",pl:"8527a4930402",pt:"31857a2d2277",ro:"e3cb5f449f0f",sk:"320611594db0",sl:"8071691ceda3",sv:"711b911ec8da",tr:"7c83ce1c3372",zh:"50518d9f494e"};var M=globalThis,N=M.ShadowRoot&&(M.ShadyCSS===void 0||M.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,U=Symbol(),pe=new WeakMap,R=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==U)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(N&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=pe.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&pe.set(t,e))}return e}toString(){return this.cssText}},fe=i=>new R(typeof i=="string"?i:i+"",void 0,U),j=(i,...e)=>{let t=i.length===1?i[0]:e.reduce((n,r,o)=>n+(a=>{if(a._$cssResult$===!0)return a.cssText;if(typeof a=="number")return a;throw Error("Value passed to 'css' function must be a 'css' function result: "+a+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+i[o+1],i[0]);return new R(t,i,U)},ge=(i,e)=>{if(N)i.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(let t of e){let n=document.createElement("style"),r=M.litNonce;r!==void 0&&n.setAttribute("nonce",r),n.textContent=t.cssText,i.appendChild(n)}},q=N?i=>i:i=>i instanceof CSSStyleSheet?(e=>{let t="";for(let n of e.cssRules)t+=n.cssText;return fe(t)})(i):i;var{is:Ge,defineProperty:Oe,getOwnPropertyDescriptor:Ie,getOwnPropertyNames:Ze,getOwnPropertySymbols:Ve,getPrototypeOf:Ue}=Object,C=globalThis,be=C.trustedTypes,je=be?be.emptyScript:"",qe=C.reactiveElementPolyfillSupport,F=(i,e)=>i,J={toAttribute(i,e){switch(e){case Boolean:i=i?je:null;break;case Object:case Array:i=i==null?i:JSON.stringify(i)}return i},fromAttribute(i,e){let t=i;switch(e){case Boolean:t=i!==null;break;case Number:t=i===null?null:Number(i);break;case Object:case Array:try{t=JSON.parse(i)}catch{t=null}}return t}},ke=(i,e)=>!Ge(i,e),we={attribute:!0,type:String,converter:J,reflect:!1,useDefault:!1,hasChanged:ke};Symbol.metadata??=Symbol("metadata"),C.litPropertyMetadata??=new WeakMap;var b=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=we){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&Oe(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:o}=Ie(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:r,set(a){let s=r?.call(this);o?.call(this,a),this.requestUpdate(e,s,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??we}static _$Ei(){if(this.hasOwnProperty(F("elementProperties")))return;let e=Ue(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(F("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(F("properties"))){let t=this.properties,n=[...Ze(t),...Ve(t)];for(let r of n)this.createProperty(r,t[r])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[n,r]of t)this.elementProperties.set(n,r)}this._$Eh=new Map;for(let[t,n]of this.elementProperties){let r=this._$Eu(t,n);r!==void 0&&this._$Eh.set(r,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let r of n)t.unshift(q(r))}else e!==void 0&&t.push(q(e));return t}static _$Eu(e,t){let n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return ge(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.Line truncated
\f\r]`,x=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ye=/-->/g,Se=/>/g,S=RegExp(`>|${J}(?:([^\\s"'>=/]+)(${J}*=${J}*(?:[^ \f\r]`,x=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Se=/-->/g,Ae=/>/g,S=RegExp(`>|${X}(?:([^\\s"'>=/]+)(${X}*=${X}*(?:[^
\f\r"'\`<>=]|("|')|))|$)`,"g"),Ae=/'/g,De=/"/g,Re=/^(?:script|style|textarea|title)$/i,ie=i=>(e,...t)=>({_$litType$:i,strings:e,values:t}),l=ie(1),ct=ie(2),ut=ie(3),z=Symbol.for("lit-noChange"),d=Symbol.for("lit-nothing"),ze=new WeakMap,A=D.createTreeWalker(D,129);function Fe(i,e){if(!re(i)||!i.hasOwnProperty("raw"))throw Error("invalid template strings array");return ve!==void 0?ve.createHTML(e):e}var Xe=(i,e)=>{let t=i.length-1,n=[],r,o=e===2?"<svg>":e===3?"<math>":"",a=x;for(let s=0;s<t;s++){let h=i[s],u,m,_=-1,g=0;for(;g<h.length&&(a.lastIndex=g,m=a.exec(h),m!==null);)g=a.lastIndex,a===x?m[1]==="!--"?a=ye:m[1]!==void 0?a=Se:m[2]!==void 0?(Re.test(m[2])&&(r=RegExp("</"+m[2],"g")),a=S):m[3]!==void 0&&(a=S):a===S?m[0]===">"?(a=r??x,_=-1):m[1]===void 0?_=-2:(_=a.lastIndex-m[2].length,u=m[1],a=m[3]===void 0?S:m[3]==='"'?De:Ae):a===De||a===Ae?a=S:a===ye||a===Se?a=x:(a=S,r=void 0);let k=a===S&&i[s+1].startsWith("/>")?" ":"";o+=a===x?h+qe:_>=0?(n.push(u),h.slice(0,_)+Ee+h.slice(_)+v+k):h+v+(_===-2?s:k)}return[Fe(i,o+(i[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]},B=class i{constructor({strings:e,_$litType$:t},n){let r;this.parts=[];let o=0,a=0,s=e.length-1,h=this.parts,[u,m]=Xe(e,t);if(this.el=i.createElement(u,n),A.currentNode=this.el.content,t===2||t===3){let _=this.el.content.firstChild;_.replaceWith(..._.childNodes)}for(;(r=A.nextNode())!==null&&h.length<s;){if(r.nodeType===1){if(r.hasAttributes())for(let _ of r.getAttributeNames())if(_.endsWith(Ee)){let g=m[a++],k=r.getAttribute(_).split(v),L=/([.?@])?(.*)/.exec(g);h.push({type:1,index:o,name:L[2],strings:k,ctor:L[1]==="."?Y:L[1]==="?"?Q:L[1]==="@"?ee:T}),r.removeAttribute(_)}else _.startsWith(v)&&(h.push({type:6,index:o}),r.removeAttribute(_));if(Re.test(r.tagName)){let _=r.textContent.split(v),g=_.length-1;if(g>0){r.textContent=K?K.emptyScript:"";for(let k=0;k<g;k++)r.append(_[k],H()),A.nextNode(),h.push({type:2,index:++o});r.append(_[g],H())}}}else if(r.nodeType===8)if(r.data===Te)h.push({type:2,index:o});else{let _=-1;for(;(_=r.data.indexOf(v,_+1))!==-1;)h.push({type:7,index:o}),_+=v.length-1}o++}}static createElement(e,t){let n=D.createElement("template");return n.innerHTML=e,n}};function E(i,e,t=i,n){if(e===z)return e;let r=n!==void 0?t._$Co?.[n]:t._$Cl,o=W(e)?void 0:e._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(i),r._$AT(i,t,n)),n!==void 0?(t._$Co??=[])[n]=r:t._$Cl=r),r!==void 0&&(e=E(i,r._$AS(i,e.values),r,n)),e}var X=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??D).importNode(t,!0);A.currentNode=r;let o=A.nextNode(),a=0,s=0,h=n[0];for(;h!==void 0;){if(a===h.index){let u;h.type===2?u=new P(o,o.nextSibling,this,e):h.type===1?u=new h.ctor(o,h.name,h.strings,this,e):h.type===6&&(u=new te(o,this,e)),this._$AV.push(u),h=n[++s]}a!==h?.index&&(o=A.nextNode(),a++)}return A.currentNode=D,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings!==void 0?(n._$AI(e,n,t),t+=n.strings.length-2):n._$AI(e[t])),t++}},P=class i{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=d,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=E(this,e,t),W(e)?e===d||e==null||e===""?(this._$AH!==d&&this._$AR(),this._$AH=d):e!==this._$AH&&e!==z&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Je(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==d&&W(this._$AH)?this._$AA.nextSibling.data=e:this.T(D.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=B.createElement(Fe(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let o=new X(r,this),a=o.u(this.options);o.p(t),this.T(a),this._$AH=o}}_$AC(e){let t=ze.get(e.strings);return t===void 0&&ze.set(e.strings,t=new B(e)),t}k(e){re(this._$AH)||(this._$AH=[],this._$AR());let t=this._$AH,n,r=0;for(let o of e)r===t.length?t.push(n=new i(this.O(H()),this.O(H()),this,this.options)):n=t[r],n._$AI(o),r++;r<t.length&&(this._$AR(n&&n._$AB.nextSibling,r),t.length=r)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let n=ke(e).nextSibling;ke(e).remove(),e=n}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},T=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,o){this.type=1,this._$AH=d,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=o,n.length>2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):thiLine truncated \f\r"'\`<>=]|("|')|))|$)`,"g"),De=/'/g,ze=/"/g,Fe=/^(?:script|style|textarea|title)$/i,oe=i=>(e,...t)=>({_$litType$:i,strings:e,values:t}),l=oe(1),ut=oe(2),mt=oe(3),z=Symbol.for("lit-noChange"),d=Symbol.for("lit-nothing"),Ee=new WeakMap,A=D.createTreeWalker(D,129);function xe(i,e){if(!ie(i)||!i.hasOwnProperty("raw"))throw Error("invalid template strings array");return ye!==void 0?ye.createHTML(e):e}var Ye=(i,e)=>{let t=i.length-1,n=[],r,o=e===2?"<svg>":e===3?"<math>":"",a=x;for(let s=0;s<t;s++){let h=i[s],u,p,_=-1,g=0;for(;g<h.length&&(a.lastIndex=g,p=a.exec(h),p!==null);)g=a.lastIndex,a===x?p[1]==="!--"?a=Se:p[1]!==void 0?a=Ae:p[2]!==void 0?(Fe.test(p[2])&&(r=RegExp("</"+p[2],"g")),a=S):p[3]!==void 0&&(a=S):a===S?p[0]===">"?(a=r??x,_=-1):p[1]===void 0?_=-2:(_=a.lastIndex-p[2].length,u=p[1],a=p[3]===void 0?S:p[3]==='"'?ze:De):a===ze||a===De?a=S:a===Se||a===Ae?a=x:(a=S,r=void 0);let k=a===S&&i[s+1].startsWith("/>")?" ":"";o+=a===x?h+Je:_>=0?(n.push(u),h.slice(0,_)+Te+h.slice(_)+v+k):h+v+(_===-2?s:k)}return[xe(i,o+(i[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]},B=class i{constructor({strings:e,_$litType$:t},n){let r;this.parts=[];let o=0,a=0,s=e.length-1,h=this.parts,[u,p]=Ye(e,t);if(this.el=i.createElement(u,n),A.currentNode=this.el.content,t===2||t===3){let _=this.el.content.firstChild;_.replaceWith(..._.childNodes)}for(;(r=A.nextNode())!==null&&h.length<s;){if(r.nodeType===1){if(r.hasAttributes())for(let _ of r.getAttributeNames())if(_.endsWith(Te)){let g=p[a++],k=r.getAttribute(_).split(v),$=/([.?@])?(.*)/.exec(g);h.push({type:1,index:o,name:$[2],strings:k,ctor:$[1]==="."?Q:$[1]==="?"?ee:$[1]==="@"?te:T}),r.removeAttribute(_)}else _.startsWith(v)&&(h.push({type:6,index:o}),r.removeAttribute(_));if(Fe.test(r.tagName)){let _=r.textContent.split(v),g=_.length-1;if(g>0){r.textContent=K?K.emptyScript:"";for(let k=0;k<g;k++)r.append(_[k],H()),A.nextNode(),h.push({type:2,index:++o});r.append(_[g],H())}}}else if(r.nodeType===8)if(r.data===Re)h.push({type:2,index:o});else{let _=-1;for(;(_=r.data.indexOf(v,_+1))!==-1;)h.push({type:7,index:o}),_+=v.length-1}o++}}static createElement(e,t){let n=D.createElement("template");return n.innerHTML=e,n}};function E(i,e,t=i,n){if(e===z)return e;let r=n!==void 0?t._$Co?.[n]:t._$Cl,o=W(e)?void 0:e._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(i),r._$AT(i,t,n)),n!==void 0?(t._$Co??=[])[n]=r:t._$Cl=r),r!==void 0&&(e=E(i,r._$AS(i,e.values),r,n)),e}var Y=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??D).importNode(t,!0);A.currentNode=r;let o=A.nextNode(),a=0,s=0,h=n[0];for(;h!==void 0;){if(a===h.index){let u;h.type===2?u=new P(o,o.nextSibling,this,e):h.type===1?u=new h.ctor(o,h.name,h.strings,this,e):h.type===6&&(u=new ne(o,this,e)),this._$AV.push(u),h=n[++s]}a!==h?.index&&(o=A.nextNode(),a++)}return A.currentNode=D,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings!==void 0?(n._$AI(e,n,t),t+=n.strings.length-2):n._$AI(e[t])),t++}},P=class i{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=d,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=E(this,e,t),W(e)?e===d||e==null||e===""?(this._$AH!==d&&this._$AR(),this._$AH=d):e!==this._$AH&&e!==z&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Xe(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==d&&W(this._$AH)?this._$AA.nextSibling.data=e:this.T(D.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=B.createElement(xe(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let o=new Y(r,this),a=o.u(this.options);o.p(t),this.T(a),this._$AH=o}}_$AC(e){let t=Ee.get(e.strings);return t===void 0&&Ee.set(e.strings,t=new B(e)),t}k(e){ie(this._$AH)||(this._$AH=[],this._$AR());let t=this._$AH,n,r=0;for(let o of e)r===t.length?t.push(n=new i(this.O(H()),this.O(H()),this,this.options)):n=t[r],n._$AI(o),r++;r<t.length&&(this._$AR(n&&n._$AB.nextSibling,r),t.length=r)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let n=ve(e).nextSibling;ve(e).remove(),e=n}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},T=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,o){this.type=1,this._$AH=d,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=o,n.length>2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):thLine truncated
<input type="checkbox" .checked=${e} @change=${o=>r(nt(o))} /> <input type="checkbox" .checked=${e} @change=${o=>r(rt(o))} />
<span>${i.t(t)}${n?l`<small>${i.t(n)}</small>`:d}</span> <span>${i.t(t)}${n?l`<small>${i.t(n)}</small>`:d}</span>
</label>`}var c=(i,e,t,n)=>f(i,i.value[e],t,n,r=>i.set(e,r)),se=(i,e,t,n)=>f(i,i.value[e],t,n,r=>i.set(e,r||void 0));function w(i,e,t,n,r){return l`<label class="field" </label>`}var c=(i,e,t,n)=>f(i,i.value[e],t,n,r=>i.set(e,r)),le=(i,e,t,n)=>f(i,i.value[e],t,n,r=>i.set(e,r||void 0));function w(i,e,t,n,r){return l`<label class="field"
>${i.t(t)} >${i.t(t)}
<select @change=${o=>i.set(e,O(o))}> <select @change=${o=>i.set(e,O(o))}>
${n.map(([o,a])=>l`<option value=${o} ?selected=${o===r}>${i.t(a)}</option>`)} ${n.map(([o,a])=>l`<option value=${o} ?selected=${o===r}>${i.t(a)}</option>`)}
</select> </select>
</label>`}function le(i,e,t,n){return l`<label class="field" </label>`}function he(i,e,t,n){return l`<label class="field"
>${i.t(t)} >${i.t(t)}
<select @change=${r=>i.set(e,Number(O(r))||void 0)}> <select @change=${r=>i.set(e,Number(O(r))||void 0)}>
${n.map(r=>l`<option value=${r.value} ?selected=${i.value[e]===r.value}>${r.text}</option>`)} ${n.map(r=>l`<option value=${r.value} ?selected=${i.value[e]===r.value}>${r.text}</option>`)}
</select> </select>
</label>`}function I(i,e,t,n=""){return l`<label class="field wide" </label>`}function I(i,e,t,n=""){return l`<label class="field wide"
>${i.t(t)} >${i.t(t)}
<input type="text" placeholder=${n} .value=${i.value[e]??""} @change=${r=>i.set(e,tt(r).trim()||void 0)} /> <input type="text" placeholder=${n} .value=${i.value[e]??""} @change=${r=>i.set(e,nt(r).trim()||void 0)} />
</label>`}function he(i,e,t,n){let r=n===void 0?"switch":n?"on":"off",o=[["switch","card_flows_switch"],["on","card_flows_on"],["off","card_flows_off"]];return l`<label class="field wide" </label>`}function de(i,e,t,n){let r=n===void 0?"switch":n?"on":"off",o=[["switch","card_flows_switch"],["on","card_flows_on"],["off","card_flows_off"]];return l`<label class="field wide"
>${i.t(t)} >${i.t(t)}
<select @change=${a=>i.set(e,O(a)==="switch"?void 0:O(a)==="on")}> <select @change=${a=>i.set(e,O(a)==="switch"?void 0:O(a)==="on")}>
${o.map(([a,s])=>l`<option value=${a} ?selected=${r===a}>${i.t(s)}</option>`)} ${o.map(([a,s])=>l`<option value=${a} ?selected=${r===a}>${i.t(s)}</option>`)}
</select> </select>
</label>`}var Pe=V` </label>`}var Le=j`
:host { :host {
display: block; display: block;
color: var(--primary-text-color); color: var(--primary-text-color);
@@ -115,29 +115,29 @@ var p={cs:"4be67fcd522e",da:"0fe66a82bf2a",es:"bd89dffd1355",fi:"9a17bc084f56",f
grid-template-columns: 1fr; grid-template-columns: 1fr;
} }
} }
`;var ce=globalThis,de=ce.__nextfloorBuiltin?.de??{},_e=ce.__nextfloorBuiltin?.en??{};ce.__nextfloorBuiltin??={de,en:_e};var $e=()=>typeof p=="object"&&p||{},rt=globalThis,Z=rt.__nextfloorTexts??=new Map;function Le(i){let e=i.toLowerCase().split("-")[0];return e!=="de"&&e!=="en"&&e in $e()?e:void 0}function it(i){let e=Le(i),t=e===void 0?void 0:Z.get(e);return t instanceof Promise?void 0:t}function Me(i,e){let t=Le(i?.language??navigator.language);if(t===void 0)return!1;let n=Z.get(t);return n===void 0&&(n=fetch(new URL(`./lang/${t}.json?v=${$e()[t]}`,import.meta.url)).then(r=>r.ok?r.json():{}).catch(()=>({})).then(r=>{Z.set(t,r&&typeof r=="object"?r:{})}),Z.set(t,n)),n instanceof Promise?(n.then(()=>e.requestUpdate()),!0):!1}function Ne(i,e,t={}){let n=i?.language??navigator.language,r=n.startsWith("de"),o=(r?void 0:it(n)?.[e])??(r?de:_e)[e]??_e[e]??de[e]??e;for(let[a,s]of Object.entries(t))o=o.replace(`{${a}}`,String(s));return o}var ue=class extends y{static properties={hass:{attribute:!1},_config:{state:!0},_floors:{state:!0},_rooms:{state:!0},_templates:{state:!0}};loading=!1;form;constructor(){super(),this._config={type:"custom:nextfloor-card"},this._floors=[],this._rooms=[],this._templates=[];let e=this;this.form={get value(){return{...ae,...e._config}},t:(t,n)=>Ne(e.hass,t,n),set:(t,n)=>e.write(t,n)}}setConfig(e){this._config=e}willUpdate(){this.hass&&!this.loading&&this._floors.length===0&&(this.loading=!0,He(this.hass).then(e=>{this._floors=e.building.floors.map(t=>({id:t.id,name:t.name})),this._templates=Object.keys(e.building.settings.card_templates??{}),this._rooms=e.building.floors.flatMap(t=>t.rooms.map(n=>({id:n.id,name:n.name,floor:t.name})))},()=>{}))}write(e,t){let n={...this._config};t===void 0||t===""||ae[e]===t?delete n[e]:n[e]=t,this.publish(n)}publish(e){this._config=e,this.dispatchEvent(new CustomEvent("config-changed",{detail:{config:e},bubbles:!0,composed:!0}))}roomsChoice(){if(this._rooms.length===0)return l``;let e=new Set(this._config.rooms??[]),t=(n,r)=>{let o=this._rooms.map(a=>a.id).filter(a=>a===n?r:e.has(a));this.form.set("rooms",o.length?o:void 0)};return l`<fieldset class="rooms"> `;var ue=globalThis,_e=ue.__nextfloorBuiltin?.de??{},ce=ue.__nextfloorBuiltin?.en??{};ue.__nextfloorBuiltin??={de:_e,en:ce};var $e=()=>typeof m=="object"&&m||{},it=globalThis,Z=it.__nextfloorTexts??=new Map;function Me(i){let e=i.toLowerCase().split("-")[0];return e!=="de"&&e!=="en"&&e in $e()?e:void 0}function ot(i){let e=Me(i),t=e===void 0?void 0:Z.get(e);return t instanceof Promise?void 0:t}function Ne(i,e){let t=Me(i?.language??navigator.language);if(t===void 0)return!1;let n=Z.get(t);return n===void 0&&(n=fetch(new URL(`./lang/${t}.json?v=${$e()[t]}`,import.meta.url)).then(r=>r.ok?r.json():{}).catch(()=>({})).then(r=>{Z.set(t,r&&typeof r=="object"?r:{})}),Z.set(t,n)),n instanceof Promise?(n.then(()=>e.requestUpdate()),!0):!1}function Ce(i,e,t={}){let n=i?.language??navigator.language,r=n.startsWith("de"),o=(r?void 0:ot(n)?.[e])??(r?_e:ce)[e]??ce[e]??_e[e]??e;for(let[a,s]of Object.entries(t))o=o.replace(`{${a}}`,String(s));return o}var V=i=>i?.symconObjects!==void 0;var me=class extends y{static properties={hass:{attribute:!1},_config:{state:!0},_floors:{state:!0},_rooms:{state:!0},_templates:{state:!0}};loading=!1;form;constructor(){super(),this._config={type:"custom:nextfloor-card"},this._floors=[],this._rooms=[],this._templates=[];let e=this;this.form={get value(){return{...se,...e._config}},t:(t,n)=>Ce(e.hass,t,n),set:(t,n)=>e.write(t,n)}}setConfig(e){this._config=e}willUpdate(){this.hass&&!this.loading&&this._floors.length===0&&(this.loading=!0,We(this.hass).then(e=>{this._floors=e.building.floors.map(t=>({id:t.id,name:t.name})),this._templates=Object.keys(e.building.settings.card_templates??{}),this._rooms=e.building.floors.flatMap(t=>t.rooms.map(n=>({id:n.id,name:n.name,floor:t.name})))},()=>{}))}write(e,t){let n={...this._config};t===void 0||t===""||se[e]===t?delete n[e]:n[e]=t,this.publish(n)}publish(e){this._config=e,this.dispatchEvent(new CustomEvent("config-changed",{detail:{config:e},bubbles:!0,composed:!0}))}roomsChoice(){if(this._rooms.length===0)return l``;let e=new Set(this._config.rooms??[]),t=(n,r)=>{let o=this._rooms.map(a=>a.id).filter(a=>a===n?r:e.has(a));this.form.set("rooms",o.length?o:void 0)};return l`<fieldset class="rooms">
<legend>${this.form.t("card_rooms")}</legend> <legend>${this.form.t("card_rooms")}</legend>
<small>${this.form.t("card_rooms_hint")}</small> <small>${this.form.t("card_rooms_hint")}</small>
${this._rooms.map(n=>l`<label class="toggle"><input type="checkbox" .checked=${e.has(n.id)} @change=${r=>t(n.id,r.target.checked)} /><span>${this._floors.length>1?`${n.floor} \xB7 `:""}${n.name}</span></label>`)} ${this._rooms.map(n=>l`<label class="toggle"><input type="checkbox" .checked=${e.has(n.id)} @change=${r=>t(n.id,r.target.checked)} /><span>${this._floors.length>1?`${n.floor} \xB7 `:""}${n.name}</span></label>`)}
</fieldset>`}floorThumbsToggle(){let e=!this._config.floor,t=this._config.floor?"card_floor_thumbs_hint_start":"card_floor_thumbs_hint";return f(this.form,this._config.floor_thumbs??e,"card_floor_thumbs",t,n=>{let r={...this._config};n===e?delete r.floor_thumbs:r.floor_thumbs=n,this.publish(r)})}controlsSection(){let e=this.form,t=this._config.controls,n=!!t&&(t===!0||t.length>0),r=t===!0?[...$]:Array.isArray(t)?t:[],o=s=>e.set("controls",s.length===$.length?!0:s.length>0?s:void 0),a=[0,10,30,60,120].map(s=>({value:s,text:s?e.t("card_hide_after_s",{n:s}):e.t("card_idle_off")}));return l`${f(e,n,"card_controls","card_controls_hint",s=>e.set("controls",s?!0:void 0))} </fieldset>`}floorThumbsToggle(){let e=!this._config.floor,t=this._config.floor?"card_floor_thumbs_hint_start":"card_floor_thumbs_hint";return f(this.form,this._config.floor_thumbs??e,"card_floor_thumbs",t,n=>{let r={...this._config};n===e?delete r.floor_thumbs:r.floor_thumbs=n,this.publish(r)})}controlsSection(){let e=this.form,t=this._config.controls,n=!!t&&(t===!0||t.length>0),r=t===!0?[...L]:Array.isArray(t)?t:[],o=s=>e.set("controls",s.length===L.length?!0:s.length>0?s:void 0),a=[0,10,30,60,120].map(s=>({value:s,text:s?e.t("card_hide_after_s",{n:s}):e.t("card_idle_off")}));return l`${f(e,n,"card_controls","card_controls_hint",s=>e.set("controls",s?!0:void 0))}
${f(e,e.value.central,"card_central","card_central_hint",s=>e.set("central",s?void 0:!1))} ${f(e,e.value.central,"card_central","card_central_hint",s=>e.set("central",s?void 0:!1))}
${f(e,e.value.lock_button!==!1,"card_lock_button",void 0,s=>e.set("lock_button",s?void 0:!1))} ${f(e,e.value.lock_button!==!1,"card_lock_button",void 0,s=>e.set("lock_button",s?void 0:!1))}
${f(e,e.value.walk_button!==!1,"card_walk_button",void 0,s=>e.set("walk_button",s?void 0:!1))} ${f(e,e.value.walk_button!==!1,"card_walk_button",void 0,s=>e.set("walk_button",s?void 0:!1))}
${f(e,e.value.time_travel!==!1,"card_travel_button",void 0,s=>e.set("time_travel",s?void 0:!1))} ${f(e,e.value.time_travel!==!1,"card_travel_button",void 0,s=>e.set("time_travel",s?void 0:!1))}
${se(e,"marker_names","card_marker_names","card_marker_names_hint")} ${se(e,"controls_hidden","card_controls_hidden","card_controls_hidden_hint")} ${le(e,"marker_names","card_marker_names","card_marker_names_hint")} ${le(e,"controls_hidden","card_controls_hidden","card_controls_hidden_hint")}
${le(e,"controls_hide_after","card_controls_hide_after",a)} ${he(e,"controls_hide_after","card_controls_hide_after",a)}
${n?l`<div class="sub"> ${n?l`<div class="sub">
${$.map(s=>l`<label class="chip"> ${L.map(s=>l`<label class="chip">
<input <input
type="checkbox" type="checkbox"
.checked=${r.includes(s)} .checked=${r.includes(s)}
@change=${h=>o(h.target.checked?$.filter(u=>u===s||r.includes(u)):r.filter(u=>u!==s))} @change=${h=>o(h.target.checked?L.filter(u=>u===s||r.includes(u)):r.filter(u=>u!==s))}
/> />
${e.t(`card_control_${s}`)} ${e.t(`card_control_${s}`)}
</label>`)} </label>`)}
</div>`:d}`}kioskSection(){let e=this.form,{night:t}=e.value,n=t==="off"||t==="sun"?t:"time",r=[0,1,2,5,10].map(a=>({value:a*60,text:a?e.t("card_idle_min",{n:a}):e.t("card_idle_off")})),o=[["off","card_night_off"],["sun","card_night_sun"],["time","card_night_time"]];return l`<h3>${e.t("card_section_kiosk")}</h3> </div>`:d}`}kioskSection(){let e=this.form,{night:t}=e.value,n=t==="off"||t==="sun"?t:"time",r=[0,1,2,5,10].map(a=>({value:a*60,text:a?e.t("card_idle_min",{n:a}):e.t("card_idle_off")})),o=[["off","card_night_off"],["sun","card_night_sun"],["time","card_night_time"]];return l`<h3>${e.t("card_section_kiosk")}</h3>
<div class="grid"> <div class="grid">
${le(e,"idle_return","card_idle_return",r)} ${he(e,"idle_return","card_idle_return",r)}
<label class="field" <label class="field"
>${e.t("card_night")} >${e.t("card_night")}
<select @change=${a=>e.set("night",{off:void 0,sun:"sun",time:"22:00-06:00"}[a.target.value])}> <select @change=${a=>e.set("night",{off:void 0,sun:"sun",time:"22:00-06:00"}[a.target.value])}>
@@ -169,17 +169,17 @@ var p={cs:"4be67fcd522e",da:"0fe66a82bf2a",es:"bd89dffd1355",fi:"9a17bc084f56",f
${[.8,1,1.25,1.5,1.75,2,2.5].map(n=>l`<option value=${n} ?selected=${(e.value.zoom??1)===n}>${Math.round(n*100)} %</option>`)} ${[.8,1,1.25,1.5,1.75,2,2.5].map(n=>l`<option value=${n} ?selected=${(e.value.zoom??1)===n}>${Math.round(n*100)} %</option>`)}
</select> </select>
</label> </label>
${c(e,"announcements","card_announcements","card_announcements_hint")} ${V(this.hass)?d:c(e,"announcements","card_announcements","card_announcements_hint")}
${e.value.announcements!==!1?l`<div class="grid">${I(e,"screen_name","screen_name")}</div>`:d} ${!V(this.hass)&&e.value.announcements!==!1?l`<div class="grid">${I(e,"screen_name","screen_name")}</div>`:d}
${c(e,"weather","card_weather","card_weather_hint")} ${c(e,"weather","card_weather","card_weather_hint")}
${e.value.weather!==!1?l`<div class="grid"> ${e.value.weather!==!1?l`<div class="grid">
<label class="field wide" ${V(this.hass)?d:l`<label class="field wide"
>${e.t("weather_entity")} >${e.t("weather_entity")}
<select @change=${n=>e.set("weather_entity",n.target.value||void 0)}> <select @change=${n=>e.set("weather_entity",n.target.value||void 0)}>
<option value="" ?selected=${!e.value.weather_entity}>${e.t("card_weather_plan")}</option> <option value="" ?selected=${!e.value.weather_entity}>${e.t("card_weather_plan")}</option>
${t.map(n=>l`<option value=${n} ?selected=${n===e.value.weather_entity}>${String(this.hass?.states[n]?.attributes.friendly_name??n)}</option>`)} ${t.map(n=>l`<option value=${n} ?selected=${n===e.value.weather_entity}>${String(this.hass?.states[n]?.attributes.friendly_name??n)}</option>`)}
</select> </select>
</label> </label>`}
<label class="field" <label class="field"
>${e.t("card_weather_density")} >${e.t("card_weather_density")}
<select @change=${n=>e.set("weather_density",Number(n.target.value))}> <select @change=${n=>e.set("weather_density",Number(n.target.value))}>
@@ -190,9 +190,9 @@ var p={cs:"4be67fcd522e",da:"0fe66a82bf2a",es:"bd89dffd1355",fi:"9a17bc084f56",f
</div>`:d} </div>`:d}
<p class="hint">${e.t("card_pro_hint")}</p>`}furnitureColors(e){let t=this._config.furniture_colors??{},n=(r,o)=>{let a={...t,[r]:o};o||delete a[r],e.set("furniture_colors",Object.keys(a).length?a:void 0)};return l`<details class="field"> <p class="hint">${e.t("card_pro_hint")}</p>`}furnitureColors(e){let t=this._config.furniture_colors??{},n=(r,o)=>{let a={...t,[r]:o};o||delete a[r],e.set("furniture_colors",Object.keys(a).length?a:void 0)};return l`<details class="field">
<summary>${e.t("furn_colors_card")}${Object.keys(t).length?` (${Object.keys(t).length})`:""}</summary> <summary>${e.t("furn_colors_card")}${Object.keys(t).length?` (${Object.keys(t).length})`:""}</summary>
${We.map(r=>l`<label class="field" ${Be.map(r=>l`<label class="field"
>${e.t(`furn_color_${r}`)} >${e.t(`furn_color_${r}`)}
<input type="color" .value=${t[r]??Be[r]} @input=${o=>n(r,o.target.value)} /> <input type="color" .value=${t[r]??Pe[r]} @input=${o=>n(r,o.target.value)} />
${t[r]?l`<button type="button" class="link" @click=${()=>n(r,null)}>${e.t("furn_color_house")}</button>`:d} ${t[r]?l`<button type="button" class="link" @click=${()=>n(r,null)}>${e.t("furn_color_house")}</button>`:d}
</label>`)} </label>`)}
</details>`}viewSection(){let e=this.form,t=e.value;return l`<h3>${e.t("card_section_view")}</h3> </details>`}viewSection(){let e=this.form,t=e.value;return l`<h3>${e.t("card_section_view")}</h3>
@@ -263,11 +263,11 @@ var p={cs:"4be67fcd522e",da:"0fe66a82bf2a",es:"bd89dffd1355",fi:"9a17bc084f56",f
<div class="grid"> <div class="grid">
${w(e,"markers","markers",[["none","markers_none"],["important","markers_important"],["all","markers_all"]],t.markers)} ${w(e,"markers","markers",[["none","markers_none"],["important","markers_important"],["all","markers_all"]],t.markers)}
${w(e,"heatmap","heatmap",[["none","heat_off"],["temperature","heat_temperature"],["humidity","heat_humidity"],["co2","heat_co2"],["mould","heat_mould"],["values","heat_values"],["wifi","heat_wifi"]],t.heatmap)} ${w(e,"heatmap","heatmap",[["none","heat_off"],["temperature","heat_temperature"],["humidity","heat_humidity"],["co2","heat_co2"],["mould","heat_mould"],["values","heat_values"],["wifi","heat_wifi"]],t.heatmap)}
${he(e,"flows","flows",t.flows)} ${he(e,"holograms","holos",t.holograms)} ${de(e,"flows","flows",t.flows)} ${de(e,"holograms","holos",t.holograms)}
</div> </div>
${c(e,"tap_in_room","card_tap_in_room","card_tap_in_room_hint")} ${w(e,"room_double_tap","room_double_tap",[["auto","card_room_double_tap_auto"],["area","room_double_tap_area"],["plan","room_double_tap_plan"],["off","room_double_tap_off"]],t.room_double_tap)} ${this.markersOutside()} ${this.controlsSection()} ${this.floorThumbsToggle()} ${c(e,"room_names","card_room_names")} ${c(e,"energy","card_energy")} ${c(e,"tap_in_room","card_tap_in_room","card_tap_in_room_hint")} ${w(e,"room_double_tap","room_double_tap",[["auto","card_room_double_tap_auto"],["area","room_double_tap_area"],["plan","room_double_tap_plan"],["off","room_double_tap_off"]],t.room_double_tap)} ${this.markersOutside()} ${this.controlsSection()} ${this.floorThumbsToggle()} ${c(e,"room_names","card_room_names")} ${c(e,"energy","card_energy")}
${c(e,"room_buttons","card_room_buttons","card_room_buttons_hint")} ${c(e,"room_panel","card_room_panel","card_room_panel_hint")} ${c(e,"fullscreen_button","card_fullscreen_button","card_fullscreen_button_hint")} ${c(e,"room_buttons","card_room_buttons","card_room_buttons_hint")} ${c(e,"room_panel","card_room_panel","card_room_panel_hint")} ${c(e,"fullscreen_button","card_fullscreen_button","card_fullscreen_button_hint")}
${c(e,"explode","card_explode")} ${c(e,"roof_fade","card_roof_fade","card_roof_fade_hint")} ${c(e,"stats","card_stats","card_stats_hint")}`}render(){return this.hass&&Me(this.hass,this)?d:l`${this.viewSection()} ${this.showSection()} ${this.featuresSection()} ${this.kioskSection()}`}static styles=Pe};customElements.get("nextfloor-card-editor")||customElements.define("nextfloor-card-editor",ue);export{ue as NextFloorCardEditor}; ${c(e,"explode","card_explode")} ${c(e,"roof_fade","card_roof_fade","card_roof_fade_hint")} ${c(e,"stats","card_stats","card_stats_hint")}`}render(){return this.hass&&Ne(this.hass,this)?d:l`${this.viewSection()} ${this.showSection()} ${this.featuresSection()} ${this.kioskSection()}`}static styles=Le};customElements.get("nextfloor-card-editor")||customElements.define("nextfloor-card-editor",me);export{me as NextFloorCardEditor};
/*! Bundled license information: /*! Bundled license information:
@lit/reactive-element/css-tag.js: @lit/reactive-element/css-tag.js:
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,256 @@
/*! NextFloor, MIT licence. Includes three.js (MIT) and Lit (BSD-3-Clause); see LICENSE and THIRD_PARTY_NOTICES.md */
var Y=globalThis,G=Y.ShadowRoot&&(Y.ShadyCSS===void 0||Y.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,nt=Symbol(),_t=new WeakMap,D=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==nt)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=n}get styleSheet(){let t=this.o,n=this.t;if(G&&t===void 0){let i=n!==void 0&&n.length===1;i&&(t=_t.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&_t.set(n,t))}return t}toString(){return this.cssText}},wt=r=>new D(typeof r=="string"?r:r+"",void 0,nt),y=(r,...t)=>{let n=r.length===1?r[0]:t.reduce((i,e,o)=>i+(s=>{if(s._$cssResult$===!0)return s.cssText;if(typeof s=="number")return s;throw Error("Value passed to 'css' function must be a 'css' function result: "+s+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(e)+r[o+1],r[0]);return new D(n,r,nt)},St=(r,t)=>{if(G)r.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(let n of t){let i=document.createElement("style"),e=Y.litNonce;e!==void 0&&i.setAttribute("nonce",e),i.textContent=n.cssText,r.appendChild(i)}},it=G?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let n="";for(let i of t.cssRules)n+=i.cssText;return wt(n)})(r):r;var{is:Jt,defineProperty:Xt,getOwnPropertyDescriptor:Yt,getOwnPropertyNames:Gt,getOwnPropertySymbols:Qt,getPrototypeOf:te}=Object,Q=globalThis,At=Q.trustedTypes,ee=At?At.emptyScript:"",ne=Q.reactiveElementPolyfillSupport,V=(r,t)=>r,rt={toAttribute(r,t){switch(t){case Boolean:r=r?ee:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let n=r;switch(t){case Boolean:n=r!==null;break;case Number:n=r===null?null:Number(r);break;case Object:case Array:try{n=JSON.parse(r)}catch{n=null}}return n}},Ht=(r,t)=>!Jt(r,t),Et={attribute:!0,type:String,converter:rt,reflect:!1,useDefault:!1,hasChanged:Ht};Symbol.metadata??=Symbol("metadata"),Q.litPropertyMetadata??=new WeakMap;var w=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,n=Et){if(n.state&&(n.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((n=Object.create(n)).wrapped=!0),this.elementProperties.set(t,n),!n.noAccessor){let i=Symbol(),e=this.getPropertyDescriptor(t,i,n);e!==void 0&&Xt(this.prototype,t,e)}}static getPropertyDescriptor(t,n,i){let{get:e,set:o}=Yt(this.prototype,t)??{get(){return this[n]},set(s){this[n]=s}};return{get:e,set(s){let c=e?.call(this);o?.call(this,s),this.requestUpdate(t,c,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Et}static _$Ei(){if(this.hasOwnProperty(V("elementProperties")))return;let t=te(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(V("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(V("properties"))){let n=this.properties,i=[...Gt(n),...Qt(n)];for(let e of i)this.createProperty(e,n[e])}let t=this[Symbol.metadata];if(t!==null){let n=litPropertyMetadata.get(t);if(n!==void 0)for(let[i,e]of n)this.elementProperties.set(i,e)}this._$Eh=new Map;for(let[n,i]of this.elementProperties){let e=this._$Eu(n,i);e!==void 0&&this._$Eh.set(e,n)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let n=[];if(Array.isArray(t)){let i=new Set(t.flat(1/0).reverse());for(let e of i)n.unshift(it(e))}else t!==void 0&&n.push(it(t));return n}static _$Eu(t,n){let i=n.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,n=this.constructor.elementProperties;for(let i of n.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return St(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,n,i){this._$AK(t,i)}_$ET(t,n){let i=this.constructor.elementProperties.get(t),e=this.constructor._$Eu(t,i);if(e!==void 0&&i.reflect===!0){let o=(i.converter?.toAttribute!==void 0?i.converter:rt).toAttribute(n,i.type);this._$Em=t,o==null?this.removeAttribute(e):this.setAttriLine truncated
\f\r]`,j=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Rt=/-->/g,Nt=/>/g,k=RegExp(`>|${ot}(?:([^\\s"'>=/]+)(${ot}*=${ot}*(?:[^
\f\r"'\`<>=]|("|')|))|$)`,"g"),Pt=/'/g,Mt=/"/g,zt=/^(?:script|style|textarea|title)$/i,pt=r=>(t,...n)=>({_$litType$:r,strings:t,values:n}),d=pt(1),ye=pt(2),ve=pt(3),N=Symbol.for("lit-noChange"),a=Symbol.for("lit-nothing"),Tt=new WeakMap,C=R.createTreeWalker(R,129);function Ut(r,t){if(!ht(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ct!==void 0?Ct.createHTML(t):t}var oe=(r,t)=>{let n=r.length-1,i=[],e,o=t===2?"<svg>":t===3?"<math>":"",s=j;for(let c=0;c<n;c++){let l=r[c],h,p,u=-1,m=0;for(;m<l.length&&(s.lastIndex=m,p=s.exec(l),p!==null);)m=s.lastIndex,s===j?p[1]==="!--"?s=Rt:p[1]!==void 0?s=Nt:p[2]!==void 0?(zt.test(p[2])&&(e=RegExp("</"+p[2],"g")),s=k):p[3]!==void 0&&(s=k):s===k?p[0]===">"?(s=e??j,u=-1):p[1]===void 0?u=-2:(u=s.lastIndex-p[2].length,h=p[1],s=p[3]===void 0?k:p[3]==='"'?Mt:Pt):s===Mt||s===Pt?s=k:s===Rt||s===Nt?s=j:(s=k,e=void 0);let $=s===k&&r[c+1].startsWith("/>")?" ":"";o+=s===j?l+ie:u>=0?(i.push(h),l.slice(0,u)+Ot+l.slice(u)+A+$):l+A+(u===-2?c:$)}return[Ut(r,o+(r[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]},K=class r{constructor({strings:t,_$litType$:n},i){let e;this.parts=[];let o=0,s=0,c=t.length-1,l=this.parts,[h,p]=oe(t,n);if(this.el=r.createElement(h,i),C.currentNode=this.el.content,n===2||n===3){let u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(e=C.nextNode())!==null&&l.length<c;){if(e.nodeType===1){if(e.hasAttributes())for(let u of e.getAttributeNames())if(u.endsWith(Ot)){let m=p[s++],$=e.getAttribute(u).split(A),_=/([.?@])?(.*)/.exec(m);l.push({type:1,index:o,name:_[2],strings:$,ctor:_[1]==="."?at:_[1]==="?"?lt:_[1]==="@"?ct:M}),e.removeAttribute(u)}else u.startsWith(A)&&(l.push({type:6,index:o}),e.removeAttribute(u));if(zt.test(e.tagName)){let u=e.textContent.split(A),m=u.length-1;if(m>0){e.textContent=tt?tt.emptyScript:"";for(let $=0;$<m;$++)e.append(u[$],B()),C.nextNode(),l.push({type:2,index:++o});e.append(u[m],B())}}}else if(e.nodeType===8)if(e.data===Ft)l.push({type:2,index:o});else{let u=-1;for(;(u=e.data.indexOf(A,u+1))!==-1;)l.push({type:7,index:o}),u+=A.length-1}o++}}static createElement(t,n){let i=R.createElement("template");return i.innerHTML=t,i}};function P(r,t,n=r,i){if(t===N)return t;let e=i!==void 0?n._$Co?.[i]:n._$Cl,o=I(t)?void 0:t._$litDirective$;return e?.constructor!==o&&(e?._$AO?.(!1),o===void 0?e=void 0:(e=new o(r),e._$AT(r,n,i)),i!==void 0?(n._$Co??=[])[i]=e:n._$Cl=e),e!==void 0&&(t=P(r,e._$AS(r,t.values),e,i)),t}var st=class{constructor(t,n){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=n}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:n},parts:i}=this._$AD,e=(t?.creationScope??R).importNode(n,!0);C.currentNode=e;let o=C.nextNode(),s=0,c=0,l=i[0];for(;l!==void 0;){if(s===l.index){let h;l.type===2?h=new W(o,o.nextSibling,this,t):l.type===1?h=new l.ctor(o,l.name,l.strings,this,t):l.type===6&&(h=new ut(o,this,t)),this._$AV.push(h),l=i[++c]}s!==l?.index&&(o=C.nextNode(),s++)}return C.currentNode=R,e}p(t){let n=0;for(let i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,n),n+=i.strings.length-2):i._$AI(t[n])),n++}},W=class r{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,n,i,e){this.type=2,this._$AH=a,this._$AN=void 0,this._$AA=t,this._$AB=n,this._$AM=i,this.options=e,this._$Cv=e?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,n=this._$AM;return n!==void 0&&t?.nodeType===11&&(t=n.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,n=this){t=P(this,t,n),I(t)?t===a||t==null||t===""?(this._$AH!==a&&this._$AR(),this._$AH=a):t!==this._$AH&&t!==N&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):re(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==a&&I(this._$AH)?this._$AA.nextSibling.data=t:this.T(R.createTextNode(t)),this._$AH=t}$(t){let{values:n,_$litType$:i}=t,e=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=K.createElement(Ut(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===e)this._$AH.p(n);else{let o=new st(e,this),s=o.u(this.options);o.p(n),this.T(s),this._$AH=o}}_$AC(t){let n=Tt.get(t.strings);return n===void 0&&Tt.set(t.strings,n=new K(t)),n}k(t){ht(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,i,e=0;for(let o of t)e===n.length?n.push(i=new r(this.O(B()),this.O(B()),this,this.options)):i=n[e],i._$AI(o),e++;e<n.length&&(this._$AR(i&&i._$AB.nextSibling,e),n.length=e)}_$AR(t=this._$AA.nextSibling,n){for(this._$AP?.(!1,!0,n);t!==this._$AB;){let i=kt(t).nextSibling;kt(t).remove(),t=i}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},M=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,n,i,e,o){this.type=1,this._$AH=a,this._$AN=void 0,this.element=t,this.name=n,this._$AM=e,this.options=o,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=Line truncated
:host {
--nf-text: var(--primary-text-color, #e1e1e1);
--nf-muted: var(--secondary-text-color, #9b9b9b);
--nf-accent: var(--primary-color, #03a9f4);
--nf-accent-text: var(--text-primary-color, #ffffff);
--nf-surface: var(--ha-card-background, var(--card-background-color, #1c1c1c));
--nf-bg: var(--primary-background-color, #111111);
--nf-bg2: var(--secondary-background-color, #1c1c1c);
/* floating bars and cards over the 3D view: the card colour, a little see-through */
--nf-chrome: color-mix(in srgb, var(--nf-surface) var(--nf-chrome-mix, 84%), transparent);
--nf-chrome-solid: var(--nf-surface);
--nf-line: var(--divider-color, rgba(255, 255, 255, 0.12));
/* quiet fills for buttons and fields, and the tonal accent of an active control */
--nf-fill: color-mix(in srgb, var(--nf-text) 7%, transparent);
--nf-fill-strong: color-mix(in srgb, var(--nf-text) 13%, transparent);
--nf-tonal: color-mix(in srgb, var(--nf-accent) 20%, transparent);
--nf-soft: var(--info-color, #4a90e2);
--nf-warm: var(--state-light-active-color, #ffa726);
--nf-danger: var(--error-color, #db4437);
--nf-good: var(--success-color, #43a047);
--nf-radius: var(--ha-card-border-radius, 12px);
--nf-shadow: var(--ha-card-box-shadow, 0 1px 2px rgba(0, 0, 0, 0.18), 0 6px 20px rgba(0, 0, 0, 0.2));
--nf-font: var(--primary-font-family, Roboto, "Noto Sans", system-ui, -apple-system, "Segoe UI", sans-serif);
--nf-title-font: var(--nf-font);
font-family: var(--nf-font);
color: var(--nf-text);
}
`,Ve=y`
:host([readable]) {
--secondary-text-color: var(--primary-text-color, #e1e1e1);
--divider-color: color-mix(in srgb, var(--primary-text-color, #e1e1e1) 40%, transparent);
--nf-chrome-mix: 97%;
}
:host([readable]) nf-room-panel,
:host([readable]) .nf-nav,
:host([readable]) .nf-overlay {
zoom: 1.2;
}
`,je=y`
/* a group of switches: one rounded pill, the active one tinted with the accent */
.nf-seg {
display: inline-flex;
padding: 4px;
gap: 2px;
border-radius: 999px;
background: var(--nf-chrome);
box-shadow: var(--nf-shadow);
backdrop-filter: blur(10px);
}
.nf-seg button,
.nf-chip {
font: inherit;
font-size: 14px;
font-weight: 500;
border: none;
background: none;
color: var(--nf-muted);
padding: 7px 14px;
border-radius: 999px;
cursor: pointer;
white-space: nowrap;
min-height: 36px;
transition:
background 0.15s,
color 0.15s;
}
.nf-seg button:hover:not(:disabled),
.nf-chip:hover {
background: var(--nf-fill);
color: var(--nf-text);
}
/* on a small stage (a small window, a zoomed browser, a dashboard column) the switches at the bottom take less room */
@container nf ((max-width: 1360px) or (max-height: 640px)) {
:is(.nf-overlay, .nf-card-controls) .nf-seg {
padding: 3px;
}
:is(.nf-overlay, .nf-card-controls) :is(.nf-seg button, .nf-chip) {
font-size: 12.5px;
padding: 5px 10px;
}
}
.nf-time-slider {
display: inline-flex;
align-items: center;
padding: 4px 10px;
}
.nf-time-slider input {
width: 160px;
accent-color: var(--nf-accent);
}
.nf-seg button[aria-pressed="true"],
.nf-chip[aria-pressed="true"] {
background: color-mix(in srgb, var(--nf-accent) 24%, var(--nf-chrome-solid));
color: var(--nf-accent);
font-weight: 600;
}
.nf-seg button:disabled {
opacity: 0.4;
cursor: default;
}
/* a single pill, like the chips of the Mushroom cards */
.nf-chip {
background: var(--nf-chrome);
color: var(--nf-text);
box-shadow: var(--nf-shadow);
backdrop-filter: blur(10px);
}
button:focus-visible,
input:focus-visible,
select:focus-visible {
outline: 2px solid var(--nf-accent);
outline-offset: 2px;
}
/* the round icon badge every row and card starts with */
.nf-ico {
display: inline-flex;
align-items: center;
justify-content: center;
flex: none;
width: 38px;
height: 38px;
border-radius: 50%;
background: var(--nf-tonal);
color: var(--nf-accent);
--mdc-icon-size: 20px;
}
.nf-ico.nf-warm {
background: color-mix(in srgb, var(--nf-warm) 22%, transparent);
color: var(--nf-warm);
}
.nf-ico.nf-off {
background: var(--nf-fill);
color: var(--nf-muted);
}
.nf-btn {
font: inherit;
font-size: 14px;
font-weight: 500;
border: none;
background: var(--nf-fill);
color: var(--nf-text);
border-radius: var(--nf-radius);
padding: 7px 14px;
cursor: pointer;
min-height: 36px;
transition: background 0.15s;
}
.nf-btn:hover {
background: var(--nf-fill-strong);
}
.nf-btn.nf-danger {
color: var(--nf-danger);
}
.nf-btn.nf-primary {
background: var(--nf-accent);
color: var(--nf-accent-text);
}
.nf-btn.nf-primary:hover {
background: color-mix(in srgb, var(--nf-accent) 88%, var(--nf-text));
}
.nf-field {
display: grid;
gap: 4px;
font-size: 12px;
color: var(--nf-muted);
}
.nf-field input,
.nf-field select,
.nf-field textarea {
font: inherit;
font-size: 14px;
color: var(--nf-text);
background: var(--nf-fill);
border: none;
border-bottom: 1px solid var(--nf-line);
border-radius: 10px 10px 4px 4px;
padding: 8px 10px;
min-width: 0;
}
.nf-field input:focus,
.nf-field select:focus,
.nf-field textarea:focus {
border-bottom-color: var(--nf-accent);
}
.nf-field input[type="range"] {
padding: 0;
accent-color: var(--nf-accent);
}
.nf-field select option {
background: var(--nf-chrome-solid);
color: var(--nf-text);
}
/* fingers need 40 px */
@media (pointer: coarse) {
.nf-seg button,
.nf-chip,
.nf-btn {
min-height: 40px;
}
}
`;function gt(r,t){let n=new Set;return t.flatMap(i=>{let e=String(r?.states[i]?.attributes.symcon_source_entity||i),o=r?.states[e]?.attributes,s=Number(o?.symcon_id);return!s||!o?.symcon_archive||n.has(s)?[]:(n.add(s),[e])})}var Vt,bt=class extends v{static properties={hass:{attribute:!1},ids:{attribute:!1},label:{attribute:!1},busy:{state:!0},error:{state:!0}};constructor(){super(),this.ids=[],this.label="",this.busy=!1,this.error=""}async open(t){t.stopPropagation(),this.busy=!0,this.error="";try{let n=new URL("./nextfloor-trend.js?v=84417e0b2573",import.meta.url).href;await(await(Vt??=import(n).catch(e=>{throw Vt=void 0,e}))).openTrend(this.hass,this.ids,this.label)}catch(n){this.error=n instanceof Error?n.message:String(n)}finally{this.busy=!1}}render(){if(!gt(this.hass,this.ids).length)return a;let t=this.label?`Trend anzeigen: ${this.label}`:"Trend anzeigen";return d`<button type="button" title=${t} aria-label=${t} aria-haspopup="dialog" ?disabled=${this.busy} @pointerdown=${n=>n.stopPropagation()} @click=${n=>{this.open(n)}}>
<svg width="12" height="12" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M3 2v15h15M5 13l4-5 4 2 4-6"/></svg>
</button>${this.error?d`<span role="alert">${this.error}</span>`:a}`}static styles=y`:host{position:relative;display:inline-flex;flex:0 0 18px;width:18px;height:18px;vertical-align:middle;margin-left:3px;font-weight:normal;line-height:0}button{display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;width:18px;height:18px;padding:2px;border:0;border-radius:3px;background:transparent;color:var(--nf-accent,#40c8ff);opacity:.8;cursor:pointer}svg{display:block;flex-shrink:0}button:hover,button:focus-visible{opacity:1;background:#40c8ff18}button:focus-visible{outline:1px solid currentColor;outline-offset:1px}button:disabled{opacity:.4}span{position:absolute;right:0;top:22px;z-index:10;box-sizing:border-box;width:200px;padding:8px;border:1px solid #ff9b9b50;border-radius:6px;background:var(--nf-chrome-solid,#1c1c1c);font:12px/1.4 system-ui;color:#ff9b9b;white-space:normal}`};customElements.get("nf-trend-button")||customElements.define("nf-trend-button",bt);function X(r,t,n=""){let i=gt(r,t);return i.length?d`<nf-trend-button .hass=${r} .ids=${i} .label=${n}></nf-trend-button>`:a}var pe={heating_manifold:"Heiz-/K\xFChlkreisverteiler",buffer_tank:"Pufferspeicher",freshwater_station:"Frischwasserstation"},Bt=r=>r.name||pe[r.type],It=r=>r.name||{heating:"Heizkreis",cooling:"K\xFChlkreis",changeover:"Heizen / K\xFChlen",pump:"Vorschubpumpe"}[r.kind],Kt=(r,t)=>t.kind==="pump"?"Pumpenkreis":t.kind==="cooling"?"K\xFChlen":t.kind==="heating"?"Heizen":g(t.mode_entity)&&b(r.states[t.mode_entity])===null?"Betriebsart \u2013":Number(g(t.mode_entity)?b(r.states[t.mode_entity]):0)===(t.cooling_value??1)?"K\xFChlen":"Heizen",et=(r,t,n)=>[f(r,"Vorlauf",t),f(r,"R\xFCcklauf",n)].filter(i=>i!==null),yt=(r,t,n)=>{let i=E(r,t),e=E(r,n);return i===null||e===null?a:d`<div class="reading delta"><span>ΔT · VL − RL</span><b>${(i-e).toLocaleString(r.language,{maximumFractionDigits:1})} K</b></div>`};function Wt(r,t){let n=F(t),i=t.type==="freshwater_station"?[]:et(r,n.flow,n.return);if(t.type==="buffer_tank"&&i.unshift(...[...n.sensors??[]].sort((e,o)=>o.level-e.level).flatMap(e=>{let o=f(r,e.name||"F\xFChler",e.entity);return o?[o]:[]})),t.type==="freshwater_station"){let e=f(r,"Zirkulation",n.circulation_temperature);e&&i.push(e)}for(let e of t.values??[]){let o=f(r,e.label||String(e.entity&&r.states[e.entity]?.attributes.friendly_name||"Wert"),e.entity);o&&i.push({...o,icon:e.icon})}return i}function qt(r,t){return[...et(r,t.flow,t.return),...[["Kaltwasser",t.cold_water],["Trinkwarmwasser",t.hot_water],["Pumpenleistung",t.power]].flatMap(([n,i])=>{let e=f(r,n,i);return e?[e]:[]})]}var vt=(r,t)=>`K${t+1} \xB7 ${r.name||`Station ${t+1}`}`,H=(r,t)=>d`<div class="reading" data-source=${t.id}><span>${t.icon?.startsWith("mdi:")?d`<ha-icon icon=${t.icon}></ha-icon>`:t.icon||a} ${t.label}</span><b>${t.text}${X(r,[t.id],t.label)}</b></div>`;function L(r,t,n){let i=S(r,n);return i.id?d`<div class="reading" data-source=${i.id}><span>${t}<small>${i.feedback?"Ist":"Soll"}</small></span><b><i class="lamp" style=${`background:${i.running===null?"#888":i.running?"#6fe1a2":"#465361"}`}></i>${U(r.states[i.id])}${X(r,[i.id],t)}</b></div>`:a}var Zt=y`
: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}
`,xt=class extends v{static properties={hass:{attribute:!1},item:{attribute:!1},readOnly:{type:Boolean}};render(){if(!this.hass||!this.item)return a;let t=F(this.item),n=Wt(this.hass,this.item),i=this.item.type==="freshwater_station"?O(this.item):[];return d`<button class="title" @click=${()=>jt(this.hass,this.item,this.readOnly)} aria-haspopup="dialog">${Bt(this.item)} ⚙</button><div class="content">
${this.item.type==="heating_manifold"?(t.circuits??[]).map(e=>d`<section class="circuit"><div class="circuit-name">${It(e)} <small>${Kt(this.hass,e)}</small></div>${q(e)?L(this.hass,"Pumpe",e.pump):a}${Z(e)?L(this.hass,"Ventil",e.valve):a}${et(this.hass,e.flow,e.return).map(o=>H(this.hass,o))}${f(this.hass,"Leistung",e.power)?H(this.hass,f(this.hass,"Leistung",e.power)):a}</section>`):a}
${i.length>1?d`<small class="cascade-count">Kaskade · ${i.length} Stationen</small>${i.map((e,o)=>{let s=S(this.hass,e.pump),c=f(this.hass,"Trinkwarmwasser",e.hot_water)||f(this.hass,"Vorlauf",e.flow);return d`<div class="station-summary" data-station=${e.id}><button class="station-name" @click=${()=>jt(this.hass,this.item,this.readOnly,e.id)}><i class="lamp" title=${`Pumpe: ${s.id?U(this.hass.states[s.id]):"\u2013"}`} style=${`background:${s.running===null?"#888":s.running?"#6fe1a2":"#a82638"}`}></i>${vt(e,o)}</button><b>${c?.text||"\u2013"}</b>${c?X(this.hass,[c.id],`${vt(e,o)} \xB7 ${c.label}`):a}</div>`})}`:i.map(e=>d`<section class="circuit">${qt(this.hass,e).map(o=>H(this.hass,o))}${L(this.hass,"Ladepumpe",e.pump)}${T(e)?L(this.hass,"Kaskadenventil",e.valve):a}</section>`)}
${n.map(e=>H(this.hass,e))}${this.item.type==="freshwater_station"?L(this.hass,"Zirkulationspumpe",t.circulation):a}
${this.item.type!=="heating_manifold"&&this.item.type!=="freshwater_station"&&!n.length?d`<p class="empty">Noch keine Fühler verknüpft</p>`:a}
</div>`}static styles=[mt,Zt,y`.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}`]},$t=class extends v{static properties={hass:{attribute:!1},item:{attribute:!1},readOnly:{type:Boolean},focusStation:{attribute:!1},pending:{state:!0},error:{state:!0}};constructor(){super(),this.pending=new Set,this.error="",this.readOnly=!1}async show(){await this.updateComplete,this.shadowRoot.querySelector("dialog").showModal(),this.focusStation&&this.shadowRoot.querySelector(`[data-station="${CSS.escape(this.focusStation)}"]`)?.scrollIntoView({block:"start"})}async send(t,n){let i=this.hass.states[t];if(!(this.readOnly||!i?.attributes.symcon_has_action||b(i)===null||this.pending.has(t))){this.pending=new Set([...this.pending,t]),this.error="";try{await this.hass.callService("symcon","set_value",{entity_id:t,value:n})}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.pending=new Set([...this.pending].filter(e=>e!==t))}}}control(t,n){if(!g(n?.command)&&!g(n?.feedback))return a;let i=g(n?.command)?n.command:null,e=i?this.hass.states[i]:void 0,o=e?.attributes,s=b(e),c=!!i&&!!o?.symcon_has_action&&s!==null&&!this.readOnly&&!this.pending.has(i),l=Number(o?.symcon_min??0),h=Number(o?.symcon_max??100),p=Number(o?.symcon_step||(o?.symcon_variable_type===1?1:.1)),u=z(e),m=$=>{let _=$.target;i&&_.value.trim()&&_.checkValidity()&&Number.isFinite(_.valueAsNumber)&&this.send(i,_.valueAsNumber)};return d`<fieldset data-control=${t}><legend>${t}</legend>${L(this.hass,t,n)}
${i?d`<div class="reading"><span>Befehl / Sollwert</span><b>${U(e)}${X(this.hass,[i],`${t} \xB7 Sollwert`)}</b></div>
${o?.symcon_variable_type===0?d`<div class="command"><button data-command=${i} ?disabled=${!c} @click=${()=>{this.send(i,!J(e))}}>${J(e)?"Ausschalten / Schlie\xDFen":"Einschalten / \xD6ffnen"}</button></div>`:[1,2].includes(Number(o?.symcon_variable_type))?d`<div class="command"><input type="range" aria-label=${`${t} Sollwert`} data-command=${i} min=${l} max=${h} step=${p} .value=${String(u??l)} ?disabled=${!c} @change=${m}/><input type="number" aria-label=${`${t} nativer Sollwert`} min=${l} max=${h} step=${p} .value=${u===null?"":String(u)} ?disabled=${!c} @change=${m}/></div>`:a}
${this.readOnly?d`<p class="readonly">Historische Ansicht · nur Anzeige</p>`:o?.symcon_has_action?a:d`<p class="readonly">Nur Anzeige · keine Symcon-Schaltaktion hinterlegt</p>`}`:a}
</fieldset>`}render(){if(!this.hass||!this.item)return a;let t=F(this.item),n=Wt(this.hass,this.item),i=this.item.type==="freshwater_station"?O(this.item):[];return d`<dialog @close=${()=>{this.remove(),x===this&&(x=null)}} @keydown=${e=>e.stopPropagation()}><header><h2>${Bt(this.item)}</h2><button aria-label="Schließen" @click=${()=>this.shadowRoot.querySelector("dialog").close()}>×</button></header><div class="body">
${this.item.type==="heating_manifold"?(t.circuits??[]).map(e=>d`<section class="circuit" data-circuit=${e.id}><h3>${It(e)} <small>${Kt(this.hass,e)}</small></h3>${q(e)?this.control("Pumpe",e.pump):a}${Z(e)?this.control("Ventil",e.valve):a}${et(this.hass,e.flow,e.return).map(o=>H(this.hass,o))}${yt(this.hass,e.flow,e.return)}${f(this.hass,"Pumpenleistung",e.power)?H(this.hass,f(this.hass,"Pumpenleistung",e.power)):a}</section>`):a}
${i.map((e,o)=>d`<details class="freshwater-unit" data-station=${e.id} ?open=${o===0||this.focusStation===e.id}><summary>${vt(e,o)}</summary>${qt(this.hass,e).map(s=>H(this.hass,s))}${yt(this.hass,e.flow,e.return)}${this.control("Ladepumpe",e.pump)}${T(e)?this.control("Kaskadenventil",e.valve):a}</details>`)}
${n.map(e=>H(this.hass,e))}${this.item.type==="buffer_tank"?yt(this.hass,t.flow,t.return):a}
${this.item.type==="freshwater_station"?this.control("Zirkulationspumpe",t.circulation):a}
${!n.length&&this.item.type!=="heating_manifold"&&this.item.type!=="freshwater_station"?d`<p class="empty">Die Fühler lassen sich im Editor über den Objektbaum zuweisen.</p>`:a}
${this.error?d`<p class="error" role="alert">${this.error}</p>`:a}
</div></dialog>`}static styles=[mt,Zt,y`: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}`]},x=null;function en(){x?.remove(),x=null}async function jt(r,t,n=!1,i){x?.remove();let e=document.createElement("nf-hydronic-dialog");x=e,Object.assign(e,{hass:r,item:t,readOnly:n,focusStation:i}),document.body.append(e),await e.show()}function nn(r,t,n=!1){if(!x)return;let i=t.floors.flatMap(e=>e.furniture).find(e=>e.id===x.item.id);if(!i||!Dt(i.type)){x.remove(),x=null;return}Object.assign(x,{hass:r,item:i,readOnly:n})}customElements.get("nf-hydronic-card")||customElements.define("nf-hydronic-card",xt);customElements.get("nf-hydronic-dialog")||customElements.define("nf-hydronic-dialog",$t);export{en as closeHydronic,he as hydronicVisual,jt as openHydronic,nn as refreshHydronic};
/*! Bundled license information:
@lit/reactive-element/css-tag.js:
(**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*)
@lit/reactive-element/reactive-element.js:
lit-html/lit-html.js:
lit-element/lit-element.js:
(**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*)
lit-html/is-server.js:
(**
* @license
* Copyright 2022 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*)
*/
@@ -0,0 +1,354 @@
/*! NextFloor, MIT licence. Includes three.js (MIT) and Lit (BSD-3-Clause); see LICENSE and THIRD_PARTY_NOTICES.md */
var j=globalThis,B=j.ShadowRoot&&(j.ShadyCSS===void 0||j.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,K=Symbol(),ct=new WeakMap,P=class{constructor(t,i,r){if(this._$cssResult$=!0,r!==K)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=i}get styleSheet(){let t=this.o,i=this.t;if(B&&t===void 0){let r=i!==void 0&&i.length===1;r&&(t=ct.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),r&&ct.set(i,t))}return t}toString(){return this.cssText}},pt=s=>new P(typeof s=="string"?s:s+"",void 0,K),w=(s,...t)=>{let i=s.length===1?s[0]:t.reduce((r,e,n)=>r+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(e)+s[n+1],s[0]);return new P(i,s,K)},ut=(s,t)=>{if(B)s.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(let i of t){let r=document.createElement("style"),e=j.litNonce;e!==void 0&&r.setAttribute("nonce",e),r.textContent=i.cssText,s.appendChild(r)}},Y=B?s=>s:s=>s instanceof CSSStyleSheet?(t=>{let i="";for(let r of t.cssRules)i+=r.cssText;return pt(i)})(s):s;var{is:Lt,defineProperty:Ot,getOwnPropertyDescriptor:Dt,getOwnPropertyNames:Nt,getOwnPropertySymbols:Ut,getPrototypeOf:It}=Object,V=globalThis,ft=V.trustedTypes,jt=ft?ft.emptyScript:"",Bt=V.reactiveElementPolyfillSupport,L=(s,t)=>s,J={toAttribute(s,t){switch(t){case Boolean:s=s?jt:null;break;case Object:case Array:s=s==null?s:JSON.stringify(s)}return s},fromAttribute(s,t){let i=s;switch(t){case Boolean:i=s!==null;break;case Number:i=s===null?null:Number(s);break;case Object:case Array:try{i=JSON.parse(s)}catch{i=null}}return i}},mt=(s,t)=>!Lt(s,t),gt={attribute:!0,type:String,converter:J,reflect:!1,useDefault:!1,hasChanged:mt};Symbol.metadata??=Symbol("metadata"),V.litPropertyMetadata??=new WeakMap;var _=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,i=gt){if(i.state&&(i.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((i=Object.create(i)).wrapped=!0),this.elementProperties.set(t,i),!i.noAccessor){let r=Symbol(),e=this.getPropertyDescriptor(t,r,i);e!==void 0&&Ot(this.prototype,t,e)}}static getPropertyDescriptor(t,i,r){let{get:e,set:n}=Dt(this.prototype,t)??{get(){return this[i]},set(o){this[i]=o}};return{get:e,set(o){let d=e?.call(this);n?.call(this,o),this.requestUpdate(t,d,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??gt}static _$Ei(){if(this.hasOwnProperty(L("elementProperties")))return;let t=It(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(L("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(L("properties"))){let i=this.properties,r=[...Nt(i),...Ut(i)];for(let e of r)this.createProperty(e,i[e])}let t=this[Symbol.metadata];if(t!==null){let i=litPropertyMetadata.get(t);if(i!==void 0)for(let[r,e]of i)this.elementProperties.set(r,e)}this._$Eh=new Map;for(let[i,r]of this.elementProperties){let e=this._$Eu(i,r);e!==void 0&&this._$Eh.set(e,i)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let i=[];if(Array.isArray(t)){let r=new Set(t.flat(1/0).reverse());for(let e of r)i.unshift(Y(e))}else t!==void 0&&i.push(Y(t));return i}static _$Eu(t,i){let r=i.attribute;return r===!1?void 0:typeof r=="string"?r:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,i=this.constructor.elementProperties;for(let r of i.keys())this.hasOwnProperty(r)&&(t.set(r,this[r]),delete this[r]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return ut(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,i,r){this._$AK(t,r)}_$ET(t,i){let r=this.constructor.elementProperties.get(t),e=this.constructor._$Eu(t,r);if(e!==void 0&&r.reflect===!0){let n=(r.converter?.toAttribute!==void 0?r.converter:J).toAttribute(i,r.type);this._$Em=t,n==null?this.removeAttribute(e):this.setAttribute(e,n),Line truncated
\f\r]`,O=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,xt=/-->/g,$t=/>/g,E=RegExp(`>|${G}(?:([^\\s"'>=/]+)(${G}*=${G}*(?:[^
\f\r"'\`<>=]|("|')|))|$)`,"g"),yt=/'/g,wt=/"/g,Et=/^(?:script|style|textarea|title)$/i,st=s=>(t,...i)=>({_$litType$:s,strings:t,values:i}),v=st(1),A=st(2),Xt=st(3),T=Symbol.for("lit-noChange"),u=Symbol.for("lit-nothing"),_t=new WeakMap,k=M.createTreeWalker(M,129);function kt(s,t){if(!nt(s)||!s.hasOwnProperty("raw"))throw Error("invalid template strings array");return vt!==void 0?vt.createHTML(t):t}var qt=(s,t)=>{let i=s.length-1,r=[],e,n=t===2?"<svg>":t===3?"<math>":"",o=O;for(let d=0;d<i;d++){let l=s[d],h,p,c=-1,b=0;for(;b<l.length&&(o.lastIndex=b,p=o.exec(l),p!==null);)b=o.lastIndex,o===O?p[1]==="!--"?o=xt:p[1]!==void 0?o=$t:p[2]!==void 0?(Et.test(p[2])&&(e=RegExp("</"+p[2],"g")),o=E):p[3]!==void 0&&(o=E):o===E?p[0]===">"?(o=e??O,c=-1):p[1]===void 0?c=-2:(c=o.lastIndex-p[2].length,h=p[1],o=p[3]===void 0?E:p[3]==='"'?wt:yt):o===wt||o===yt?o=E:o===xt||o===$t?o=O:(o=E,e=void 0);let m=o===E&&s[d+1].startsWith("/>")?" ":"";n+=o===O?l+Vt:c>=0?(r.push(h),l.slice(0,c)+St+l.slice(c)+S+m):l+S+(c===-2?d:m)}return[kt(s,n+(s[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),r]},U=class s{constructor({strings:t,_$litType$:i},r){let e;this.parts=[];let n=0,o=0,d=t.length-1,l=this.parts,[h,p]=qt(t,i);if(this.el=s.createElement(h,r),k.currentNode=this.el.content,i===2||i===3){let c=this.el.content.firstChild;c.replaceWith(...c.childNodes)}for(;(e=k.nextNode())!==null&&l.length<d;){if(e.nodeType===1){if(e.hasAttributes())for(let c of e.getAttributeNames())if(c.endsWith(St)){let b=p[o++],m=e.getAttribute(c).split(S),y=/([.?@])?(.*)/.exec(b);l.push({type:1,index:n,name:y[2],strings:m,ctor:y[1]==="."?Q:y[1]==="?"?tt:y[1]==="@"?et:R}),e.removeAttribute(c)}else c.startsWith(S)&&(l.push({type:6,index:n}),e.removeAttribute(c));if(Et.test(e.tagName)){let c=e.textContent.split(S),b=c.length-1;if(b>0){e.textContent=W?W.emptyScript:"";for(let m=0;m<b;m++)e.append(c[m],D()),k.nextNode(),l.push({type:2,index:++n});e.append(c[b],D())}}}else if(e.nodeType===8)if(e.data===At)l.push({type:2,index:n});else{let c=-1;for(;(c=e.data.indexOf(S,c+1))!==-1;)l.push({type:7,index:n}),c+=S.length-1}n++}}static createElement(t,i){let r=M.createElement("template");return r.innerHTML=t,r}};function H(s,t,i=s,r){if(t===T)return t;let e=r!==void 0?i._$Co?.[r]:i._$Cl,n=N(t)?void 0:t._$litDirective$;return e?.constructor!==n&&(e?._$AO?.(!1),n===void 0?e=void 0:(e=new n(s),e._$AT(s,i,r)),r!==void 0?(i._$Co??=[])[r]=e:i._$Cl=e),e!==void 0&&(t=H(s,e._$AS(s,t.values),e,r)),t}var X=class{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:i},parts:r}=this._$AD,e=(t?.creationScope??M).importNode(i,!0);k.currentNode=e;let n=k.nextNode(),o=0,d=0,l=r[0];for(;l!==void 0;){if(o===l.index){let h;l.type===2?h=new I(n,n.nextSibling,this,t):l.type===1?h=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(h=new it(n,this,t)),this._$AV.push(h),l=r[++d]}o!==l?.index&&(n=k.nextNode(),o++)}return k.currentNode=M,e}p(t){let i=0;for(let r of this._$AV)r!==void 0&&(r.strings!==void 0?(r._$AI(t,r,i),i+=r.strings.length-2):r._$AI(t[i])),i++}},I=class s{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,r,e){this.type=2,this._$AH=u,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=r,this.options=e,this._$Cv=e?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=H(this,t,i),N(t)?t===u||t==null||t===""?(this._$AH!==u&&this._$AR(),this._$AH=u):t!==this._$AH&&t!==T&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Wt(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==u&&N(this._$AH)?this._$AA.nextSibling.data=t:this.T(M.createTextNode(t)),this._$AH=t}$(t){let{values:i,_$litType$:r}=t,e=typeof r=="number"?this._$AC(t):(r.el===void 0&&(r.el=U.createElement(kt(r.h,r.h[0]),this.options)),r);if(this._$AH?._$AD===e)this._$AH.p(i);else{let n=new X(e,this),o=n.u(this.options);n.p(i),this.T(o),this._$AH=n}}_$AC(t){let i=_t.get(t.strings);return i===void 0&&_t.set(t.strings,i=new U(t)),i}k(t){nt(this._$AH)||(this._$AH=[],this._$AR());let i=this._$AH,r,e=0;for(let n of t)e===i.length?i.push(r=new s(this.O(D()),this.O(D()),this,this.options)):r=i[e],r._$AI(n),e++;e<i.length&&(this._$AR(r&&r._$AB.nextSibling,e),i.length=e)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){let r=bt(t).nextSibling;bt(t).remove(),t=r}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},R=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,r,e,n){this.type=1,this._$AH=u,this._$AN=void 0,this.element=t,this.name=i,this._$AM=e,this.options=n,r.length>2||r[0]!==""||r[1]!==""?(this._$AH=Array(r.length-1).fill(new String),this.strings=r):thiLine truncated
:host {
--nf-text: var(--primary-text-color, #e1e1e1);
--nf-muted: var(--secondary-text-color, #9b9b9b);
--nf-accent: var(--primary-color, #03a9f4);
--nf-accent-text: var(--text-primary-color, #ffffff);
--nf-surface: var(--ha-card-background, var(--card-background-color, #1c1c1c));
--nf-bg: var(--primary-background-color, #111111);
--nf-bg2: var(--secondary-background-color, #1c1c1c);
/* floating bars and cards over the 3D view: the card colour, a little see-through */
--nf-chrome: color-mix(in srgb, var(--nf-surface) var(--nf-chrome-mix, 84%), transparent);
--nf-chrome-solid: var(--nf-surface);
--nf-line: var(--divider-color, rgba(255, 255, 255, 0.12));
/* quiet fills for buttons and fields, and the tonal accent of an active control */
--nf-fill: color-mix(in srgb, var(--nf-text) 7%, transparent);
--nf-fill-strong: color-mix(in srgb, var(--nf-text) 13%, transparent);
--nf-tonal: color-mix(in srgb, var(--nf-accent) 20%, transparent);
--nf-soft: var(--info-color, #4a90e2);
--nf-warm: var(--state-light-active-color, #ffa726);
--nf-danger: var(--error-color, #db4437);
--nf-good: var(--success-color, #43a047);
--nf-radius: var(--ha-card-border-radius, 12px);
--nf-shadow: var(--ha-card-box-shadow, 0 1px 2px rgba(0, 0, 0, 0.18), 0 6px 20px rgba(0, 0, 0, 0.2));
--nf-font: var(--primary-font-family, Roboto, "Noto Sans", system-ui, -apple-system, "Segoe UI", sans-serif);
--nf-title-font: var(--nf-font);
font-family: var(--nf-font);
color: var(--nf-text);
}
`,pe=w`
:host([readable]) {
--secondary-text-color: var(--primary-text-color, #e1e1e1);
--divider-color: color-mix(in srgb, var(--primary-text-color, #e1e1e1) 40%, transparent);
--nf-chrome-mix: 97%;
}
:host([readable]) nf-room-panel,
:host([readable]) .nf-nav,
:host([readable]) .nf-overlay {
zoom: 1.2;
}
`,ue=w`
/* a group of switches: one rounded pill, the active one tinted with the accent */
.nf-seg {
display: inline-flex;
padding: 4px;
gap: 2px;
border-radius: 999px;
background: var(--nf-chrome);
box-shadow: var(--nf-shadow);
backdrop-filter: blur(10px);
}
.nf-seg button,
.nf-chip {
font: inherit;
font-size: 14px;
font-weight: 500;
border: none;
background: none;
color: var(--nf-muted);
padding: 7px 14px;
border-radius: 999px;
cursor: pointer;
white-space: nowrap;
min-height: 36px;
transition:
background 0.15s,
color 0.15s;
}
.nf-seg button:hover:not(:disabled),
.nf-chip:hover {
background: var(--nf-fill);
color: var(--nf-text);
}
/* on a small stage (a small window, a zoomed browser, a dashboard column) the switches at the bottom take less room */
@container nf ((max-width: 1360px) or (max-height: 640px)) {
:is(.nf-overlay, .nf-card-controls) .nf-seg {
padding: 3px;
}
:is(.nf-overlay, .nf-card-controls) :is(.nf-seg button, .nf-chip) {
font-size: 12.5px;
padding: 5px 10px;
}
}
.nf-time-slider {
display: inline-flex;
align-items: center;
padding: 4px 10px;
}
.nf-time-slider input {
width: 160px;
accent-color: var(--nf-accent);
}
.nf-seg button[aria-pressed="true"],
.nf-chip[aria-pressed="true"] {
background: color-mix(in srgb, var(--nf-accent) 24%, var(--nf-chrome-solid));
color: var(--nf-accent);
font-weight: 600;
}
.nf-seg button:disabled {
opacity: 0.4;
cursor: default;
}
/* a single pill, like the chips of the Mushroom cards */
.nf-chip {
background: var(--nf-chrome);
color: var(--nf-text);
box-shadow: var(--nf-shadow);
backdrop-filter: blur(10px);
}
button:focus-visible,
input:focus-visible,
select:focus-visible {
outline: 2px solid var(--nf-accent);
outline-offset: 2px;
}
/* the round icon badge every row and card starts with */
.nf-ico {
display: inline-flex;
align-items: center;
justify-content: center;
flex: none;
width: 38px;
height: 38px;
border-radius: 50%;
background: var(--nf-tonal);
color: var(--nf-accent);
--mdc-icon-size: 20px;
}
.nf-ico.nf-warm {
background: color-mix(in srgb, var(--nf-warm) 22%, transparent);
color: var(--nf-warm);
}
.nf-ico.nf-off {
background: var(--nf-fill);
color: var(--nf-muted);
}
.nf-btn {
font: inherit;
font-size: 14px;
font-weight: 500;
border: none;
background: var(--nf-fill);
color: var(--nf-text);
border-radius: var(--nf-radius);
padding: 7px 14px;
cursor: pointer;
min-height: 36px;
transition: background 0.15s;
}
.nf-btn:hover {
background: var(--nf-fill-strong);
}
.nf-btn.nf-danger {
color: var(--nf-danger);
}
.nf-btn.nf-primary {
background: var(--nf-accent);
color: var(--nf-accent-text);
}
.nf-btn.nf-primary:hover {
background: color-mix(in srgb, var(--nf-accent) 88%, var(--nf-text));
}
.nf-field {
display: grid;
gap: 4px;
font-size: 12px;
color: var(--nf-muted);
}
.nf-field input,
.nf-field select,
.nf-field textarea {
font: inherit;
font-size: 14px;
color: var(--nf-text);
background: var(--nf-fill);
border: none;
border-bottom: 1px solid var(--nf-line);
border-radius: 10px 10px 4px 4px;
padding: 8px 10px;
min-width: 0;
}
.nf-field input:focus,
.nf-field select:focus,
.nf-field textarea:focus {
border-bottom-color: var(--nf-accent);
}
.nf-field input[type="range"] {
padding: 0;
accent-color: var(--nf-accent);
}
.nf-field select option {
background: var(--nf-chrome-solid);
color: var(--nf-text);
}
/* fingers need 40 px */
@media (pointer: coarse) {
.nf-seg button,
.nf-chip,
.nf-btn {
min-height: 40px;
}
}
`;var Tt={auto:"Automatisch",raw:"Rohdaten",minute:"1 Minute","5minutes":"5 Minuten","15minutes":"15 Minuten",hour:"Stunde",day:"Tag",week:"Woche",month:"Monat",year:"Jahr"};function zt(s,t){let i=new Set;return t.flatMap(r=>{let e=String(s?.states[r]?.attributes.symcon_source_entity||r),n=s?.states[e]?.attributes,o=Number(n?.symcon_id);return!o||!n?.symcon_archive||i.has(o)?[]:(i.add(o),[e])})}function at(s){if(!Number.isFinite(s))return"";let t=new Date(s*1e3);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}T${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function Ct(s,t,i,r){let e=h=>h.trim()&&Number.isFinite(Number(h.replace(",",".")))?Number(h.replace(",",".")):null,n=e(t),o=e(i),d=n??s.reduce((h,p)=>Math.min(h,p),r||!s.length?0:1/0),l=o??s.reduce((h,p)=>Math.max(h,p),r?0:s.length?-1/0:1);if(d===l&&(n===null&&!r&&(d-=Math.max(1,Math.abs(d)*.05)),o===null&&(l+=Math.max(1,Math.abs(l)*.05))),d>=l)throw new Error("Der untere Wertebereich muss kleiner als der obere sein.");return[d,l]}function Ht(s,t){let i=r=>{let e=String(r??"");return`"${/^[=+@\-\t\r]/.test(e)?"'":""}${e.replaceAll('"','""')}"`};return"\uFEFF"+[["Variable","Zeit","Wert","Minimum","Maximum"].join(";"),...s.flatMap(r=>r.points.map(e=>[t[r.entity_id]||r.entity_id,new Date(e.t*1e3).toISOString(),e.v,e.min??"",e.max??""].map(i).join(";")))].join(`\r
`)}var lt=class extends ${static properties={text:{attribute:!1}};constructor(){super(),this.text=""}get dialog(){return this.renderRoot.querySelector("dialog")}render(){return v`<button class="info" type="button" aria-label="Information anzeigen" aria-haspopup="dialog" title="Information" @click=${()=>this.dialog?.showModal()}>ⓘ</button>
<dialog aria-label="Information" @keydown=${t=>t.stopPropagation()} @click=${t=>{if(t.target!==t.currentTarget)return;let i=this.dialog.getBoundingClientRect();(t.clientX<i.left||t.clientX>i.right||t.clientY<i.top||t.clientY>i.bottom)&&this.dialog?.close()}}>
<header><b>Information</b><button class="close" type="button" aria-label="Schließen" @click=${()=>this.dialog?.close()}>×</button></header>
<p>${this.text}</p>
</dialog>`}static styles=[q,w`
:host { display:inline-block; margin:4px 0; vertical-align:middle; }
button { font:inherit; cursor:pointer; color:var(--nf-muted); background:transparent; border:1px solid var(--nf-line); border-radius:50%; pointer-events:auto; }
.info { width:26px; height:26px; padding:0; font-size:18px; line-height:24px; }
button:hover { color:var(--nf-accent); }
button:focus-visible { outline:2px solid var(--nf-accent); outline-offset:2px; }
dialog { box-sizing:border-box; width:min(560px,calc(100vw - 32px)); max-height:80vh; max-height:80dvh; overflow:auto; padding:18px 22px; border:1px solid var(--nf-line); border-radius:14px; background:var(--nf-chrome-solid); color:var(--nf-text); font:14px/1.5 system-ui,sans-serif; box-shadow:var(--nf-shadow); pointer-events:auto; }
dialog::backdrop { background:#050b16a6; }
header { display:flex; align-items:center; justify-content:space-between; gap:20px; font-size:16px; }
.close { width:30px; height:30px; padding:0; font-size:23px; }
p { white-space:pre-wrap; overflow-wrap:anywhere; margin:16px 0 4px; }
`]};customElements.get("nf-help-popup")||customElements.define("nf-help-popup",lt);var Rt=["#4ec9ff","#ffbe69","#ae9bff","#72deb0","#ff87aa","#ebde72"],z=(s,t)=>String(s.states[t]?.attributes.friendly_name||t),Pt=s=>({variable_not_logged:"Die Variable wird nicht mehr geloggt.",trend_range_too_large_for_resolution:"Bitte f\xFCr diesen Zeitraum eine gr\xF6bere Aufl\xF6sung w\xE4hlen.",invalid_trend_range:"Bitte einen g\xFCltigen Zeitraum w\xE4hlen."})[String(s instanceof Error?s.message:s)]||String(s instanceof Error?s.message:s),ht=class extends ${static properties={hass:{attribute:!1},ids:{attribute:!1},label:{attribute:!1},from:{state:!0},to:{state:!0},resolution:{state:!0},chartStyle:{state:!0},field:{state:!0},min:{state:!0},max:{state:!0},zero:{state:!0},band:{state:!0},live:{state:!0},series:{state:!0},hiddenSeries:{state:!0},loading:{state:!0},errors:{state:!0},hover:{state:!0},width:{state:!0},plotHeight:{state:!0},page:{state:!0}};request=0;drag=null;timer;observer;resize=()=>{this.plotHeight=Math.round(Math.min(600,Math.max(220,window.innerHeight*(window.innerWidth<600?.52:.65))))};constructor(){super(),this.ids=[],this.label="",this.to=Math.floor(Date.now()/1e3),this.from=this.to-86400,this.resolution="auto",this.chartStyle="auto",this.field="v",this.min="",this.max="",this.zero=!1,this.band=!0,this.live=!1,this.series=[],this.hiddenSeries=new Set,this.loading=!1,this.errors=[],this.hover=null,this.width=900,this.plotHeight=400,this.page=0}async open(){await this.updateComplete,this.renderRoot.querySelector("dialog").showModal(),this.observer=new ResizeObserver(([t])=>{this.width=Math.max(280,Math.floor(t.contentRect.width))}),this.observer.observe(this.renderRoot.querySelector(".body")),this.resize(),window.addEventListener("resize",this.resize),this.timer=setInterval(()=>{if(this.live&&!this.loading){let t=this.to-this.from;this.to=Math.floor(Date.now()/1e3),this.from=this.to-t,this.load()}},3e4),await this.load()}disconnectedCallback(){super.disconnectedCallback(),++this.request,clearInterval(this.timer),this.observer?.disconnect(),window.removeEventListener("resize",this.resize)}async load(){let t=++this.request,i=this.from,r=this.to;if(this.errors=[],this.series=[],this.hover=null,this.page=0,!Number.isSafeInteger(i)||!Number.isSafeInteger(r)||i<1||r<=i){this.errors=["Das Ende muss nach dem Beginn des Zeitraums liegen."],this.loading=!1;return}this.loading=!0;let e=[],n=[];for(let o=0;o<this.ids.length&&t===this.request;o+=3){let d=this.ids.slice(o,o+3);(await Promise.allSettled(d.map(h=>this.hass.callWS({type:"nextfloor/archive/trend",entity_id:h,start:i,end:r,aggregation:this.resolution})))).forEach((h,p)=>h.status==="fulfilled"?e.push(h.value):n.push(`${z(this.hass,d[p])}: ${Pt(h.reason)}`))}t!==this.request||!this.isConnected||(this.series=e,this.errors=n,this.loading=!1)}range(t,i){this.from=Math.max(1,Math.floor(t)),this.to=Math.max(this.from+1,Math.floor(i)),this.live=!1,this.load()}zoom(t,i=.5){let r=Math.max(60,Math.min(315576e3,(this.to-this.from)*t)),e=this.from+(this.to-this.from)*i;this.range(e-r*i,e+r*(1-i))}stamp(t){return new Date(t*1e3).toLocaleString(this.hass.language,{dateStyle:"short",timeStyle:"medium"})}number(t){return t.toLocaleString(this.hass.language,{maximumFractionDigits:Math.abs(t)<.01&&t!==0?5:2})}unit(t){return String(this.hass.states[t]?.attributes.unit_of_measurement??"")}selected(){return this.series.filter(t=>!this.hiddenSeries.has(t.entity_id))}value(t){let i=this.field==="v"?t.v:t[this.field]??t.v;return typeof i=="number"&&Number.isFinite(i)?i:null}color(t){return Rt[this.ids.indexOf(t)%Rt.length]}ratio(t){let i=t.currentTarget.getBoundingClientRect();return Math.max(0,Math.min(1,((t.clientX-i.left)/i.width*this.width-64)/(this.width-80)))}exportCsv(){let t=Object.fromEntries(this.ids.map(e=>[e,String(this.hass.states[e]?.attributes.symcon_path||z(this.hass,e))])),i=URL.createObjectURL(new Blob([Ht(this.selected(),t)],{type:"text/csv;charset=utf-8"})),r=document.createElement("a");r.href=i,r.download="Symcon-Trend.csv",r.click(),setTimeout(()=>URL.revokeObjectURL(i),1e3)}plot(t,i){let r=t.flatMap(a=>a.points.flatMap(f=>{let g=this.value(f);return g===null?[]:this.band&&!a.counter?[g,f.min??g,f.max??g]:[g]}));if(!r.length)return v`<p class="note">Keine numerischen Archivwerte in diesem Zeitraum.</p>`;let e,n;try{[e,n]=Ct(r,this.min,this.max,this.zero||this.chartStyle==="bar"||t.some(a=>a.type===0)||this.chartStyle==="auto"&&t.some(a=>a.counter&&a.aggregation!=="raw"))}catch(a){return v`<p role="alert">${Pt(a)}</p>`}let o=new Set(this.selected().filter(a=>a.type!==3).map(a=>this.unit(a.entity_id))).size,d=Math.max(200,Math.round(this.plotHeight/Math.max(1,Math.min(o,2)))),l=64,h=this.width-16,p=14,c=d-32,b=a=>l+(a-this.from)/(this.to-this.from)*(h-l),m=a=>c-(a-e)/(n-e)*(c-p),y=(a,f=this.field)=>Number(f==="v"?a.v:a[f]??a.v),Z=(a,f=this.field)=>{let g=a.points.filter(C=>typeof C.v=="number"),x=this.chartStyle==="step"||this.chartStyle==="auto"&&a.type==Line truncated
@pointerdown=${a=>{this.drag=this.ratio(a),a.currentTarget.setPointerCapture(a.pointerId)}}
@pointerup=${a=>{if(this.drag===null)return;let f=this.drag,g=this.ratio(a);if(this.drag=null,Math.abs(f-g)>.02){let x=this.to-this.from;this.range(this.from+x*Math.min(f,g),this.from+x*Math.max(f,g))}}}
@pointercancel=${()=>{this.drag=null}} @pointermove=${a=>{this.hover=this.from+(this.to-this.from)*this.ratio(a)}}>
<defs><clipPath id="plot-clip"><rect x=${l} y=${p} width=${h-l} height=${c-p}/></clipPath></defs>
${[0,1,2,3,4].map(a=>{let f=e+(n-e)*a/4;return A`<line class="grid" x1=${l} x2=${h} y1=${m(f)} y2=${m(f)}/><text x=${l-7} y=${m(f)+4} text-anchor="end">${this.number(f)}</text>`})}
${Array.from({length:F},(a,f)=>{let g=this.from+(this.to-this.from)*f/(F-1);return A`<text x=${b(g)} y=${d-8} text-anchor=${f===0?"start":f===F-1?"end":"middle"}>${new Date(g*1e3).toLocaleString(this.hass.language,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})}</text>`})}
<g clip-path="url(#plot-clip)">${t.map(a=>{let f=this.chartStyle==="bar"||this.chartStyle==="auto"&&a.counter&&a.aggregation!=="raw",g=this.color(a.entity_id);return f?a.points.filter(x=>this.value(x)!==null).map(x=>A`<rect fill=${g} opacity=".65" x=${b(x.t)} y=${Math.min(m(this.value(x)),m(0))} width=${Math.max(1,Math.min(h,b(x.t+Math.max(1,x.d)))-b(x.t)-1)} height=${Math.max(1,Math.abs(m(this.value(x))-m(0)))}/>`):A`${this.band&&a.aggregation!=="raw"&&!a.counter?A`<path d=${Z(a,"min")} fill="none" stroke=${g} opacity=".3"/><path d=${Z(a,"max")} fill="none" stroke=${g} opacity=".3"/>`:u}<path d=${Z(a)} fill="none" stroke=${g} stroke-width="2" vector-effect="non-scaling-stroke"/>${a.points.length===1?A`<circle cx=${b(a.points[0].t)} cy=${m(y(a.points[0]))} r="3" fill=${g}/>`:u}`})}${this.hover!==null?A`<line x1=${b(this.hover)} x2=${b(this.hover)} y1=${p} y2=${c} stroke="currentColor" stroke-dasharray="3 4" opacity=".5"/>`:u}</g>
</svg></section>`}table(t){let i=t.flatMap(n=>n.points.map(o=>({id:n.entity_id,...o}))).sort((n,o)=>o.t-n.t),r=Math.max(1,Math.ceil(i.length/100)),e=Math.min(this.page,r-1);return v`<div class="table"><table><thead><tr><th>Zeit</th><th>Variable</th><th>Wert</th></tr></thead><tbody>${i.slice(e*100,(e+1)*100).map(n=>v`<tr><td>${this.stamp(n.t)}</td><td>${z(this.hass,n.id)}</td><td>${typeof n.v=="number"?this.number(n.v):n.v} ${this.unit(n.id)}</td></tr>`)}</tbody></table></div><div class="actions"><button ?disabled=${!e} @click=${()=>{this.page=e-1}}>Zurück</button><span>${e+1} / ${r}</span><button ?disabled=${e>=r-1} @click=${()=>{this.page=e+1}}>Weiter</button></div>`}render(){let t=this.selected(),i=t.length>0&&t.every(e=>e.type===3),r=this.hover===null?"Letzter Wert":this.stamp(this.hover);return v`<dialog aria-label="Variablentrend" @close=${()=>this.remove()} @keydown=${e=>{e.stopPropagation();let n=this.renderRoot.querySelector(".settings");e.key==="Escape"&&n?.open&&(e.preventDefault(),n.open=!1)}} @click=${e=>{let n=this.renderRoot.querySelector(".settings");n?.open&&!e.composedPath().includes(n)&&(n.open=!1)}}>
<header><div><h2>${this.label||"Variablentrend"}</h2><span class="range">${new Date(this.from*1e3).toLocaleString(this.hass.language,{dateStyle:"short",timeStyle:"short"})} – ${new Date(this.to*1e3).toLocaleString(this.hass.language,{dateStyle:"short",timeStyle:"short"})}</span></div><button aria-label="Schließen" @click=${()=>this.renderRoot.querySelector("dialog")?.close()}>×</button></header>
<div class="body"><div class="toolbar"><div class="presets">${[["1 h",3600],["6 h",21600],["24 h",86400],["7 Tage",604800],["30 Tage",2592e3],["1 Jahr",31536e3]].map(([e,n])=>v`<button aria-pressed=${this.to-this.from===n} @click=${()=>{let o=Math.floor(Date.now()/1e3);this.range(o-Number(n),o)}}>${e}</button>`)}</div>
<div class="navigation"><button aria-label="Vorheriger Zeitraum" title="Vorheriger Zeitraum" @click=${()=>this.range(this.from-(this.to-this.from),this.from)}>←</button><button aria-label="Nächster Zeitraum" title="Nächster Zeitraum" @click=${()=>this.range(this.to,this.to+(this.to-this.from))}>→</button><button aria-label="Hineinzoomen" title="Hineinzoomen" @click=${()=>this.zoom(.5)}>+</button><button aria-label="Herauszoomen" title="Herauszoomen" @click=${()=>this.zoom(2)}>−</button><button aria-label="Aktualisieren" title="Aktualisieren" aria-busy=${this.loading} @click=${()=>{this.load()}} ?disabled=${this.loading}>↻</button></div>
<label class="live-toggle" title="Alle 30 Sekunden aktualisieren"><input type="checkbox" .checked=${this.live} @change=${e=>{this.live=e.target.checked}}/> Live</label>
<details class="settings"><summary aria-label="Trend-Einstellungen" title="Zeitraum, Auflösung und Darstellung">⚙︎</summary><div class="settings-panel">
<form @submit=${e=>{e.preventDefault(),this.load()}}><div class="fields time-fields">
<label>Von<input type="datetime-local" .value=${at(this.from)} @change=${e=>{this.from=Math.floor(new Date(e.target.value).getTime()/1e3),this.live=!1,this.load()}}/></label>
<label>Bis<input type="datetime-local" .value=${at(this.to)} @change=${e=>{this.to=Math.floor(new Date(e.target.value).getTime()/1e3),this.live=!1,this.load()}}/></label>
<label>Auflösung<select .value=${this.resolution} @change=${e=>{this.resolution=e.target.value,this.load()}}>${Object.entries(Tt).map(([e,n])=>v`<option value=${e}>${n}</option>`)}</select></label>
<button type="submit" ?disabled=${this.loading}>${this.loading?"L\xE4dt \u2026":"Anzeigen"}</button>
</div></form>
<div class="display-settings"><b class="group-title">Darstellung und Wertebereich</b><div class="fields display-fields">
<label>Darstellung<select .value=${this.chartStyle} @change=${e=>{this.chartStyle=e.target.value}}>${Object.entries({auto:"Automatisch",line:"Linie",step:"Stufen",bar:"Balken",table:"Tabelle"}).map(([e,n])=>v`<option value=${e}>${n}</option>`)}</select></label>
<label>Aggregierter Wert<select .value=${this.field} @change=${e=>{this.field=e.target.value}}><option value="v">Mittelwert / Verbrauch</option><option value="min">Minimum</option><option value="max">Maximum</option></select></label>
<label>Y-Minimum<input type="number" step="any" placeholder="Automatisch" .value=${this.min} @input=${e=>{this.min=e.target.value}}/></label>
<label>Y-Maximum<input type="number" step="any" placeholder="Automatisch" .value=${this.max} @input=${e=>{this.max=e.target.value}}/></label>
</div><div class="checks"><label><input type="checkbox" .checked=${this.zero} @change=${e=>{this.zero=e.target.checked}}/> Nullpunkt einbeziehen</label><label><input type="checkbox" .checked=${this.band} @change=${e=>{this.band=e.target.checked}}/> Min/Max anzeigen</label></div></div>
<div class="actions"><button @click=${()=>this.exportCsv()} ?disabled=${!t.length}>CSV</button>
<nf-help-popup .text=${"Zeitraum und Aufl\xF6sung lesen die originalen Symcon-Archivdaten. Rohdaten zeigen gespeicherte \xC4nderungen; ein zuvor bekannter Wert wird zum Beginn fortgef\xFChrt. Bei Z\xE4hlern sind aggregierte Werte der Verbrauch pro Intervall, bei Messwerten der Mittelwert. Mehrere Variablen werden einzeln dargestellt; unterschiedliche Einheiten erhalten eigene Diagramme. Zoomen: +/\u2212, Mausrad oder im Diagramm einen Zeitraum ziehen. Eigene Y-Grenzen gelten f\xFCr alle Diagramme. Begrenzte Rohdatenabfragen werden gekennzeichnet; w\xE4hle dann einen k\xFCrzeren Zeitraum oder eine Aggregation."}></nf-help-popup>
</div></div></details></div>
<div class="legend">${this.ids.map(e=>v`<label title=${String(this.hass.states[e]?.attributes.symcon_path||z(this.hass,e))}><input type="checkbox" .checked=${!this.hiddenSeries.has(e)} @change=${n=>{let o=new Set(this.hiddenSeries);n.target.checked?o.delete(e):o.add(e),this.hiddenSeries=o,this.requestUpdate()}}/><i style=${`background:${this.color(e)}`}></i>${z(this.hass,e)}</label>`)}</div>
${this.errors.map(e=>v`<p class="error" role="alert">${e}</p>`)}${this.loading?v`<p class="note" role="status">Archivwerte werden geladen …</p>`:u}
${t.filter(e=>e.truncated).map(e=>v`<p class="error" role="status">${z(this.hass,e.entity_id)}: Die Abfrage ist auf ${(e.limit??1e4).toLocaleString(this.hass.language)} Einträge begrenzt. Bitte Zeitraum verkürzen oder Auflösung ändern.</p>`)}
${t.some(e=>e.counter&&e.aggregation!=="raw")?v`<p class="note">Zähler: Verbrauch pro Intervall</p>`:u}
<div class="charts" style=${`min-height:${this.plotHeight}px`}>
${this.chartStyle==="table"||i?this.table(t):[...new Set(t.filter(e=>e.type!==3).map(e=>this.unit(e.entity_id)))].map(e=>this.plot(t.filter(n=>n.type!==3&&this.unit(n.entity_id)===e),e))}
${t.some(e=>e.type===3)&&!i&&this.chartStyle!=="table"?this.table(t.filter(e=>e.type===3)):u}
${!this.loading&&t.length&&t.every(e=>!e.points.length)?v`<p class="note">Keine Archivwerte in diesem Zeitraum.</p>`:u}
</div>
<div class="cursor"><b>${r}</b>${t.map(e=>{let n=e.points.at(-1);if(this.hover!==null){let o=0,d=e.points.length;for(;o<d;){let l=o+d>>>1;e.points[l].t<=this.hover?o=l+1:d=l}n=e.points[o-1]}return v`<span style=${`color:${this.color(e.entity_id)}`}>${z(this.hass,e.entity_id)}: ${n?typeof n.v=="number"?`${this.number(this.value(n))} ${this.unit(e.entity_id)}`:n.v:"\u2013"}</span>`})}</div>
</div>
</dialog>`}static styles=[q,w`
:host { font:13px/1.4 system-ui,sans-serif; color:var(--nf-text); }
dialog { box-sizing:border-box; width:min(1080px,calc(100vw - 24px)); max-height:92vh; max-height:92dvh; padding:0; border:1px solid var(--nf-line); border-radius:12px; background:var(--nf-chrome-solid,#1c1c1c); color:inherit; box-shadow:var(--nf-shadow); overflow:auto; }
dialog::backdrop { background:#050b16a8; }
header { display:flex; justify-content:space-between; align-items:center; gap:12px; padding:8px 12px; border-bottom:1px solid var(--nf-line); position:sticky; top:0; z-index:3; background:var(--nf-chrome-solid,#1c1c1c); }
header>div { display:flex; align-items:baseline; flex-wrap:wrap; gap:3px 14px; min-width:0; }
h2 { font-size:15px; margin:0; }
.range { font-size:11px; color:var(--nf-muted); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
header button { width:26px; height:26px; font-size:19px; padding:0; flex-shrink:0; }
.body { padding:8px 12px; }
.toolbar { position:relative; display:flex; align-items:center; flex-wrap:wrap; gap:5px 10px; margin-bottom:6px; }
.presets,.navigation { display:flex; align-items:center; gap:3px; }
button,input,select { box-sizing:border-box; color:var(--nf-text); font:inherit; }
button,select,input:not([type=checkbox]),summary { border:1px solid var(--nf-line); border-radius:5px; padding:4px 7px; background:var(--nf-fill,#292929); min-width:0; }
button { cursor:pointer; font-size:12px; }
button:disabled { opacity:.45; }
button:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible { outline:2px solid var(--nf-accent); outline-offset:2px; }
.toolbar button,.toolbar summary { height:26px; }
.navigation button { width:26px; padding:0; font-size:16px; }
.presets button { padding:3px 6px; font-size:11px; }
.presets button[aria-pressed=true],.settings[open]>summary { border-color:var(--nf-accent); background:color-mix(in srgb,var(--nf-accent) 16%,var(--nf-fill)); }
.live-toggle { display:flex; align-items:center; gap:3px; font-size:11px; white-space:nowrap; }
input[type=checkbox] { margin:0; }
.settings { margin-left:auto; }
.settings:not([open])>.settings-panel { display:none; }
summary { display:flex; align-items:center; justify-content:center; width:28px; padding:0; list-style:none; font-size:17px; cursor:pointer; }
summary::-webkit-details-marker { display:none; }
.settings-panel { position:absolute; z-index:2; top:calc(100% + 5px); right:0; box-sizing:border-box; width:min(620px,100%); max-height:min(62vh,480px); overflow:auto; padding:10px 12px; border:1px solid var(--nf-line); border-radius:8px; background:var(--nf-chrome-solid,#1c1c1c); box-shadow:var(--nf-shadow); }
.fields { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); align-items:end; gap:7px 10px; margin:0 0 10px; }
.fields label { display:grid; gap:3px; color:var(--nf-muted); font-size:11px; }
.fields input,.fields select { height:28px; width:100%; font-size:12px; }
.time-fields button { justify-self:start; }
.display-settings { padding-top:8px; border-top:1px solid var(--nf-line); }
.group-title { display:block; margin-bottom:6px; font-size:12px; }
.actions,.checks,.legend,.cursor { display:flex; align-items:center; flex-wrap:wrap; gap:6px 10px; }
.checks { margin:0 0 6px; }
.checks label,.legend label { display:flex; align-items:center; gap:4px; font-size:11px; }
.legend { margin:4px 0 0; }
.legend i { display:inline-block; width:8px; height:8px; border-radius:50%; flex-shrink:0; }
.legend label { max-width:100%; overflow-wrap:anywhere; }
.plot { display:block; width:100%; touch-action:none; user-select:none; }
.plot text { fill:var(--nf-muted); font:11px system-ui; }
.grid { stroke:var(--nf-line); }
h3 { font-size:11px; color:var(--nf-muted); margin:3px 0 0; }
.chart-group { margin-bottom:4px; }
.cursor { font-size:11px; align-items:baseline; border-top:1px solid var(--nf-line); padding-top:6px; }
.cursor>b { color:var(--nf-muted); font-weight:normal; }
.cursor span { overflow-wrap:anywhere; }
.note,.error { font-size:12px; margin:6px 0; }
.note { color:var(--nf-muted); }
.error { color:#ffa5a5; }
.table { overflow:auto; max-height:60vh; margin:8px 0; }
table { width:100%; border-collapse:collapse; font-size:12px; }
td,th { text-align:left; padding:5px; border-bottom:1px solid var(--nf-line); overflow-wrap:anywhere; }
td:first-child { white-space:nowrap; }
th { position:sticky; top:0; background:var(--nf-chrome-solid,#1c1c1c); }
@media(max-width:500px) {
header { padding:7px 9px; }
header>div { display:grid; gap:1px; }
h2 { font-size:14px; }
.body { padding:7px 9px; }
.toolbar { gap:4px 6px; }
.presets { gap:2px; }
.presets button { padding:3px 5px; }
.settings-panel { padding:9px; }
input[type=datetime-local] { font-size:11px; padding:3px; }
}
`]};customElements.get("nf-trend-dialog")||customElements.define("nf-trend-dialog",ht);async function _e(s,t,i){let r=zt(s,t);if(!r.length)return;let e=document.createElement("nf-trend-dialog");Object.assign(e,{hass:s,ids:r,label:i}),document.body.append(e);try{await e.open()}catch(n){throw e.remove(),n}}export{ht as NfTrendDialog,_e as openTrend};
/*! Bundled license information:
@lit/reactive-element/css-tag.js:
(**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*)
@lit/reactive-element/reactive-element.js:
lit-html/lit-html.js:
lit-element/lit-element.js:
(**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*)
lit-html/is-server.js:
(**
* @license
* Copyright 2022 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*)
*/
File diff suppressed because it is too large. Load diff
+109 -1
View File
@@ -43,6 +43,14 @@ START_VIEW_SCHEMA = vol.Schema(
extra=vol.ALLOW_EXTRA, extra=vol.ALLOW_EXTRA,
) )
_UTILITY_METERS = vol.Any(
None,
{
vol.Optional(kind): {vol.Optional("power"): _ENTITY_REF, vol.Optional("energy"): _ENTITY_REF}
for kind in ("electricity", "water", "gas", "heating", "cooling")
},
)
ROOM_SCHEMA = vol.Schema( ROOM_SCHEMA = vol.Schema(
{ {
# room climate read from chosen sensors (None = automatic, "none" = no value) # room climate read from chosen sensors (None = automatic, "none" = no value)
@@ -52,11 +60,13 @@ ROOM_SCHEMA = vol.Schema(
vol.Optional("temperature", default=None): _SENSOR_REFS, vol.Optional("temperature", default=None): _SENSOR_REFS,
vol.Optional("humidity", default=None): _SENSOR_REFS, vol.Optional("humidity", default=None): _SENSOR_REFS,
vol.Optional("co2", default=None): _SENSOR_REFS, vol.Optional("co2", default=None): _SENSOR_REFS,
vol.Optional("illuminance", default=None): _SENSOR_REFS,
}, },
), ),
vol.Required("id"): _ID, vol.Required("id"): _ID,
vol.Required("name"): _NAME, vol.Required("name"): _NAME,
vol.Required("area_id"): vol.Any(None, vol.All(str, vol.Length(max=255))), vol.Required("area_id"): vol.Any(None, vol.All(str, vol.Length(max=255))),
vol.Optional("utility_meters"): _UTILITY_METERS,
# light moods saved in the room panel: each light off, or on with brightness and colour # light moods saved in the room panel: each light off, or on with brightness and colour
vol.Optional("moods"): vol.All( vol.Optional("moods"): vol.All(
[ [
@@ -72,6 +82,23 @@ ROOM_SCHEMA = vol.Schema(
), ),
# underfloor heating: the entity whose heating makes the floor glow # underfloor heating: the entity whose heating makes the floor glow
vol.Optional("floor_heating"): vol.Any(None, vol.All(str, vol.Length(max=255))), vol.Optional("floor_heating"): vol.Any(None, vol.All(str, vol.Length(max=255))),
vol.Optional("hvac"): vol.Any(
None,
{
**{
vol.Optional(key): _ENTITY_REF
for key in (
"supply_vsr",
"extract_vsr",
"supply_temperature",
"extract_temperature",
"reheat",
"status",
)
},
vol.Optional("schedules"): vol.All([vol.All(str, vol.Length(max=255))], vol.Length(max=100)),
},
),
vol.Required("points"): vol.All([_POINT], vol.Length(min=3, max=MAX_POINTS)), vol.Required("points"): vol.All([_POINT], vol.Length(min=3, max=MAX_POINTS)),
vol.Required("floor_material"): vol.All(str, vol.Length(max=32)), vol.Required("floor_material"): vol.All(str, vol.Length(max=32)),
# the camera this room opens with when it is tapped (None = framed from above) # the camera this room opens with when it is tapped (None = framed from above)
@@ -326,6 +353,65 @@ _PIN_OFFSET = vol.Any(
vol.Schema({vol.Optional(k): vol.All(vol.Coerce(float), vol.Range(min=-5, max=5)) for k in ("x", "y", "z")}), vol.Schema({vol.Optional(k): vol.All(vol.Coerce(float), vol.Range(min=-5, max=5)) for k in ("x", "y", "z")}),
) )
_HYDRONIC_CONTROL = {
vol.Optional("command"): _ENTITY_REF,
vol.Optional("feedback"): _ENTITY_REF,
vol.Optional("inverted"): bool,
}
_CHARGING_STATION = {
**{vol.Optional(key): _ENTITY_REF for key in ("soc", "start", "end", "duration", "energy", "lock")},
**{
vol.Optional(key): vol.In(["auto", "value", "seconds", "milliseconds"])
for key in ("start_format", "end_format")
},
vol.Optional("duration_unit"): vol.In(["auto", "value", "seconds", "minutes", "hours"]),
}
_FRESHWATER_STATION = {
vol.Required("id"): _ID,
vol.Required("name"): vol.All(str, vol.Length(max=100)),
**{vol.Optional(key): _ENTITY_REF for key in ("flow", "return", "hot_water", "cold_water", "power")},
vol.Optional("pump"): _HYDRONIC_CONTROL,
vol.Optional("valve"): _HYDRONIC_CONTROL,
vol.Optional("has_valve"): bool,
}
_HYDRONIC = {
vol.Optional("card"): bool,
vol.Optional("circuits"): vol.All(
[
{
vol.Required("id"): _ID,
vol.Required("name"): vol.All(str, vol.Length(max=100)),
vol.Required("kind"): vol.In(["heating", "cooling", "changeover", "pump"]),
vol.Optional("has_pump"): bool,
vol.Optional("has_valve"): bool,
vol.Optional("valve_type"): vol.In(["mixing", "two_way"]),
vol.Optional("pump"): _HYDRONIC_CONTROL,
vol.Optional("valve"): _HYDRONIC_CONTROL,
**{vol.Optional(key): _ENTITY_REF for key in ("flow", "return", "power", "mode_entity")},
vol.Optional("cooling_value"): vol.All(vol.Coerce(int), vol.Range(min=-2147483648, max=2147483647)),
}
],
vol.Length(max=32),
),
vol.Optional("sensors"): vol.All(
[
{
vol.Required("id"): _ID,
vol.Required("name"): vol.All(str, vol.Length(max=100)),
vol.Required("entity"): _ENTITY_REF,
vol.Required("level"): vol.All(vol.Coerce(float), vol.Range(min=0, max=1)),
}
],
vol.Length(max=64),
),
**{vol.Optional(key): _ENTITY_REF for key in ("flow", "return", "circulation_temperature", "hot_water")},
vol.Optional("pump"): _HYDRONIC_CONTROL,
vol.Optional("circulation"): _HYDRONIC_CONTROL,
vol.Optional("cold_water"): _ENTITY_REF,
vol.Optional("stations"): vol.All([_FRESHWATER_STATION], vol.Length(min=1, max=16)),
vol.Optional("buffer_id"): vol.Any(None, _ID),
}
FURNITURE_SCHEMA = vol.Schema( FURNITURE_SCHEMA = vol.Schema(
{ {
vol.Required("id"): _ID, vol.Required("id"): _ID,
@@ -363,6 +449,9 @@ FURNITURE_SCHEMA = vol.Schema(
# linked entities (e.g. the TV's media player, a power sensor): None = automatic, "none" = no entity # linked entities (e.g. the TV's media player, a power sensor): None = automatic, "none" = no entity
vol.Optional("entity", default=None): vol.Any(None, vol.All(str, vol.Length(max=255))), vol.Optional("entity", default=None): vol.Any(None, vol.All(str, vol.Length(max=255))),
vol.Optional("power", default=None): vol.Any(None, vol.All(str, vol.Length(max=255))), vol.Optional("power", default=None): vol.Any(None, vol.All(str, vol.Length(max=255))),
vol.Optional("power_card"): bool,
vol.Optional("charging"): vol.Any(None, _CHARGING_STATION),
vol.Optional("hydronic"): vol.Any(None, _HYDRONIC),
# smart fridge: door sensors of the left and the right door # smart fridge: door sensors of the left and the right door
vol.Optional("door_left", default=None): vol.Any(None, vol.All(str, vol.Length(max=255))), vol.Optional("door_left", default=None): vol.Any(None, vol.All(str, vol.Length(max=255))),
vol.Optional("door_right", default=None): vol.Any(None, vol.All(str, vol.Length(max=255))), vol.Optional("door_right", default=None): vol.Any(None, vol.All(str, vol.Length(max=255))),
@@ -528,7 +617,23 @@ BACKGROUND_SCHEMA = vol.Schema(
extra=vol.ALLOW_EXTRA, extra=vol.ALLOW_EXTRA,
) )
OUTDOOR_TYPES = ["lawn", "terrace", "path", "driveway", "pool", "bed", "wild", "hedge", "fence", "pergola"] OUTDOOR_TYPES = [
"lawn",
"terrace",
"path",
"driveway",
"street",
"sidewalk",
"gravel",
"river",
"stream",
"pool",
"bed",
"wild",
"hedge",
"fence",
"pergola",
]
FENCE_GATE_SCHEMA = vol.Schema( FENCE_GATE_SCHEMA = vol.Schema(
{ {
@@ -769,6 +874,7 @@ FLOOR_SCHEMA = vol.Schema(
), ),
# the floor's own meter: a power sensor shown on the floor label and the house card of this floor # the floor's own meter: a power sensor shown on the floor label and the house card of this floor
vol.Optional("power_entity", default=None): vol.Any(None, vol.All(str, vol.Length(max=255))), vol.Optional("power_entity", default=None): vol.Any(None, vol.All(str, vol.Length(max=255))),
vol.Optional("utility_meters"): _UTILITY_METERS,
vol.Optional("outdoor", default=list): vol.All([OUTDOOR_SCHEMA], vol.Length(max=MAX_ITEMS)), vol.Optional("outdoor", default=list): vol.All([OUTDOOR_SCHEMA], vol.Length(max=MAX_ITEMS)),
# free-standing walls (partitions); room walls come from the room edges # free-standing walls (partitions); room walls come from the room edges
vol.Optional("walls", default=list): vol.All([FREE_WALL_SCHEMA], vol.Length(max=MAX_ITEMS)), vol.Optional("walls", default=list): vol.All([FREE_WALL_SCHEMA], vol.Length(max=MAX_ITEMS)),
@@ -958,6 +1064,7 @@ SETTINGS_SCHEMA = vol.Schema(
vol.Optional("roof", default=lambda: {"type": "none", "pitch": 35, "overhang": 0.4}): ROOF_SCHEMA, vol.Optional("roof", default=lambda: {"type": "none", "pitch": 35, "overhang": 0.4}): ROOF_SCHEMA,
# the weather entity for the weather outside (None = the first one) # the weather entity for the weather outside (None = the first one)
vol.Optional("weather_entity", default=None): vol.Any(None, vol.All(str, vol.Length(max=255))), vol.Optional("weather_entity", default=None): vol.Any(None, vol.All(str, vol.Length(max=255))),
vol.Optional("weather_variables"): vol.Any(None, {str: _ENTITY_REF}),
# which weather effects the 3D view shows (None = all but fog) # which weather effects the 3D view shows (None = all but fog)
# warning for a window open while it rains # warning for a window open while it rains
vol.Optional("rain_warning", default=True): bool, vol.Optional("rain_warning", default=True): bool,
@@ -1073,6 +1180,7 @@ ENERGY_SCHEMA = vol.Schema(
# Which sensor tells the room of a person (ESPresense, Bermuda: the state is a room or area name) # Which sensor tells the room of a person (ESPresense, Bermuda: the state is a room or area name)
PRESENCE_SCHEMA = vol.Schema( PRESENCE_SCHEMA = vol.Schema(
{ {
vol.Optional("name"): vol.Any(None, _NAME),
vol.Required("person"): vol.All(str, vol.Length(max=255)), vol.Required("person"): vol.All(str, vol.Length(max=255)),
vol.Required("sensor"): vol.Any(None, _ENTITY), vol.Required("sensor"): vol.Any(None, _ENTITY),
vol.Optional("room"): vol.Any(None, vol.All(str, vol.Length(max=64))), vol.Optional("room"): vol.Any(None, vol.All(str, vol.Length(max=64))),
+27 -4
View File
@@ -3,6 +3,7 @@
import { build, context } from "esbuild"; import { build, context } from "esbuild";
import { createHash } from "node:crypto"; import { createHash } from "node:crypto";
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync } from "node:fs"; import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync } from "node:fs";
import { validateSymconPackage } from "../symcon/tests/validate-package.mjs";
const out = "../custom_components/nextfloor/frontend"; const out = "../custom_components/nextfloor/frontend";
// IP-Symcon ships the same browser UI through the module's protected WebHook. Its designer and // IP-Symcon ships the same browser UI through the module's protected WebHook. Its designer and
@@ -21,6 +22,7 @@ const common = {
legalComments: "eof", legalComments: "eof",
banner: { js: "/*! NextFloor, MIT licence. Includes three.js (MIT) and Lit (BSD-3-Clause); see LICENSE and THIRD_PARTY_NOTICES.md */" }, banner: { js: "/*! NextFloor, MIT licence. Includes three.js (MIT) and Lit (BSD-3-Clause); see LICENSE and THIRD_PARTY_NOTICES.md */" },
logLevel: "info", logLevel: "info",
define: { __NF_TREND_HASH__: JSON.stringify("dev"), __NF_HYDRONIC_HASH__: JSON.stringify("dev") },
}; };
const hashOf = (file) => createHash("sha256").update(readFileSync(file)).digest("hex").slice(0, 12); const hashOf = (file) => createHash("sha256").update(readFileSync(file)).digest("hex").slice(0, 12);
@@ -31,6 +33,8 @@ const langFiles = readdirSync("lang").filter((f) => /^[a-z]{2}\.json$/.test(f));
const langs = JSON.stringify(Object.fromEntries(langFiles.map((f) => [f.slice(0, 2), hashOf(`lang/${f}`)]))); const langs = JSON.stringify(Object.fromEntries(langFiles.map((f) => [f.slice(0, 2), hashOf(`lang/${f}`)])));
const viewerConfig = { ...common, entryPoints: ["src/viewer/viewer3d.ts"], outfile: `${out}/nextfloor-3d.js` }; const viewerConfig = { ...common, entryPoints: ["src/viewer/viewer3d.ts"], outfile: `${out}/nextfloor-3d.js` };
const trendConfig = { ...common, entryPoints: ["src/components/trend-dialog.ts"], outfile: `${out}/nextfloor-trend.js` };
const hydronicConfig = { ...common, entryPoints: ["src/components/hydronic-card.ts"], outfile: `${out}/nextfloor-hydronics.js` };
// the card's visual editor only loads in the dashboard's card dialog // the card's visual editor only loads in the dashboard's card dialog
const cardEditorConfig = { ...common, entryPoints: ["src/card-editor.ts"], outfile: `${out}/nextfloor-card-editor.js`, define: { __NF_LANGS__: langs, "globalThis.__NF_SHARED_TEXTS__": "true" } }; const cardEditorConfig = { ...common, entryPoints: ["src/card-editor.ts"], outfile: `${out}/nextfloor-card-editor.js`, define: { __NF_LANGS__: langs, "globalThis.__NF_SHARED_TEXTS__": "true" } };
// the editor is only needed by admins who open it, so it is a bundle of its own as well // the editor is only needed by admins who open it, so it is a bundle of its own as well
@@ -39,17 +43,19 @@ const editorConfig = (viewerHash) => ({
...common, ...common,
entryPoints: ["src/components/editor.ts"], entryPoints: ["src/components/editor.ts"],
outfile: `${out}/nextfloor-editor.js`, outfile: `${out}/nextfloor-editor.js`,
define: { __NF_VIEWER_HASH__: JSON.stringify(viewerHash), __NF_LANGS__: langs, "globalThis.__NF_SHARED_TEXTS__": "true" }, define: { ...common.define, __NF_VIEWER_HASH__: JSON.stringify(viewerHash), __NF_LANGS__: langs, "globalThis.__NF_SHARED_TEXTS__": "true" },
}); });
// The main bundle loads the 3D bundle with a hash of its content in the URL, so a new 3D bundle is // The main bundle loads the 3D bundle with a hash of its content in the URL, so a new 3D bundle is
// never taken from the browser cache (the integration version only changes after a restart). // never taken from the browser cache (the integration version only changes after a restart).
// the frontend knows its own version, to notice a backend that still runs an older one // the frontend knows its own version, to notice a backend that still runs an older one
const version = JSON.parse(readFileSync("../custom_components/nextfloor/manifest.json", "utf8")).version; const version = JSON.parse(readFileSync("../custom_components/nextfloor/manifest.json", "utf8")).version;
const symconVersion = JSON.parse(readFileSync("../symcon/library.json", "utf8")).version;
const mainConfig = (viewerHash, editorHash, cardEditorHash) => ({ const mainConfig = (viewerHash, editorHash, cardEditorHash) => ({
...common, ...common,
entryPoints: ["src/main.ts"], entryPoints: ["src/main.ts"],
outfile: `${out}/nextfloor.js`, outfile: `${out}/nextfloor.js`,
define: { define: {
...common.define,
__NF_VIEWER_HASH__: JSON.stringify(viewerHash), __NF_VIEWER_HASH__: JSON.stringify(viewerHash),
__NF_EDITOR_HASH__: JSON.stringify(editorHash), __NF_EDITOR_HASH__: JSON.stringify(editorHash),
__NF_CARD_EDITOR_HASH__: JSON.stringify(cardEditorHash), __NF_CARD_EDITOR_HASH__: JSON.stringify(cardEditorHash),
@@ -64,17 +70,18 @@ const symconEditorConfig = (viewerHash) => ({
...common, ...common,
entryPoints: ["src/components/editor.ts"], entryPoints: ["src/components/editor.ts"],
outfile: `${symconOut}/nextfloor-editor.js`, outfile: `${symconOut}/nextfloor-editor.js`,
define: { __NF_VIEWER_HASH__: JSON.stringify(viewerHash), __NF_LANGS__: langs, "globalThis.__NF_SHARED_TEXTS__": "true" }, define: { ...common.define, __NF_VIEWER_HASH__: JSON.stringify(viewerHash), __NF_LANGS__: langs, "globalThis.__NF_SHARED_TEXTS__": "true" },
}); });
const symconHostConfig = (viewerHash, editorHash, cardEditorHash) => ({ const symconHostConfig = (viewerHash, editorHash, cardEditorHash) => ({
...common, ...common,
entryPoints: ["src/symcon-host.ts"], entryPoints: ["src/symcon-host.ts"],
outfile: `${symconOut}/nextfloor-designer.js`, outfile: `${symconOut}/nextfloor-designer.js`,
define: { define: {
...common.define,
__NF_VIEWER_HASH__: JSON.stringify(viewerHash), __NF_VIEWER_HASH__: JSON.stringify(viewerHash),
__NF_EDITOR_HASH__: JSON.stringify(editorHash), __NF_EDITOR_HASH__: JSON.stringify(editorHash),
__NF_CARD_EDITOR_HASH__: JSON.stringify(cardEditorHash), __NF_CARD_EDITOR_HASH__: JSON.stringify(cardEditorHash),
__NF_VERSION__: JSON.stringify(version), __NF_VERSION__: JSON.stringify(symconVersion),
__NF_LANGS__: langs, __NF_LANGS__: langs,
}, },
}); });
@@ -104,7 +111,12 @@ function copySymconAssets() {
// Size budgets, small enough for old wall tablets. The editor bundles only load for admins and the card's settings, so they // Size budgets, small enough for old wall tablets. The editor bundles only load for admins and the card's settings, so they
// may grow more than the view; German and English texts ride in every bundle. // may grow more than the view; German and English texts ride in every bundle.
const BUDGET = { "nextfloor.js": 650 * 1024, "nextfloor-3d.js": 1000 * 1024, "nextfloor-editor.js": 720 * 1024, "nextfloor-card-editor.js": 240 * 1024 }; // Native utility discovery/reports plus the building/floor overview need about 14 KB in the shared runtime.
// Hydronic geometry/readouts load separately; only model references, anchors and the loader join the host.
// Metered-device detail discovery adds about 2 KB; keep a small, explicit margin.
// Charging telemetry, native time/duration formatting and labels add another 5 KB.
// Zoom detail levels and bounded device-card layouts add about 1.5 KB.
const BUDGET = { "nextfloor.js": 682 * 1024, "nextfloor-3d.js": 1000 * 1024, "nextfloor-editor.js": 720 * 1024, "nextfloor-card-editor.js": 240 * 1024, "nextfloor-trend.js": 100 * 1024, "nextfloor-hydronics.js": 100 * 1024 };
copyAssets(); copyAssets();
copySymconAssets(); copySymconAssets();
@@ -112,6 +124,10 @@ if (watch) {
// in watch mode the hash is not tracked; a dev reload fetches the bundle anyway // in watch mode the hash is not tracked; a dev reload fetches the bundle anyway
for (const c of [ for (const c of [
viewerConfig, viewerConfig,
trendConfig,
hydronicConfig,
{ ...hydronicConfig, outfile: `${symconOut}/nextfloor-hydronics.js` },
{ ...trendConfig, outfile: `${symconOut}/nextfloor-trend.js` },
editorConfig("dev"), editorConfig("dev"),
cardEditorConfig, cardEditorConfig,
mainConfig("dev", "dev", "dev"), mainConfig("dev", "dev", "dev"),
@@ -122,6 +138,12 @@ if (watch) {
builderConfig, builderConfig,
]) await (await context(c)).watch(); ]) await (await context(c)).watch();
} else { } else {
await build(trendConfig);
copyFileSync(trendConfig.outfile, `${symconOut}/nextfloor-trend.js`);
common.define.__NF_TREND_HASH__ = JSON.stringify(hashOf(trendConfig.outfile));
await build(hydronicConfig);
copyFileSync(hydronicConfig.outfile, `${symconOut}/nextfloor-hydronics.js`);
common.define.__NF_HYDRONIC_HASH__ = JSON.stringify(hashOf(hydronicConfig.outfile));
await build(viewerConfig); await build(viewerConfig);
const editor = editorConfig(hashOf(viewerConfig.outfile)); const editor = editorConfig(hashOf(viewerConfig.outfile));
await build(editor); await build(editor);
@@ -132,6 +154,7 @@ if (watch) {
await build(symconEditor); await build(symconEditor);
await build(symconCardEditorConfig); await build(symconCardEditorConfig);
await build(symconHostConfig(hashOf(symconViewerConfig.outfile), hashOf(symconEditor.outfile), hashOf(symconCardEditorConfig.outfile))); await build(symconHostConfig(hashOf(symconViewerConfig.outfile), hashOf(symconEditor.outfile), hashOf(symconCardEditorConfig.outfile)));
validateSymconPackage();
await build(builderConfig); await build(builderConfig);
let over = false; let over = false;
for (const [file, limit] of Object.entries(BUDGET)) { for (const [file, limit] of Object.entries(BUDGET)) {
+5
View File
@@ -7,6 +7,7 @@ import { translate } from "./i18n.ts";
import { pointInPolygon, type Building, type Opening, type OwnAlert } from "./model.ts"; import { pointInPolygon, type Building, type Opening, type OwnAlert } from "./model.ts";
import type { HomeAssistant } from "./types.ts"; import type { HomeAssistant } from "./types.ts";
import { weatherEntity } from "./weather.ts"; import { weatherEntity } from "./weather.ts";
import { nativeBool } from "./entities/symcon-values.ts";
export type AlertKind = "smoke" | "gas" | "co" | "water" | "alarm" | "alarm_pending" | "window_rain" | "power_outage" | "contact_lost" | "unlocked_night" | "own"; export type AlertKind = "smoke" | "gas" | "co" | "water" | "alarm" | "alarm_pending" | "window_rain" | "power_outage" | "contact_lost" | "unlocked_night" | "own";
@@ -157,6 +158,10 @@ export function isRaining(hass: HomeAssistant, sources: Pick<AlertSources, "weat
if (sources.rain) { if (sources.rain) {
const st = hass.states[sources.rain]; const st = hass.states[sources.rain];
if (!st || st.state === "unavailable" || st.state === "unknown") return false; if (!st || st.state === "unavailable" || st.state === "unknown") return false;
if (st.attributes.symcon_id) {
const wet = nativeBool(st);
return wet === null ? false : sources.rainInverted ? !wet : wet;
}
const rate = Number(st.state); const rate = Number(st.state);
const wet = Number.isFinite(rate) ? rate > 0 : st.state === "on" || /rain|regen|wet|nass/i.test(st.state); const wet = Number.isFinite(rate) ? rate > 0 : st.state === "on" || /rain|regen|wet|nass/i.test(st.state);
return sources.rainInverted ? !wet : wet; return sources.rainInverted ? !wet : wet;
+5 -4
View File
@@ -10,6 +10,7 @@ import { checkbox, choice, DEFAULTS, flagOption, followOrForce, numberChoice, sw
import { editorStyles } from "./card-editor/styles.ts"; import { editorStyles } from "./card-editor/styles.ts";
import { awaitingLanguage, translate, type I18nKey } from "./i18n.ts"; import { awaitingLanguage, translate, type I18nKey } from "./i18n.ts";
import type { HomeAssistant } from "./types.ts"; import type { HomeAssistant } from "./types.ts";
import { isSymcon } from "./entities/symcon-values.ts";
export class NextFloorCardEditor extends LitElement { export class NextFloorCardEditor extends LitElement {
static properties = { static properties = {
@@ -188,18 +189,18 @@ export class NextFloorCardEditor extends LitElement {
${[0.8, 1, 1.25, 1.5, 1.75, 2, 2.5].map((z) => html`<option value=${z} ?selected=${(f.value.zoom ?? 1) === z}>${Math.round(z * 100)} %</option>`)} ${[0.8, 1, 1.25, 1.5, 1.75, 2, 2.5].map((z) => html`<option value=${z} ?selected=${(f.value.zoom ?? 1) === z}>${Math.round(z * 100)} %</option>`)}
</select> </select>
</label> </label>
${switchOption(f, "announcements", "card_announcements", "card_announcements_hint")} ${isSymcon(this.hass) ? nothing : switchOption(f, "announcements", "card_announcements", "card_announcements_hint")}
${f.value.announcements !== false ? html`<div class="grid">${textField(f, "screen_name", "screen_name")}</div>` : nothing} ${!isSymcon(this.hass) && f.value.announcements !== false ? html`<div class="grid">${textField(f, "screen_name", "screen_name")}</div>` : nothing}
${switchOption(f, "weather", "card_weather", "card_weather_hint")} ${switchOption(f, "weather", "card_weather", "card_weather_hint")}
${f.value.weather !== false ${f.value.weather !== false
? html`<div class="grid"> ? html`<div class="grid">
<label class="field wide" ${isSymcon(this.hass) ? nothing : html`<label class="field wide"
>${f.t("weather_entity")} >${f.t("weather_entity")}
<select @change=${(e: Event) => f.set("weather_entity", (e.target as HTMLSelectElement).value || undefined)}> <select @change=${(e: Event) => f.set("weather_entity", (e.target as HTMLSelectElement).value || undefined)}>
<option value="" ?selected=${!f.value.weather_entity}>${f.t("card_weather_plan")}</option> <option value="" ?selected=${!f.value.weather_entity}>${f.t("card_weather_plan")}</option>
${weatherEntities.map((id) => html`<option value=${id} ?selected=${id === f.value.weather_entity}>${String(this.hass?.states[id]?.attributes.friendly_name ?? id)}</option>`)} ${weatherEntities.map((id) => html`<option value=${id} ?selected=${id === f.value.weather_entity}>${String(this.hass?.states[id]?.attributes.friendly_name ?? id)}</option>`)}
</select> </select>
</label> </label>`}
<label class="field" <label class="field"
>${f.t("card_weather_density")} >${f.t("card_weather_density")}
<select @change=${(e: Event) => f.set("weather_density", Number((e.target as HTMLSelectElement).value))}> <select @change=${(e: Event) => f.set("weather_density", Number((e.target as HTMLSelectElement).value))}>
+13 -4
View File
@@ -18,6 +18,9 @@ import type { Building } from "./model.ts";
import { roomsOnly } from "./rooms-only.ts"; import { roomsOnly } from "./rooms-only.ts";
import { colorSchemeOf, controls, readableStyles, tokens } from "./styles.ts"; import { colorSchemeOf, controls, readableStyles, tokens } from "./styles.ts";
import type { HomeAssistant } from "./types.ts"; import type { HomeAssistant } from "./types.ts";
import { withCoverControls } from "./entities/cover-controls.ts";
import { withSymconWeather } from "./symcon-weather.ts";
import { isSymcon } from "./entities/symcon-values.ts";
import type { WallMode } from "./viewer/viewer3d.ts"; import type { WallMode } from "./viewer/viewer3d.ts";
import { lookNow } from "./themes.ts"; import { lookNow } from "./themes.ts";
@@ -49,6 +52,7 @@ export class NextFloorCard extends LitElement {
_clean: { state: true }, _clean: { state: true },
_night: { state: true }, _night: { state: true },
_orbit: { state: true }, _orbit: { state: true },
_roomNames: { state: true },
}; };
declare hass: HomeAssistant; declare hass: HomeAssistant;
@@ -71,6 +75,7 @@ export class NextFloorCard extends LitElement {
/** Kiosk: the night dimming is on, and the screensaver turn runs (after an idle return). */ /** Kiosk: the night dimming is on, and the screensaver turn runs (after an idle return). */
private declare _night: boolean; private declare _night: boolean;
private declare _orbit: boolean; private declare _orbit: boolean;
private declare _roomNames: boolean | null;
private readonly data = new BuildingController(this); private readonly data = new BuildingController(this);
private readonly kiosk = new KioskTimers({ private readonly kiosk = new KioskTimers({
@@ -95,6 +100,7 @@ export class NextFloorCard extends LitElement {
this._clean = false; this._clean = false;
this._night = false; this._night = false;
this._orbit = false; this._orbit = false;
this._roomNames = null;
} }
private view3d() { private view3d() {
@@ -146,6 +152,7 @@ export class NextFloorCard extends LitElement {
setConfig(config: CardConfig): void { setConfig(config: CardConfig): void {
if (config.height !== undefined && !(config.height > 100)) throw new Error("height must be a number of pixels above 100"); if (config.height !== undefined && !(config.height > 100)) throw new Error("height must be a number of pixels above 100");
this._roomNames = null;
this._own = config; this._own = config;
this._config = withTemplate(config, this.data.building?.settings.card_templates as CardTemplates | undefined); this._config = withTemplate(config, this.data.building?.settings.card_templates as CardTemplates | undefined);
this._floorId = undefined; this._floorId = undefined;
@@ -313,7 +320,7 @@ export class NextFloorCard extends LitElement {
}; };
const eye = c?.controls_hidden !== undefined || (c?.controls_hide_after ?? 0) > 0; const eye = c?.controls_hidden !== undefined || (c?.controls_hide_after ?? 0) > 0;
return html`<nf-view3d return html`<nf-view3d
.hass=${this.hass} .hass=${withSymconWeather(withCoverControls(this.hass, b.floors), b.settings)}
.building=${b} .building=${b}
.packs=${this.data.packs} .packs=${this.data.packs}
.floorId=${s.floorId} .floorId=${s.floorId}
@@ -352,12 +359,14 @@ export class NextFloorCard extends LitElement {
.flows=${c?.flows ?? null} .flows=${c?.flows ?? null}
.holograms=${c?.holograms ?? null} .holograms=${c?.holograms ?? null}
.floorThumbs=${this.thumbs} .floorThumbs=${this.thumbs}
.roomLabels=${c?.room_names !== false} .roomLabels=${this._roomNames ?? (c?.room_names !== false)}
.roomNamesButton=${true}
@room-names-change=${(e: CustomEvent<{ value: boolean }>) => (this._roomNames = e.detail.value)}
.floorStack=${c?.floor_stack ?? "dim"} .floorStack=${c?.floor_stack ?? "dim"}
.panelOpen=${!!this._roomId && c?.room_panel !== false} .panelOpen=${!!this._roomId && c?.room_panel !== false}
.alerts=${c?.alerts !== false} .alerts=${c?.alerts !== false}
.alertJump=${!!c?.alert_jump} .alertJump=${!!c?.alert_jump}
.announcements=${c?.announcements !== false && !screenMuted()} .announcements=${!isSymcon(this.hass) && c?.announcements !== false && !screenMuted()}
.sensorBar=${c?.sensor_bar !== false} .sensorBar=${c?.sensor_bar !== false}
.glassWalls=${typeof c?.glass_walls === "number" ? Math.min(100, Math.max(0, c.glass_walls)) : null} .glassWalls=${typeof c?.glass_walls === "number" ? Math.min(100, Math.max(0, c.glass_walls)) : null}
.screenName=${c?.screen_name ?? screenName()} .screenName=${c?.screen_name ?? screenName()}
@@ -392,7 +401,7 @@ export class NextFloorCard extends LitElement {
return html`<nf-room-panel return html`<nf-room-panel
.building=${this.plan() ?? null} .building=${this.plan() ?? null}
class="nf-card-panel" class="nf-card-panel"
.hass=${this.hass} .hass=${withCoverControls(this.hass, b.floors)}
.room=${b.floors.flatMap((f) => f.rooms).find((r) => r.id === this._roomId) ?? null} .room=${b.floors.flatMap((f) => f.rooms).find((r) => r.id === this._roomId) ?? null}
.floor=${b.floors.find((f) => f.rooms.some((r) => r.id === this._roomId)) ?? null} .floor=${b.floors.find((f) => f.rooms.some((r) => r.id === this._roomId)) ?? null}
.outside=${this._roomId === OUTSIDE ? outsideEntities(this.hass, b.floors) : null} .outside=${this._roomId === OUTSIDE ? outsideEntities(this.hass, b.floors) : null}
+77
View File
@@ -0,0 +1,77 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { box, entity, floorWith, hassOf } from "./entities/fixtures.ts";
import { emptyBuilding, normalizeBuilding, type Furniture } from "./model.ts";
import { chargingDurationText, chargingReadouts, chargingRefs, chargingTimeText, isChargingStation } from "./charging-station.ts";
import { furniturePowerCards } from "./live/furniture-power-card.ts";
import { watchedEntities } from "./components/view3d/watch-list.ts";
const point = (id: string, value: number | string, extra: Record<string, unknown> = {}) => entity(id, "open", { symcon_id: 123, symcon_variable_type: typeof value === "number" ? 1 : 3, symcon_value: value, ...extra });
const item = (extra: Partial<Furniture> = {}): Furniture => ({ id: "charger", type: "wallbox", name: "Meine Wallbox", x: 2, z: 2, w: .3, d: .3, h: .4, rotation: 0, variant: null, power_card: true, power: "none", ...extra });
test("built-in and both pack wallboxes offer charging data without classifying linked variable names", () => {
for (const type of ["wallbox", "pack:nextfloor.a_smart:wallbox", "pack:nextfloor.energie:wallbox", "pack:test:ev_bike_charger", "pack:test:ev_charger", "pack:test:charging_station"]) assert.equal(isChargingStation(type), true);
for (const type of ["desk", "pack:test:wallbox_holder", "pack:wallbox:desk"]) assert.equal(isChargingStation(type), false);
});
test("zero SoC, zero duration and arbitrary native Integer aliases remain authoritative", () => {
const h = hassOf([point("cover.1", 0, { symcon_formatted: "0" }), point("climate.2", 0), point("light.3", 0, { symcon_formatted: "Stecker frei" }), point("cover.4", 12.35, { symcon_formatted: "12,35 kWh", unit_of_measurement: "kWh" })], {}, { language: "de", symconObjects: [] });
const f = item({ charging: { soc: "cover.1", duration: "climate.2", energy: "cover.4", lock: "light.3" } });
assert.deepEqual(chargingReadouts(h, f).map((r) => [r.id, r.text]), [["soc", "0 %"], ["duration", "0:00:00"], ["energy", "12,35 kWh"], ["lock", "Stecker frei"]]);
h.states["light.3"] = point("light.3", 7, { symcon_formatted: "Wartung: verriegelt" });
assert.equal(chargingReadouts(h, f).at(-1)?.text, "Wartung: verriegelt");
h.states["light.3"].state = "unavailable";
assert.equal(chargingReadouts(h, f).at(-1)?.text, "–");
assert.deepEqual(chargingReadouts(h, item({ charging: { soc: null, energy: "none" } })), []);
});
test("native timestamp profiles, strings, seconds and milliseconds display dates without changing source values", () => {
const h = hassOf([], {}, { language: "de" }), ts = Date.UTC(2026, 10, 12, 13, 45, 0) / 1000;
const st = point("cover.start", ts);
const expected = new Date(ts * 1000).toLocaleString("de", { year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" });
assert.equal(chargingTimeText(h, st), expected);
assert.equal(chargingTimeText(h, point("cover.ms", ts * 1000)), expected);
assert.equal(chargingTimeText(h, point("cover.iso", new Date(ts * 1000).toISOString())), expected);
assert.equal(chargingTimeText(h, point("cover.date", ts, { symcon_formatted: "12.11.2026" })), "12.11.2026");
assert.equal(chargingTimeText(h, point("cover.time", 45000, { symcon_formatted: "12:30" })), "12:30");
assert.equal(chargingTimeText(h, point("cover.raw", ts, { symcon_formatted: "Eigene Anzeige" }), "value"), "Eigene Anzeige");
assert.equal(chargingTimeText(h, point("cover.raw", ts, { symcon_formatted: "Eigene Anzeige" }), "seconds"), expected);
assert.equal(chargingTimeText(h, point("cover.ms", ts * 1000), "milliseconds"), expected);
assert.equal(chargingTimeText(h, point("cover.invalid", "noch nicht gestartet")), "noch nicht gestartet");
assert.equal(st.attributes.symcon_value, ts);
});
test("duration conversion respects units, explicit overrides and native formatted duration profiles", () => {
const h = hassOf([], {}, { language: "de" });
assert.equal(chargingDurationText(h, point("cover.s", 90061)), "25:01:01");
assert.equal(chargingDurationText(h, point("cover.min", 61, { unit_of_measurement: "min", symcon_formatted: "61 min" })), "1:01:00");
assert.equal(chargingDurationText(h, point("cover.h", 1.5, { unit_of_measurement: "h" })), "1:30:00");
assert.equal(chargingDurationText(h, point("cover.h", 1.5), "hours"), "1:30:00");
assert.equal(chargingDurationText(h, point("cover.min", 2), "minutes"), "0:02:00");
assert.equal(chargingDurationText(h, point("cover.s", -3)), "−0:00:03");
assert.equal(chargingDurationText(h, point("cover.native", 3661, { symcon_formatted: "1 Std 1 Min" })), "1 Std 1 Min");
assert.equal(chargingDurationText(h, point("cover.text", "02:15:00")), "02:15:00");
assert.equal(chargingDurationText(h, point("cover.raw", 61, { symcon_formatted: "61 min" }), "value"), "61 min");
assert.equal(chargingDurationText(h, undefined), "–");
});
test("a charging-data-only floating card needs no power or switch and remains scoped and opt-in", () => {
const f = item({ charging: { soc: "sensor.1", lock: "sensor.2" } }), h = hassOf([point("sensor.1", 55), point("sensor.2", 0, { symcon_formatted: "Entriegelt" })]);
const b = { ...emptyBuilding(), floors: [floorWith([box("r", 0, 0, 5, 5)], { furniture: [f] })] };
const [card] = furniturePowerCards(h, b, new Map([[f.id, { entity: null, power: "sensor.ignored" }]]), null, null);
assert.equal(card.powerEntity, null); assert.equal(card.power, null);
assert.deepEqual(card.readings?.map((r) => r.text), ["55 %", "Entriegelt"]);
assert.deepEqual(furniturePowerCards(h, b, new Map(), "other", null), []);
f.power_card = false; assert.deepEqual(furniturePowerCards(h, b, new Map(), null, null), []);
});
test("all six links survive JSON normalization and trigger live updates even without room climate sensors", () => {
const f = item({ charging: { soc: "cover.1", start: "light.2", end: "climate.3", duration: "switch.4", energy: "sensor.5", lock: "cover.6", start_format: "milliseconds", end_format: "value", duration_unit: "minutes" } });
const b = normalizeBuilding(JSON.parse(JSON.stringify({ ...emptyBuilding(), floors: [floorWith([], { furniture: [f] })] })));
assert.deepEqual(b.floors[0].furniture[0].charging, f.charging);
const h = hassOf([], {}, { symconObjects: [] });
const watched = watchedEntities({ hass: h, building: b, furnitureLinks: new Map(), openingLinks: new Map(), needsRoomSensors: false, alertSources: null, weatherEntityId: null });
assert.ok(chargingRefs(f).every((id) => watched.includes(id)));
assert.equal(chargingReadouts(h, f).length, 6, "temporarily missing linked values retain their row as a dash");
assert.ok(chargingReadouts(h, f).every((r) => r.text === "–"));
});
+83
View File
@@ -0,0 +1,83 @@
import type { EntityRef, Furniture } from "./model.ts";
import type { HassEntity, HomeAssistant } from "./types.ts";
import { nativeNumber, nativeText, nativeValue } from "./entities/symcon-values.ts";
import { formatNumber, translate, type I18nKey } from "./i18n.ts";
export type ChargingTimeFormat = "auto" | "value" | "seconds" | "milliseconds";
export type ChargingDurationUnit = "auto" | "value" | "seconds" | "minutes" | "hours";
export interface ChargingStationConfig {
soc?: EntityRef; start?: EntityRef; end?: EntityRef; duration?: EntityRef; energy?: EntityRef; lock?: EntityRef;
start_format?: ChargingTimeFormat; end_format?: ChargingTimeFormat; duration_unit?: ChargingDurationUnit;
}
export interface ChargingReadout { id: string; entity: string; icon: string; label: string; text: string }
/** Furniture type identifiers only; linked variables are never classified by their names. */
export const isChargingStation = (type: string): boolean => type === "wallbox" || /^pack:[^:]+:(wallbox|ev_charger|ev_bike_charger|charging_station)$/.test(type);
const fields = [
["soc", "🔋", "furn_soc"], ["start", "▶", "charging_start"], ["end", "■", "charging_end"],
["duration", "⏱", "charging_duration"], ["energy", "⚡", "charging_energy"], ["lock", "🔐", "charging_lock"],
] as const satisfies readonly (readonly [keyof ChargingStationConfig, string, I18nKey])[];
const real = (id: EntityRef | undefined): id is string => !!id && id !== "none";
const numericText = (text: string): boolean => /^[+-]?\d+(?:[.,\s]\d{3})*(?:[.,]\d+)?$/.test(text.trim());
const sourceOf = (hass: HomeAssistant, id: string) => String(hass.states[id]?.attributes.symcon_source_entity || id);
export function chargingRefs(item: Pick<Furniture, "type" | "charging">): string[] {
return isChargingStation(item.type) ? [...new Set(fields.map(([key]) => item.charging?.[key]).filter(real))] : [];
}
/** Preserve Symcon's formatted profile values, particularly arbitrary Integer associations. */
function valueText(hass: HomeAssistant, st: HassEntity | undefined, fallbackUnit = ""): string {
if (nativeValue(st) === null) return "–";
const formatted = st?.attributes.symcon_formatted;
if (typeof formatted === "string" && formatted.trim()) {
return fallbackUnit && /^[-+]?\d+(?:[.,]\d+)?$/.test(formatted.trim()) ? `${formatted} ${fallbackUnit}` : formatted;
}
const n = nativeNumber(st);
return n === null ? nativeText(st) : `${formatNumber(hass, n, Number.isInteger(n) ? 0 : 2)}${st?.attributes.unit_of_measurement || fallbackUnit ? ` ${st?.attributes.unit_of_measurement || fallbackUnit}` : ""}`;
}
export function chargingTimeText(hass: HomeAssistant, st: HassEntity | undefined, format: ChargingTimeFormat = "auto"): string {
if (nativeValue(st) === null) return "–";
if (format === "value") return valueText(hass, st);
const n = nativeNumber(st), raw = nativeValue(st);
let ms: number | null = null;
if (format !== "auto") ms = n === null ? null : n * (format === "seconds" ? 1000 : 1);
else {
const formatted = st?.attributes.symcon_formatted;
// Native date/time profiles already know their preferred display, including time-only values.
if (typeof formatted === "string" && formatted.trim() && !numericText(formatted)) return formatted;
if (n !== null && n >= 1e8) ms = n < 1e11 ? n * 1000 : n;
else if (typeof raw === "string" && /^\d{4}-\d\d-\d\d[T ]\d\d:\d\d/.test(raw)) ms = Date.parse(raw);
}
if (ms === null || !Number.isFinite(ms) || !Number.isFinite(new Date(ms).getTime())) return valueText(hass, st);
return new Date(ms).toLocaleString(hass.language || "de", { year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" });
}
export function chargingDurationText(hass: HomeAssistant, st: HassEntity | undefined, unit: ChargingDurationUnit = "auto"): string {
if (nativeValue(st) === null) return "–";
if (unit === "value") return valueText(hass, st);
const n = nativeNumber(st);
if (n === null) return valueText(hass, st);
if (unit === "auto") {
const formatted = st?.attributes.symcon_formatted;
const suffix = String(st?.attributes.unit_of_measurement ?? "").trim();
// Retain native duration profiles/aliases, unless this is just a number with its unit.
if (typeof formatted === "string" && formatted.trim() && !numericText(formatted) && !(suffix && formatted.trim().endsWith(suffix) && numericText(formatted.trim().slice(0, -suffix.length).trim()))) return formatted;
unit = /^(min|minute[n]?|minutes)$/i.test(suffix) ? "minutes" : /^(h|std\.?|stunde[n]?|hours?)$/i.test(suffix) ? "hours" : "seconds";
}
const seconds = Math.round(Math.abs(n) * (unit === "hours" ? 3600 : unit === "minutes" ? 60 : 1));
if (!Number.isSafeInteger(seconds)) return valueText(hass, st);
return `${n < 0 ? "−" : ""}${Math.floor(seconds / 3600)}:${String(Math.floor(seconds / 60) % 60).padStart(2, "0")}:${String(seconds % 60).padStart(2, "0")}`;
}
export function chargingReadouts(hass: HomeAssistant, item: Pick<Furniture, "type" | "charging">): ChargingReadout[] {
if (!isChargingStation(item.type)) return [];
const config = item.charging;
return fields.flatMap(([key, icon, label]) => {
const ref = config?.[key];
if (!real(ref)) return [];
const entity = sourceOf(hass, ref), st = hass.states[entity];
const text = key === "start" || key === "end" ? chargingTimeText(hass, st, config?.[`${key}_format`])
: key === "duration" ? chargingDurationText(hass, st, config?.duration_unit) : valueText(hass, st, key === "soc" ? "%" : "");
return [{ id: key, entity, icon, label: translate(hass, label), text }];
});
}
+28 -13
View File
@@ -1,6 +1,9 @@
// 2D editor: floors, rooms (rectangles and free shapes), snapping, undo, background template. // 2D editor: floors, rooms (rectangles and free shapes), snapping, undo, background template.
import { html, LitElement, nothing, svg, type PropertyValues, type TemplateResult } from "lit"; import { html, LitElement, nothing, svg, type PropertyValues, type TemplateResult } from "lit";
import { withCoverControls } from "../entities/cover-controls.ts";
import { withSymconWeather } from "../symcon-weather.ts";
import { hint } from "./editor/fields.ts";
import { fetchImage, importPack, storeImage } from "../api.ts"; import { fetchImage, importPack, storeImage } from "../api.ts";
import { defaultHeight, entityName, kindOf, roomEntities } from "../devices.ts"; import { defaultHeight, entityName, kindOf, roomEntities } from "../devices.ts";
import { closeGaps, suggestedThickness } from "../geometry/gaps.ts"; import { closeGaps, suggestedThickness } from "../geometry/gaps.ts";
@@ -74,7 +77,7 @@ import { LibraryState, renderLibrary, renderPreview, type LibraryActions } from
import { arcFreeWall, arcRoomEdge, insertCorner } from "./editor/ops/rooms.ts"; import { arcFreeWall, arcRoomEdge, insertCorner } from "./editor/ops/rooms.ts";
import type { ArcActions, ArcEdit } from "./editor/forms/arc.ts"; import type { ArcActions, ArcEdit } from "./editor/forms/arc.ts";
import { dragStep, facingAngle, gridPositionAfter, hasLeftStart, headingAngle, outlineWithCornerAt, shifted, steppedDelta, straightEnd } from "./editor/ops/drags.ts"; import { dragStep, facingAngle, gridPositionAfter, hasLeftStart, headingAngle, outlineWithCornerAt, shifted, steppedDelta, straightEnd } from "./editor/ops/drags.ts";
import { snapToPlan } from "./editor/ops/snapping.ts"; import { snapOutdoorMove, snapToPlan, type SnapOptions } from "./editor/ops/snapping.ts";
import { draftLayer, guidesLayer } from "./editor/canvas/draft.ts"; import { draftLayer, guidesLayer } from "./editor/canvas/draft.ts";
import { devicesLayer, furnitureLayer, notesLayer } from "./editor/canvas/items.ts"; import { devicesLayer, furnitureLayer, notesLayer } from "./editor/canvas/items.ts";
import { dimensionsLayer } from "./editor/canvas/plan.ts"; import { dimensionsLayer } from "./editor/canvas/plan.ts";
@@ -97,6 +100,7 @@ import { EditHistory } from "./editor/history.ts";
import { copyOfFurniture, copyOfOutdoorArea, deviceForFurniture, furnitureForDevice, newFloorOpening, newFreeWall, newFurniture, newOutdoorArea, offsetOnEdge, openingKindPatch, parkingSpotFor, placeInRoom, removeDevice, roomCentre, turnedBy } from "./editor/ops/items.ts"; import { copyOfFurniture, copyOfOutdoorArea, deviceForFurniture, furnitureForDevice, newFloorOpening, newFreeWall, newFurniture, newOutdoorArea, offsetOnEdge, openingKindPatch, parkingSpotFor, placeInRoom, removeDevice, roomCentre, turnedBy } from "./editor/ops/items.ts";
import { NO_CHANGE, NOTHING_TO_MOVE, nudge, type NudgeTarget } from "./editor/ops/nudge.ts"; import { NO_CHANGE, NOTHING_TO_MOVE, nudge, type NudgeTarget } from "./editor/ops/nudge.ts";
import { areaChoice, copyOfRoom, cornerMoved, evenCeilingLights, newRoom, rectangleAfter, removeCorner, removeRoom, type RectField } from "./editor/ops/rooms.ts"; import { areaChoice, copyOfRoom, cornerMoved, evenCeilingLights, newRoom, rectangleAfter, removeCorner, removeRoom, type RectField } from "./editor/ops/rooms.ts";
import { isSymcon } from "../entities/symcon-values.ts";
import { translate as moveScope, turnQuarterClockwise, type Scope } from "./editor/ops/transform.ts"; import { translate as moveScope, turnQuarterClockwise, type Scope } from "./editor/ops/transform.ts";
import { Selection, type ItemKind } from "./editor/selection.ts"; import { Selection, type ItemKind } from "./editor/selection.ts";
import { SideState } from "./editor/side-state.ts"; import { SideState } from "./editor/side-state.ts";
@@ -182,6 +186,7 @@ export class NfEditor extends LitElement {
hass: { attribute: false }, hass: { attribute: false },
building: { attribute: false }, building: { attribute: false },
narrow: { type: Boolean }, narrow: { type: Boolean },
roomLabels: { attribute: false },
packs: { attribute: false }, packs: { attribute: false },
loadCardEditor: { attribute: false }, loadCardEditor: { attribute: false },
_doc: { state: true }, _doc: { state: true },
@@ -221,6 +226,8 @@ export class NfEditor extends LitElement {
declare hass: HomeAssistant; declare hass: HomeAssistant;
declare building: Building; declare building: Building;
declare narrow: boolean; declare narrow: boolean;
/** Show room names in the 3D preview; the host remembers this view preference. */
declare roomLabels: boolean;
/** Imported furniture packs (from the panel's controller). */ /** Imported furniture packs (from the panel's controller). */
declare packs: FurniturePack[] | undefined; declare packs: FurniturePack[] | undefined;
/** Loads the card's settings dialog, for the card templates (set by the panel). */ /** Loads the card's settings dialog, for the card templates (set by the panel). */
@@ -317,6 +324,7 @@ export class NfEditor extends LitElement {
constructor() { constructor() {
super(); super();
this.narrow = false; this.narrow = false;
this.roomLabels = true;
this._floorId = null; this._floorId = null;
this._arcEdit = null; this._arcEdit = null;
this._routeDraft = null; this._routeDraft = null;
@@ -538,7 +546,7 @@ export class NfEditor extends LitElement {
case "set_area": case "set_area":
return this.change((doc) => { return this.change((doc) => {
const room = onFloor(doc)?.rooms.find((r) => r.id === fix.roomId); const room = onFloor(doc)?.rooms.find((r) => r.id === fix.roomId);
if (room) Object.assign(room, areaChoice(room, fix.areaId, this.hass?.areas ?? {})); if (room) Object.assign(room, areaChoice(room, fix.areaId, this.hass?.areas ?? {}, !isSymcon(this.hass)));
}); });
case "add_area_rooms": { case "add_area_rooms": {
const floor = onFloor(this._doc); const floor = onFloor(this._doc);
@@ -1043,7 +1051,7 @@ export class NfEditor extends LitElement {
</div>`} </div>`}
${this.render3dBar()} ${this.render3dBar()}
<nf-view3d <nf-view3d
.hass=${this.hass} .hass=${this.hass ? withSymconWeather(withCoverControls(this.hass, this._doc3d.floors), this._doc3d.settings) : undefined}
.building=${this._doc3d} .building=${this._doc3d}
.floorId=${this.houseTool ? null : this._floorId} .floorId=${this.houseTool ? null : this._floorId}
.roomId=${null} .roomId=${null}
@@ -1065,7 +1073,7 @@ export class NfEditor extends LitElement {
.selectedDevice=${this.sel.device} .selectedDevice=${this.sel.device}
.quality=${"auto"} .quality=${"auto"}
.floorThumbs=${false} .floorThumbs=${false}
.roomLabels=${true} .roomLabels=${this.roomLabels}
.floorStack=${this.houseTool ? "stacked" : "single"} .floorStack=${this.houseTool ? "stacked" : "single"}
.panelOpen=${false} .panelOpen=${false}
.alerts=${false} .alerts=${false}
@@ -1231,10 +1239,10 @@ export class NfEditor extends LitElement {
// ------------------------------------------------------------------ snapping // ------------------------------------------------------------------ snapping
/** The place in the plan a point lands on: corners and walls of other rooms, then the grid. `free` skips all of that. */ /** The place in the plan a point lands on: corners and walls of other rooms, then the grid. `free` skips all of that. */
private snap(p: Vec2, skip?: { roomId: string; index?: number }, free = false): Vec2 { private snap(p: Vec2, skip?: SnapOptions["skip"], free = false, outdoor = false): Vec2 {
this._guides = {}; this._guides = {};
if (free) return p; if (free) return p;
const snapped = snapToPlan(p, { rooms: this.floor?.rooms ?? [], grid: this._doc.settings.grid, reach: SNAP_PX / this._view.scale, skip }); const snapped = snapToPlan(p, { rooms: this.floor?.rooms ?? [], outdoor: outdoor ? this.floor?.outdoor : undefined, grid: this._doc.settings.grid, reach: SNAP_PX / this._view.scale, skip });
this._guides = snapped.guides; this._guides = snapped.guides;
return snapped.point; return snapped.point;
} }
@@ -1473,7 +1481,7 @@ export class NfEditor extends LitElement {
private pressDrawingTool(press: Press): Gesture | undefined { private pressDrawingTool(press: Press): Gesture | undefined {
const tool = this._tool; const tool = this._tool;
if (tool === "rect" || tool === "outdoor" || tool === "hole" || tool === "stairs") { if (tool === "rect" || tool === "outdoor" || tool === "hole" || tool === "stairs") {
const start = this.snap(press.world, undefined, press.fine); const start = this.snap(press.world, undefined, press.fine, tool === "outdoor");
return { kind: "rect", start, end: start, outdoor: tool === "outdoor", hole: tool === "hole", stairs: tool === "stairs" }; return { kind: "rect", start, end: start, outdoor: tool === "outdoor", hole: tool === "hole", stairs: tool === "stairs" };
} }
if (tool === "polygon" || tool === "measure") return { kind: "tap", startScreen: press.local, last: press.local, panning: false }; if (tool === "polygon" || tool === "measure") return { kind: "tap", startScreen: press.local, last: press.local, panning: false };
@@ -1605,7 +1613,7 @@ export class NfEditor extends LitElement {
const world = this.toWorld(...local); const world = this.toWorld(...local);
const drag = this.drag; const drag = this.drag;
if (!drag) { if (!drag) {
if (this._tool !== "select" && this._tool !== "furniture" && this.floor) this._cursor = this.snap(world, undefined, e.altKey); if (this._tool !== "select" && this._tool !== "furniture" && this.floor) this._cursor = this.snap(world, undefined, e.altKey, this._tool === "outdoor");
return; return;
} }
this.moveDrag(drag, { local, world, fine: e.altKey, straight: e.shiftKey }); this.moveDrag(drag, { local, world, fine: e.altKey, straight: e.shiftKey });
@@ -1653,7 +1661,7 @@ export class NfEditor extends LitElement {
drag.last = local; drag.last = local;
return; return;
case "rect": case "rect":
drag.end = this.snap(world, undefined, fine); drag.end = this.snap(world, undefined, fine, !!drag.outdoor);
this.requestUpdate(); this.requestUpdate();
return; return;
case "freewall": case "freewall":
@@ -1778,13 +1786,16 @@ export class NfEditor extends LitElement {
drag.moved = true; drag.moved = true;
const area = this.floorOf(drag)?.outdoor.find((o) => o.id === drag.id); const area = this.floorOf(drag)?.outdoor.find((o) => o.id === drag.id);
if (!area) return; if (!area) return;
const by = steppedDelta(drag.start, world, dragStep(grid, fine)); const initial = this.floorOf(drag)!;
const snapped = fine ? { by: steppedDelta(drag.start, world, dragStep(grid, true)), guides: {} } : snapOutdoorMove(area.points, [world[0] - drag.start[0], world[1] - drag.start[1]], { rooms: initial.rooms, outdoor: initial.outdoor, grid, reach: SNAP_PX / this._view.scale, skip: { outdoorId: drag.id } });
const { by } = snapped;
this._guides = snapped.guides;
this.live(drag, (_, floor) => void (floor.outdoor.find((o) => o.id === drag.id)!.points = area.points.map((p) => shifted(p, by)))); this.live(drag, (_, floor) => void (floor.outdoor.find((o) => o.id === drag.id)!.points = area.points.map((p) => shifted(p, by))));
return; return;
} }
case "outvertex": { case "outvertex": {
drag.moved = true; drag.moved = true;
const to = this.snap(world, undefined, fine); const to = this.snap(world, { outdoorId: drag.id }, fine, true);
const area = this.floorOf(drag)?.outdoor.find((o) => o.id === drag.id); const area = this.floorOf(drag)?.outdoor.find((o) => o.id === drag.id);
if (!area) return; if (!area) return;
this.live(drag, (_, floor) => { this.live(drag, (_, floor) => {
@@ -2629,7 +2640,7 @@ export class NfEditor extends LitElement {
private setArea(areaId: string): void { private setArea(areaId: string): void {
const room = this.room; const room = this.room;
if (room) this.updateRoom(areaChoice(room, areaId, this.hass?.areas ?? {})); if (room) this.updateRoom(areaChoice(room, areaId, this.hass?.areas ?? {}, !isSymcon(this.hass)));
} }
private setRect(field: RectField, value: number): void { private setRect(field: RectField, value: number): void {
@@ -3182,6 +3193,10 @@ export class NfEditor extends LitElement {
</button>`, </button>`,
)} )}
</div> </div>
<button class="nf-chip nf-room-names-toggle" aria-pressed=${this.roomLabels} title=${this.t("room_names_toggle_hint")} @click=${() => {
this.roomLabels = !this.roomLabels;
this.dispatchEvent(new CustomEvent("room-names-change", { detail: { value: this.roomLabels }, bubbles: true, composed: true }));
}}>${this.t("room_names_short")}</button>
<div class="nf-seg"> <div class="nf-seg">
<button ?disabled=${!this._canUndo} @click=${() => this.undo()} title="Ctrl+Z">${this.t("undo")}</button> <button ?disabled=${!this._canUndo} @click=${() => this.undo()} title="Ctrl+Z">${this.t("undo")}</button>
<button ?disabled=${!this._canRedo} @click=${() => this.redo()} title="Ctrl+Y">${this.t("redo")}</button> <button ?disabled=${!this._canRedo} @click=${() => this.redo()} title="Ctrl+Y">${this.t("redo")}</button>
@@ -3210,7 +3225,7 @@ export class NfEditor extends LitElement {
${this.planLayers(floor, walls?.walls ?? null)} ${this.planLayers(floor, walls?.walls ?? null)}
</svg> </svg>
${this.renderContext()} ${this.renderContext()}
<p class="nf-hint ${this._fixedHint ? "nf-hint-fixed" : ""}">${this._pick ? this.t("robot_cal_doing") : !floor ? this.t("hint_empty") : this._fixedHint ? this.t("fixed_drag_hint") : this.t(`hint_${this._tool}` as I18nKey)}</p> ${this._pick || this._fixedHint ? html`<p class="nf-hint ${this._fixedHint ? "nf-hint-fixed" : ""}">${this._pick ? this.t("robot_cal_doing") : this.t("fixed_drag_hint")}</p>` : html`<div class="nf-hint">${hint(!floor ? this.t("hint_empty") : this.t(`hint_${this._tool}` as I18nKey))}</div>`}
<button class="nf-keys-open" title=${this.t("keys_title")} aria-label=${this.t("keys_title")} @click=${() => (this._keys = true)}>?</button> <button class="nf-keys-open" title=${this.t("keys_title")} aria-label=${this.t("keys_title")} @click=${() => (this._keys = true)}>?</button>
${this.isAdmin ${this.isAdmin
? renderTour((k, vars) => this.t(k, vars), this._tour, (step) => { ? renderTour((k, vars) => this.t(k, vars), this._tour, (step) => {
+4 -3
View File
@@ -7,6 +7,7 @@ import { LitElement, html, nothing, type PropertyValues } from "lit";
import { uid, type BleFingerprint, type BleTag } from "../../model.ts"; import { uid, type BleFingerprint, type BleTag } from "../../model.ts";
import { fingerprintsOf, locate, RECORD_SECONDS, replaceRoom, signalLevel, type Reading } from "./ops/ble.ts"; import { fingerprintsOf, locate, RECORD_SECONDS, replaceRoom, signalLevel, type Reading } from "./ops/ble.ts";
import type { EditorHost } from "./host.ts"; import type { EditorHost } from "./host.ts";
import { hint } from "./fields.ts";
interface Scan { interface Scan {
address: string | null; address: string | null;
@@ -187,7 +188,7 @@ export class NfBleLocate extends LitElement {
<span class="nf-ble-track"><span class="nf-ble-fill" style="width:${Math.round(signalLevel(r.rssi) * 100)}%"></span></span> <span class="nf-ble-track"><span class="nf-ble-fill" style="width:${Math.round(signalLevel(r.rssi) * 100)}%"></span></span>
<span class="nf-ble-db">${Math.round(r.rssi)}</span> <span class="nf-ble-db">${Math.round(r.rssi)}</span>
</div>`)} </div>`)}
${entries.length === 1 ? html`<p class="nf-sub">${t("ble_one_scanner")}</p>` : nothing} ${entries.length === 1 ? hint(t("ble_one_scanner")) : nothing}
</div>`; </div>`;
} }
@@ -215,7 +216,7 @@ export class NfBleLocate extends LitElement {
</button> </button>
${this._room && count(this._room) ? html`<button class="nf-btn" ?disabled=${recording} @click=${() => this.update2(tag.id, (x) => (x.prints = x.prints.filter((p) => p.room !== this._room)))}>${t("ble_forget_room")}</button>` : nothing} ${this._room && count(this._room) ? html`<button class="nf-btn" ?disabled=${recording} @click=${() => this.update2(tag.id, (x) => (x.prints = x.prints.filter((p) => p.room !== this._room)))}>${t("ble_forget_room")}</button>` : nothing}
</div> </div>
<p class="nf-sub">${t("ble_learn_hint")}</p>`; ${hint(t("ble_learn_hint"))}`;
} }
protected render() { protected render() {
@@ -238,7 +239,7 @@ export class NfBleLocate extends LitElement {
<button class="nf-btn" title=${t("delete")} @click=${() => this.removeTag(x.id)}>✕</button> <button class="nf-btn" title=${t("delete")} @click=${() => this.removeTag(x.id)}>✕</button>
</div>`, </div>`,
)} )}
${tag ? html`<div class="nf-ble-learn">${this.learn(tag)}<p class="nf-sub">${t("ble_sensor_hint", { name: tag.name })}</p></div>` : nothing} ${tag ? html`<div class="nf-ble-learn">${this.learn(tag)}${hint(t("ble_sensor_hint", { name: tag.name }))}</div>` : nothing}
<div class="nf-form"> <div class="nf-form">
<label class="nf-field nf-wide">${t("ble_add")} <label class="nf-field nf-wide">${t("ble_add")}
<select .value=${this._pick} @change=${(e: Event) => (this._pick = (e.target as HTMLSelectElement).value)}> <select .value=${this._pick} @change=${(e: Event) => (this._pick = (e.target as HTMLSelectElement).value)}>
@@ -0,0 +1,21 @@
import { html, type TemplateResult } from "lit";
import { uid, type DeviceValueLink } from "../../model.ts";
import { valueSymbol } from "../../entities/device-values.ts";
import { entityOptions } from "./entities.ts";
import { entityField, hint, textField } from "./fields.ts";
import type { EditorHost } from "./host.ts";
export function renderDeviceValues(host: EditorHost, links: readonly DeviceValueLink[] = [], set: (next: DeviceValueLink[] | undefined) => void): TemplateResult {
const options = entityOptions(host.hass, (id) => !host.hass?.states[id]?.attributes.symcon_source_entity || links.some((l) => l.entity === id));
const patch = (id: string, change: Partial<DeviceValueLink>) => set(links.map((l) => l.id === id ? { ...l, ...change } : l));
return html`<div class="nf-value-links nf-wide">
<div class="nf-h3row"><h4>${host.t("device_values")}</h4><button class="nf-btn nf-value-add" title=${host.t("device_value_add")} aria-label=${host.t("device_value_add")} ?disabled=${!host.admin} @click=${() => set([...links, { id: uid("value"), entity: null }])}>+</button></div>
${links.map((l, i) => html`<div class="nf-form nf-value-link" data-value=${l.id}>
${entityField(host, `${host.t("device_value")} ${i + 1}`, l.entity, undefined, options, (v) => patch(l.id, { entity: v === "none" ? null : v }))}
${textField(host, host.t("device_value_icon"), l.icon ?? "", (icon) => patch(l.id, { icon: icon || null }), { maxlength: 16, placeholder: valueSymbol(l.entity ? host.hass?.states[l.entity] : undefined) })}
${textField(host, host.t("device_value_label"), l.label ?? "", (label) => patch(l.id, { label: label || null }), { maxlength: 60 })}
<button class="nf-link nf-value-remove nf-wide" ?disabled=${!host.admin} @click=${() => { const next = links.filter((v) => v.id !== l.id); set(next.length ? next : undefined); }}>× ${host.t("device_value_remove")}</button>
</div>`)}
${hint(host.t("device_values_hint"))}
</div>`;
}
@@ -1,7 +1,8 @@
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { test } from "node:test"; import { test } from "node:test";
import { entity, hassOf } from "../../entities/fixtures.ts"; import { entity, hassOf } from "../../entities/fixtures.ts";
import { entityOptions, isBinary, isNumeric, isPowerSensor, powerSensorOf } from "./entities.ts"; import { entityOptions, isBinary, isNumeric, isPowerSensor, nativeEntityOptions, powerSensorOf } from "./entities.ts";
import { symconControl } from "../../symcon-controls.ts";
test("numbers and switches are told apart by their domain", () => { test("numbers and switches are told apart by their domain", () => {
for (const id of ["sensor.a", "input_number.b", "number.c"]) assert.equal(isNumeric(id), true, id); for (const id of ["sensor.a", "input_number.b", "number.c"]) assert.equal(isNumeric(id), true, id);
@@ -48,3 +49,15 @@ test("an energy device's own power sensor wins over the found one, and 'none' me
assert.equal(powerSensorOf({ id: "m1" }, found), "sensor.found"); assert.equal(powerSensorOf({ id: "m1" }, found), "sensor.found");
assert.equal(powerSensorOf({ id: "m2" }, found), null); assert.equal(powerSensorOf({ id: "m2" }, found), null);
}); });
test("native manual choices never depend on a variable's name, path, unit, profile or inferred domain", () => {
const names = ["Garage_EG_Allgemein_Li_Schalten", "Treppenhaus EG schalten", "Rolladen", "Schloss", "Irgendwas"];
const states = names.map((name, n) => entity(`${n % 2 ? "switch" : "cover"}.${100 + n}`, "off", { symcon_id: 100 + n, symcon_variable_type: 0, symcon_value: false, symcon_profile: `~${name}`, friendly_name: name, symcon_path: `Haus / ${name} / Value` }));
const h = hassOf([...states, ...states.map((s) => symconControl(s, "light")!), entity("climate.200", "heat", { symcon_id: 200, symcon_variable_type: 2, unit_of_measurement: "unbekannt" }), entity("sensor.300", "Text", { symcon_id: 300, symcon_variable_type: 3 })], {}, { symconObjects: [] });
assert.deepEqual(nativeEntityOptions(h, { types: [0], role: "light" }, null).map((o) => o.id).sort(), names.map((_, n) => `light.${100 + n}`));
assert.equal(nativeEntityOptions(h, { types: [1, 2] }, null)[0].id, "climate.200");
assert.equal(nativeEntityOptions(h, {}, null).length, 7, "all native datatypes are available for a general value field, without alias duplicates");
assert.deepEqual(nativeEntityOptions(h, { unsupported: "Eine Variable ist kein Kalender." }, null), [], "native variables cannot impersonate an unsupported calendar capability");
assert.equal(nativeEntityOptions(h, { types: [0], role: "light" }, "cover.100").find((o) => o.id === "cover.100")?.sourceEntity, undefined, "saved native references remain stable");
assert.equal(nativeEntityOptions(h, { types: [0], excluded: (id) => id === "cover.100" ? "Bereits verknüpft" : undefined }, null).length, 4);
});
@@ -2,12 +2,15 @@
import { entityName } from "../../devices.ts"; import { entityName } from "../../devices.ts";
import type { HomeAssistant } from "../../types.ts"; import type { HomeAssistant } from "../../types.ts";
import { isSymconVariable } from "../../entities/symcon-values.ts";
import type { PickerRequirement } from "../picker-rejection.ts";
export interface EntityOption { export interface EntityOption {
id: string; id: string;
label: string; label: string;
/** A human-readable location, e.g. the path of an IP-Symcon variable in the object tree. */ /** A human-readable location, e.g. the path of an IP-Symcon variable in the object tree. */
detail?: string; detail?: string;
sourceEntity?: string;
} }
/** Entities that carry a number: sensors and the number helpers. */ /** Entities that carry a number: sensors and the number helpers. */
@@ -45,11 +48,26 @@ export function entityOptions(hass: HomeAssistant | undefined, accept: (id: stri
// In Symcon this is the complete object-tree path. The browser only uses the synthetic id internally; // In Symcon this is the complete object-tree path. The browser only uses the synthetic id internally;
// a person always picks a named variable from the tree path, never types an object id. // a person always picks a named variable from the tree path, never types an object id.
if (path) option.detail = `Objektbaum: ${path}`; if (path) option.detail = `Objektbaum: ${path}`;
if (typeof state?.attributes.symcon_source_entity === "string") option.sourceEntity = state.attributes.symcon_source_entity;
return option; return option;
}) })
.sort((a, b) => a.label.localeCompare(b.label)); .sort((a, b) => a.label.localeCompare(b.label));
} }
/** Native manual selection depends on the field's datatype, never on a guessed domain/name/profile. */
export function nativeEntityOptions(hass: HomeAssistant, requirement: PickerRequirement, value: string | null): EntityOption[] {
if (requirement.unsupported) return [];
return entityOptions(hass, (id) => isSymconVariable(hass, id, requirement.types) && !requirement.excluded?.(id)).map((option) => {
if (!requirement.role) return option;
const state = hass.states[option.id];
const role = `${requirement.role}.${state.attributes.symcon_id}`;
const current = value ? hass.states[value] : undefined;
// Keep saved native references stable; new choices use the field's explicit control role.
const id = value && (value === option.id || current?.attributes.symcon_source_entity === option.id) ? value : hass.states[role] ? role : option.id;
return id === option.id ? option : { ...option, id, sourceEntity: option.id };
});
}
/** The power sensor of an energy device: set by hand, or the one found on its Home Assistant device. */ /** The power sensor of an energy device: set by hand, or the one found on its Home Assistant device. */
export function powerSensorOf(item: { id: string; power?: string | null }, found: Map<string, { power: string | null }>): string | null { export function powerSensorOf(item: { id: string; power?: string | null }, found: Map<string, { power: string | null }>): string | null {
return item.power && item.power !== "none" ? item.power : (found.get(item.id)?.power ?? null); return item.power && item.power !== "none" ? item.power : (found.get(item.id)?.power ?? null);
+11 -6
View File
@@ -6,10 +6,12 @@ import { unsafeHTML } from "lit/directives/unsafe-html.js";
import { entityName } from "../../devices.ts"; import { entityName } from "../../devices.ts";
import type { I18nKey } from "../../i18n.ts"; import type { I18nKey } from "../../i18n.ts";
import { MARKER_SHOWS, type MarkerShow, type PinOffset } from "../../model.ts"; import { MARKER_SHOWS, type MarkerShow, type PinOffset } from "../../model.ts";
import type { EntityOption } from "./entities.ts"; import { nativeEntityOptions, type EntityOption } from "./entities.ts";
import type { EditorHost } from "./host.ts"; import type { EditorHost } from "./host.ts";
import type { PickerRequirement } from "../picker-rejection.ts";
import { pluginMdiIcon } from "../../plugins/registry.ts"; import { pluginMdiIcon } from "../../plugins/registry.ts";
import "../entity-picker.ts"; import "../entity-picker.ts";
import "../help-popup.ts";
const valueOf = (e: Event) => (e.target as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement).value; const valueOf = (e: Event) => (e.target as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement).value;
@@ -87,15 +89,18 @@ export function colorField(host: EditorHost, label: string, value: string | null
* A searchable picker for an entity. `auto` is what "automatic" would choose: a name, null for "nothing found", or undefined when * A searchable picker for an entity. `auto` is what "automatic" would choose: a name, null for "nothing found", or undefined when
* there is no automatic choice. The stored value is null for automatic, "none" for none, and the entity id otherwise. * there is no automatic choice. The stored value is null for automatic, "none" for none, and the entity id otherwise.
*/ */
export function entityField(host: EditorHost, label: string, value: string | null, auto: string | null | undefined, options: EntityOption[], onChange: (v: string | null) => void): TemplateResult { export function entityField(host: EditorHost, label: string, value: string | null, auto: string | null | undefined, options: EntityOption[], onChange: (v: string | null) => void, requirement: PickerRequirement = {}): TemplateResult {
const autoText = auto === undefined ? null : auto ? host.t("entity_auto", { name: entityName(host.hass, auto) }) : host.t("entity_auto_none"); const autoText = auto === undefined ? null : auto ? host.t("entity_auto", { name: entityName(host.hass, auto) }) : host.t("entity_auto_none");
// the fixed choices (automatic, none) come first, then the entities filtered as one types // the fixed choices (automatic, none) come first, then the entities filtered as one types
const fixed = [...(autoText !== null ? [{ id: "__auto", label: autoText }] : []), { id: "none", label: host.t("entity_none") }]; const fixed = [...(autoText !== null ? [{ id: "__auto", label: autoText }] : []), { id: "none", label: host.t("entity_none") }];
const current = value ?? (autoText !== null ? "__auto" : "none"); const current = value ?? (autoText !== null ? "__auto" : "none");
const choices = host.hass?.symconObjects !== undefined && !requirement.schedule ? nativeEntityOptions(host.hass, requirement, value) : options;
return html`<label class="nf-field nf-wide" return html`<label class="nf-field nf-wide"
>${label} >${label}
<nf-entity-picker <nf-entity-picker
.options=${options} .options=${choices}
.objectTree=${host.hass?.symconObjects}
.context=${{ ...requirement, label, states: host.hass?.states }}
.fixed=${fixed} .fixed=${fixed}
.value=${current} .value=${current}
.placeholder=${host.t("entity_search")} .placeholder=${host.t("entity_search")}
@@ -149,7 +154,7 @@ export function pinShiftField(host: EditorHost, value: PinOffset | null | undefi
<div class="nf-form"> <div class="nf-form">
${numberField(host, "↔ x", v.x ?? 0, set("x"), 0.05)} ${numberField(host, "↕ z", v.z ?? 0, set("z"), 0.05)} ${numberField(host, host.t("pin_shift_up"), v.y ?? 0, set("y"), 0.05)} ${numberField(host, "↔ x", v.x ?? 0, set("x"), 0.05)} ${numberField(host, "↕ z", v.z ?? 0, set("z"), 0.05)} ${numberField(host, host.t("pin_shift_up"), v.y ?? 0, set("y"), 0.05)}
${value ? html`<button class="nf-btn nf-field-btn" ?disabled=${!host.admin} @click=${() => onChange(null)}>${host.t("height_auto")}</button>` : nothing} ${value ? html`<button class="nf-btn nf-field-btn" ?disabled=${!host.admin} @click=${() => onChange(null)}>${host.t("height_auto")}</button>` : nothing}
<p class="nf-sub nf-wide">${host.t("pin_shift_hint")}</p> ${hint(host.t("pin_shift_hint"), "nf-wide")}
</div> </div>
</details>`; </details>`;
} }
@@ -157,8 +162,8 @@ export function pinShiftField(host: EditorHost, value: PinOffset | null | undefi
/** A row of buttons at the bottom of a form. */ /** A row of buttons at the bottom of a form. */
export const actions = (...buttons: (TemplateResult | typeof nothing)[]): TemplateResult => html`<div class="nf-actions">${buttons}</div>`; export const actions = (...buttons: (TemplateResult | typeof nothing)[]): TemplateResult => html`<div class="nf-actions">${buttons}</div>`;
/** A help line under a form. */ /** A compact information button that opens the explanation in a dialog. */
export const hint = (text: string, extraClass = ""): TemplateResult => html`<p class="nf-sub ${extraClass}">${text}</p>`; export const hint = (text: string, extraClass = ""): TemplateResult => html`<nf-help-popup class=${extraClass} .text=${text}></nf-help-popup>`;
/** A percentage between 10 and 150 for how strongly a lamp glows. 100 % is stored as "no value of its own". */ /** A percentage between 10 and 150 for how strongly a lamp glows. 100 % is stored as "no value of its own". */
export function glowField(host: EditorHost, value: number | null | undefined, onChange: (v: number | null) => void, o: { label?: I18nKey; hint?: I18nKey; lowest?: number } = {}): TemplateResult { export function glowField(host: EditorHost, value: number | null | undefined, onChange: (v: number | null) => void, o: { label?: I18nKey; hint?: I18nKey; lowest?: number } = {}): TemplateResult {
@@ -0,0 +1,31 @@
import { html, nothing, type TemplateResult } from "lit";
import { isChargingStation, type ChargingStationConfig, type ChargingDurationUnit, type ChargingTimeFormat } from "../../../charging-station.ts";
import type { Furniture } from "../../../model.ts";
import { entityOptions } from "../entities.ts";
import { entityField, hint, selectField } from "../fields.ts";
import type { EditorHost } from "../host.ts";
export function chargingStationFields(host: EditorHost, item: Furniture, update: (patch: Partial<Furniture>) => void): TemplateResult | typeof nothing {
if (!isChargingStation(item.type)) return nothing;
const t = host.t, c = item.charging ?? {}, options = entityOptions(host.hass, () => true);
const set = (patch: Partial<ChargingStationConfig>) => {
const charging = { ...c, ...patch };
update({ charging: Object.values(charging).some((v) => v != null) ? charging : null });
};
const timeFormats: [ChargingTimeFormat, string][] = [["auto", t("charging_auto")], ["value", t("charging_value")], ["seconds", t("charging_unix_seconds")], ["milliseconds", t("charging_unix_ms")]];
const units: [ChargingDurationUnit, string][] = [["auto", t("charging_auto")], ["value", t("charging_value")], ["seconds", t("charging_seconds")], ["minutes", t("charging_minutes")], ["hours", t("charging_hours")]];
const field = (key: "soc" | "start" | "end" | "duration" | "energy" | "lock", label: string, types: number[]) => entityField(host, label, c[key] ?? null, undefined, options, (v) => set({ [key]: v === "none" ? null : v }), { types });
return html`<div class="nf-form nf-links nf-charging-links">
<b class="nf-wide">${t("charging_data")}</b>
${hint(t("charging_hint"), "nf-wide")}
${field("soc", t("furn_soc"), [1, 2])}
${field("start", t("charging_start"), [1, 2, 3])}
${c.start && c.start !== "none" ? selectField(host, `${t("charging_start")} · ${t("charging_time_format")}`, c.start_format ?? "auto", timeFormats, (start_format) => set({ start_format }), { wide: true }) : nothing}
${field("end", t("charging_end"), [1, 2, 3])}
${c.end && c.end !== "none" ? selectField(host, `${t("charging_end")} · ${t("charging_time_format")}`, c.end_format ?? "auto", timeFormats, (end_format) => set({ end_format }), { wide: true }) : nothing}
${field("duration", t("charging_duration"), [1, 2, 3])}
${c.duration && c.duration !== "none" ? selectField(host, t("charging_duration_unit"), c.duration_unit ?? "auto", units, (duration_unit) => set({ duration_unit }), { wide: true }) : nothing}
${field("energy", t("charging_energy"), [1, 2])}
${field("lock", t("charging_lock"), [1])}
</div>`;
}
@@ -2,7 +2,7 @@
// fields or the furniture; only what depends on the compass follows (the sun's light, wind, the compass labels of roof faces). // fields or the furniture; only what depends on the compass follows (the sun's light, wind, the compass labels of roof faces).
import { html, svg, type TemplateResult } from "lit"; import { html, svg, type TemplateResult } from "lit";
import { numberField } from "../fields.ts"; import { hint, numberField } from "../fields.ts";
import type { EditorHost } from "../host.ts"; import type { EditorHost } from "../host.ts";
import { turnedNorth } from "../ops/settings.ts"; import { turnedNorth } from "../ops/settings.ts";
@@ -29,7 +29,7 @@ export function renderCompass(host: EditorHost, north: number, set: (north: numb
<button class="nf-btn" ?disabled=${!host.admin} @click=${turn(-90)}>↺ 90°</button> <button class="nf-btn" ?disabled=${!host.admin} @click=${turn(-90)}>↺ 90°</button>
<button class="nf-btn" ?disabled=${!host.admin} @click=${turn(90)}>↻ 90°</button> <button class="nf-btn" ?disabled=${!host.admin} @click=${turn(90)}>↻ 90°</button>
</div> </div>
<span class="nf-sub">${t("compass_hint")}</span> ${hint(t("compass_hint"))}
</div> </div>
</div>`; </div>`;
} }
@@ -1,12 +1,14 @@
// The device list of a room: the entities of its area to place, the rows with their pins, and the room's climate sensors. // The device list of a room: the entities of its area to place, the rows with their pins, and the room's climate sensors.
import { html, nothing, type TemplateResult } from "lit"; import { html, nothing, type TemplateResult } from "lit";
import { CLIMATE_CLASSES, entityAreaId, entityKind, entityName, groupByDevice, isPlaceable, isRoomClimateSensor, kindOf, otherAreaEntities, roomClimateSensors, unassignedEntities, type ClimateKey, roomEntities } from "../../../devices.ts"; import { entityAreaId, entityKind, entityName, groupByDevice, isClimateValueSensor, isPlaceable, isRoomClimateSensor, kindOf, otherAreaEntities, roomClimateSensors, unassignedEntities, type ClimateKey, roomEntities } from "../../../devices.ts";
import { iconPath } from "../../../icons.ts"; import { iconPath } from "../../../icons.ts";
import { pointInPolygon, type Room } from "../../../model.ts"; import { pointInPolygon, type Room } from "../../../model.ts";
import { entityOptions, isNumeric } from "../entities.ts"; import { entityOptions } from "../entities.ts";
import { deviceIcon, entityField, hint } from "../fields.ts"; import { checkField, deviceIcon, entityField, hint } from "../fields.ts";
import type { EditorHost } from "../host.ts"; import type { EditorHost } from "../host.ts";
import { isSymcon } from "../../../entities/symcon-values.ts";
import { renderSymconRoomHvac } from "../symcon-fields.ts";
import { matchesQuery, placedElsewhere, placedInRoom, rankedBy, takeFirst, withToggled } from "../ops/device-list.ts"; import { matchesQuery, placedElsewhere, placedInRoom, rankedBy, takeFirst, withToggled } from "../ops/device-list.ts";
import type { SideState } from "../side-state.ts"; import type { SideState } from "../side-state.ts";
@@ -126,29 +128,31 @@ export function renderDeviceList(host: EditorHost, state: SideState, room: Room,
export function renderRoomClimate(host: EditorHost, room: Room, patch: (patch: Partial<Room>) => void): TemplateResult | typeof nothing { export function renderRoomClimate(host: EditorHost, room: Room, patch: (patch: Partial<Room>) => void): TemplateResult | typeof nothing {
const { hass } = host; const { hass } = host;
if (!hass) return nothing; if (!hass) return nothing;
const chosen = !!room.climate && Object.values(room.climate).some((x) => x != null); const chosen = !!room.floor_heating || !!room.hvac || (!!room.climate && Object.values(room.climate).some((x) => x != null));
const change = (key: ClimateKey, value: string | string[] | null) => { const change = (key: ClimateKey, value: string | string[] | null) => {
const next = { ...(room.climate ?? {}), [key]: value }; const next = { ...(room.climate ?? {}), [key]: value };
patch({ climate: Object.values(next).every((x) => x == null) ? null : next }); patch({ climate: Object.values(next).every((x) => x == null) ? null : next });
}; };
const field = (key: ClimateKey, label: string) => { const field = (key: ClimateKey, label: string) => {
const found = roomClimateSensors(hass, host.floor ?? null, { ...room, climate: null }, key); const found = roomClimateSensors(hass, host.floor ?? null, { ...room, climate: null }, key);
const wanted = entityOptions(hass, (id) => isNumeric(id) && hass.states[id]?.attributes.device_class === CLIMATE_CLASSES[key]); const picked = [room.climate?.[key] ?? null].flat();
const wanted = entityOptions(hass, (id) => isClimateValueSensor(hass, id, key, true) && (!hass.states[id]?.attributes.symcon_source_entity || picked.includes(id)));
// the room's own sensors first, then the others; device temperatures (a printer, a heat pump) come last // the room's own sensors first, then the others; device temperatures (a printer, a heat pump) come last
const options = rankedBy(wanted, (id) => (entityAreaId(hass, id) === room.area_id ? 0 : 1) + (isRoomClimateSensor(hass, id) ? 0 : 2)); const options = rankedBy(wanted, (id) => (entityAreaId(hass, id) === room.area_id ? 0 : 1) + (isRoomClimateSensor(hass, id) ? 0 : 2));
const picked = [room.climate?.[key] ?? null].flat();
// several sensors are averaged: once one is chosen, another can be added; "none" in a slot drops it // several sensors are averaged: once one is chosen, another can be added; "none" in a slot drops it
const save = (list: (string | null)[]) => { const save = (list: (string | null)[]) => {
const ids = list.filter((id): id is string => !!id && id !== "none"); const ids = list.filter((id): id is string => !!id && id !== "none");
change(key, list[0] === "none" ? "none" : ids.length > 1 ? ids : (ids[0] ?? null)); change(key, ids.length > 1 ? ids : (ids[0] ?? (list.includes("none") ? "none" : null)));
}; };
const real = picked[0] && picked[0] !== "none"; const real = picked[0] && picked[0] !== "none";
const slots = real ? [...picked, null] : picked; const slots = real ? [...picked, null] : picked;
return slots.map((id, i) => entityField(host, i ? host.t("climate_more") : label, id, i ? undefined : (found[0] ?? null), options, (v) => save(slots.map((x, j) => (j === i ? v : x))))); return slots.map((id, i) => entityField(host, i ? host.t("climate_more") : label, id, i ? undefined : (found[0] ?? null), options, (v) => save(slots.map((x, j) => (j === i ? v : x))), { types: [1, 2] }));
}; };
return html`<details class="nf-points" ?open=${chosen}> return html`<details class="nf-points" ?open=${chosen || !!room.climate_card}>
<summary>${host.t("climate")}</summary> <summary>${host.t("climate")}</summary>
<div class="nf-form">${field("temperature", host.t("climate_temperature"))} ${field("humidity", host.t("climate_humidity"))} ${field("co2", host.t("climate_co2"))}</div> <div class="nf-form">${field("temperature", host.t("climate_temperature"))} ${field("humidity", host.t("climate_humidity"))} ${field("co2", host.t("climate_co2"))} ${field("illuminance", host.t("climate_illuminance"))}${isSymcon(hass) ? renderSymconRoomHvac(host, room, patch) : nothing}</div>
${checkField(host, host.t("climate_card"), !!room.climate_card, (on) => patch({ climate_card: on || undefined }))}
${hint(host.t("climate_card_hint"))}
${hint(host.t("climate_hint"))} ${hint(host.t("climate_hint"))}
</details>`; </details>`;
} }
+12 -1
View File
@@ -7,7 +7,10 @@ import { iconPath } from "../../../icons.ts";
import { ceilingAt, FURNITURE_TYPES, isLamp, type LampMount, type Placement } from "../../../model.ts"; import { ceilingAt, FURNITURE_TYPES, isLamp, type LampMount, type Placement } from "../../../model.ts";
import { packItemLabel, packLabel } from "../../../furniture-names.ts"; import { packItemLabel, packLabel } from "../../../furniture-names.ts";
import { isClimateFurniture, isElectric, isPackType, packType, type FurniturePack } from "../../../packs.ts"; import { isClimateFurniture, isElectric, isPackType, packType, type FurniturePack } from "../../../packs.ts";
import { checkField, deviceIcon, glowField, iconField, markerField, pinShiftField, numberField, selectField, textField } from "../fields.ts"; import { checkField, deviceIcon, entityField, glowField, hint, iconField, markerField, pinShiftField, numberField, selectField, textField } from "../fields.ts";
import { entityOptions } from "../entities.ts";
import { isPositionVariable } from "../../../entities/position-value.ts";
import { renderDeviceValues } from "../device-values.ts";
import type { EditorHost } from "../host.ts"; import type { EditorHost } from "../host.ts";
import { lightEffectFields } from "../light-effect-fields.ts"; import { lightEffectFields } from "../light-effect-fields.ts";
import { pluginDeviceSettings, pluginText, settingsWithDefaults } from "../../../plugins/registry.ts"; import { pluginDeviceSettings, pluginText, settingsWithDefaults } from "../../../plugins/registry.ts";
@@ -96,6 +99,13 @@ export function renderDeviceForm(host: EditorHost, placed: Placement, actions: D
${entityName(host.hass, placed.entity_id)} ${entityName(host.hass, placed.entity_id)}
</p> </p>
<div class="nf-form"> <div class="nf-form">
${kind === "cover" ? entityField(host, t("cover_tilt_entity"), placed.cover_tilt ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("cover.")), (v) => set({ cover_tilt: v && v !== "none" ? v : null }), { types: [1, 2], role: "cover" }) : nothing}
${kind === "cover" ? html`
${checkField(host, t("cover_direction_invert"), !!placed.cover_inverted, (on) => set({ cover_inverted: on || undefined }))}
${checkField(host, t("cover_tilt_direction_invert"), !!placed.cover_tilt_inverted, (on) => set({ cover_tilt_inverted: on || undefined }))}
${entityField(host, t("cover_position_entity"), placed.position ?? null, undefined, entityOptions(host.hass, (id) => isPositionVariable(host.hass, id)), (v) => set({ position: v && v !== "none" ? v : null }), { types: [1, 2] })}
${placed.position ? checkField(host, t("cover_position_invert"), !!placed.position_inverted, (on) => set({ position_inverted: on || undefined })) : nothing}
${hint(t("cover_direction_hint"), "nf-wide")}` : nothing}
${light ? html`${selectField(host, t("lamp_mount"), mount, lampMounts, mountChange, { wide: true })}${glowField(host, placed.glow_scale, (v) => set({ glow_scale: v }))}` : nothing} ${light ? html`${selectField(host, t("lamp_mount"), mount, lampMounts, mountChange, { wide: true })}${glowField(host, placed.glow_scale, (v) => set({ glow_scale: v }))}` : nothing}
${light ? lightEffectFields(host, placed, host.hass?.states[placed.entity_id]?.attributes.effect_list, set) : nothing} ${light ? lightEffectFields(host, placed, host.hass?.states[placed.entity_id]?.attributes.effect_list, set) : nothing}
${placed.entity_id.startsWith("media_player.") ? glowField(host, placed.sound_rings, (v) => set({ sound_rings: v }), { label: "sound_rings", hint: "sound_rings_hint", lowest: 0 }) : nothing} ${placed.entity_id.startsWith("media_player.") ? glowField(host, placed.sound_rings, (v) => set({ sound_rings: v }), { label: "sound_rings", hint: "sound_rings_hint", lowest: 0 }) : nothing}
@@ -111,6 +121,7 @@ export function renderDeviceForm(host: EditorHost, placed: Placement, actions: D
${placed.name ? checkField(host, t("show_name"), !!placed.show_name, (on) => set({ show_name: on || undefined })) : nothing} ${placed.name ? checkField(host, t("show_name"), !!placed.show_name, (on) => set({ show_name: on || undefined })) : nothing}
${iconField(host, placed.icon, (v) => set({ icon: v }))} ${iconField(host, placed.icon, (v) => set({ icon: v }))}
${pluginFields(host, placed, set)} ${pluginFields(host, placed, set)}
${renderDeviceValues(host, placed.values, (values) => set({ values }))}
</div> </div>
${host.admin ${host.admin
? html`<div class="nf-actions"> ? html`<div class="nf-actions">
@@ -96,8 +96,8 @@ export function renderEdgeHeights(host: EditorHost, room: Room, actions: EdgeAct
</div>`; </div>`;
}); });
}; };
return html`<div class="nf-edge-box"> return html`<details class="nf-edge-box">
<h4>${t("wall_heights")}</h4> <summary>${t("wall_heights")}</summary>
${room.points.flatMap((_, edge) => rowsOf(edge))} ${hint(t("room_wall_hint"))} ${room.points.flatMap((_, edge) => rowsOf(edge))} ${hint(t("room_wall_hint"))}
</div>`; </details>`;
} }
+22 -3
View File
@@ -1,7 +1,10 @@
// The side panel's floor part: the floors of the house as chips, and the form of the selected floor. // The side panel's floor part: the floors of the house as chips, and the form of the selected floor.
import { html, nothing, type TemplateResult } from "lit"; import { html, nothing, type TemplateResult } from "lit";
import { DEFAULT_PAINT_OUTSIDE, type Floor } from "../../../model.ts"; import { DEFAULT_PAINT_OUTSIDE, UTILITY_KINDS, type Floor } from "../../../model.ts";
import { isSymcon, isSymconVariable } from "../../../entities/symcon-values.ts";
import { floorMeter, floorUtilityReadings, UTILITY_ICONS, UTILITY_LABELS } from "../../../utilities.ts";
import "../../utility-report.ts";
import type { HassFloor } from "../../../types.ts"; import type { HassFloor } from "../../../types.ts";
import { checkField, colorField, entityField, hint, numberField, selectField, textField } from "../fields.ts"; import { checkField, colorField, entityField, hint, numberField, selectField, textField } from "../fields.ts";
import { entityOptions } from "../entities.ts"; import { entityOptions } from "../entities.ts";
@@ -93,6 +96,23 @@ function copyChoices(host: EditorHost, state: SideState, floorActions: FloorActi
</div>`; </div>`;
} }
function utilityMeters(host: EditorHost, floor: Floor): TemplateResult {
const options = entityOptions(host.hass, (id) => isSymconVariable(host.hass, id, [1, 2]));
return html`<details class="nf-wide nf-utility-meters"><summary>Stockwerkszähler</summary><div class="nf-form">
${hint("Ohne eigenen Stockwerkszähler werden die Bereichszähler der Räume summiert. In der verknüpften Bereichskategorie werden Kategorien oder Dummy-Module namens Elektro/Strom, Wasser, Gas, Heizen und Kühlen durchsucht. Darin werden Leistung bzw. Durchfluss und Verbrauch bzw. Energie erkannt. Ein eigener Stockwerkszähler ersetzt nur die zugehörige Raumsumme. × stellt die automatische Raumsumme wieder her. Einheiten und Verbrauchszeiträume werden getrennt ausgewertet.", "nf-wide")}
${UTILITY_KINDS.map((kind) => html`<b class="nf-wide">${UTILITY_ICONS[kind]} ${UTILITY_LABELS[kind]}</b>${(["power", "energy"] as const).map((metric) => html`<label class="nf-field nf-wide">${metric === "power" ? "Leistung / Durchfluss" : "Energie / Verbrauch"}
<nf-entity-picker .options=${options} .objectTree=${host.hass?.symconObjects} .fixed=${[{ id: "__auto", label: "Raumsumme (automatisch)" }]} .value=${floorMeter(host.hass!, floor, kind, metric) ?? "__auto"} ?disabled=${!host.admin}
.context=${{ label: `${UTILITY_LABELS[kind]}: ${metric === "power" ? "Leistung / Durchfluss" : "Energie / Verbrauch"}`, types: [1, 2], states: host.hass?.states }}
@change=${(e: CustomEvent<{ value: string | null }>) => {
e.stopPropagation();
const value = e.detail.value;
host.change((_, f) => { f.utility_meters = { ...f.utility_meters, [kind]: { ...f.utility_meters?.[kind], [metric]: value && value !== "__auto" && value !== "none" ? value : null } }; });
}}></nf-entity-picker>
</label>`)}`)}
<nf-utility-report class="nf-wide" .hass=${host.hass} .readings=${floorUtilityReadings(host.hass!, floor, host.doc.floors.flatMap((f) => f.rooms))}></nf-utility-report>
</div></details>`;
}
function floorForm(host: EditorHost, state: SideState, floorActions: FloorActions, floor: Floor): TemplateResult { function floorForm(host: EditorHost, state: SideState, floorActions: FloorActions, floor: Floor): TemplateResult {
const t = host.t; const t = host.t;
const update = (patch: Partial<Floor>) => host.change((_, f) => Object.assign(f, patch)); const update = (patch: Partial<Floor>) => host.change((_, f) => Object.assign(f, patch));
@@ -106,8 +126,7 @@ function floorForm(host: EditorHost, state: SideState, floorActions: FloorAction
${numberField(host, t("height"), floor.height, (v) => update({ height: Math.max(1, v) }), 0.05, 1)} ${numberField(host, t("height"), floor.height, (v) => update({ height: Math.max(1, v) }), 0.05, 1)}
${Object.keys(host.hass?.floors ?? {}).length > 0 ? selectField(host, t("ha_floor"), floor.ha_floor ?? "", haChoices, (v) => update({ ha_floor: v || null }), { wide: true }) : nothing} ${Object.keys(host.hass?.floors ?? {}).length > 0 ? selectField(host, t("ha_floor"), floor.ha_floor ?? "", haChoices, (v) => update({ ha_floor: v || null }), { wide: true }) : nothing}
${checkField(host, t("floor_layer"), !!floor.layer, (on) => update({ layer: on || undefined }), { title: t("floor_layer_hint") })} ${checkField(host, t("floor_layer"), !!floor.layer, (on) => update({ layer: on || undefined }), { title: t("floor_layer_hint") })}
${entityField(host, t("floor_power"), floor.power_entity ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("sensor.") && host.hass?.states[id]?.attributes.device_class === "power"), (v) => update({ power_entity: v && v !== "none" ? v : null }))} ${isSymcon(host.hass) ? utilityMeters(host, floor) : html`${entityField(host, t("floor_power"), floor.power_entity ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("sensor.") && host.hass?.states[id]?.attributes.device_class === "power"), (v) => update({ power_entity: v && v !== "none" ? v : null }))}${floor.power_entity ? hint(t("floor_power_hint"), "nf-wide") : nothing}`}
${floor.power_entity ? hint(t("floor_power_hint"), "nf-wide") : nothing}
${floor.layer ? nothing : colorField(host, t("wall_paint_floor"), floor.wall_paint_outside, host.doc.settings.wall_paint_outside ?? DEFAULT_PAINT_OUTSIDE, (v) => update({ wall_paint_outside: v }))} ${floor.layer ? nothing : colorField(host, t("wall_paint_floor"), floor.wall_paint_outside, host.doc.settings.wall_paint_outside ?? DEFAULT_PAINT_OUTSIDE, (v) => update({ wall_paint_outside: v }))}
${areaRow(host, floor, floorActions)} ${areaRow(host, floor, floorActions)}
${host.admin && lacking.length > 0 ${host.admin && lacking.length > 0
@@ -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>`;
}
@@ -11,6 +11,10 @@ import { checkField, entityField, glowField, hint, iconField, markerField, pinSh
import type { EditorHost } from "../host.ts"; import type { EditorHost } from "../host.ts";
import { lightEffectFields } from "../light-effect-fields.ts"; import { lightEffectFields } from "../light-effect-fields.ts";
import { lightEffectSource } from "../../../light-effects.ts"; import { lightEffectSource } from "../../../light-effects.ts";
import { renderDeviceValues } from "../device-values.ts";
import { isSymcon, isSymconVariable } from "../../../entities/symcon-values.ts";
import { isChargingStation } from "../../../charging-station.ts";
import { chargingStationFields } from "./charging-station.ts";
import { calibrationFrom, calibrationFromRooms, gridPlaces, gridRooms, mapCamera, nudgeCalibration, type CalibrationNudge, type Place } from "../../../live/vacuum-map.ts"; import { calibrationFrom, calibrationFromRooms, gridPlaces, gridRooms, mapCamera, nudgeCalibration, type CalibrationNudge, type Place } from "../../../live/vacuum-map.ts";
/** What the forms of a piece of furniture make the editor do. */ /** What the forms of a piece of furniture make the editor do. */
@@ -193,7 +197,7 @@ export function careLink(host: EditorHost, item: Furniture, kind: "bin" | "mail"
export function coverLink(host: EditorHost, item: Furniture, actions: FurnitureLinkActions): TemplateResult { export function coverLink(host: EditorHost, item: Furniture, actions: FurnitureLinkActions): TemplateResult {
const t = host.t; const t = host.t;
return html`<div class="nf-form nf-links"> return html`<div class="nf-form nf-links">
${entityField(host, t("furn_cover_entity"), item.cover_entity ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("cover.")), (v) => actions.update({ cover_entity: noneAsNull(v) }))} ${entityField(host, t("furn_cover_entity"), item.cover_entity ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("cover.")), (v) => actions.update({ cover_entity: noneAsNull(v) }), { types: [1, 2], role: "cover" })}
${checkField(host, t("furn_cover_inverted"), !!item.cover_inverted, (on) => actions.update({ cover_inverted: on || undefined }), { title: t("furn_cover_inverted_hint") })} ${checkField(host, t("furn_cover_inverted"), !!item.cover_inverted, (on) => actions.update({ cover_inverted: on || undefined }), { title: t("furn_cover_inverted_hint") })}
${hint(t("furn_cover_hint"), "nf-wide")} ${hint(t("furn_cover_hint"), "nf-wide")}
</div>`; </div>`;
@@ -211,7 +215,7 @@ export function gangLinks(host: EditorHost, item: Furniture, gangs: number, acti
actions.update({ gang_entities: next }); actions.update({ gang_entities: next });
}; };
return html`<div class="nf-form nf-links"> return html`<div class="nf-form nf-links">
${Array.from({ length: gangs }, (_, i) => entityField(host, gangs === 1 ? t(socket ? "gang_socket_one" : "gang_switch_one") : t(socket ? "gang_socket" : "gang_switch", { n: i + 1 }), current[i] ?? null, undefined, options, set(i)))} ${Array.from({ length: gangs }, (_, i) => entityField(host, gangs === 1 ? t(socket ? "gang_socket_one" : "gang_switch_one") : t(socket ? "gang_socket" : "gang_switch", { n: i + 1 }), current[i] ?? null, undefined, options, set(i), { types: [0, 1, 2], role: "light" }))}
${hint(t(socket ? "gang_socket_hint" : "gang_switch_hint"), "nf-wide")} ${hint(t(socket ? "gang_socket_hint" : "gang_switch_hint"), "nf-wide")}
</div>`; </div>`;
} }
@@ -225,8 +229,8 @@ function coolingLinks(host: EditorHost, item: Furniture, actions: FurnitureLinkA
return id.startsWith("sensor.") && (a?.device_class === "temperature" || a?.unit_of_measurement === "°C" || a?.unit_of_measurement === "°F"); return id.startsWith("sensor.") && (a?.device_class === "temperature" || a?.unit_of_measurement === "°C" || a?.unit_of_measurement === "°F");
}); });
return linkBlock( return linkBlock(
entityField(host, t("fridge_temp"), item.temp_entity ?? null, undefined, temps, (v) => actions.update({ temp_entity: noneAsNull(v) })), entityField(host, t("fridge_temp"), item.temp_entity ?? null, undefined, temps, (v) => actions.update({ temp_entity: noneAsNull(v) }), { types: [1, 2] }),
entityField(host, t("freezer_temp"), item.temp_entity2 ?? null, undefined, temps, (v) => actions.update({ temp_entity2: noneAsNull(v) })), entityField(host, t("freezer_temp"), item.temp_entity2 ?? null, undefined, temps, (v) => actions.update({ temp_entity2: noneAsNull(v) }), { types: [1, 2] }),
hint(t("fridge_temp_hint"), "nf-wide"), hint(t("fridge_temp_hint"), "nf-wide"),
); );
} }
@@ -239,7 +243,7 @@ function deviceTempLink(host: EditorHost, item: Furniture, actions: FurnitureLin
return id.startsWith("sensor.") && (a?.device_class === "temperature" || a?.unit_of_measurement === "°C" || a?.unit_of_measurement === "°F"); return id.startsWith("sensor.") && (a?.device_class === "temperature" || a?.unit_of_measurement === "°C" || a?.unit_of_measurement === "°F");
}); });
return linkBlock( return linkBlock(
entityField(host, t("device_temp"), item.temp_entity ?? null, undefined, temps, (v) => actions.update({ temp_entity: noneAsNull(v) })), entityField(host, t("device_temp"), item.temp_entity ?? null, undefined, temps, (v) => actions.update({ temp_entity: noneAsNull(v) }), { types: [1, 2] }),
hint(t("device_temp_hint"), "nf-wide"), hint(t("device_temp_hint"), "nf-wide"),
); );
} }
@@ -256,7 +260,7 @@ function extraLightFields(host: EditorHost, item: Furniture, actions: FurnitureL
actions.update({ extra_lights: next.filter(Boolean).length ? next.filter(Boolean) : undefined }); actions.update({ extra_lights: next.filter(Boolean).length ? next.filter(Boolean) : undefined });
}; };
const rows = Math.min(4, current.length + 1); const rows = Math.min(4, current.length + 1);
return html`${Array.from({ length: rows }, (_, i) => entityField(host, t("lamp_extra_light", { n: i + 2 }), current[i] ?? null, undefined, options, set(i)))}${hint(t("lamp_extra_hint"), "nf-wide")}`; return html`${Array.from({ length: rows }, (_, i) => entityField(host, t("lamp_extra_light", { n: i + 2 }), current[i] ?? null, undefined, options, set(i), { types: [0, 1, 2], role: "light" }))}${hint(t("lamp_extra_hint"), "nf-wide")}`;
} }
export function furnitureLinks(host: EditorHost, item: Furniture, actions: FurnitureLinkActions): TemplateResult | typeof nothing { export function furnitureLinks(host: EditorHost, item: Furniture, actions: FurnitureLinkActions): TemplateResult | typeof nothing {
@@ -265,53 +269,58 @@ export function furnitureLinks(host: EditorHost, item: Furniture, actions: Furni
const t = host.t; const t = host.t;
const lamp = isLamp(item.type); const lamp = isLamp(item.type);
const main = mainEntity(item, hass); const main = mainEntity(item, hass);
const power = entityOptions(hass, (id) => isPowerSensor(hass, id)); const power = entityOptions(hass, (id) => isSymcon(hass) ? isSymconVariable(hass, id, [1, 2]) : isPowerSensor(hass, id));
const set = (key: keyof Furniture) => (v: string | null) => actions.update({ [key]: noneAsNull(v) }); const set = (key: keyof Furniture) => (v: string | null) => actions.update({ [key]: noneAsNull(v) });
const kindOptions = (accept: (id: string) => boolean) => entityOptions(hass, accept); const kindOptions = (accept: (id: string) => boolean) => entityOptions(hass, accept);
const strings = (host.doc.settings.roof.strings ?? []).filter((s) => s.inverter === item.id).map((s) => s.name); const strings = (host.doc.settings.roof.strings ?? []).filter((s) => s.inverter === item.id).map((s) => s.name);
const hasLink = !!item.entity && item.entity !== "none"; const hasLink = !!item.entity && item.entity !== "none";
const autoPower = automaticLink(host, item, "power");
const powerRef = item.power === "none" ? null : item.power || autoPower;
const doors = item.type === "fridge_smart" ? kindOptions((id) => id.startsWith("binary_sensor.")) : []; const doors = item.type === "fridge_smart" ? kindOptions((id) => id.startsWith("binary_sensor.")) : [];
const hintKey: I18nKey = item.type === "ceiling_fan" ? "fan_hint" : lamp ? (item.type === "lamp_pendant" ? "lamp_hint_pendant" : "lamp_hint") : isMediaFurniture(item.type) ? "furn_links_hint_tv" : item.type === "robot_vacuum" ? "robot_hint" : "furn_links_hint"; const hintKey: I18nKey = item.type === "ceiling_fan" ? "fan_hint" : lamp ? (item.type === "lamp_pendant" ? "lamp_hint_pendant" : "lamp_hint") : isMediaFurniture(item.type) ? "furn_links_hint_tv" : item.type === "robot_vacuum" ? "robot_hint" : "furn_links_hint";
return html`${linkBlock( return html`${linkBlock(
item.type === "grid_point" ? hint(t("grid_point_hint"), "nf-wide") : entityField(host, t(main.label), item.entity ?? null, automaticLink(host, item, "entity"), kindOptions(main.accept), (v) => actions.update({ entity: v })), item.type === "grid_point" ? hint(t("grid_point_hint"), "nf-wide") : entityField(host, t(main.label), item.entity ?? null, automaticLink(host, item, "entity"), kindOptions(main.accept), (v) => actions.update({ entity: v }), lamp ? { types: [0, 1, 2], role: "light" } : {}),
item.type === "ceiling_fan" item.type === "ceiling_fan"
? entityField(host, t("furn_fan_entity"), item.fan_entity ?? null, automaticLink(host, item, "fan"), kindOptions((id) => id.startsWith("fan.")), (v) => actions.update({ fan_entity: v })) ? entityField(host, t("furn_fan_entity"), item.fan_entity ?? null, automaticLink(host, item, "fan"), kindOptions((id) => id.startsWith("fan.")), (v) => actions.update({ fan_entity: v }), { types: [0, 1, 2] })
: nothing, : nothing,
!lamp && !(ENERGY_DEVICES as readonly string[]).includes(item.type) && !hasScreen(item.type) ? stateLinks(host, item, actions) : nothing, !lamp && !(ENERGY_DEVICES as readonly string[]).includes(item.type) && !hasScreen(item.type) ? stateLinks(host, item, actions) : nothing,
lamp && hasLink lamp && hasLink
? html`${entityField(host, t("furn_color_entity"), item.color_entity ?? null, undefined, kindOptions((id) => id.startsWith("light.") && id !== item.entity), set("color_entity"))}${hint(t("furn_color_entity_hint"), "nf-wide")}` ? html`${entityField(host, t("furn_color_entity"), item.color_entity ?? null, undefined, kindOptions((id) => id.startsWith("light.") && id !== item.entity), set("color_entity"), { types: [0, 1, 2], role: "light" })}${hint(t("furn_color_entity_hint"), "nf-wide")}`
: nothing, : nothing,
lamp && hasLink ? extraLightFields(host, item, actions) : nothing, lamp && hasLink ? extraLightFields(host, item, actions) : nothing,
lamp ? glowField(host, item.glow_scale, (v) => actions.update({ glow_scale: v })) : nothing, lamp ? glowField(host, item.glow_scale, (v) => actions.update({ glow_scale: v })) : nothing,
lamp ? lightEffectFields(host, item, lightEffectSource(hass, item, item.entity && item.entity !== "none" ? item.entity : automaticLink(host, item, "entity"))?.attributes.effect_list, actions.update) : nothing, lamp ? lightEffectFields(host, item, lightEffectSource(hass, item, item.entity && item.entity !== "none" ? item.entity : automaticLink(host, item, "entity"))?.attributes.effect_list, actions.update) : nothing,
hasScreen(item.type) ? glowField(host, item.ambilight, (v) => actions.update({ ambilight: v }), { label: "ambilight", hint: "ambilight_hint", lowest: 0 }) : nothing, hasScreen(item.type) ? glowField(host, item.ambilight, (v) => actions.update({ ambilight: v }), { label: "ambilight", hint: "ambilight_hint", lowest: 0 }) : nothing,
(isMediaFurniture(item.type) || isSpeakerFurniture(item.type)) ? glowField(host, item.sound_rings, (v) => actions.update({ sound_rings: v }), { label: "sound_rings", hint: "sound_rings_hint", lowest: 0 }) : nothing, (isMediaFurniture(item.type) || isSpeakerFurniture(item.type)) ? glowField(host, item.sound_rings, (v) => actions.update({ sound_rings: v }), { label: "sound_rings", hint: "sound_rings_hint", lowest: 0 }) : nothing,
item.type === "grid_point" ? nothing : entityField(host, t(meterParent(host.doc, item) ? "meter_sub_power" : powerLabel(item.type)), item.power ?? null, automaticLink(host, item, "power"), power, (v) => actions.update({ power: v })), item.type === "grid_point" ? nothing : html`${entityField(host, t(meterParent(host.doc, item) ? "meter_sub_power" : powerLabel(item.type)), item.power ?? null, autoPower, power, (v) => actions.update({ power: v }), { types: [1, 2] })}
${checkField(host, t(isChargingStation(item.type) ? "charging_card" : "furniture_power_card"), !!item.power_card, (on) => actions.update({ power_card: on || undefined }))}${hint(t(isChargingStation(item.type) ? "charging_hint" : "furniture_power_card_hint"), "nf-wide")}`,
)} )}
${isCooling(item.type) ? coolingLinks(host, item, actions) : lamp || item.type === "grid_point" ? nothing : deviceTempLink(host, item, actions)} ${isCooling(item.type) ? coolingLinks(host, item, actions) : lamp || item.type === "grid_point" ? nothing : deviceTempLink(host, item, actions)}
${item.type === "meter" ? subMeterLinks(host, item, actions) : nothing} ${item.type === "meter" ? subMeterLinks(host, item, actions) : nothing}
${item.type === "inverter" || item.type === "home_battery" ? deviceMeterLink(host, item, actions) : nothing} ${item.type === "inverter" || item.type === "home_battery" ? deviceMeterLink(host, item, actions) : nothing}
${item.type === "meter" && !meterParent(host.doc, item) ? linkBlock(entityField(host, t("furn_export"), item.export ?? null, undefined, power, set("export")), hint(t("furn_export_hint"), "nf-wide")) : nothing} ${item.type === "meter" && !meterParent(host.doc, item) ? linkBlock(entityField(host, t("furn_export"), item.export ?? null, undefined, power, set("export"), { types: [1, 2] }), hint(t("furn_export_hint"), "nf-wide")) : nothing}
${item.type === "inverter" && (host.doc.settings.roof.solar ?? []).length > 0 ? hint(strings.length > 0 ? t("inverter_strings", { names: strings.join(", ") }) : t("inverter_strings_none"), "nf-wide") : nothing} ${item.type === "inverter" && (host.doc.settings.roof.solar ?? []).length > 0 ? hint(strings.length > 0 ? t("inverter_strings", { names: strings.join(", ") }) : t("inverter_strings_none"), "nf-wide") : nothing}
${item.type === "home_battery" ${item.type === "home_battery"
? linkBlock( ? linkBlock(
entityField(host, t("furn_soc"), item.soc ?? null, undefined, kindOptions((id) => isNumeric(id) && (hass.states[id]?.attributes.device_class === "battery" || hass.states[id]?.attributes.unit_of_measurement === "%")), set("soc")), entityField(host, t("furn_soc"), item.soc ?? null, undefined, kindOptions((id) => isNumeric(id) && (hass.states[id]?.attributes.device_class === "battery" || hass.states[id]?.attributes.unit_of_measurement === "%")), set("soc"), { types: [1, 2] }),
entityField(host, t("furn_charge"), item.charge ?? null, undefined, power, set("charge")), entityField(host, t("furn_charge"), item.charge ?? null, undefined, power, set("charge"), { types: [1, 2] }),
hint(t("furn_charge_hint"), "nf-wide"), hint(t("furn_charge_hint"), "nf-wide"),
) )
: nothing} : nothing}
${item.type === "wallbox" ? linkBlock(entityField(host, t("furn_wallbox_status"), item.status ?? null, undefined, kindOptions((id) => isBinary(id) || isNumeric(id)), set("status"))) : nothing} ${isChargingStation(item.type) ? linkBlock(entityField(host, t("furn_wallbox_status"), item.status ?? null, undefined, kindOptions((id) => isBinary(id) || isNumeric(id)), set("status"), { types: [0, 1, 2, 3] })) : nothing}
${!lamp || item.entity ${chargingStationFields(host, item, actions.update)}
${!lamp || hasLink || powerRef
? html`${checkField(host, t("device_confirm"), !!item.confirm, (on) => actions.update({ confirm: on }), { title: t("device_confirm_hint") })} ? html`${checkField(host, t("device_confirm"), !!item.confirm, (on) => actions.update({ confirm: on }), { title: t("device_confirm_hint") })}
<div class="nf-form">${markerField(host, item.marker ?? null, (v) => actions.update({ marker: v }))}${iconField(host, item.icon, (v) => actions.update({ icon: v }))}${lamp ? nothing : pinShiftField(host, item.pin_offset, (v) => actions.update({ pin_offset: v }))}</div>` <div class="nf-form">${markerField(host, item.marker ?? null, (v) => actions.update({ marker: v }))}${iconField(host, item.icon, (v) => actions.update({ icon: v }))}${lamp ? nothing : pinShiftField(host, item.pin_offset, (v) => actions.update({ pin_offset: v }))}</div>`
: nothing} : nothing}
${item.type === "robot_vacuum" ${item.type === "robot_vacuum"
? linkBlock(entityField(host, t("furn_robot_room"), item.room_sensor ?? null, robotRoomSensor(hass, furnitureEntities(hass, host.doc.floors).get(item.id)?.entity ?? null, null), kindOptions(isNumeric), (v) => actions.update({ room_sensor: v }))) ? linkBlock(entityField(host, t("furn_robot_room"), item.room_sensor ?? null, robotRoomSensor(hass, furnitureEntities(hass, host.doc.floors).get(item.id)?.entity ?? null, null), kindOptions(isNumeric), (v) => actions.update({ room_sensor: v }), { types: [1, 2] }))
: nothing} : nothing}
${item.type === "robot_vacuum" && hasLink ? robotMapBlock(host, item) : nothing} ${item.type === "robot_vacuum" && hasLink ? robotMapBlock(host, item) : nothing}
${item.type === "fridge_smart" ${item.type === "fridge_smart"
? html`${linkBlock(entityField(host, t("furn_door_left"), item.door_left ?? null, undefined, doors, (v) => actions.update({ door_left: v })), entityField(host, t("furn_door_right"), item.door_right ?? null, undefined, doors, (v) => actions.update({ door_right: v })))} ? html`${linkBlock(entityField(host, t("furn_door_left"), item.door_left ?? null, undefined, doors, (v) => actions.update({ door_left: v }), { types: [0] }), entityField(host, t("furn_door_right"), item.door_right ?? null, undefined, doors, (v) => actions.update({ door_right: v }), { types: [0] }))}
${hint(t("fridge_hint"))}` ${hint(t("fridge_hint"))}`
: nothing} : nothing}
${renderDeviceValues(host, item.values, (values) => actions.update({ values }))}
${hint(t(hintKey))}`; ${hint(t(hintKey))}`;
} }
@@ -17,6 +17,8 @@ import { dataField, TARGET_EXAMPLES } from "./house.ts";
import { parkingForm } from "./parking.ts"; import { parkingForm } from "./parking.ts";
import { stairForm } from "./stairs.ts"; import { stairForm } from "./stairs.ts";
import { DEFAULT_STAIR } from "../../../geometry/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 { export interface FurnitureActions extends FurnitureLinkActions {
rotate(delta: number): void; 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-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> <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)} ${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} ${hasPicture(item.type) ? pictureFields(host, item, actions) : nothing}
${packItem(item.type)?.pet ${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>` ? 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>`
@@ -5,6 +5,8 @@ import { entityName, outsideEntities } from "../../../devices.ts";
import type { I18nKey } from "../../../i18n.ts"; import type { I18nKey } from "../../../i18n.ts";
import { BUTTON_ACTIONS, uid, type ButtonAction, type Circuit, type CustomButton, type ForecastCard, type MediaPreset, type OwnAlert, type StartView } from "../../../model.ts"; import { BUTTON_ACTIONS, uid, type ButtonAction, type Circuit, type CustomButton, type ForecastCard, type MediaPreset, type OwnAlert, type StartView } from "../../../model.ts";
import { entityOptions, isNumeric } from "../entities.ts"; import { entityOptions, isNumeric } from "../entities.ts";
import { isSymcon } from "../../../entities/symcon-values.ts";
import { renderSymconPresence } from "../symcon-fields.ts";
import { actions, checkField, colorField, entityField, hint, iconField, selectField, textField } from "../fields.ts"; import { actions, checkField, colorField, entityField, hint, iconField, selectField, textField } from "../fields.ts";
import type { EditorHost } from "../host.ts"; import type { EditorHost } from "../host.ts";
import { likelyRoomSensors, parseButtonData, patchPresence, startViewYaml } from "../ops/house.ts"; import { likelyRoomSensors, parseButtonData, patchPresence, startViewYaml } from "../ops/house.ts";
@@ -49,7 +51,7 @@ function favorites(host: EditorHost): TemplateResult {
return html`<summary>${host.t("favorites")}${list.length > 0 ? html` <span class="nf-lib-count">${list.length}</span>` : nothing}</summary> return html`<summary>${host.t("favorites")}${list.length > 0 ? html` <span class="nf-lib-count">${list.length}</span>` : nothing}</summary>
${hint(host.t("favorites_hint"))} ${list.map(row)} ${hint(host.t("favorites_hint"))} ${list.map(row)}
${list.length < MAX_FAVORITES ${list.length < MAX_FAVORITES
? html`<div class="nf-form">${entityField(host, host.t("favorites_add"), null, undefined, options, (v) => v && v !== "none" && !list.includes(v) && store([...list, v]))}</div>` ? html`<div class="nf-form">${entityField(host, host.t("favorites_add"), null, undefined, options, (v) => v && v !== "none" && !list.includes(v) && store([...list, v]), { excluded: (id) => list.includes(id) ? "Diese Variable ist bereits als Favorit verknüpft." : undefined })}</div>`
: nothing}`; : nothing}`;
} }
@@ -64,7 +66,7 @@ function outsideHidden(host: EditorHost, paneView?: () => StartView | null): Tem
<h4>${host.t("outside_hidden")}${list.length > 0 ? html` <span class="nf-lib-count">${list.length}</span>` : nothing}</h4> <h4>${host.t("outside_hidden")}${list.length > 0 ? html` <span class="nf-lib-count">${list.length}</span>` : nothing}</h4>
${hint(host.t("outside_hidden_hint"))} ${hint(host.t("outside_hidden_hint"))}
${list.map((id, i) => html`<div class="nf-row nf-dev-row"><span class="nf-dev-name"><span>${entityName(host.hass, id)}</span></span>${iconButton(host.t("delete"), "✕", () => store(removeAt(list, i)))}</div>`)} ${list.map((id, i) => html`<div class="nf-row nf-dev-row"><span class="nf-dev-name"><span>${entityName(host.hass, id)}</span></span>${iconButton(host.t("delete"), "✕", () => store(removeAt(list, i)))}</div>`)}
<div class="nf-form">${entityField(host, host.t("outside_hidden_add"), null, undefined, options, (v) => v && v !== "none" && !list.includes(v) && store([...list, v]))}</div>`; <div class="nf-form">${entityField(host, host.t("outside_hidden_add"), null, undefined, options, (v) => v && v !== "none" && !list.includes(v) && store([...list, v]), { excluded: (id) => list.includes(id) ? "Diese Variable ist hier bereits eingetragen." : undefined })}</div>`;
} }
/** The camera Outside opens with: the editor's 3D pane as it stands now (#83). */ /** The camera Outside opens with: the editor's 3D pane as it stands now (#83). */
@@ -132,7 +134,7 @@ function calendars(host: EditorHost): TemplateResult {
const days = host.doc.settings.today_days ?? 1; const days = host.doc.settings.today_days ?? 1;
return html`<h4>📅 ${t("today_calendars")}</h4> return html`<h4>📅 ${t("today_calendars")}</h4>
${hint(t("today_calendars_hint"))} ${list.map(row)} ${hint(t("today_calendars_hint"))} ${list.map(row)}
${list.length < 12 ? html`<div class="nf-form">${entityField(host, t("favorites_add"), null, undefined, options, (v) => v && v !== "none" && !list.includes(v) && store([...list, v]))}</div>` : nothing} ${list.length < 12 ? html`<div class="nf-form">${entityField(host, t("favorites_add"), null, undefined, options, (v) => v && v !== "none" && !list.includes(v) && store([...list, v]), { unsupported: "Dieses Feld benötigt eine Kalenderquelle mit Terminen. Eine Symcon-Variable ist kein Kalender; Kalenderquellen werden vom Symcon-Modul derzeit nicht bereitgestellt." })}</div>` : nothing}
${list.length ${list.length
? html`<div class="nf-form"> ? html`<div class="nf-form">
${selectField(host, t("today_days"), String(days), [1, 2, 3, 5, 7].map((n): [string, string] => [String(n), t(n === 1 ? "today_days_one" : "today_days_n", { n })]), (v) => host.change((d) => (d.settings.today_days = Number(v) > 1 ? Number(v) : undefined)))} ${selectField(host, t("today_days"), String(days), [1, 2, 3, 5, 7].map((n): [string, string] => [String(n), t(n === 1 ? "today_days_one" : "today_days_n", { n })]), (v) => host.change((d) => (d.settings.today_days = Number(v) > 1 ? Number(v) : undefined)))}
@@ -267,6 +269,7 @@ export function renderStartView(host: EditorHost, paneView: () => StartView | nu
/** Which room sensor says where each person is. */ /** Which room sensor says where each person is. */
export function renderPresence(host: EditorHost): TemplateResult { export function renderPresence(host: EditorHost): TemplateResult {
if (isSymcon(host.hass)) return renderSymconPresence(host);
const linked = host.doc.presence.map((l) => l.person); const linked = host.doc.presence.map((l) => l.person);
const persons = [...new Set([...Object.keys(host.hass?.states ?? {}).filter((id) => id.startsWith("person.")).sort(), ...linked])]; const persons = [...new Set([...Object.keys(host.hass?.states ?? {}).filter((id) => id.startsWith("person.")).sort(), ...linked])];
const numeric = entityOptions(host.hass, isNumeric); const numeric = entityOptions(host.hass, isNumeric);
@@ -296,6 +299,7 @@ export function renderPresence(host: EditorHost): TemplateResult {
/** Locating Bluetooth tags by room: pick a tag, walk through the rooms, record them (the element does the work). */ /** Locating Bluetooth tags by room: pick a tag, walk through the rooms, record them (the element does the work). */
export function renderBleLocate(host: EditorHost, doc: unknown): TemplateResult { export function renderBleLocate(host: EditorHost, doc: unknown): TemplateResult {
if (isSymcon(host.hass)) return html``;
return html`<details class="nf-section"> return html`<details class="nf-section">
<summary>${host.t("ble")}</summary> <summary>${host.t("ble")}</summary>
${hint(host.t("ble_hint"))} ${hint(host.t("ble_hint"))}
@@ -0,0 +1,53 @@
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";
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);
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) ? selectField(host, "Ventilbauart", c.valve_type ?? "mixing", [["mixing", "Mischer (Dreiwegeventil)"], ["two_way", "Durchgangsventil (Zweiwege)" ]], (valve_type) => patch({ valve_type }), { wide: true }) : 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" ? renderFreshwaterForm(host,item,update) : nothing}
${renderDeviceValues(host, item.values, (values) => update({ values }))}
</section>`;
}
@@ -6,6 +6,7 @@ import { entityName, openingEntities, windowPosition } from "../../../devices.ts
import type { I18nKey } from "../../../i18n.ts"; import type { I18nKey } from "../../../i18n.ts";
import { DOOR_STYLES, OPENING_PRESETS, openingPreset, openingStyle, WINDOW_OPENINGS, WINDOW_STYLES, type Opening, type OpeningPreset, type OpeningStyle } from "../../../model.ts"; import { DOOR_STYLES, OPENING_PRESETS, openingPreset, openingStyle, WINDOW_OPENINGS, WINDOW_STYLES, type Opening, type OpeningPreset, type OpeningStyle } from "../../../model.ts";
import { entityOptions, isNumeric } from "../entities.ts"; import { entityOptions, isNumeric } from "../entities.ts";
import { isPositionVariable } from "../../../entities/position-value.ts";
import { checkField, entityField, hint, numberField, selectField } from "../fields.ts"; import { checkField, entityField, hint, numberField, selectField } from "../fields.ts";
import type { EditorHost } from "../host.ts"; import type { EditorHost } from "../host.ts";
@@ -41,7 +42,7 @@ function choices(host: EditorHost) {
return { return {
covers: entityOptions(hass, (id) => id.startsWith("cover.")), covers: entityOptions(hass, (id) => id.startsWith("cover.")),
// numbers that can report where a blind is // numbers that can report where a blind is
positions: entityOptions(hass, (id) => /^(sensor|number|input_number)\./.test(id) && Number.isFinite(Number(stateOf(id)?.state))), positions: entityOptions(hass, (id) => isPositionVariable(hass, id)),
// plain contacts, and handle sensors with three states (open, tilted, closed) // plain contacts, and handle sensors with three states (open, tilted, closed)
contacts: entityOptions(hass, (id) => isContact(id) || (isNumeric(id) && windowPosition(stateOf(id)) !== null)), contacts: entityOptions(hass, (id) => isContact(id) || (isNumeric(id) && windowPosition(stateOf(id)) !== null)),
plainContacts: entityOptions(hass, isContact), plainContacts: entityOptions(hass, isContact),
@@ -167,9 +168,13 @@ function blindFields(host: EditorHost, o: Opening, actions: OpeningActions, list
const window = o.type === "window"; const window = o.type === "window";
const automatic = automaticLink(host, o, "cover"); const automatic = automaticLink(host, o, "cover");
const hasBlind = o.cover !== "none" && (o.cover || automatic); const hasBlind = o.cover !== "none" && (o.cover || automatic);
return html`${entityField(host, t(window ? "cover_entity" : "door_cover"), o.cover, automatic, lists.covers, (v) => actions.update({ cover: v }))} const symcon = host.hass?.symconObjects !== undefined;
return html`${entityField(host, t(symcon ? "symcon_cover_position" : window ? "cover_entity" : "door_cover"), o.cover, automatic, lists.covers, (v) => actions.update({ cover: v }), { types: [1, 2], role: "cover" })}
${symcon || (hasBlind && o.blind === "venetian") ? entityField(host, t("cover_tilt_entity"), o.cover_tilt ?? null, undefined, lists.covers, (v) => actions.update({ cover_tilt: noneAsNull(v) }), { types: [1, 2], role: "cover" }) : nothing}
${hasBlind ${hasBlind
? html`${entityField(host, t("cover_position_entity"), o.position ?? null, undefined, lists.positions, (v) => actions.update({ position: noneAsNull(v) }))} ? html`${checkField(host, t("cover_direction_invert"), !!o.cover_inverted, (on) => actions.update({ cover_inverted: on || undefined }))}
${o.cover_tilt || o.blind === "venetian" ? checkField(host, t("cover_tilt_direction_invert"), !!o.cover_tilt_inverted, (on) => actions.update({ cover_tilt_inverted: on || undefined })) : nothing}
${entityField(host, t("cover_position_entity"), o.position ?? null, undefined, lists.positions, (v) => actions.update({ position: noneAsNull(v) }), { types: [1, 2] })}
${o.position ? checkField(host, t("cover_position_invert"), !!o.position_inverted, (on) => actions.update({ position_inverted: on })) : nothing} ${o.position ? checkField(host, t("cover_position_invert"), !!o.position_inverted, (on) => actions.update({ position_inverted: on })) : nothing}
${checkField(host, t("device_confirm"), !!o.confirm, (on) => actions.update({ confirm: on }), { title: t("cover_confirm_hint") })} ${checkField(host, t("device_confirm"), !!o.confirm, (on) => actions.update({ confirm: on }), { title: t("cover_confirm_hint") })}
${window ${window
@@ -177,7 +182,10 @@ function blindFields(host: EditorHost, o: Opening, actions: OpeningActions, list
${entityField(host, t("cover2_entity"), o.cover2 ?? null, undefined, lists.covers, (v) => actions.update({ cover2: noneAsNull(v) }))}` ${entityField(host, t("cover2_entity"), o.cover2 ?? null, undefined, lists.covers, (v) => actions.update({ cover2: noneAsNull(v) }))}`
: nothing} : nothing}
${!window && o.type !== "garage" ? entityField(host, t("cover2_entity"), o.cover2 ?? null, undefined, lists.covers, (v) => actions.update({ cover2: noneAsNull(v) })) : nothing} ${!window && o.type !== "garage" ? entityField(host, t("cover2_entity"), o.cover2 ?? null, undefined, lists.covers, (v) => actions.update({ cover2: noneAsNull(v) })) : nothing}
${o.cover2 && o.cover2 !== "none" ? entityField(host, t("cover2_tilt_entity"), o.cover2_tilt ?? null, undefined, lists.covers, (v) => actions.update({ cover2_tilt: noneAsNull(v) })) : nothing}
${o.cover2 && o.cover2 !== "none" ? html`${checkField(host, t("cover2_direction_invert"), !!o.cover2_inverted, (on) => actions.update({ cover2_inverted: on || undefined }))}${checkField(host, t("cover2_tilt_direction_invert"), !!o.cover2_tilt_inverted, (on) => actions.update({ cover2_tilt_inverted: on || undefined }))}` : nothing}
${numberField(host, t("cover_my"), o.my_position ?? 0, (v) => actions.update({ my_position: v > 0 ? Math.min(100, Math.round(v)) : null }), 5, 0)} ${numberField(host, t("cover_my"), o.my_position ?? 0, (v) => actions.update({ my_position: v > 0 ? Math.min(100, Math.round(v)) : null }), 5, 0)}
${hint(t("cover_direction_hint"), "nf-wide")}
${hint(t("blind_hint"), "nf-wide")}` ${hint(t("blind_hint"), "nf-wide")}`
: nothing}`; : nothing}`;
} }
@@ -49,7 +49,7 @@ export function renderOutdoorForm(host: EditorHost, area: OutdoorArea, actions:
${checkField(host, t("outdoor_outline"), area.outline !== false, (on) => set({ outline: on ? undefined : false }), { title: t("outdoor_outline_hint") })} ${checkField(host, t("outdoor_outline"), area.outline !== false, (on) => set({ outline: on ? undefined : false }), { title: t("outdoor_outline_hint") })}
${area.type === "fence" || area.type === "pergola" ? checkField(host, t("outdoor_open"), !!area.open, (on) => set({ open: on || undefined }), { title: t("outdoor_open_hint") }) : nothing} ${area.type === "fence" || area.type === "pergola" ? checkField(host, t("outdoor_open"), !!area.open, (on) => set({ open: on || undefined }), { title: t("outdoor_open_hint") }) : nothing}
${area.type === "pergola" ? checkField(host, t("outdoor_bracing"), !!area.bracing, (on) => set({ bracing: on || undefined })) : nothing} ${area.type === "pergola" ? checkField(host, t("outdoor_bracing"), !!area.bracing, (on) => set({ bracing: on || undefined })) : nothing}
${checkField(host, t("outdoor_cut"), cutsOut(area), (on) => set({ cut: on === (area.type === "pool") ? undefined : on }), { title: t("outdoor_cut_hint") })} ${checkField(host, t("outdoor_cut"), cutsOut(area), (on) => set({ cut: on === cutsOut({ ...area, cut: undefined }) ? undefined : on }), { title: t("outdoor_cut_hint") })}
</div> </div>
${area.type === "fence" ? fenceGates(host, area, set) : nothing} ${area.type === "fence" ? fenceGates(host, area, set) : nothing}
${host.admin ${host.admin
+1 -1
View File
@@ -106,7 +106,7 @@ function windowForm(deps: RoofPanelDeps, win: RoofWindow): TemplateResult {
const covers = entityOptions(host.hass, (id) => id.startsWith("cover.")); const covers = entityOptions(host.hass, (id) => id.startsWith("cover."));
const contacts = entityOptions(host.hass, (id) => isBinary(id) || isNumeric(id)); const contacts = entityOptions(host.hass, (id) => isBinary(id) || isNumeric(id));
const link = (label: I18nKey, value: string | null | undefined, options: typeof covers, key: "cover" | "contact" | "tilt" | "window") => const link = (label: I18nKey, value: string | null | undefined, options: typeof covers, key: "cover" | "contact" | "tilt" | "window") =>
entityField(host, t(label), value ?? null, undefined, options, (v) => set({ [key]: v === "none" ? null : v })); entityField(host, t(label), value ?? null, undefined, options, (v) => set({ [key]: v === "none" ? null : v }), key === "cover" || key === "window" ? { types: [1, 2], role: "cover" } : { types: [0, 1, 2] });
const moveToFace = (key: string) => { const moveToFace = (key: string) => {
const next = faces.find((f) => f.key === key); const next = faces.find((f) => f.key === key);
if (next) set({ ...proposeWindow(next, win.id), w: win.w, h: win.h, cover: win.cover, contact: win.contact, tilt: win.tilt, window: win.window, name: win.name }); if (next) set({ ...proposeWindow(next, win.id), w: win.w, h: win.h, cover: win.cover, contact: win.contact, tilt: win.tilt, window: win.window, name: win.name });
+10 -7
View File
@@ -7,13 +7,15 @@ import { PACKAGES, type PackageId } from "../../../packages.ts";
import { entityOptions } from "../entities.ts"; import { entityOptions } from "../entities.ts";
import { checkField, colorField, entityField, hint, numberField, selectField, textField } from "../fields.ts"; import { checkField, colorField, entityField, hint, numberField, selectField, textField } from "../fields.ts";
import type { EditorHost } from "../host.ts"; import type { EditorHost } from "../host.ts";
import type { RectField } from "../ops/rooms.ts"; import { areaLeafName, type RectField } from "../ops/rooms.ts";
import { SPOT_TYPES, spotCount, spotItems } from "../ops/spots.ts"; import { SPOT_TYPES, spotCount, spotItems } from "../ops/spots.ts";
import type { SideState } from "../side-state.ts"; import type { SideState } from "../side-state.ts";
import { formatArea, formatLength } from "../../../units.ts"; import { formatArea, formatLength } from "../../../units.ts";
import { generateWalls, innerSize, type Wall } from "../../../geometry/walls.ts"; import { generateWalls, innerSize, type Wall } from "../../../geometry/walls.ts";
import { countsAsLiving, roomArea } from "../../../geometry/living-area.ts"; import { countsAsLiving, roomArea } from "../../../geometry/living-area.ts";
import { roomSpeaker } from "../../../live/announce.ts"; import { roomSpeaker } from "../../../live/announce.ts";
import { isSymcon } from "../../../entities/symcon-values.ts";
import { renderSymconRoomMeters } from "../symcon-fields.ts";
/** What the room form makes the editor do, and the parts of it that the editor still draws itself. */ /** What the room form makes the editor do, and the parts of it that the editor still draws itself. */
export interface RoomActions { export interface RoomActions {
@@ -64,7 +66,7 @@ function spotForm(host: EditorHost, state: SideState, room: Room, actions: RoomA
${selectField(host, host.t("spots_type"), draft.type, types, (type) => change({ type }), { wide: true })} ${selectField(host, host.t("spots_type"), draft.type, types, (type) => change({ type }), { wide: true })}
${numberField(host, host.t("spots_cols"), draft.cols, (v) => change({ cols: spotCount(v) }), 1, 1)} ${numberField(host, host.t("spots_cols"), draft.cols, (v) => change({ cols: spotCount(v) }), 1, 1)}
${numberField(host, host.t("spots_rows"), draft.rows, (v) => change({ rows: spotCount(v) }), 1, 1)} ${numberField(host, host.t("spots_rows"), draft.rows, (v) => change({ rows: spotCount(v) }), 1, 1)}
${entityField(host, host.t("furn_entity_light"), draft.entity, undefined, lights, (v) => change({ entity: v === "none" ? null : v }))} ${entityField(host, host.t("furn_entity_light"), draft.entity, undefined, lights, (v) => change({ entity: v === "none" ? null : v }), { types: [0, 1, 2], role: "light" })}
<div class="nf-actions nf-wide"> <div class="nf-actions nf-wide">
<button class="nf-btn nf-primary" ?disabled=${count === 0} @click=${() => actions.placeSpots()}>${host.t("spots_add", { n: count })}</button> <button class="nf-btn nf-primary" ?disabled=${count === 0} @click=${() => actions.placeSpots()}>${host.t("spots_add", { n: count })}</button>
<button class="nf-btn" @click=${() => (state.spots = null)}>${host.t("cancel")}</button> <button class="nf-btn" @click=${() => (state.spots = null)}>${host.t("cancel")}</button>
@@ -113,14 +115,14 @@ function ceilingField(host: EditorHost, room: Room, floor: Floor, actions: RoomA
${room.ceiling != null ? html`<button class="nf-btn nf-field-btn" ?disabled=${!host.admin} @click=${() => actions.patch({ ceiling: null })}>${t("height_auto")}</button>` : nothing} ${room.ceiling != null ? html`<button class="nf-btn nf-field-btn" ?disabled=${!host.admin} @click=${() => actions.patch({ ceiling: null })}>${t("height_auto")}</button>` : nothing}
${hint(t("room_ceiling_tip"), "nf-wide")} ${hint(t("room_ceiling_tip"), "nf-wide")}
${room.ceiling != null && room.ceiling > floor.height + 0.005 ${room.ceiling != null && room.ceiling > floor.height + 0.005
? html`<p class="nf-sub nf-wide">${t("room_ceiling_through", { ceiling: formatNumber(host.hass, room.ceiling, 2), floor: formatNumber(host.hass, floor.height, 2) })}</p>` ? hint(t("room_ceiling_through", { ceiling: formatNumber(host.hass, room.ceiling, 2), floor: formatNumber(host.hass, floor.height, 2) }), "nf-wide")
: nothing}`; : nothing}`;
} }
/** Announcements in the room: its speaker (automatic, chosen, or none) and a quiet time. */ /** Announcements in the room: its speaker (automatic, chosen, or none) and a quiet time. */
function announceFields(host: EditorHost, room: Room, floor: Floor | null, actions: RoomActions): TemplateResult { function announceFields(host: EditorHost, room: Room, floor: Floor | null, actions: RoomActions): TemplateResult {
const t = host.t; const t = host.t;
if (!host.hass) return html``; if (!host.hass || isSymcon(host.hass)) return html``;
const auto = roomSpeaker(host.hass, floor, { ...room, announce_speaker: null }); const auto = roomSpeaker(host.hass, floor, { ...room, announce_speaker: null });
const speakers = entityOptions(host.hass, (id) => /^(media_player|assist_satellite)\./.test(id) || (id.startsWith("notify.") && id.endsWith("_announce"))); const speakers = entityOptions(host.hass, (id) => /^(media_player|assist_satellite)\./.test(id) || (id.startsWith("notify.") && id.endsWith("_announce")));
const quiet = room.announce_quiet ?? null; const quiet = room.announce_quiet ?? null;
@@ -160,6 +162,7 @@ export function renderRoomForm(host: EditorHost, state: SideState, room: Room, a
<div class="nf-form"> <div class="nf-form">
${textField(host, t("room_name"), room.name, (v) => actions.patch({ name: v }), { wide: true })} ${textField(host, t("room_name"), room.name, (v) => actions.patch({ name: v }), { wide: true })}
${selectField(host, t("area"), room.area_id ?? "", areaChoices, (id) => actions.setArea(id), { wide: true })} ${selectField(host, t("area"), room.area_id ?? "", areaChoices, (id) => actions.setArea(id), { wide: true })}
${isSymcon(host.hass) && room.area_id ? html`<button type="button" class="nf-btn nf-wide nf-take-area-name" ?disabled=${!host.admin || !areaLeafName(host.hass, room.area_id)} @click=${() => actions.patch({ name: areaLeafName(host.hass, room.area_id!) })}>Bereichsnamen übernehmen</button>` : nothing}
${(room.sub_areas ?? []).map((a) => html`<span class="nf-chip nf-wide">${host.hass?.areas?.[a]?.name ?? a} <button class="nf-btn nf-field-btn" ?disabled=${!host.admin} title=${t("delete")} @click=${() => actions.patch({ sub_areas: (room.sub_areas ?? []).filter((x) => x !== a).length ? (room.sub_areas ?? []).filter((x) => x !== a) : null })}>✕</button></span>`)} ${(room.sub_areas ?? []).map((a) => html`<span class="nf-chip nf-wide">${host.hass?.areas?.[a]?.name ?? a} <button class="nf-btn nf-field-btn" ?disabled=${!host.admin} title=${t("delete")} @click=${() => actions.patch({ sub_areas: (room.sub_areas ?? []).filter((x) => x !== a).length ? (room.sub_areas ?? []).filter((x) => x !== a) : null })}>✕</button></span>`)}
${room.area_id ${room.area_id
? selectField(host, t("sub_area_add"), "", areaChoices.filter(([id]) => id !== room.area_id && !(room.sub_areas ?? []).includes(id)), (id) => id && actions.patch({ sub_areas: [...(room.sub_areas ?? []), id] }), { wide: true, title: t("sub_area_hint") }) ? selectField(host, t("sub_area_add"), "", areaChoices.filter(([id]) => id !== room.area_id && !(room.sub_areas ?? []).includes(id)), (id) => id && actions.patch({ sub_areas: [...(room.sub_areas ?? []), id] }), { wide: true, title: t("sub_area_hint") })
@@ -171,8 +174,8 @@ export function renderRoomForm(host: EditorHost, state: SideState, room: Room, a
${hint(t("room_floor_offset_hint"), "nf-wide")} ${hint(t("room_floor_offset_hint"), "nf-wide")}
${entityField(host, t("room_clean"), room.clean_entity ?? null, undefined, entityOptions(host.hass, (id) => /^(script|button|input_button)\./.test(id)), (v) => actions.patch({ clean_entity: v && v !== "none" ? v : null }))} ${entityField(host, t("room_clean"), room.clean_entity ?? null, undefined, entityOptions(host.hass, (id) => /^(script|button|input_button)\./.test(id)), (v) => actions.patch({ clean_entity: v && v !== "none" ? v : null }))}
${room.clean_entity ? nothing : hint(t("room_clean_hint"), "nf-wide")} ${room.clean_entity ? nothing : hint(t("room_clean_hint"), "nf-wide")}
${entityField(host, t("floor_heating"), room.floor_heating ?? null, undefined, entityOptions(host.hass, (id) => /^(climate|switch|valve|binary_sensor|input_boolean)\./.test(id)), (v) => actions.patch({ floor_heating: v && v !== "none" ? v : null }))} ${isSymcon(host.hass) ? nothing : entityField(host, t("floor_heating"), room.floor_heating ?? null, undefined, entityOptions(host.hass, (id) => /^(climate|switch|valve|binary_sensor|input_boolean)\./.test(id)), (v) => actions.patch({ floor_heating: v && v !== "none" ? v : null }))}
${room.floor_heating ? hint(t("floor_heating_hint"), "nf-wide") : nothing} ${room.floor_heating && !isSymcon(host.hass) ? hint(t("floor_heating_hint"), "nf-wide") : nothing}
${announceFields(host, room, host.floor ?? null, actions)} ${announceFields(host, room, host.floor ?? null, actions)}
${inner ? html`<p class="nf-sub nf-wide" title=${t("room_inner_hint")}>${t("room_inner", { w: formatLength(host.hass, inner[0]), d: formatLength(host.hass, inner[1]) })}</p>` : nothing} ${inner ? html`<p class="nf-sub nf-wide" title=${t("room_inner_hint")}>${t("room_inner", { w: formatLength(host.hass, inner[0]), d: formatLength(host.hass, inner[1]) })}</p>` : nothing}
${livingLine(host, room, walls)} ${livingLine(host, room, walls)}
@@ -187,7 +190,7 @@ export function renderRoomForm(host: EditorHost, state: SideState, room: Room, a
<button class="nf-btn" title=${t("room_start_view_hint")} ?disabled=${!host.admin} @click=${() => actions.rememberView()}>${t("room_start_view")}</button> <button class="nf-btn" title=${t("room_start_view_hint")} ?disabled=${!host.admin} @click=${() => actions.rememberView()}>${t("room_start_view")}</button>
${room.start_view ? html`<button class="nf-btn" title=${t("room_start_view_reset")} ?disabled=${!host.admin} @click=${() => actions.patch({ start_view: null })}>↺</button>` : nothing} ${room.start_view ? html`<button class="nf-btn" title=${t("room_start_view_reset")} ?disabled=${!host.admin} @click=${() => actions.patch({ start_view: null })}>↺</button>` : nothing}
</div> </div>
${actions.wallHeights} ${actions.climate} ${corners(host, room, rectangle, actions)} ${actions.wallHeights} ${actions.climate} ${isSymcon(host.hass) ? renderSymconRoomMeters(host, room, (change) => actions.patch(change)) : nothing} ${corners(host, room, rectangle, actions)}
${host.admin ${host.admin
? html`<div class="nf-actions"> ? html`<div class="nf-actions">
<button class="nf-btn nf-primary" @click=${() => (state.packages = !state.packages)}>${t("pkg_open")}</button> <button class="nf-btn nf-primary" @click=${() => (state.packages = !state.packages)}>${t("pkg_open")}</button>
@@ -1,5 +1,7 @@
import { html, nothing, type TemplateResult } from "lit"; import { html, nothing, type TemplateResult } from "lit";
import { weatherEntity } from "../../../weather.ts"; import { weatherEntity } from "../../../weather.ts";
import { isSymcon } from "../../../entities/symcon-values.ts";
import { renderSymconWeather } from "../symcon-fields.ts";
import type { I18nKey } from "../../../i18n.ts"; import type { I18nKey } from "../../../i18n.ts";
import { DEFAULT_PAINT_INSIDE, DEFAULT_PAINT_OUTSIDE, DEFAULT_WEATHER_EFFECTS, WEATHER_EFFECTS, type Building, type RoofType } from "../../../model.ts"; import { DEFAULT_PAINT_INSIDE, DEFAULT_PAINT_OUTSIDE, DEFAULT_WEATHER_EFFECTS, WEATHER_EFFECTS, type Building, type RoofType } from "../../../model.ts";
import { entityName } from "../../../devices.ts"; import { entityName } from "../../../devices.ts";
@@ -53,7 +55,7 @@ function statusFields(host: EditorHost, ids: string[], set: (ids: string[]) => v
)} )}
</div>` </div>`
: nothing} : nothing}
${ids.length < 12 ? entityField(host, t("status_add"), null, undefined, options, (v) => v && v !== "none" && set([...ids, v])) : nothing} ${ids.length < 12 ? entityField(host, t("status_add"), null, undefined, options, (v) => v && v !== "none" && set([...ids, v]), { excluded: (id) => ids.includes(id) ? "Diese Variable ist in der Statusanzeige bereits verknüpft." : undefined }) : nothing}
${hint(t("status_entities_hint"), "nf-wide")}`; ${hint(t("status_entities_hint"), "nf-wide")}`;
} }
@@ -91,14 +93,14 @@ export function renderSettings(host: EditorHost, actions: SettingsActions): Temp
: nothing} : nothing}
${gable ? numberField(host, t("roof_pitch"), s.roof.pitch, (v) => setRoof({ pitch: clamp(v, 5, 60) }), 1, 5) : nothing} ${gable ? numberField(host, t("roof_pitch"), s.roof.pitch, (v) => setRoof({ pitch: clamp(v, 5, 60) }), 1, 5) : nothing}
${s.roof.type !== "none" ? numberField(host, t("roof_overhang"), s.roof.overhang, (v) => setRoof({ overhang: clamp(v, 0, 2) }), 0.05, 0) : nothing} ${s.roof.type !== "none" ? numberField(host, t("roof_overhang"), s.roof.overhang, (v) => setRoof({ overhang: clamp(v, 0, 2) }), 0.05, 0) : nothing}
${host.hass ? entityField(host, t("weather_entity"), s.weather_entity ?? null, weatherEntity(host.hass, null), entityOptions(host.hass, (id) => id.startsWith("weather.")), (v) => set({ weather_entity: v })) : nothing} ${isSymcon(host.hass) ? renderSymconWeather(host, s, set) : host.hass ? entityField(host, t("weather_entity"), s.weather_entity ?? null, weatherEntity(host.hass, null), entityOptions(host.hass, (id) => id.startsWith("weather.")), (v) => set({ weather_entity: v })) : nothing}
<div class="nf-sub nf-wide">${t("weather_effects")}</div> <div class="nf-sub nf-wide">${t("weather_effects")}</div>
${WEATHER_EFFECTS.map((effect) => checkField(host, t(`weather_effect_${effect}` as I18nKey), current.includes(effect), (on) => set({ weather_effects: withEffect(current, effect, on) }), { wide: false }))} ${WEATHER_EFFECTS.map((effect) => checkField(host, t(`weather_effect_${effect}` as I18nKey), current.includes(effect), (on) => set({ weather_effects: withEffect(current, effect, on) }), { wide: false }))}
${checkField(host, t("rain_warning"), s.rain_warning !== false, (on) => set({ rain_warning: on }))} ${checkField(host, t("rain_warning"), s.rain_warning !== false, (on) => set({ rain_warning: on }))}
${host.hass && s.rain_warning !== false ${host.hass && !isSymcon(host.hass) && s.rain_warning !== false
? entityField(host, t("rain_sensor"), s.rain_sensor ?? null, undefined, entityOptions(host.hass, (id) => /^(binary_sensor|sensor)\./.test(id)), (v) => set({ rain_sensor: v === "none" ? null : v })) ? entityField(host, t("rain_sensor"), s.rain_sensor ?? null, undefined, entityOptions(host.hass, (id) => /^(binary_sensor|sensor)\./.test(id)), (v) => set({ rain_sensor: v === "none" ? null : v }))
: nothing} : nothing}
${host.hass && s.rain_warning !== false && s.rain_sensor && s.rain_sensor !== "none" ? checkField(host, t("rain_sensor_inverted"), !!s.rain_sensor_inverted, (on) => set({ rain_sensor_inverted: on || undefined }), { title: t("rain_sensor_inverted_hint") }) : nothing} ${host.hass && !isSymcon(host.hass) && s.rain_warning !== false && s.rain_sensor && s.rain_sensor !== "none" ? checkField(host, t("rain_sensor_inverted"), !!s.rain_sensor_inverted, (on) => set({ rain_sensor_inverted: on || undefined }), { title: t("rain_sensor_inverted_hint") }) : nothing}
${host.hass ? entityField(host, t("outage_sensor"), s.outage_sensor ?? null, undefined, entityOptions(host.hass, (id) => /^(binary_sensor|sensor)\./.test(id)), (v) => set({ outage_sensor: v === "none" ? null : v })) : nothing} ${host.hass ? entityField(host, t("outage_sensor"), s.outage_sensor ?? null, undefined, entityOptions(host.hass, (id) => /^(binary_sensor|sensor)\./.test(id)), (v) => set({ outage_sensor: v === "none" ? null : v })) : nothing}
${hint(t("outage_hint"), "nf-wide")} ${hint(t("outage_hint"), "nf-wide")}
${checkField(host, t("contact_warning"), !!s.contact_warning, (on) => set({ contact_warning: on || undefined }), { title: t("contact_warning_hint") })} ${checkField(host, t("contact_warning"), !!s.contact_warning, (on) => set({ contact_warning: on || undefined }), { title: t("contact_warning_hint") })}
@@ -106,7 +108,7 @@ export function renderSettings(host: EditorHost, actions: SettingsActions): Temp
${selectField(host, t("room_double_tap"), s.room_double_tap ?? "area", [["area", t("room_double_tap_area")], ["plan", t("room_double_tap_plan")], ["off", t("room_double_tap_off")]] as const, (v) => set({ room_double_tap: v === "plan" || v === "off" ? v : null }), { title: t("room_double_tap_hint") })} ${selectField(host, t("room_double_tap"), s.room_double_tap ?? "area", [["area", t("room_double_tap_area")], ["plan", t("room_double_tap_plan")], ["off", t("room_double_tap_off")]] as const, (v) => set({ room_double_tap: v === "plan" || v === "off" ? v : null }), { title: t("room_double_tap_hint") })}
${checkField(host, t("motion_markers_active"), !!s.motion_markers_active, (on) => set({ motion_markers_active: on || undefined }), { title: t("motion_markers_active_hint") })} ${checkField(host, t("motion_markers_active"), !!s.motion_markers_active, (on) => set({ motion_markers_active: on || undefined }), { title: t("motion_markers_active_hint") })}
${host.hass ? statusFields(host, s.status_entities ?? [], (status_entities) => set({ status_entities: status_entities.length ? status_entities : null })) : nothing} ${host.hass ? statusFields(host, s.status_entities ?? [], (status_entities) => set({ status_entities: status_entities.length ? status_entities : null })) : nothing}
${host.hass ? entityField(host, t("announce_tts"), s.announce_tts ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("tts.")), (v) => set({ announce_tts: v === "none" ? null : v })) : nothing} ${isSymcon(host.hass) ? nothing : html`${host.hass ? entityField(host, t("announce_tts"), s.announce_tts ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("tts.")), (v) => set({ announce_tts: v === "none" ? null : v })) : nothing}
<label class="nf-field nf-wide" <label class="nf-field nf-wide"
>${t("announce_phrases")} >${t("announce_phrases")}
<textarea <textarea
@@ -120,11 +122,11 @@ export function renderSettings(host: EditorHost, actions: SettingsActions): Temp
}} }}
></textarea> ></textarea>
</label> </label>
${hint(t("announce_phrases_hint"), "nf-wide")} ${hint(t("announce_phrases_hint"), "nf-wide")}`}
${checkField(host, t("sun_patches"), s.sun_patches !== false, (on) => set({ sun_patches: on }), { title: t("sun_patches_hint") })} ${checkField(host, t("sun_patches"), s.sun_patches !== false, (on) => set({ sun_patches: on }), { title: t("sun_patches_hint") })}
${checkField(host, t("sun_arc"), s.sun_arc === true, (on) => set({ sun_arc: on }), { title: t("sun_arc_hint") })} ${checkField(host, t("sun_arc"), s.sun_arc === true, (on) => set({ sun_arc: on }), { title: t("sun_arc_hint") })}
${backdropFields(host, s.backdrop ?? null, (backdrop) => set({ backdrop }))} ${backdropFields(host, s.backdrop ?? null, (backdrop) => set({ backdrop }))}
</div> </div>
${hint(`${t("north_hint")} ${t("weather_entity_hint")}`)} ${hint(isSymcon(host.hass) ? t("north_hint") : `${t("north_hint")} ${t("weather_entity_hint")}`)}
</details>`; </details>`;
} }
@@ -2,6 +2,7 @@ import { html, nothing, type TemplateResult } from "lit";
import { LIGHT_ANIMATIONS, type LightEffectConfig } from "../../light-effects.ts"; import { LIGHT_ANIMATIONS, type LightEffectConfig } from "../../light-effects.ts";
import { pluginLightAnimationNames } from "../../plugins/registry.ts"; import { pluginLightAnimationNames } from "../../plugins/registry.ts";
import type { EditorHost } from "./host.ts"; import type { EditorHost } from "./host.ts";
import { hint } from "./fields.ts";
/** A small local-only mapping editor. Unknown stored identifiers remain untouched until edited. */ /** A small local-only mapping editor. Unknown stored identifiers remain untouched until edited. */
export function lightEffectFields(host: EditorHost, config: LightEffectConfig, effects: unknown, update: (patch: LightEffectConfig) => void): TemplateResult { export function lightEffectFields(host: EditorHost, config: LightEffectConfig, effects: unknown, update: (patch: LightEffectConfig) => void): TemplateResult {
@@ -32,7 +33,7 @@ export function lightEffectFields(host: EditorHost, config: LightEffectConfig, e
}; };
return html`<details class="nf-wide"> return html`<details class="nf-wide">
<summary>${host.t("light_effects")}</summary> <summary>${host.t("light_effects")}</summary>
<p class="nf-sub">${host.t("light_effects_hint")}</p> ${hint(host.t("light_effects_hint"))}
<label class="nf-check"><input type="checkbox" .checked=${config.animations_enabled !== false} ?disabled=${!host.admin} <label class="nf-check"><input type="checkbox" .checked=${config.animations_enabled !== false} ?disabled=${!host.admin}
@change=${(e: Event) => update({ animations_enabled: (e.target as HTMLInputElement).checked })} />${host.t("light_effects_enabled")}</label> @change=${(e: Event) => update({ animations_enabled: (e.target as HTMLInputElement).checked })} />${host.t("light_effects_enabled")}</label>
${names.map((name) => html`<label class="nf-field nf-wide">${name} ${names.map((name) => html`<label class="nf-field nf-wide">${name}
@@ -46,6 +47,7 @@ export function lightEffectFields(host: EditorHost, config: LightEffectConfig, e
<label class="nf-field nf-wide">${host.t("light_effect_add")}<input type="text" ?disabled=${!host.admin} placeholder="Regenbogen" <label class="nf-field nf-wide">${host.t("light_effect_add")}<input type="text" ?disabled=${!host.admin} placeholder="Regenbogen"
@input=${(e: Event) => (e.target as HTMLInputElement).setCustomValidity("")} @input=${(e: Event) => (e.target as HTMLInputElement).setCustomValidity("")}
@change=${(e: Event) => { const input = e.target as HTMLInputElement; if (set(input.value, "none", input, true)) input.value = ""; }} /></label> @change=${(e: Event) => { const input = e.target as HTMLInputElement; if (set(input.value, "none", input, true)) input.value = ""; }} /></label>
<p class="nf-sub" data-effect-feedback role="status" aria-live="polite">${host.t("light_effect_name_limit")} ${host.t("light_effect_count_limit")}</p> ${hint(`${host.t("light_effect_name_limit")} ${host.t("light_effect_count_limit")}`)}
<p class="nf-sub" data-effect-feedback role="status" aria-live="polite"></p>
</details>`; </details>`;
} }
@@ -25,6 +25,7 @@ import {
type Vec2, type Vec2,
} from "../../../model.ts"; } from "../../../model.ts";
import { furnitureSize } from "../../../packs.ts"; import { furnitureSize } from "../../../packs.ts";
import { defaultHydronic, isHydronic } from "../../../hydronic-model.ts";
const thousandths = (v: number) => Math.round(v * 1000) / 1000; const thousandths = (v: number) => Math.round(v * 1000) / 1000;
const quarterTurns = (degrees: number, by: number) => (((degrees + by) % 360) + 360) % 360; 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 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 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 }; 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 // 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 }; if (type === "stairs") item.stair = { ...DEFAULT_STAIR };
return item; return item;
@@ -1,9 +1,9 @@
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { test } from "node:test"; import { test } from "node:test";
import { box, floorWith, opening } from "../../../entities/fixtures.ts"; import { box, floorWith, opening, hassOf } from "../../../entities/fixtures.ts";
import type { Placement } from "../../../model.ts"; import type { Placement } from "../../../model.ts";
import { setWallSlope } from "./edges.ts"; import { setWallSlope } from "./edges.ts";
import { insertCorner, areaChoice, copyOfRoom, cornerMoved, evenCeilingLights, newRoom, rectangleAfter, removeCorner, removeRoom } from "./rooms.ts"; import { insertCorner, areaChoice, areaLeafName, copyOfRoom, cornerMoved, evenCeilingLights, newRoom, rectangleAfter, removeCorner, removeRoom } from "./rooms.ts";
const lamp = (id: string, x: number, z: number, extra: Partial<Placement> = {}): Placement => ({ entity_id: id, x, z, y: null, ...extra }); const lamp = (id: string, x: number, z: number, extra: Partial<Placement> = {}): Placement => ({ entity_id: id, x, z, y: null, ...extra });
@@ -73,6 +73,14 @@ test("choosing an area names a room that only had a placeholder name", () => {
assert.deepEqual(areaChoice({ ...box("r", 0, 0, 1, 1), name: "Lounge" }, "", areas), { area_id: null }); assert.deepEqual(areaChoice({ ...box("r", 0, 0, 1, 1), name: "Lounge" }, "", areas), { area_id: null });
}); });
test("Symcon area selection preserves the name and explicit adoption uses the real leaf category", () => {
const h = hassOf([], {}, { areas: { "symcon-category-10": { area_id: "symcon-category-10", name: "Haus / OG / Büro" } }, symconObjects: [{ object_id: 10, parent_id: 2, name: "Büro / Nord", path: "Haus / OG / Büro / Nord", object_type: 0, position: 0, hidden: true, icon: "" }] });
assert.deepEqual(areaChoice({ ...box("r", 0, 0, 1, 1), name: "Room 3" }, "symcon-category-10", h.areas!, false), { area_id: "symcon-category-10" });
assert.equal(areaLeafName(h, "symcon-category-10"), "Büro / Nord");
assert.equal(areaLeafName({ ...h, symconObjects: [] }, "symcon-category-10"), "Büro");
assert.equal(areaLeafName(h, "missing"), "");
});
test("ceiling lights spread over the room in a grid, a short last row over the full width", () => { test("ceiling lights spread over the room in a grid, a short last row over the full width", () => {
const room = box("r", 0, 0, 6, 4); const room = box("r", 0, 0, 6, 4);
const lights = [lamp("light.a", 1, 1), lamp("light.b", 1.1, 1), lamp("light.c", 1.2, 1), lamp("light.d", 1.3, 1), lamp("light.e", 1.4, 1)]; const lights = [lamp("light.a", 1, 1), lamp("light.b", 1.1, 1), lamp("light.c", 1.2, 1), lamp("light.d", 1.3, 1), lamp("light.e", 1.4, 1)];
+10 -2
View File
@@ -3,6 +3,7 @@
import { bounds, pointInPolygon, uid, type Floor, type Opening, type Placement, type Room, type Vec2 } from "../../../model.ts"; import { bounds, pointInPolygon, uid, type Floor, type Opening, type Placement, type Room, type Vec2 } from "../../../model.ts";
import { arcPoints, pieceAt, polylineLength } from "../../../geometry/arcs.ts"; import { arcPoints, pieceAt, polylineLength } from "../../../geometry/arcs.ts";
import { kindOf } from "../../../devices.ts"; import { kindOf } from "../../../devices.ts";
import type { HomeAssistant } from "../../../types.ts";
const thousandths = (v: number) => Math.round(v * 1000) / 1000; const thousandths = (v: number) => Math.round(v * 1000) / 1000;
const rounded = (points: readonly Vec2[]): Vec2[] => points.map(([x, z]) => [thousandths(x), thousandths(z)]); const rounded = (points: readonly Vec2[]): Vec2[] => points.map(([x, z]) => [thousandths(x), thousandths(z)]);
@@ -73,10 +74,17 @@ const GENERIC_NAME = /^(Raum|Room) \d+$/;
* What choosing a Home Assistant area does to a room: it gets the area, and a name that was only a placeholder ("Room 3", or the * What choosing a Home Assistant area does to a room: it gets the area, and a name that was only a placeholder ("Room 3", or the
* name of some area) takes the area's name. * name of some area) takes the area's name.
*/ */
export function areaChoice(room: Room, areaId: string, areas: Readonly<Record<string, { name: string }>>): Partial<Room> { export function areaChoice(room: Room, areaId: string, areas: Readonly<Record<string, { name: string }>>, takeName = true): Partial<Room> {
const area = areaId ? areas[areaId] : undefined; const area = areaId ? areas[areaId] : undefined;
const placeholder = !room.name || GENERIC_NAME.test(room.name) || Object.values(areas).some((a) => a.name === room.name); const placeholder = !room.name || GENERIC_NAME.test(room.name) || Object.values(areas).some((a) => a.name === room.name);
return { area_id: areaId || null, ...(area && placeholder ? { name: area.name } : {}) }; return { area_id: areaId || null, ...(takeName && area && placeholder ? { name: area.name } : {}) };
}
/** Use the actual leaf category, even when its native name contains a slash. */
export function areaLeafName(hass: HomeAssistant | undefined, areaId: string): string {
const id = /^symcon-category-(\d+)$/.exec(areaId)?.[1];
return (id ? hass?.symconObjects?.find((n) => n.object_id === Number(id))?.name : undefined)
?? hass?.areas?.[areaId]?.name.split(" / ").at(-1)?.trim() ?? "";
} }
/** /**
@@ -1,7 +1,8 @@
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { test } from "node:test"; import { test } from "node:test";
import { box } from "../../../entities/fixtures.ts"; import { box } from "../../../entities/fixtures.ts";
import { snapToPlan } from "./snapping.ts"; import type { Vec2 } from "../../../model.ts";
import { snapOutdoorMove, snapToPlan } from "./snapping.ts";
const options = (extra = {}) => ({ rooms: [box("a", 0, 0, 4, 3)], grid: 0.1, reach: 0.2, ...extra }); const options = (extra = {}) => ({ rooms: [box("a", 0, 0, 4, 3)], grid: 0.1, reach: 0.2, ...extra });
@@ -41,3 +42,47 @@ test("walls along an axis are held to the grid when snapped to", () => {
const snapped = snapToPlan([2.37, 3.12], options({ grid: 0.5, reach: 0.3 })); const snapped = snapToPlan([2.37, 3.12], options({ grid: 0.5, reach: 0.3 }));
assert.deepEqual(snapped.point, [2.5, 3]); assert.deepEqual(snapped.point, [2.5, 3]);
}); });
const rect = (id: string, x: number, z: number, w: number, d: number) => ({ id, points: [[x, z], [x + w, z], [x + w, z + d], [x, z + d]] as Vec2[] });
const neighbor = rect("neighbor", 4.03, 0.07, 3, 3);
const outside = { rooms: [], outdoor: [neighbor], grid: 0.5, reach: 0.2 };
test("outdoor drawing and corner resizing snap to off-grid corners and edges", () => {
assert.deepEqual(snapToPlan([4.12, 0.14], outside).point, [4.03, 0.07]);
assert.deepEqual(snapToPlan([4.12, 1.2], outside).point, [4.03, 1]);
const self = rect("self", 0, 0, 4, 3);
const o = { ...outside, outdoor: [self, neighbor], skip: { outdoorId: "self" } };
assert.deepEqual(snapToPlan([4.06, 0.08], o).point, [4.03, 0.07]);
assert.deepEqual(snapToPlan([0.04, 0.06], { ...o, outdoor: [self] }).guides, {});
});
test("whole outdoor areas snap corners before rounding the pointer delta to a coarse grid", () => {
const moving = rect("moving", 0, 0, 2, 2);
const result = snapOutdoorMove(moving.points, [2.12, 0.14], { ...outside, outdoor: [moving, neighbor], skip: { outdoorId: "moving" } });
assert.deepEqual(result.by, [2.03, 0.07]);
assert.deepEqual(result.guides, { point: [4.03, 0.07] });
assert.deepEqual(moving.points, rect("moving", 0, 0, 2, 2).points, "never mutate the drag snapshot");
});
test("whole-area edges snap without changing shape, including a long edge covering a shorter target", () => {
const moving = rect("m", 0, -4, 2, 10);
const result = snapOutdoorMove(moving.points, [2.12, 0.32], outside);
assert.deepEqual(result.by, [2.03, 0.5]);
assert.deepEqual(result.guides, { x: 4.03 });
const diagonal = { id: "d", points: [[5, -2], [11, 4], [11, -2]] as Vec2[] };
const atEdge = snapOutdoorMove(rect("m", 0, 0, 1, 1).points, [7.1, 0], { ...outside, outdoor: [diagonal] });
assert.deepEqual(atEdge.by, [7.05, 0.05]);
});
test("distant areas keep grid translation and IDs never collide across rooms and outdoor areas", () => {
assert.deepEqual(snapOutdoorMove(rect("m", 0, 0, 1, 1).points, [10.12, 12.3], outside), { by: [10, 12.5], guides: {} });
const r = rect("same", 4.03, 0.07, 3, 3);
assert.deepEqual(snapToPlan([4.1, 0.1], { ...outside, rooms: [r], outdoor: [r], skip: { outdoorId: "same" } }).point, [4.03, 0.07]);
});
test("an open outdoor outline has no phantom closing edge to snap to", () => {
const o = { ...outside, outdoor: [{ id: "fence", open: true, points: [[0, 0], [4, 0], [4, 4]] as Vec2[] }] };
assert.equal(snapToPlan([2.1, 2.14], o).guides.point, undefined);
const moving = o.outdoor[0];
assert.deepEqual(snapOutdoorMove(moving.points, [0, 0], { ...outside, outdoor: [moving, rect("target", 1.9, 2, 0.2, 0.2)], skip: { outdoorId: moving.id } }).guides, {});
});
+61 -11
View File
@@ -1,19 +1,19 @@
// Where a point drawn in the plan lands: on a corner of another room, on another room's wall (so walls can meet in a T), or on the // Plan snapping: room corners/walls, optional outdoor corners/edges, then the grid and axis guides.
// grid, lined up with other corners along each axis.
import type { Room, Vec2 } from "../../../model.ts"; import type { OutdoorArea, Room, Vec2 } from "../../../model.ts";
import type { Guides } from "../canvas/draft.ts"; import type { Guides } from "../canvas/draft.ts";
const thousandths = (v: number) => Math.round(v * 1000) / 1000; const thousandths = (v: number) => Math.round(v * 1000) / 1000;
export interface SnapOptions { export interface SnapOptions {
rooms: readonly Room[]; rooms: readonly Pick<Room, "id" | "points">[];
outdoor?: readonly Pick<OutdoorArea, "id" | "points" | "open">[];
/** The grid step in metres. */ /** The grid step in metres. */
grid: number; grid: number;
/** How close a point must be to something to snap to it, in metres. */ /** How close a point must be to something to snap to it, in metres. */
reach: number; reach: number;
/** A room (or one corner of it) that is being moved and so is not something to snap to. */ /** Exclude the moving outline; rooms can also exclude just one corner. */
skip?: { roomId: string; index?: number }; skip?: { roomId?: string; outdoorId?: string; index?: number };
} }
export interface Snapped { export interface Snapped {
@@ -23,7 +23,7 @@ export interface Snapped {
const distance = (a: Vec2, b: Vec2) => Math.hypot(a[0] - b[0], a[1] - b[1]); const distance = (a: Vec2, b: Vec2) => Math.hypot(a[0] - b[0], a[1] - b[1]);
/** The nearest corner of the other rooms within reach, if any. */ /** The nearest corner within reach, if any. */
function nearestCorner(corners: readonly Vec2[], p: Vec2, reach: number): Vec2 | null { function nearestCorner(corners: readonly Vec2[], p: Vec2, reach: number): Vec2 | null {
let best: Vec2 | null = null; let best: Vec2 | null = null;
let bestDistance = reach; let bestDistance = reach;
@@ -35,12 +35,12 @@ function nearestCorner(corners: readonly Vec2[], p: Vec2, reach: number): Vec2 |
} }
/** The point on a wall of another room that is nearest to p, within reach. Walls along an axis are held to the grid. */ /** The point on a wall of another room that is nearest to p, within reach. Walls along an axis are held to the grid. */
function nearestOnWall(rooms: readonly Room[], p: Vec2, o: SnapOptions): Vec2 | null { function nearestOnWall(rooms: readonly { id: string; points: Vec2[]; open?: boolean }[], p: Vec2, o: SnapOptions): Vec2 | null {
let best: Vec2 | null = null; let best: Vec2 | null = null;
let bestDistance = o.reach; let bestDistance = o.reach;
for (const room of rooms) { for (const room of rooms) {
if (o.skip && room.id === o.skip.roomId) continue;
room.points.forEach((a, i) => { room.points.forEach((a, i) => {
if (room.open && i === room.points.length - 1) return;
const b = room.points[(i + 1) % room.points.length]; const b = room.points[(i + 1) % room.points.length];
const [dx, dz] = [b[0] - a[0], b[1] - a[1]]; const [dx, dz] = [b[0] - a[0], b[1] - a[1]];
const squared = dx * dx + dz * dz; const squared = dx * dx + dz * dz;
@@ -79,10 +79,60 @@ function gridOrAligned(corners: readonly Vec2[], p: Vec2, o: SnapOptions): Snapp
} }
export function snapToPlan(p: Vec2, o: SnapOptions): Snapped { export function snapToPlan(p: Vec2, o: SnapOptions): Snapped {
const corners = o.rooms.flatMap((room) => room.points.filter((_, i) => !(o.skip && room.id === o.skip.roomId && (o.skip.index === undefined || o.skip.index === i)))); // Separate namespaces: imported room and outdoor IDs need not be unique across both collections.
const areas = (o.outdoor ?? []).filter((a) => a.id !== o.skip?.outdoorId);
const corners = [...o.rooms.flatMap((room) => room.points.filter((_, i) => !(o.skip && room.id === o.skip.roomId && (o.skip.index === undefined || o.skip.index === i)))), ...areas.flatMap((a) => a.points)];
const corner = nearestCorner(corners, p, o.reach); const corner = nearestCorner(corners, p, o.reach);
if (corner) return { point: [corner[0], corner[1]], guides: { point: corner } }; if (corner) return { point: [corner[0], corner[1]], guides: { point: corner } };
const wall = nearestOnWall(o.rooms, p, o); const wall = nearestOnWall([...o.rooms.filter((r) => r.id !== o.skip?.roomId), ...areas], p, { ...o, skip: undefined });
if (wall) return { point: [thousandths(wall[0]), thousandths(wall[1])], guides: { point: wall } }; if (wall) return { point: [thousandths(wall[0]), thousandths(wall[1])], guides: { point: wall } };
return gridOrAligned(corners, p, o); return gridOrAligned(corners, p, o);
} }
/** Translate an entire outline onto nearby corners/edges, preserving every length and angle. */
export function snapOutdoorMove(points: readonly Vec2[], delta: Vec2, o: SnapOptions): { by: Vec2; guides: Guides } {
const targets = [...o.rooms.filter((r) => r.id !== o.skip?.roomId), ...(o.outdoor ?? []).filter((a) => a.id !== o.skip?.outdoorId)];
const moved = points.map((p): Vec2 => [p[0] + delta[0], p[1] + delta[1]]);
const movingOpen = o.outdoor?.find((a) => a.id === o.skip?.outdoorId)?.open;
const grid: Vec2 = delta.map((v) => thousandths(Math.round(v / o.grid) * o.grid)) as Vec2;
let corner: { by: Vec2; point: Vec2 } | undefined;
let best = o.reach;
for (const p of moved) for (const area of targets) for (const q of area.points) {
const d = distance(p, q);
if (d < best) {
best = d;
corner = { by: [delta[0] + q[0] - p[0], delta[1] + q[1] - p[1]], point: q };
}
}
if (corner) return { by: corner.by.map(thousandths) as Vec2, guides: { point: corner.point } };
let x: { offset: number; at: number } | undefined;
let z: { offset: number; at: number } | undefined;
let diagonal: { correction: Vec2; point: Vec2; d: number } | undefined;
const inspect = (p: Vec2, a: Vec2, b: Vec2, reverse = false) => {
const dx = b[0] - a[0], dz = b[1] - a[1], squared = dx * dx + dz * dz;
if (squared < 1e-9) return;
const t = ((p[0] - a[0]) * dx + (p[1] - a[1]) * dz) / squared;
if (t < 0 || t > 1) return;
const foot: Vec2 = [a[0] + t * dx, a[1] + t * dz];
const d = distance(p, foot);
if (d >= o.reach) return;
const sign = reverse ? -1 : 1;
const correction: Vec2 = [sign * (foot[0] - p[0]), sign * (foot[1] - p[1])];
if (Math.abs(dx) < 1e-9) {
if (!x || d < Math.abs(x.offset)) x = { offset: correction[0], at: reverse ? p[0] : a[0] };
} else if (Math.abs(dz) < 1e-9) {
if (!z || d < Math.abs(z.offset)) z = { offset: correction[1], at: reverse ? p[1] : a[1] };
} else if (!diagonal || d < diagonal.d) diagonal = { correction, point: reverse ? p : foot, d };
};
for (const area of targets) {
const open = "open" in area && area.open;
for (let i = 0; i < area.points.length - (open ? 1 : 0); i++) {
const a = area.points[i], b = area.points[(i + 1) % area.points.length];
for (const p of moved) inspect(p, a, b);
}
// A longer moving edge can cover a shorter stationary edge without either moving corner projecting onto it.
for (const p of area.points) for (let i = 0; i < moved.length - (movingOpen ? 1 : 0); i++) inspect(p, moved[i], moved[(i + 1) % moved.length], true);
}
if (!x && !z && diagonal) return { by: [thousandths(delta[0] + diagonal.correction[0]), thousandths(delta[1] + diagonal.correction[1])], guides: { point: diagonal.point } };
return { by: [x ? thousandths(delta[0] + x.offset) : grid[0], z ? thousandths(delta[1] + z.offset) : grid[1]], guides: { ...(x ? { x: x.at } : {}), ...(z ? { z: z.at } : {}) } };
}
+26 -3
View File
@@ -2,6 +2,9 @@ import { css } from "lit";
/** The editor's own styles: the plan canvas, the side panel with its forms and libraries, the 3D pane and the phone layout. */ /** The editor's own styles: the plan canvas, the side panel with its forms and libraries, the 3D pane and the phone layout. */
export const editorStyles = css` export const editorStyles = css`
.nf-value-links h4 { margin: 12px 0; }
.nf-value-add { min-width: 30px; font-size: 18px; padding: 3px 8px; }
.nf-value-link { padding: 8px 0; border-bottom: 1px solid var(--nf-line); }
:host { :host {
display: block; display: block;
height: 100%; height: 100%;
@@ -959,13 +962,25 @@ export const editorStyles = css`
fill: rgba(61, 224, 160, 0.1); fill: rgba(61, 224, 160, 0.1);
stroke: rgba(61, 224, 160, 0.5); stroke: rgba(61, 224, 160, 0.5);
} }
.nf-out-pool polygon { .nf-out-pool polygon,
.nf-out-river polygon,
.nf-out-stream polygon {
fill: color-mix(in srgb, var(--nf-accent) 18%, transparent); fill: color-mix(in srgb, var(--nf-accent) 18%, transparent);
stroke: var(--nf-accent); stroke: var(--nf-accent);
} }
.nf-out-terrace polygon { .nf-out-terrace polygon {
fill: rgba(150, 130, 255, 0.12); fill: rgba(150, 130, 255, 0.12);
} }
.nf-out-street polygon {
fill: rgba(100, 110, 125, 0.28);
}
.nf-out-sidewalk polygon {
fill: rgba(175, 185, 200, 0.24);
}
.nf-out-gravel polygon {
fill: rgba(184, 163, 130, 0.24);
stroke: rgba(184, 163, 130, 0.65);
}
.nf-free-wall { .nf-free-wall {
cursor: grab; cursor: grab;
} }
@@ -982,13 +997,17 @@ export const editorStyles = css`
border-radius: 12px; border-radius: 12px;
background: color-mix(in srgb, var(--nf-accent) 6%, transparent); background: color-mix(in srgb, var(--nf-accent) 6%, transparent);
} }
.nf-edge-box h4 { .nf-edge-box > summary {
margin: 0 0 4px; cursor: pointer;
color: var(--nf-accent); color: var(--nf-accent);
font-size: 13px; font-size: 13px;
font-weight: 700;
letter-spacing: 0.06em; letter-spacing: 0.06em;
text-transform: uppercase; text-transform: uppercase;
} }
.nf-edge-box[open] > summary {
margin-bottom: 8px;
}
/* a wall row: name and length, the height, then the buttons (full height, no wall, cut) in one line; /* a wall row: name and length, the height, then the buttons (full height, no wall, cut) in one line;
a split point gets a line of its own below */ a split point gets a line of its own below */
.nf-edge-height { .nf-edge-height {
@@ -1996,4 +2015,8 @@ export const editorStyles = css`
font-size: 12.5px; font-size: 12.5px;
color: var(--nf-warm); 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,64 @@
import { html, nothing } from "lit";
import { UTILITY_KINDS, WEATHER_VARIABLE_KEYS, type BuildingSettings, type PresenceLink, type Room, type RoomHvac } from "../../model.ts";
import { UTILITY_ICONS, UTILITY_LABELS } from "../../utilities.ts";
import { WEATHER_VARIABLE_LABELS } from "../../symcon-weather.ts";
import { ROOM_HVAC_FIELDS } from "../../entities/room-hvac.ts";
import { isSymconVariable } from "../../entities/symcon-values.ts";
import { entityName } from "../../devices.ts";
import { entityOptions } from "./entities.ts";
import { checkField, entityField, hint, textField } from "./fields.ts";
import type { EditorHost } from "./host.ts";
export function renderSymconRoomMeters(host: EditorHost, room: Room, patch: (change: Partial<Room>) => void) {
const options = entityOptions(host.hass, (id) => isSymconVariable(host.hass, id, [1, 2]));
return html`<details class="nf-room-utility-meters"><summary>Eigene Raumzähler</summary><div class="nf-form">
${hint("Nur direkt zugewiesene Raumzähler erscheinen als eingerückte Raumzeile unter dem verknüpften Bereich. Die Bereichswerte stehen einmal beim Bereich; vorhandene Bereichssummen enthalten die Raumwerte bereits. Fehlt dem Bereich ein passender Zähler, werden dafür die eigenen Raumzähler summiert.", "nf-wide")}
${UTILITY_KINDS.map((kind) => html`<b class="nf-wide">${UTILITY_ICONS[kind]} ${UTILITY_LABELS[kind]}</b>${(["power", "energy"] as const).map((metric) => entityField(host, metric === "power" ? "Leistung / Durchfluss" : "Energie / Verbrauch", room.utility_meters?.[kind]?.[metric] ?? null, undefined, options, (v) => {
const meters = { ...room.utility_meters, [kind]: { ...room.utility_meters?.[kind], [metric]: v === "none" ? null : v } };
if (!Object.values(meters[kind]!).some((id) => id && id !== "none")) delete meters[kind];
patch({ utility_meters: Object.keys(meters).length ? meters : null });
}, { types: [1, 2] }))}`)}
</div></details>`;
}
export function renderSymconRoomHvac(host: EditorHost, room: Room, patch: (change: Partial<Room>) => void) {
const set = (change: Partial<RoomHvac>) => patch({ hvac: { ...room.hvac, ...change } });
const schedules = room.hvac?.schedules ?? [];
const plans = entityOptions(host.hass, (id) => !!host.hass?.states[id]?.attributes.symcon_schedule);
return html`
${entityField(host, host.t("floor_heating"), room.floor_heating ?? null, undefined, entityOptions(host.hass, (id) => isSymconVariable(host.hass, id, [0, 1, 2])), (v) => patch({ floor_heating: v === "none" ? null : v }), { types: [0, 1, 2] })}
${ROOM_HVAC_FIELDS.map((field) => entityField(host, field.label, room.hvac?.[field.key] ?? null, undefined, entityOptions(host.hass, (id) => isSymconVariable(host.hass, id, field.types)), (v) => set({ [field.key]: v === "none" ? null : v }), { types: field.types }))}
${hint("Raumstatus zeigt den in Symcon hinterlegten Alias der Integer-Variable. Beschreibbare Heizungs- und Lüftungswerte können im Raummenü bedient werden.", "nf-wide")}
${schedules.map((id, i) => entityField(host, `Schaltuhr ${i + 1}`, id, undefined, plans.filter((p) => p.id === id || !schedules.includes(p.id)), (v) => set({ schedules: v && v !== "none" ? schedules.map((old, j) => i === j ? v : old) : schedules.filter((_, j) => i !== j) }), { schedule: true, excluded: (entity) => schedules.includes(entity) ? "Diese Schaltuhr ist in diesem Raum bereits verknüpft." : undefined }))}
${entityField(host, "Schaltuhr hinzufügen", null, undefined, plans.filter((p) => !schedules.includes(p.id)), (v) => v && v !== "none" && set({ schedules: [...schedules, v] }), { schedule: true, excluded: (entity) => schedules.includes(entity) ? "Diese Schaltuhr ist in diesem Raum bereits verknüpft." : undefined })}`;
}
export function renderSymconWeather(host: EditorHost, settings: BuildingSettings, set: (change: Partial<BuildingSettings>) => void) {
const types = (key: string) => key === "condition" ? [0, 1, 2, 3] : key === "wind_bearing" ? [1, 2, 3] : ["snow", "fog", "lightning"].includes(key) ? [0, 1, 2] : [1, 2];
return html`<details class="nf-wide nf-symcon-weather"><summary>Wettervariablen</summary><div class="nf-form">
${WEATHER_VARIABLE_KEYS.map((key) => entityField(host, WEATHER_VARIABLE_LABELS[key], settings.weather_variables?.[key] ?? null, undefined,
entityOptions(host.hass, (id) => isSymconVariable(host.hass, id, types(key))),
(v) => set({ weather_variables: { ...settings.weather_variables, [key]: v === "none" ? null : v } }), { types: types(key) }))}
${entityField(host, host.t("rain_sensor"), settings.rain_sensor ?? null, undefined, entityOptions(host.hass, (id) => isSymconVariable(host.hass, id, [0, 1, 2])), (v) => set({ rain_sensor: v === "none" ? null : v }), { types: [0, 1, 2] })}
${settings.rain_sensor ? checkField(host, host.t("rain_sensor_inverted"), !!settings.rain_sensor_inverted, (on) => set({ rain_sensor_inverted: on || undefined })) : nothing}
${hint("Wähle die Wetterwerte einzeln aus dem Symcon-Objektbaum. Einheiten werden aus den Variablen übernommen. Der Regensensor kann Boolean oder eine numerische Regenrate sein.", "nf-wide")}
</div></details>`;
}
export function renderSymconPresence(host: EditorHost) {
const links = host.doc.presence;
const replace = (next: PresenceLink[]) => host.replace({ ...structuredClone(host.doc), presence: next });
const patch = (i: number, change: Partial<PresenceLink>) => replace(links.map((link, j) => j === i ? { ...link, ...change, sensor: null } : link));
const rooms = host.doc.floors.flatMap((f) => f.rooms.map((r) => ({ id: r.id, name: `${f.name} · ${r.name}` })));
const options = entityOptions(host.hass, (id) => isSymconVariable(host.hass, id, [0]));
return html`<details class="nf-section nf-symcon-presence"><summary>${host.t("presence")}</summary>
${links.map((link, i) => html`<div class="nf-form">
${textField(host, "Person", link.name ?? entityName(host.hass, link.person), (name) => patch(i, { name }), { wide: true, maxlength: 100 })}
${entityField(host, "Anwesenheit (Boolean)", link.person, undefined, options.filter((o) => o.id === link.person || !links.some((l) => l.person === o.id)), (v) => v && v !== "none" ? patch(i, { person: v }) : replace(links.filter((_, j) => j !== i)), { types: [0], excluded: (entity) => links.some((l) => l.person === entity) ? "Diese Anwesenheitsvariable ist bereits mit einer Person verknüpft." : undefined })}
<label class="nf-field nf-wide">Raum für die 3D-Anzeige<select ?disabled=${!host.admin} .value=${link.room ?? ""} @change=${(e: Event) => patch(i, { room: (e.target as HTMLSelectElement).value || null })}><option value="">Kein Raum</option>${rooms.map((r) => html`<option value=${r.id}>${r.name}</option>`)}</select></label>
<button class="nf-link nf-wide" ?disabled=${!host.admin} @click=${() => replace(links.filter((_, j) => j !== i))}>× Person entfernen</button>
</div>`)}
<div class="nf-form">${entityField(host, "Person hinzufügen (Boolean)", null, undefined, options.filter((o) => !links.some((l) => l.person === o.id)), (v) => v && v !== "none" && replace([...links, { person: v, sensor: null }]), { types: [0], excluded: (entity) => links.some((l) => l.person === entity) ? "Diese Anwesenheitsvariable ist bereits mit einer Person verknüpft." : undefined })}</div>
${hint("Jede Person wird mit einer beliebigen Boolean-Variable verknüpft: true bedeutet anwesend, false abwesend. Ein Raum ist optional und bestimmt die Position der Person in 3D.")}
</details>`;
}
+2 -1
View File
@@ -9,6 +9,7 @@ import { openingPreset } from "../../model.ts";
import type { EditorHost } from "./host.ts"; import type { EditorHost } from "./host.ts";
import { furnitureAt, openingAt, wallElevation, wallFrame, type ElevationBox } from "./ops/wall-view.ts"; import { furnitureAt, openingAt, wallElevation, wallFrame, type ElevationBox } from "./ops/wall-view.ts";
import { formatLength } from "../../units.ts"; import { formatLength } from "../../units.ts";
import { hint } from "./fields.ts";
const SNAP = 0.01; const SNAP = 0.01;
const snap = (v: number) => Math.round(v / SNAP) * SNAP; const snap = (v: number) => Math.round(v / SNAP) * SNAP;
@@ -172,7 +173,7 @@ export class NfWallView extends LitElement {
<input type="number" step="0.01" min="0" .value=${sel.y0.toFixed(2)} ?disabled=${!this.host.admin} @change=${(e: Event) => this.place(sel, sel.x0, Number((e.target as HTMLInputElement).value))} <input type="number" step="0.01" min="0" .value=${sel.y0.toFixed(2)} ?disabled=${!this.host.admin} @change=${(e: Event) => this.place(sel, sel.x0, Number((e.target as HTMLInputElement).value))}
/></label>` /></label>`
: nothing}` : nothing}`
: html`<span class="muted">${t("wall_view_hint")}</span>`} : hint(t("wall_view_hint"))}
</footer> </footer>
</div> </div>
</div>`; </div>`;
+18
View File
@@ -4,12 +4,17 @@
import { css, html, LitElement, nothing } from "lit"; import { css, html, LitElement, nothing } from "lit";
import { tokens } from "../styles.ts"; import { tokens } from "../styles.ts";
import type { SymconObject } from "../types.ts";
import type { PickerContext } from "./picker-rejection.ts";
import "./symcon-object-picker.ts";
export interface PickerOption { export interface PickerOption {
id: string; id: string;
label: string; label: string;
/** Secondary, non-editable context such as an IP-Symcon object-tree path. */ /** Secondary, non-editable context such as an IP-Symcon object-tree path. */
detail?: string; detail?: string;
/** Native variable entity behind an explicit Symcon light/cover role. */
sourceEntity?: string;
} }
const MAX_SHOWN = 40; const MAX_SHOWN = 40;
@@ -17,6 +22,8 @@ const MAX_SHOWN = 40;
export class EntityPicker extends LitElement { export class EntityPicker extends LitElement {
static properties = { static properties = {
options: { attribute: false }, options: { attribute: false },
objectTree: { attribute: false },
context: { attribute: false },
fixed: { attribute: false }, fixed: { attribute: false },
value: { attribute: false }, value: { attribute: false },
disabled: { type: Boolean }, disabled: { type: Boolean },
@@ -28,6 +35,8 @@ export class EntityPicker extends LitElement {
/** Entities to choose from. */ /** Entities to choose from. */
declare options: PickerOption[]; declare options: PickerOption[];
declare objectTree: readonly SymconObject[] | undefined;
declare context: PickerContext | undefined;
/** Choices shown before the entities (e.g. automatic, none); ids must not look like entity ids. */ /** Choices shown before the entities (e.g. automatic, none); ids must not look like entity ids. */
declare fixed: PickerOption[]; declare fixed: PickerOption[];
/** The chosen id (an option's or a fixed choice's). */ /** The chosen id (an option's or a fixed choice's). */
@@ -42,6 +51,7 @@ export class EntityPicker extends LitElement {
constructor() { constructor() {
super(); super();
this.options = []; this.options = [];
this.objectTree = undefined;
this.fixed = []; this.fixed = [];
this.value = null; this.value = null;
this.disabled = false; this.disabled = false;
@@ -105,6 +115,12 @@ export class EntityPicker extends LitElement {
} }
protected render() { protected render() {
if (this.objectTree !== undefined) return html`<nf-symcon-object-picker
.objects=${this.objectTree} .options=${this.options} .fixed=${this.fixed} .value=${this.value}
.context=${this.context}
.disabled=${this.disabled} .placeholder=${this.placeholder}
@change=${(event: CustomEvent<{ value: string | null }>) => { this.value = event.detail.value; }}
></nf-symcon-object-picker>`;
const current = this.current; const current = this.current;
const hits = this._open ? this.hits : []; const hits = this._open ? this.hits : [];
return html`<div class="wrap"> return html`<div class="wrap">
@@ -157,6 +173,8 @@ export class EntityPicker extends LitElement {
:host { :host {
display: block; display: block;
position: relative; position: relative;
min-width: 0;
max-width: 100%;
} }
input { input {
width: 100%; width: 100%;
+34
View File
@@ -0,0 +1,34 @@
import { css, html, LitElement } from "lit";
import { tokens } from "../styles.ts";
/** Explanations stay reachable by keyboard without taking space in the form. */
export class NfHelpPopup extends LitElement {
static properties = { text: { attribute: false } };
declare text: string;
constructor() { super(); this.text = ""; }
private get dialog() { return this.renderRoot.querySelector<HTMLDialogElement>("dialog"); }
render() {
return html`<button class="info" type="button" aria-label="Information anzeigen" aria-haspopup="dialog" title="Information" @click=${() => this.dialog?.showModal()}>ⓘ</button>
<dialog aria-label="Information" @keydown=${(event: KeyboardEvent) => event.stopPropagation()} @click=${(event: MouseEvent) => {
if (event.target !== event.currentTarget) return;
const r = this.dialog!.getBoundingClientRect();
if (event.clientX < r.left || event.clientX > r.right || event.clientY < r.top || event.clientY > r.bottom) this.dialog?.close();
}}>
<header><b>Information</b><button class="close" type="button" aria-label="Schließen" @click=${() => this.dialog?.close()}>×</button></header>
<p>${this.text}</p>
</dialog>`;
}
static styles = [tokens, css`
:host { display:inline-block; margin:4px 0; vertical-align:middle; }
button { font:inherit; cursor:pointer; color:var(--nf-muted); background:transparent; border:1px solid var(--nf-line); border-radius:50%; pointer-events:auto; }
.info { width:26px; height:26px; padding:0; font-size:18px; line-height:24px; }
button:hover { color:var(--nf-accent); }
button:focus-visible { outline:2px solid var(--nf-accent); outline-offset:2px; }
dialog { box-sizing:border-box; width:min(560px,calc(100vw - 32px)); max-height:80vh; max-height:80dvh; overflow:auto; padding:18px 22px; border:1px solid var(--nf-line); border-radius:14px; background:var(--nf-chrome-solid); color:var(--nf-text); font:14px/1.5 system-ui,sans-serif; box-shadow:var(--nf-shadow); pointer-events:auto; }
dialog::backdrop { background:#050b16a6; }
header { display:flex; align-items:center; justify-content:space-between; gap:20px; font-size:16px; }
.close { width:30px; height:30px; padding:0; font-size:23px; }
p { white-space:pre-wrap; overflow-wrap:anywhere; margin:16px 0 4px; }
`];
}
if (!customElements.get("nf-help-popup")) customElements.define("nf-help-popup", NfHelpPopup);
+121
View File
@@ -0,0 +1,121 @@
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";
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" };
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 = 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") { 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);
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),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}
${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,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 }, 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();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;
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),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}
${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}.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, focusStation?:string): Promise<void> {
activeDialog?.remove();
const dialog = document.createElement("nf-hydronic-dialog") as HydronicDialog;
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;
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);
+4 -3
View File
@@ -9,6 +9,7 @@ import type { FurniturePack } from "../packs.ts";
import { controls, tokens } from "../styles.ts"; import { controls, tokens } from "../styles.ts";
import type { HomeAssistant } from "../types.ts"; import type { HomeAssistant } from "../types.ts";
import type { ModelInfo } from "../viewer/viewer3d.ts"; import type { ModelInfo } from "../viewer/viewer3d.ts";
import { hint } from "./editor/fields.ts";
type Present = "unknown" | "yes" | "no"; type Present = "unknown" | "yes" | "no";
@@ -214,7 +215,7 @@ export class NfModelUpload extends LitElement {
<button class="nf-btn" @click=${() => this.turn(-1)}>↺ 90°</button> <button class="nf-btn" @click=${() => this.turn(-1)}>↺ 90°</button>
<button class="nf-btn" @click=${() => this.turn(1)}>↻ 90°</button> <button class="nf-btn" @click=${() => this.turn(1)}>↻ 90°</button>
</div> </div>
<small class="nf-sub">${this.t("model_front_hint")}</small> ${hint(this.t("model_front_hint"))}
</div> </div>
<div class="nf-field"> <div class="nf-field">
<span>${this.t("model_paint")}</span> <span>${this.t("model_paint")}</span>
@@ -242,12 +243,12 @@ export class NfModelUpload extends LitElement {
if (slots.length === 0 || !(this.hass?.user?.is_admin ?? false)) return nothing; if (slots.length === 0 || !(this.hass?.user?.is_admin ?? false)) return nothing;
return html`<section class="nf-ext-card"> return html`<section class="nf-ext-card">
<h3>${this.t("models")}</h3> <h3>${this.t("models")}</h3>
<p class="nf-sub">${this.t("models_hint")}</p> ${hint(this.t("models_hint"))}
${slots.map((slot) => this.row(slot))} ${slots.map((slot) => this.row(slot))}
${this._draft ? this.editor(this._draft) : nothing} ${this._draft ? this.editor(this._draft) : nothing}
${this._busy && !this._draft ? html`<p class="nf-sub">${this.t("loading")}</p>` : nothing} ${this._busy && !this._draft ? html`<p class="nf-sub">${this.t("loading")}</p>` : nothing}
${this._message ? html`<p class="nf-sub ${this._message.ok ? "nf-notice" : "nf-pack-error"}">${this._message.text}</p>` : nothing} ${this._message ? html`<p class="nf-sub ${this._message.ok ? "nf-notice" : "nf-pack-error"}">${this._message.text}</p>` : nothing}
<p class="nf-sub">${this.t("models_licence")}</p> ${hint(this.t("models_licence"))}
</section>`; </section>`;
} }
@@ -0,0 +1,37 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { entity } from "../entities/fixtures.ts";
import type { SymconObject } from "../types.ts";
import { pickerRejection } from "./picker-rejection.ts";
const node = (object_type: number, entity_id?: string): SymconObject => ({ object_id: 123, parent_id: 0, name: "Value", path: "Haus / Garage / Value", object_type, entity_id, hidden: false, position: 0, icon: "" });
test("rejections distinguish a native datatype mismatch from an unavailable value", () => {
const states = { "cover.123": entity("cover.123", "unavailable", { symcon_variable_type: 0 }) };
const reason = pickerRejection(node(2, "cover.123"), { label: "Leistung", types: [1, 2], states });
assert.match(reason, /Datentyp Boolean/);
assert.match(reason, /Integer oder Float/);
assert.ok(!reason.includes("cover.123"));
assert.match(pickerRejection(node(2, "cover.123"), { states, excluded: () => "Bereits verknüpft." }), /Bereits verknüpft/);
});
test("missing data, instances, categories, broken links and unsupported schedules have distinct guidance", () => {
assert.match(pickerRejection(node(2), {}), /noch nicht geladen.*neu/);
assert.match(pickerRejection(node(2, "sensor.123"), { states: {} }), /nicht mehr vorhanden/);
assert.match(pickerRejection(node(2, "sensor.123"), { states: { "sensor.123": entity("sensor.123", "1") } }), /native Datentyp.*neu/);
assert.match(pickerRejection(node(1)), /Instanz.*Variable/);
assert.match(pickerRejection(node(0)), /Kategorie.*auf/);
assert.match(pickerRejection(node(6)), /Link.*direkt/);
assert.match(pickerRejection(node(4)), /keine unterstützte.*Schaltuhr/);
assert.match(pickerRejection(node(2, "sensor.123"), { schedule: true }), /Wochenplan-Ereignis.*keine Variable/);
assert.equal(pickerRejection(node(2, "sensor.123"), { unsupported: "Eine Variable ist kein Kalender." }), "Eine Variable ist kein Kalender.");
});
test("a remaining field exclusion reports native metadata without making up a restriction", () => {
const reason = pickerRejection(node(2, "cover.123"), { label: "Eigener Filter", states: { "cover.123": entity("cover.123", "open", { symcon_variable_type: 2, unit_of_measurement: "W" }) } });
assert.match(reason, /Eigener Filter/);
assert.match(reason, /Datentyp: Float/);
assert.match(reason, /Einheit: W/);
assert.match(reason, /erkannte Funktion: Jalousie/);
assert.ok(!reason.includes("Name") && !reason.includes("Schaltaktion"), "only known exclusion details are reported");
});
@@ -0,0 +1,49 @@
import type { HassEntity, SymconObject } from "../types.ts";
/** The field's native requirements, kept separate from the selectable options. */
export interface PickerRequirement {
label?: string;
types?: readonly number[];
/** Explicit purpose of a control; never inferred from the variable's name or path. */
role?: "light" | "cover";
schedule?: boolean;
/** A capability the native variable source cannot supply (e.g. a calendar). */
unsupported?: string;
/** A more specific exclusion, e.g. a variable already used by another entry. */
excluded?: (entity: string) => string | undefined;
}
export interface PickerContext extends PickerRequirement {
states?: Record<string, HassEntity>;
}
const DATA_TYPES = ["Boolean", "Integer", "Float", "String"];
const FUNCTIONS: Record<string, string> = { light: "Licht", cover: "Jalousie/Tor", switch: "Schalter", binary_sensor: "Binärsensor", sensor: "Sensor", climate: "Heizung", lock: "Schloss", script: "Skript", schedule: "Schaltuhr", media_player: "Mediengerät", fan: "Lüfter" };
/** Explain an actual rejected selection without guessing at missing metadata or exposing synthetic IDs. */
export function pickerRejection(node: SymconObject, context: PickerContext = {}): string {
if (node.virtual || node.object_type === 0) return "Das ist eine Kategorie. Klappe sie auf und wähle den Datenpunkt darunter aus.";
if (node.object_type === 1) return "Das ist eine Instanz. Klappe sie auf und wähle ihre Variable aus, zum Beispiel „Value“.";
if (context.schedule && node.object_type !== 4) return "Hier wird eine klassische Symcon-Schaltuhr (Wochenplan-Ereignis) erwartet, keine Variable.";
if (context.unsupported) return context.unsupported;
if (!node.entity_id) {
if (node.object_type === 2) return "Diese Variable wurde noch nicht geladen. Lade die Variablen oben in der Titelleiste neu und öffne die Auswahl erneut.";
if (node.object_type === 6) return "Dieser Link verweist auf keinen unterstützten Datenpunkt. Wähle die Variable direkt im Objektbaum aus.";
if (node.object_type === 4) return "Dieses Ereignis ist keine unterstützte klassische Symcon-Schaltuhr (Wochenplan).";
return "Dieser Objekttyp kann in diesem Feld nicht verknüpft werden. Wähle eine passende Variable aus.";
}
const state = context.states?.[node.entity_id];
if (context.states && !state) return "Diese Variable ist im aktuellen Datenbestand nicht mehr vorhanden. Lade die Variablen oben in der Titelleiste neu.";
const type = state?.attributes.symcon_variable_type;
const actual = type === undefined ? undefined : DATA_TYPES[Number(type)];
if (state && !state.attributes.symcon_schedule && !actual) return "Der native Datentyp dieser Variable ist nicht verfügbar. Lade die Variablen oben in der Titelleiste neu.";
if (actual && context.types && !context.types.includes(Number(type))) {
return `Datentyp ${actual} passt hier nicht. Für „${context.label || "dieses Feld"}“ wird ${context.types.map((t) => DATA_TYPES[t]).join(" oder ")} benötigt.`;
}
const excluded = context.excluded?.(node.entity_id);
if (excluded) return excluded;
const kind = FUNCTIONS[node.entity_id.split(".")[0]];
const unit = state?.attributes.unit_of_measurement;
const details = [actual && `Datentyp: ${actual}`, unit && `Einheit: ${unit}`, kind && `erkannte Funktion: ${kind}`].filter(Boolean).join(" · ");
return `Dieser Datenpunkt erfüllt den Filter${context.label ? ` für „${context.label}“` : " dieses Feldes"} nicht.${details ? ` ${details}.` : ""}`;
}
+9 -5
View File
@@ -7,6 +7,7 @@ import { translate, type I18nKey } from "../i18n.ts";
import { openMoreInfo, stateText } from "../markers.ts"; import { openMoreInfo, stateText } from "../markers.ts";
import { tokens } from "../styles.ts"; import { tokens } from "../styles.ts";
import type { HassEntity, HomeAssistant } from "../types.ts"; import type { HassEntity, HomeAssistant } from "../types.ts";
import { coverWithTilt } from "../entities/covers.ts";
const COLORS: [number, number, number][] = [ const COLORS: [number, number, number][] = [
[255, 181, 71], [255, 181, 71],
@@ -45,6 +46,7 @@ export class NfQuickMenu extends LitElement {
presets: { attribute: false }, presets: { attribute: false },
confirmSwitch: { type: Boolean }, confirmSwitch: { type: Boolean },
myPosition: { attribute: false }, myPosition: { attribute: false },
tiltEntity: { attribute: false },
low: { type: Boolean, reflect: true }, low: { type: Boolean, reflect: true },
}; };
@@ -58,6 +60,7 @@ export class NfQuickMenu extends LitElement {
declare confirmSwitch: boolean; declare confirmSwitch: boolean;
/** Blinds: the favourite position (Somfy's "My", %), a button in the ring moves there; null = none. */ /** Blinds: the favourite position (Somfy's "My", %), a button in the ring moves there; null = none. */
declare myPosition: number | null; declare myPosition: number | null;
declare tiltEntity: string | null;
/** Tablet level: no blur behind the menu. */ /** Tablet level: no blur behind the menu. */
declare low: boolean; declare low: boolean;
private t(key: I18nKey, vars?: Record<string, string | number>): string { private t(key: I18nKey, vars?: Record<string, string | number>): string {
@@ -125,6 +128,7 @@ export class NfQuickMenu extends LitElement {
} }
private renderCover(st: HassEntity) { private renderCover(st: HassEntity) {
st = coverWithTilt(this.hass, st, this.tiltEntity);
const pos = typeof st.attributes.current_position === "number" ? (st.attributes.current_position as number) : null; const pos = typeof st.attributes.current_position === "number" ? (st.attributes.current_position as number) : null;
const moving = st.state === "opening" || st.state === "closing"; const moving = st.state === "opening" || st.state === "closing";
const setPos = coverPositionable(st); const setPos = coverPositionable(st);
@@ -138,9 +142,9 @@ export class NfQuickMenu extends LitElement {
...(setPos ? [75, 50].map((p) => slot(`${p}`, `${p} %`, () => this.ask() && this.call("cover", "set_cover_position", { position: p }), at(p))) : []), ...(setPos ? [75, 50].map((p) => slot(`${p}`, `${p} %`, () => this.ask() && this.call("cover", "set_cover_position", { position: p }), at(p))) : []),
slot("▼", this.t("cover_close"), () => this.ask() && this.call("cover", "close_cover"), at(0)), slot("▼", this.t("cover_close"), () => this.ask() && this.call("cover", "close_cover"), at(0)),
...(setPos ? [25].map((p) => slot(`${p}`, `${p} %`, () => this.ask() && this.call("cover", "set_cover_position", { position: p }), at(p))) : []), ...(setPos ? [25].map((p) => slot(`${p}`, `${p} %`, () => this.ask() && this.call("cover", "set_cover_position", { position: p }), at(p))) : []),
slot("■", this.t("cover_stop"), () => this.call("cover", "stop_cover"), moving), ...(Number(st.attributes.supported_features ?? 0) & 8 ? [slot("■", this.t("cover_stop"), () => this.call("cover", "stop_cover"), moving)] : []),
// the favourite position: a cover that sets positions goes there; a Somfy RTS motor without feedback goes to its own "My" on stop // the favourite position: a cover that sets positions goes there; a Somfy RTS motor without feedback goes to its own "My" on stop
...(this.myPosition != null ...(this.myPosition != null && (setPos || Number(st.attributes.supported_features ?? 0) & 8)
? [slot("My", this.t("cover_my_go", { p: this.myPosition }), () => this.ask() && (setPos ? this.call("cover", "set_cover_position", { position: this.myPosition }) : this.call("cover", "stop_cover")), at(this.myPosition))] ? [slot("My", this.t("cover_my_go", { p: this.myPosition }), () => this.ask() && (setPos ? this.call("cover", "set_cover_position", { position: this.myPosition }) : this.call("cover", "stop_cover")), at(this.myPosition))]
: []), : []),
]; ];
@@ -158,7 +162,7 @@ export class NfQuickMenu extends LitElement {
@click=${() => (moving ? this.call("cover", "stop_cover") : this.ask() && this.call("cover", closed > 50 ? "open_cover" : "close_cover"))} @click=${() => (moving ? this.call("cover", "stop_cover") : this.ask() && this.call("cover", closed > 50 ? "open_cover" : "close_cover"))}
> >
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 4h16M5 4v15M19 4v15M7 8h10M7 12h10M7 16h10" /></svg> <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 4h16M5 4v15M19 4v15M7 8h10M7 12h10M7 16h10" /></svg>
<b>${pos !== null ? `${pos} %` : stateText(this.hass, st)}</b> <b>${pos !== null ? `${Math.round(pos)} %` : stateText(this.hass, st)}</b>
</button> </button>
</div> </div>
${setPos ${setPos
@@ -181,7 +185,7 @@ export class NfQuickMenu extends LitElement {
const tilt = typeof st.attributes.current_tilt_position === "number" ? (st.attributes.current_tilt_position as number) : null; const tilt = typeof st.attributes.current_tilt_position === "number" ? (st.attributes.current_tilt_position as number) : null;
if (features & COVER_SET_TILT && tilt !== null) if (features & COVER_SET_TILT && tilt !== null)
return html`<label class="qm-tilt" return html`<label class="qm-tilt"
><span>${this.t("cover_tilt")} · ${tilt} %</span> ><span>${this.t("cover_tilt")} · ${Math.round(tilt)} %</span>
<input <input
class="qm-slider" class="qm-slider"
type="range" type="range"
@@ -189,7 +193,7 @@ export class NfQuickMenu extends LitElement {
max="100" max="100"
.value=${String(tilt)} .value=${String(tilt)}
aria-label=${this.t("cover_tilt")} aria-label=${this.t("cover_tilt")}
@change=${(e: Event) => this.call("cover", "set_cover_tilt_position", { tilt_position: Number((e.target as HTMLInputElement).value) })} @change=${(e: Event) => this.call("cover", "set_cover_tilt_position", { entity_id: st.attributes.nf_cover_control ? this.entity : this.tiltEntity || this.entity, tilt_position: Number((e.target as HTMLInputElement).value) })}
/></label>`; /></label>`;
if (features & (COVER_OPEN_TILT | COVER_CLOSE_TILT)) if (features & (COVER_OPEN_TILT | COVER_CLOSE_TILT))
return html`<div class="qm-tilt-buttons"> return html`<div class="qm-tilt-buttons">
+91
View File
@@ -0,0 +1,91 @@
import { css, html, LitElement, nothing } from "lit";
import type { Room } from "../model.ts";
import type { HomeAssistant } from "../types.ts";
import { ROOM_HVAC_FIELDS } from "../entities/room-hvac.ts";
import { nativeBool, nativeNumber, nativeText, nativeValue } from "../entities/symcon-values.ts";
import { controls, tokens } from "../styles.ts";
import { trendButton } from "./trend-button.ts";
interface SchedulePoint { hour: number; minute: number; second: number; action: number }
interface ScheduleGroup { id: number; days: number; points: SchedulePoint[] }
interface ScheduleAction { id: number; name: string; color: number }
export class NfRoomHvac extends LitElement {
static properties = { hass: { attribute: false }, room: { attribute: false }, _pending: { state: true }, _error: { state: true } };
declare hass: HomeAssistant;
declare room: Room;
private declare _pending: Set<string>;
private declare _error: string;
constructor() { super(); this._pending = new Set(); this._error = ""; }
private async send(id: string, domain: string, service: string, data: Record<string, unknown>) {
this._pending = new Set([...this._pending, id]);
this._error = "";
try { await this.hass.callService(domain, service, { entity_id: id, ...data }); }
catch (error) { this._error = error instanceof Error ? error.message : String(error); }
finally { this._pending = new Set([...this._pending].filter((x) => x !== id)); }
}
private value(label: string, id: string, control: boolean) {
const st = this.hass.states[id], value = nativeValue(st), a = st?.attributes;
const writable = control && !!a?.symcon_has_action && value !== null && !this._pending.has(id);
return html`<div class="value"><span>${label}</span><b>${nativeText(st)}${trendButton(this.hass, [id], label)}</b>
${control && a?.symcon_has_action && a.symcon_variable_type === 0 ? html`<button class="nf-chip" aria-pressed=${nativeBool(st) === true} ?disabled=${!writable} @click=${() => void this.send(id, "symcon", "set_value", { value: !nativeBool(st) })}>${nativeBool(st) ? "Ein" : "Aus"}</button>`
: control && a?.symcon_has_action && [1, 2].includes(Number(a.symcon_variable_type)) ? html`<input type="number" aria-label=${label} .value=${String(nativeNumber(st) ?? "")} min=${String(a.symcon_min ?? 0)} max=${String(a.symcon_max ?? 100)} step=${String(a.symcon_step || (a.symcon_variable_type === 1 ? 1 : 0.1))} ?disabled=${!writable}
@change=${(event: Event) => { const input = event.target as HTMLInputElement; if (input.value.trim() && input.checkValidity()) void this.send(id, "symcon", "set_value", { value: Number(input.value) }); }} />` : nothing}
</div>`;
}
private schedule(id: string) {
const st = this.hass.states[id];
if (!st?.attributes.symcon_schedule) return html`<p class="missing">Schaltuhr nicht verfügbar</p>`;
const actions = (st.attributes.actions ?? []) as ScheduleAction[];
const groups = (st.attributes.groups ?? []) as ScheduleGroup[];
const next = Number(st.attributes.next_run ?? 0);
const nextAction = actions.find((a) => a.id === st.attributes.next_action);
const days = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"];
const time = (p: SchedulePoint) => `${String(p.hour).padStart(2, "0")}:${String(p.minute).padStart(2, "0")}${p.second ? `:${String(p.second).padStart(2, "0")}` : ""}`;
return html`<details class="schedule"><summary>${String(st.attributes.friendly_name ?? "Schaltuhr")}</summary>
<label class="nf-check"><input type="checkbox" .checked=${st.state === "on"} ?disabled=${this._pending.has(id)} @change=${(e: Event) => void this.send(id, "schedule", "set_active", { active: (e.target as HTMLInputElement).checked })} /> Aktiv</label>
${next > 0 ? html`<p class="next">Nächster Schaltpunkt: ${new Date(next * 1000).toLocaleString(this.hass.language)}${nextAction ? ` · ${nextAction.name}` : ""}</p>` : nothing}
${groups.length ? groups.map((group) => html`<div class="schedule-group"><b>${days.filter((_, i) => group.days & (1 << i)).join(" · ")}</b><div class="points">
${[...group.points].sort((a, b) => a.hour * 3600 + a.minute * 60 + a.second - (b.hour * 3600 + b.minute * 60 + b.second)).map((point) => {
const action = actions.find((a) => a.id === point.action);
return html`<span class="point"><time>${time(point)}</time><span class="dot" style=${`background:#${Number(action?.color ?? 0x8796a9).toString(16).padStart(6, "0").slice(-6)}`}></span>${action?.name || "Aktion"}</span>`;
})}
</div></div>`) : html`<p class="missing">Keine Schaltpunkte vorhanden.</p>`}
</details>`;
}
render() {
if (!this.hass || !this.room) return nothing;
const rows = ROOM_HVAC_FIELDS.filter((field) => field.key !== "status" && this.room.hvac?.[field.key] && this.room.hvac[field.key] !== "none");
const plans = this.room.hvac?.schedules ?? [];
const heating = this.room.floor_heating && this.room.floor_heating !== "none" ? this.room.floor_heating : null;
return html`${heating || rows.length ? html`<section><h3>Raumklima</h3>${heating ? this.value("Fußbodenheizung", heating, true) : nothing}${rows.map((field) => this.value(field.label, this.room.hvac![field.key]!, !!field.control))}</section>` : nothing}
${plans.length ? html`<section><h3>Schaltuhren</h3>${plans.map((id) => this.schedule(id))}</section>` : nothing}
${this._error ? html`<p role="alert" class="error">${this._error}</p>` : nothing}`;
}
static styles = [tokens, controls, css`
:host { display:block; }
section { margin:18px 0; }
h3 { font-size:12px; text-transform:uppercase; letter-spacing:.05em; color:var(--nf-muted); margin:0 0 8px; }
.value { display:grid; grid-template-columns:minmax(0,1fr) auto; gap:8px; align-items:center; padding:10px 0; border-bottom:1px solid var(--nf-line); }
.value b { font-size:13px; color:var(--nf-muted); }
.value input,.value button { grid-column:2; max-width:110px; min-width:0; }
input[type=number] { background:var(--nf-fill); color:var(--nf-text); border:1px solid var(--nf-line); border-radius:8px; padding:6px 8px; font:inherit; box-sizing:border-box; }
.schedule { margin:8px 0; padding:10px; border:1px solid var(--nf-line); border-radius:10px; }
summary { cursor:pointer; font-weight:600; }
.nf-check { margin-top:10px; }
.next,.missing { color:var(--nf-muted); font-size:12px; }
.schedule-group { padding:10px 0; border-top:1px solid var(--nf-line); font-size:12px; }
.points { display:flex; gap:6px 14px; flex-wrap:wrap; margin-top:8px; }
.point { display:inline-flex; align-items:center; gap:6px; }
.point time { font-variant-numeric:tabular-nums; }
.dot { width:8px; height:8px; border-radius:50%; }
.error { color:var(--nf-danger,#ff6b7a); font-size:12px; }
`];
}
if (!customElements.get("nf-room-hvac")) customElements.define("nf-room-hvac", NfRoomHvac);
+52 -21
View File
@@ -8,6 +8,11 @@ import { iconPath } from "../icons.ts";
import { openMoreInfo, stateText } from "../markers.ts"; import { openMoreInfo, stateText } from "../markers.ts";
import { pluginRoomSections } from "../plugins/registry.ts"; import { pluginRoomSections } from "../plugins/registry.ts";
import { canAnnounce, roomHasSpeaker } from "../live/announce.ts"; import { canAnnounce, roomHasSpeaker } from "../live/announce.ts";
import { isSymcon, nativeText } from "../entities/symcon-values.ts";
import "./room-hvac.ts";
import "./utility-report.ts";
import { roomUtilityReadings, utilityText } from "../utilities.ts";
import { trendButton } from "./trend-button.ts";
import type { Building, Floor, LightMood, LightSetting, Room } from "../model.ts"; import type { Building, Floor, LightMood, LightSetting, Room } from "../model.ts";
import { roomPower, roomPowerSensors } from "../heatmap.ts"; import { roomPower, roomPowerSensors } from "../heatmap.ts";
import { energyCost, loadRoomEnergy, type RoomEnergy } from "../live/room-energy.ts"; import { energyCost, loadRoomEnergy, type RoomEnergy } from "../live/room-energy.ts";
@@ -21,6 +26,11 @@ import { hassAt, loadHistory } from "../live/time-travel.ts";
import { curvePath } from "../live/day-curves.ts"; import { curvePath } from "../live/day-curves.ts";
import { controls, tokens } from "../styles.ts"; import { controls, tokens } from "../styles.ts";
import type { HassEntity, HomeAssistant } from "../types.ts"; import type { HassEntity, HomeAssistant } from "../types.ts";
import { coverTiltEntity, coverWithTilt } from "../entities/covers.ts";
import { deviceValueReadouts } from "../entities/device-values.ts";
import { pointInPolygon } from "../model.ts";
import { chargingReadouts } from "../charging-station.ts";
import { furnitureName } from "../furniture-names.ts";
const COVER_SET_POSITION = 4; const COVER_SET_POSITION = 4;
const COVER_STOP = 8; const COVER_STOP = 8;
@@ -204,6 +214,7 @@ export class NfRoomPanel extends LitElement {
private async loadEnergy(room: Room): Promise<void> { private async loadEnergy(room: Room): Promise<void> {
if (!this.floor || !this.building) return; if (!this.floor || !this.building) return;
if (isSymcon(this.hass)) { this._energy = null; return; }
const ids = roomPowerSensors(this.hass, this.building, this.floor, room); const ids = roomPowerSensors(this.hass, this.building, this.floor, room);
try { try {
const energy = await loadRoomEnergy(this.hass, ids); const energy = await loadRoomEnergy(this.hass, ids);
@@ -448,7 +459,9 @@ export class NfRoomPanel extends LitElement {
: (this.memo = { entities: this.hass.entities, floor: this.floor, room, ...(this.floor ? roomPanelEntities(this.hass, this.floor, room) : { shown: all, more: [] }) }); : (this.memo = { entities: this.hass.entities, floor: this.floor, room, ...(this.floor ? roomPanelEntities(this.hass, this.floor, room) : { shown: all, more: [] }) });
const extra = groupByDevice(this.hass, more).map((g) => g.primary); const extra = groupByDevice(this.hass, more).map((g) => g.primary);
const hiddenCount = extra.length; const hiddenCount = extra.length;
const ids = this._showAll ? [...shown, ...extra] : shown; const hvacRefs = [room.floor_heating, ...Object.values(room.hvac ?? {}).flat()].filter((x): x is string => !!x && x !== "none");
const hvacNative = new Set(hvacRefs.map((id) => this.hass.states[id]?.attributes.symcon_id).filter(Boolean));
const ids = (this._showAll ? [...shown, ...extra] : shown).filter((id) => !isSymcon(this.hass) || !hvacNative.has(this.hass.states[id]?.attributes.symcon_id));
const by = (kinds: DeviceKind[]) => ids.filter((id) => kinds.includes(kindOf(id)!)).map((id) => this.hass.states[id]); const by = (kinds: DeviceKind[]) => ids.filter((id) => kinds.includes(kindOf(id)!)).map((id) => this.hass.states[id]);
const lights = by(["light"]); const lights = by(["light"]);
const covers = by(["cover"]); const covers = by(["cover"]);
@@ -463,7 +476,7 @@ export class NfRoomPanel extends LitElement {
<header class="nf-rp-head"> <header class="nf-rp-head">
<div> <div>
<h2>${room.name}</h2> <h2>${room.name}</h2>
${facts.length ? html`<p class="nf-rp-facts">${facts.join(" · ")}</p>` : nothing} ${this.renderEnergy()} ${this.renderSunYear()} ${this.renderShade()} ${facts.length ? html`<p class="nf-rp-facts">${facts.map((fact, i) => html`${i ? " · " : nothing}${fact}`)}</p>` : nothing} ${this.renderEnergy()} ${this.renderSunYear()} ${this.renderShade()}
${this.renderOpenWhileHeating(climates)} ${this.renderEmptyLights(room, lightsOn)} ${this.renderOpenWhileHeating(climates)} ${this.renderEmptyLights(room, lightsOn)}
${this.renderCurve()} ${this.renderCurve()}
</div> </div>
@@ -475,11 +488,12 @@ export class NfRoomPanel extends LitElement {
</button> </button>
</header> </header>
<div class="nf-rp-body" ?hidden=${this._folded}> <div class="nf-rp-body" ?hidden=${this._folded}>
<nf-utility-report .hass=${this.hass} .readings=${roomUtilityReadings(this.hass, room, this.building?.floors.flatMap((f) => f.rooms))}></nf-utility-report>
${this.renderAllOff([...lights, ...media, ...switches])} ${this.renderAllOff([...lights, ...media, ...switches])}
${this.renderClean(room)} ${this.renderClean(room)}
${!room.area_id && !outside ${!room.area_id && !outside && !(isSymcon(this.hass) && hvacRefs.length)
? html`<p class="nf-rp-note">${this.t("panel_no_area")}</p>` ? html`<p class="nf-rp-note">${this.t("panel_no_area")}</p>`
: !ids.length : !ids.length && !(isSymcon(this.hass) && hvacRefs.length)
? html`<p class="nf-rp-note">${this.t("panel_empty")}</p>` ? html`<p class="nf-rp-note">${this.t("panel_empty")}</p>`
: nothing} : nothing}
${scenes.length ${scenes.length
@@ -528,11 +542,13 @@ export class NfRoomPanel extends LitElement {
: nothing, : nothing,
) )
: nothing} : nothing}
${isSymcon(this.hass) ? html`<nf-room-hvac .hass=${this.hass} .room=${room}></nf-room-hvac>` : nothing}
${climates.length ? this.section("panel_climate", climates.map((st) => this.climateRow(st))) : nothing} ${climates.length ? this.section("panel_climate", climates.map((st) => this.climateRow(st))) : nothing}
${media.length ? this.section("panel_media", media.map((st) => this.mediaRow(st))) : nothing} ${media.length ? this.section("panel_media", media.map((st) => this.mediaRow(st))) : nothing}
${switches.length ? this.section("panel_switches", switches.map((st) => this.switchRow(st))) : nothing} ${switches.length ? this.section("panel_switches", switches.map((st) => this.switchRow(st))) : nothing}
${sensors.length ? this.section("panel_sensors", sensors.map((st) => this.sensorRow(st))) : nothing} ${sensors.length ? this.section("panel_sensors", sensors.map((st) => this.sensorRow(st))) : nothing}
${canAnnounce(this.hass) && roomHasSpeaker(this.hass, this.floor, room) ? this.announceSection(room) : nothing} ${this.extraValues(room)}
${!isSymcon(this.hass) && canAnnounce(this.hass) && roomHasSpeaker(this.hass, this.floor, room) ? this.announceSection(room) : nothing}
${this.pluginSections(room, ids)} ${this.pluginSections(room, ids)}
${hiddenCount ${hiddenCount
? html`<button class="nf-btn nf-rp-small nf-rp-more" @click=${() => (this._showAll = !this._showAll)}> ? html`<button class="nf-btn nf-rp-small nf-rp-more" @click=${() => (this._showAll = !this._showAll)}>
@@ -544,8 +560,15 @@ export class NfRoomPanel extends LitElement {
} }
/** Header facts: the room's temperature and humidity from its climate sensors (chosen or automatic). */ /** Header facts: the room's temperature and humidity from its climate sensors (chosen or automatic). */
private facts(climates: HassEntity[]): string[] { private extraValues(room: Room) {
const out: string[] = []; if (!this.floor) return nothing;
const groups = [...this.floor.placements.filter((p) => !p.outside && pointInPolygon([p.x, p.z], room.points)).map((p) => ({ name: p.name || entityName(this.hass, p.entity_id), rows: deviceValueReadouts(this.hass, p.values) })),
...this.floor.furniture.filter((f) => pointInPolygon([f.x, f.z], room.points)).map((f) => ({ name: f.name || (f.entity && f.entity !== "none" ? entityName(this.hass, f.entity) : furnitureName(this.hass, f.type)), rows: [...chargingReadouts(this.hass, f), ...deviceValueReadouts(this.hass, f.values)] }))].filter((g) => g.rows.length);
return groups.length ? this.section("device_values", groups.map((g) => html`<div class="nf-extra-values"><b>${g.name}</b>${g.rows.map((v) => html`<div class="nf-rp-row"><span class="nf-rp-icon">${v.icon}</span><span class="nf-rp-name">${v.label}</span><b class="nf-rp-state">${v.text}${trendButton(this.hass, [v.entity], v.label)}</b></div>`)}</div>`)) : nothing;
}
private facts(climates: HassEntity[]): (string | TemplateResult)[] {
const out: (string | TemplateResult)[] = [];
const room = this.room; const room = this.room;
// Outside has no climate of its own // Outside has no climate of its own
if (!room) return out; if (!room) return out;
@@ -559,13 +582,17 @@ export class NfRoomPanel extends LitElement {
}; };
const climateTemp = climates.find((c) => typeof c.attributes.current_temperature === "number"); const climateTemp = climates.find((c) => typeof c.attributes.current_temperature === "number");
const temp = value("temperature", "°C"); const temp = value("temperature", "°C");
if (temp) out.push(temp); if (temp) out.push(html`${temp}${trendButton(this.hass, roomClimateSensors(this.hass, this.floor, room, "temperature"), "Temperatur")}`);
else if (climateTemp && room.climate?.temperature !== "none") out.push(`${formatNumber(this.hass, climateTemp.attributes.current_temperature as number, 1)} ${tempUnit(this.hass)}`); else if (climateTemp && room.climate?.temperature !== "none") out.push(html`${formatNumber(this.hass, climateTemp.attributes.current_temperature as number, 1)} ${tempUnit(this.hass)}${trendButton(this.hass, [climateTemp.entity_id], "Temperatur")}`);
const hum = value("humidity", "%"); const hum = value("humidity", "%");
if (hum) out.push(hum); if (hum) out.push(html`${hum}${trendButton(this.hass, roomClimateSensors(this.hass, this.floor, room, "humidity"), "Luftfeuchte")}`);
const lux = roomClimateValue(this.hass, this.floor ?? null, room, "illuminance");
if (lux !== null) out.push(html`☀ ${formatNumber(this.hass, lux, 0)} lx${trendButton(this.hass, roomClimateSensors(this.hass, this.floor, room, "illuminance"), "Helligkeit")}`);
// what the room's devices draw now // what the room's devices draw now
const power = this.floor && this.building ? roomPower(this.hass, this.building, this.floor, room) : null; const meter = roomUtilityReadings(this.hass, room, this.building?.floors.flatMap((f) => f.rooms)).find((r) => r.kind === "electricity" && r.metric === "power" && r.unit === "W");
if (power !== null) out.push(`⚡ ${powerText(this.hass, power)}`); const power = !meter && this.floor && this.building ? roomPower(this.hass, this.building, this.floor, room) : null;
if (meter) out.push(html`⚡ ${utilityText(this.hass, meter)}${trendButton(this.hass, meter.sources, "Leistung")}`);
else if (power !== null) out.push(`⚡ ${powerText(this.hass, power)}`);
// how long its windows and doors stand open (the one open longest) // how long its windows and doors stand open (the one open longest)
const openSince = this.floor const openSince = this.floor
? this.floor.openings ? this.floor.openings
@@ -608,7 +635,9 @@ export class NfRoomPanel extends LitElement {
if (need && !off.includes("air")) out.push(`💨 ${this.t(`air_${need}`)}`); if (need && !off.includes("air")) out.push(`💨 ${this.t(`air_${need}`)}`);
// how comfortable it is (0 … 100) // how comfortable it is (0 … 100)
const comfort = comfortScore(t, h, roomClimateValue(this.hass, this.floor, room, "co2"), isSummer(new Date(), this.hass.config?.latitude)); const comfort = comfortScore(t, h, roomClimateValue(this.hass, this.floor, room, "co2"), isSummer(new Date(), this.hass.config?.latitude));
if (comfort !== null && (t !== null || h !== null) && !off.includes("comfort")) out.push(`😊 ${this.t("comfort_n", { n: comfort })}`); const status = room.hvac?.status;
if (status && status !== "none") out.push(html`${nativeText(this.hass.states[status])}${trendButton(this.hass, [status], "Raumstatus")}`);
else if (comfort !== null && (t !== null || h !== null) && !off.includes("comfort")) out.push(`😊 ${this.t("comfort_n", { n: comfort })}`);
return out; return out;
} }
@@ -674,9 +703,9 @@ export class NfRoomPanel extends LitElement {
return html`<div class="nf-rp-row"> return html`<div class="nf-rp-row">
<span class="nf-rp-icon ${on ? "nf-rp-on" : ""}">${icon("light")}</span> <span class="nf-rp-icon ${on ? "nf-rp-on" : ""}">${icon("light")}</span>
${this.nameButton(id)} ${this.nameButton(id)}
<span class="nf-rp-state">${this.stateOf(st)}</span> <span class="nf-rp-state">${this.stateOf(st)}${trendButton(this.hass, [st.entity_id])}</span>
${this.toggle(st, on, () => this.call("light", "toggle", { entity_id: id }))} ${this.toggle(st, on, () => this.call("light", "toggle", { entity_id: id }))}
${on && dimmable && !simple ${dimmable && !simple
? html`<label class="nf-rp-slider" ? html`<label class="nf-rp-slider"
><span>${this.t("brightness")}</span> ><span>${this.t("brightness")}</span>
<input <input
@@ -715,6 +744,8 @@ export class NfRoomPanel extends LitElement {
} }
private coverRow(st: HassEntity) { private coverRow(st: HassEntity) {
const tiltEntity = coverTiltEntity(this.hass, this.building?.floors ?? [], st.entity_id);
st = coverWithTilt(this.hass, st, tiltEntity);
const a = st.attributes; const a = st.attributes;
const features = (a.supported_features as number | undefined) ?? 0; const features = (a.supported_features as number | undefined) ?? 0;
const id = st.entity_id; const id = st.entity_id;
@@ -723,7 +754,7 @@ export class NfRoomPanel extends LitElement {
return html`<div class="nf-rp-row"> return html`<div class="nf-rp-row">
<span class="nf-rp-icon">${icon("cover")}</span> <span class="nf-rp-icon">${icon("cover")}</span>
${this.nameButton(id)} ${this.nameButton(id)}
<span class="nf-rp-state">${this.stateOf(st)}</span> <span class="nf-rp-state">${this.stateOf(st)}${trendButton(this.hass, [st.entity_id])}</span>
<div class="nf-rp-buttons"> <div class="nf-rp-buttons">
<button class="nf-btn nf-rp-small" ?disabled=${na} @click=${() => this.askFor(id) && this.call("cover", "open_cover", { entity_id: id })}>${this.t("cover_open")}</button> <button class="nf-btn nf-rp-small" ?disabled=${na} @click=${() => this.askFor(id) && this.call("cover", "open_cover", { entity_id: id })}>${this.t("cover_open")}</button>
${features & COVER_STOP ${features & COVER_STOP
@@ -752,7 +783,7 @@ export class NfRoomPanel extends LitElement {
max="100" max="100"
?disabled=${na} ?disabled=${na}
.value=${String(a.current_tilt_position)} .value=${String(a.current_tilt_position)}
@change=${(e: Event) => this.call("cover", "set_cover_tilt_position", { entity_id: id, tilt_position: Number((e.target as HTMLInputElement).value) })} @change=${(e: Event) => this.call("cover", "set_cover_tilt_position", { entity_id: a.nf_cover_control ? id : tiltEntity ?? id, tilt_position: Number((e.target as HTMLInputElement).value) })}
/></label>` /></label>`
: features & 48 : features & 48
? html`<div class="nf-rp-buttons"> ? html`<div class="nf-rp-buttons">
@@ -775,7 +806,7 @@ export class NfRoomPanel extends LitElement {
return html`<div class="nf-rp-row"> return html`<div class="nf-rp-row">
<span class="nf-rp-icon ${a.hvac_action === "heating" ? "nf-rp-on" : ""}">${icon("climate")}</span> <span class="nf-rp-icon ${a.hvac_action === "heating" ? "nf-rp-on" : ""}">${icon("climate")}</span>
${this.nameButton(id)} ${this.nameButton(id)}
<span class="nf-rp-state">${this.stateOf(st)}</span> <span class="nf-rp-state">${this.stateOf(st)}${trendButton(this.hass, [st.entity_id])}</span>
${target !== null ${target !== null
? html`<div class="nf-rp-stepper nf-rp-wide"> ? html`<div class="nf-rp-stepper nf-rp-wide">
<button class="nf-btn" aria-label=${this.t("temp_down")} @click=${() => set(target - step)}>−</button> <button class="nf-btn" aria-label=${this.t("temp_down")} @click=${() => set(target - step)}>−</button>
@@ -824,7 +855,7 @@ export class NfRoomPanel extends LitElement {
return html`<div class="nf-rp-row"> return html`<div class="nf-rp-row">
<span class="nf-rp-icon ${st.state === "playing" ? "nf-rp-on" : ""}">${icon("media")}</span> <span class="nf-rp-icon ${st.state === "playing" ? "nf-rp-on" : ""}">${icon("media")}</span>
${this.nameButton(id)} ${this.nameButton(id)}
<span class="nf-rp-state">${this.stateOf(st, this.stateLabel(st.state))}</span> <span class="nf-rp-state">${this.stateOf(st, this.stateLabel(st.state))}${trendButton(this.hass, [st.entity_id])}</span>
${title ? html`<p class="nf-rp-media nf-rp-wide">${title}</p>` : nothing} ${title ? html`<p class="nf-rp-media nf-rp-wide">${title}</p>` : nothing}
<div class="nf-rp-buttons nf-rp-wide"> <div class="nf-rp-buttons nf-rp-wide">
<button class="nf-btn nf-rp-small" aria-label=${this.t("previous")} ?disabled=${na} @click=${() => this.call("media_player", "media_previous_track", { entity_id: id })}> <button class="nf-btn nf-rp-small" aria-label=${this.t("previous")} ?disabled=${na} @click=${() => this.call("media_player", "media_previous_track", { entity_id: id })}>
@@ -860,7 +891,7 @@ export class NfRoomPanel extends LitElement {
return html`<div class="nf-rp-row"> return html`<div class="nf-rp-row">
<span class="nf-rp-icon ${on ? "nf-rp-on" : ""}">${icon(kind)}</span> <span class="nf-rp-icon ${on ? "nf-rp-on" : ""}">${icon(kind)}</span>
${this.nameButton(id)} ${this.nameButton(id)}
<span class="nf-rp-state">${this.stateOf(st)}</span> <span class="nf-rp-state">${this.stateOf(st)}${trendButton(this.hass, [st.entity_id])}</span>
${this.toggle(st, on, act)} ${this.toggle(st, on, act)}
</div>`; </div>`;
} }
@@ -871,7 +902,7 @@ export class NfRoomPanel extends LitElement {
return html`<div class="nf-rp-row"> return html`<div class="nf-rp-row">
<span class="nf-rp-icon ${warn ? "nf-rp-on" : ""}">${icon(kind)}</span> <span class="nf-rp-icon ${warn ? "nf-rp-on" : ""}">${icon(kind)}</span>
${this.nameButton(st.entity_id)} ${this.nameButton(st.entity_id)}
<span class="nf-rp-state">${this.stateOf(st)}</span> <span class="nf-rp-state">${this.stateOf(st)}${trendButton(this.hass, [st.entity_id])}</span>
</div>`; </div>`;
} }
@@ -0,0 +1,292 @@
// Native modal dialog with the actual Symcon object hierarchy. Numeric IDs never become input fields.
import { css, html, LitElement, nothing, svg, type PropertyValues } from "lit";
import { repeat } from "lit/directives/repeat.js";
import { tokens } from "../styles.ts";
import type { SymconObject } from "../types.ts";
import type { PickerOption } from "./entity-picker.ts";
import { indexSymconTree, symconAncestors, symconTreeRows, type SymconTree, type SymconTreeRow } from "./symcon-tree.ts";
import { pickerRejection, type PickerContext } from "./picker-rejection.ts";
const TYPES = ["Kategorie", "Instanz", "Variable", "Skript", "Ereignis", "Medium", "Link"];
export class SymconObjectPicker extends LitElement {
static properties = {
objects: { attribute: false }, options: { attribute: false }, fixed: { attribute: false },
value: { attribute: false }, disabled: { type: Boolean }, placeholder: { attribute: false },
context: { attribute: false }, _notice: { state: true },
_query: { state: true }, _expanded: { state: true }, _pending: { state: true }, _active: { state: true }, _selected: { state: true },
};
declare objects: readonly SymconObject[];
declare options: PickerOption[];
declare fixed: PickerOption[];
declare value: string | null;
declare disabled: boolean;
declare placeholder: string;
declare context: PickerContext | undefined;
private declare _notice: string;
private declare _query: string;
private declare _expanded: Set<number>;
private declare _pending: string | null;
private declare _active: number | null;
private declare _selected: number | null;
private tree: SymconTree = indexSymconTree([]);
private allowed = new Map<string, PickerOption>();
private allowedSources = new Map<string, string>();
constructor() {
super();
this.objects = [];
this.options = [];
this.fixed = [];
this.value = null;
this.disabled = false;
this.placeholder = "Datenpunkt auswählen";
this._notice = "";
this._query = "";
this._expanded = new Set();
this._pending = null;
this._active = null;
this._selected = null;
}
protected willUpdate(changed: PropertyValues): void {
if (changed.has("objects")) this.tree = indexSymconTree(this.objects);
if (changed.has("options") || changed.has("fixed")) {
this.allowed = new Map([...this.fixed, ...this.options].map((option) => [option.id, option]));
this.allowedSources = new Map(this.options.filter((o) => o.sourceEntity).map((o) => [o.sourceEntity!, o.id]));
}
}
private get dialog(): HTMLDialogElement | null { return this.renderRoot.querySelector("dialog"); }
private variableNode(entity: string | null): SymconObject | undefined {
const source = this.allowed.get(entity ?? "")?.sourceEntity ?? entity;
const native = this.objects.find((node) => node.entity_id === source && (node.object_type === 2 || node.object_type === 4));
return native ? this.tree.nodes.get(native.object_id) : undefined;
}
private async open(): Promise<void> {
if (this.disabled) return;
this._pending = this.allowed.has(this.value ?? "") ? this.value : null;
this._query = "";
this._notice = "";
const selected = this.variableNode(this.value)
?? this.objects.find((node) => node.entity_id === this.value);
this._active = selected?.object_id ?? null;
this._selected = selected?.object_id ?? null;
const expanded = new Set(this._expanded);
if (selected) for (const id of symconAncestors(this.tree, selected.object_id)) expanded.add(id);
this._expanded = expanded;
await this.updateComplete;
if (!this.isConnected) return;
if (!this.dialog?.open) this.dialog?.showModal();
this.renderRoot.querySelector<HTMLInputElement>(".search")?.focus();
this.renderRoot.querySelector("[aria-selected=true]")?.scrollIntoView({ block: "nearest" });
}
private close(): void { this.dialog?.close(); }
private clear(event: Event): void {
event.preventDefault();
event.stopPropagation();
if (this.disabled) return;
this.value = this.fixed.some((option) => option.id === "none") ? "none" : null;
this._pending = this.value;
this._selected = null;
this._active = null;
this.close();
this.dispatchEvent(new CustomEvent("change", { detail: { value: this.value }, bubbles: true, composed: true }));
}
private commit(): void {
if (this.disabled || !this._pending || !this.allowed.has(this._pending)) return;
this.value = this._pending;
this.close();
this.dispatchEvent(new CustomEvent("change", { detail: { value: this.value }, bubbles: true, composed: true }));
}
private toggle(id: number): void {
const expanded = new Set(this._expanded);
if (expanded.has(id)) expanded.delete(id); else expanded.add(id);
this._expanded = expanded;
}
private select(node: SymconObject): void {
this._active = node.object_id;
const entity = this.entityFor(node);
if (entity) {
this._pending = entity;
this._selected = node.object_id;
this._notice = "";
} else {
this._pending = null;
this._selected = null;
this._notice = pickerRejection(node, this.context);
}
}
private entityFor(node: SymconObject): string | undefined {
if (!node.entity_id) return undefined;
return this.allowed.has(node.entity_id) ? node.entity_id : this.allowedSources.get(node.entity_id);
}
private async onTreeKey(event: KeyboardEvent): Promise<void> {
const rows = symconTreeRows(this.tree, this._expanded, this._query);
const i = Math.max(0, rows.findIndex((row) => row.node.object_id === this._active));
const row = rows[i];
if (!row) return;
let next = i;
if (event.key === "ArrowDown") next = Math.min(rows.length - 1, i + 1);
else if (event.key === "ArrowUp") next = Math.max(0, i - 1);
else if (event.key === "Home") next = 0;
else if (event.key === "End") next = rows.length - 1;
else if (event.key === "ArrowRight") {
if (row.hasChildren && !row.expanded) this.toggle(row.node.object_id);
else if (row.hasChildren) next = Math.min(rows.length - 1, i + 1);
} else if (event.key === "ArrowLeft") {
if (row.expanded && !this._query) this.toggle(row.node.object_id);
else next = Math.max(0, rows.findIndex((item) => item.node.object_id === row.node.parent_id));
} else if (event.key === " " || event.key === "Enter") {
this.select(row.node);
if (event.key === "Enter" && this.entityFor(row.node)) this.commit();
} else return;
event.preventDefault();
if (next !== i || this._active === null) this._active = rows[next].node.object_id;
await this.updateComplete;
this.renderRoot.querySelector(`#object-${this._active}`)?.scrollIntoView({ block: "nearest" });
}
private icon(type: number) {
const paths = [
svg`<path d="M3 6h7l2 2h9v12H3z"/>`,
svg`<path d="m12 3 9 5v9l-9 5-9-5V8zM3 8l9 5 9-5M12 13v9"/>`,
svg`<circle cx="12" cy="12" r="8"/><path d="m9 9 6 6m0-6-6 6"/>`,
svg`<path d="m8 7-5 5 5 5m8-10 5 5-5 5m-3-12-2 14"/>`,
svg`<circle cx="12" cy="12" r="9"/><path d="M12 6v6l4 2"/>`,
svg`<rect x="3" y="4" width="18" height="16" rx="2"/><path d="m4 17 5-5 4 4 3-3 5 4"/>`,
svg`<path d="m10 14 4-4m-6 2-2 2a4 4 0 0 0 6 6l3-3m-6-9 3-3a4 4 0 0 1 6 6l-2 2"/>`,
];
return svg`<svg class="icon type-${type}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true">${paths[type] ?? paths[1]}</svg>`;
}
private renderRow(row: SymconTreeRow) {
const { node } = row;
const entity = this.entityFor(node);
const selectable = !!entity;
return html`<div id="object-${node.object_id}" role="treeitem"
aria-level=${row.depth + 1} aria-posinset=${row.index} aria-setsize=${row.siblings}
aria-expanded=${row.hasChildren ? String(row.expanded) : nothing}
aria-selected=${selectable ? String(node.object_id === this._selected && entity === this._pending) : nothing}
aria-disabled=${!selectable && [2, 4, 6].includes(node.object_type) ? "true" : nothing}
class="node ${selectable ? "selectable" : ""} ${node.hidden ? "hidden-object" : ""} ${this._active === node.object_id ? "active" : ""}"
style=${`--depth:${row.depth}`} title=${node.path}
@click=${() => { this.select(node); this.renderRoot.querySelector<HTMLElement>(".tree")?.focus(); }}
@dblclick=${() => { if (selectable) { this.select(node); this.commit(); } else if (row.hasChildren) this.toggle(node.object_id); }}>
<button class="twisty" type="button" tabindex="-1" aria-label=${row.expanded ? "Zuklappen" : "Aufklappen"}
?disabled=${!row.hasChildren} @click=${(event: Event) => { event.stopPropagation(); this._active = node.object_id; this.toggle(node.object_id); }}>
${row.hasChildren ? (row.expanded ? "▾" : "▸") : nothing}
</button>
${this.icon(node.object_type)}<span class="node-name">${node.name || "(Ohne Namen)"}</span>
<small>${node.virtual ? "Systembereich" : (TYPES[node.object_type] ?? "Objekt")}${node.hidden ? " · ausgeblendet" : ""}</small>
${selectable && node.object_id === this._selected && entity === this._pending ? html`<span class="selected-mark" aria-hidden="true">✓</span>` : nothing}
</div>`;
}
protected render() {
const current = this.allowed.get(this.value ?? "");
const selectedNode = this.variableNode(this.value);
const pending = this.allowed.get(this._pending ?? "");
const selectedObject = this._selected === null ? undefined : this.tree.nodes.get(this._selected);
const pendingNode = (selectedObject && this.entityFor(selectedObject) === this._pending ? selectedObject : undefined) ?? this.variableNode(this._pending);
const rows = symconTreeRows(this.tree, this._expanded, this._query);
const active = rows.find((row) => row.node.object_id === this._active);
const linked = !!this.value && !this.fixed.some((option) => option.id === this.value);
return html`<div class="field"><button type="button" class="trigger" ?disabled=${this.disabled} aria-haspopup="dialog" @click=${this.open}>
<span class="trigger-text"><strong>${selectedNode?.name ?? current?.label ?? "Datenpunkt auswählen"}</strong>
${selectedNode ? html`<small title=${selectedNode.path}>${selectedNode.path}</small>` : nothing}</span><span class="picker-icon" aria-hidden="true">⌘</span>
</button>${linked ? html`<button class="clear" type="button" ?disabled=${this.disabled} aria-label="Verknüpfung entfernen" title="Verknüpfung entfernen" @click=${this.clear}>×</button>` : nothing}</div>
<dialog aria-labelledby="picker-title" @click=${(event: MouseEvent) => {
event.stopPropagation();
if (event.target === this.dialog) {
const bounds = this.dialog!.getBoundingClientRect();
if (event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom) this.close();
}
}} @keydown=${(event: KeyboardEvent) => event.stopPropagation()} @change=${(event: Event) => event.stopPropagation()}>
<header><div><h2 id="picker-title">Datenpunkt auswählen</h2><p>IP-Symcon · ${this.context?.label || "Objektbaum"}</p></div>
<button class="close" type="button" aria-label="Schließen" @click=${this.close}>×</button></header>
<div class="search-bar"><input class="search" type="search" placeholder="Im Objektbaum suchen …" aria-label="Objektbaum durchsuchen"
.value=${this._query} @input=${(event: Event) => { this._query = (event.target as HTMLInputElement).value; this._active = null; this._notice = ""; }}>
<button class="text-button" type="button" @click=${() => { this._query = ""; this._expanded = new Set(); this._active = null; }}>Alles zuklappen</button>
</div>
${this.fixed.length ? html`<div class="fixed" aria-label="Weitere Auswahlmöglichkeiten">${this.fixed.map((option) => html`
<button type="button" aria-pressed=${option.id === this._pending} @click=${() => { this._pending = option.id; this._active = null; this._selected = null; this._notice = ""; }}>${option.label}</button>`)}</div>` : nothing}
<div class="tree" role="tree" tabindex="0" aria-label="Symcon-Objektbaum" aria-activedescendant=${active ? `object-${active.node.object_id}` : nothing}
@keydown=${this.onTreeKey}>
${repeat(rows, (row) => row.node.object_id, (row) => this.renderRow(row))}
${!rows.length ? html`<p class="empty">${this.objects.length ? "Keine Objekte gefunden." : "Kein Objektbaum verfügbar. Bitte das Symcon-Modul aktualisieren und den Designer neu laden."}</p>` : nothing}
</div>
${this._notice ? html`<div class="rejection" role="status" aria-live="polite">${this._notice}</div>` : nothing}
<footer><div class="selection"><strong>${pendingNode?.name ?? pending?.label ?? "Noch kein Datenpunkt ausgewählt"}</strong>
<small>${pendingNode?.path ?? "Nur passende Datenpunkte können ausgewählt werden."}</small></div>
<div class="actions"><button type="button" @click=${this.close}>Abbrechen</button>
<button class="apply" type="button" ?disabled=${this.disabled || !pending} @click=${this.commit}>Übernehmen</button></div>
</footer>
</dialog>`;
}
static styles = [tokens, css`
:host { display:block; min-width:0; max-width:100%; font:inherit; color:var(--nf-text); }
button,input { font:inherit; box-sizing:border-box; }
button { cursor:pointer; color:var(--nf-text); border:1px solid var(--nf-line); background:var(--nf-chrome-solid); border-radius:9px; padding:8px 12px; }
button:disabled { opacity:.45; cursor:default; }
button:focus-visible,input:focus-visible { outline:2px solid var(--nf-accent); outline-offset:2px; }
.field { display:flex; gap:6px; min-width:0; }
.trigger { flex:1; min-width:0; width:100%; display:flex; align-items:center; justify-content:space-between; text-align:left; gap:12px; padding:9px 11px; }
.trigger-text { flex:1; min-width:0; overflow:hidden; }
.trigger strong { display:block; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.picker-icon { flex:none; }
.clear { flex:none; width:32px; padding:0; font-size:22px; }
strong { font-weight:500; } small { display:block; color:var(--nf-muted); font-size:11px; }
.trigger small { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; margin-top:3px; }
dialog { width:min(780px,calc(100vw - 32px)); max-width:none; height:min(690px,calc(100dvh - 32px)); max-height:none; box-sizing:border-box; padding:0; border:1px solid var(--nf-line); border-radius:16px; color:var(--nf-text); background:var(--nf-chrome-solid); box-shadow:0 24px 80px #0008; font:14px system-ui,sans-serif; }
dialog[open] { display:flex; flex-direction:column; }
dialog::backdrop { background:#050b16a6; backdrop-filter:blur(3px); }
header { display:flex; align-items:center; justify-content:space-between; padding:20px 22px 16px; border-bottom:1px solid var(--nf-line); }
h2 { font-size:18px; font-weight:600; margin:0 0 4px; } header p { margin:0; color:var(--nf-muted); font-size:12px; }
.close { font-size:25px; padding:0; width:32px; height:32px; border-color:transparent; }
.search-bar { display:flex; align-items:center; gap:12px; padding:16px 20px 10px; }
.search { flex:1; min-width:0; border:1px solid var(--nf-line); border-radius:9px; padding:10px 12px; background:var(--nf-bg); color:var(--nf-text); }
.text-button { border:0; background:transparent; color:var(--nf-muted); font-size:12px; padding:6px 0; white-space:nowrap; }
.fixed { display:flex; flex-wrap:wrap; gap:6px; padding:0 20px 10px; }
.fixed button { padding:5px 10px; font-size:12px; }
.fixed [aria-pressed=true] { color:var(--nf-accent); border-color:var(--nf-accent); }
.tree { flex:1; min-height:80px; overflow:auto; overscroll-behavior:contain; margin:0 12px; padding:4px 0 12px; outline-offset:-2px; }
.node { display:flex; align-items:center; gap:8px; min-height:34px; border-radius:6px; padding:2px 10px 2px calc(4px + var(--depth)*22px); box-sizing:border-box; width:max-content; min-width:100%; }
.node:hover { background:color-mix(in srgb,var(--nf-accent) 8%,transparent); }
.node.active { outline:1px solid color-mix(in srgb,var(--nf-accent) 40%,transparent); outline-offset:-1px; }
.node[aria-selected=true] { background:color-mix(in srgb,var(--nf-accent) 16%,transparent); color:var(--nf-accent); }
.node.selectable { cursor:pointer; }
.node[aria-disabled=true] .node-name { color:var(--nf-muted); }
.node.hidden-object .node-name { font-style:italic; }
.node-name { flex:1; white-space:nowrap; }
.node small { margin-left:20px; white-space:nowrap; }
.twisty { border:0; background:transparent; border-radius:4px; padding:0; width:20px; height:26px; flex:none; font-size:18px; }
.icon { flex:none; width:17px; height:17px; color:#8796a9; } .type-0 { color:#c69a42; } .type-1 { color:#8d9ac6; } .type-2 { color:#55a58c; }
.selected-mark { margin-left:8px; }
.empty { padding:20px; color:var(--nf-muted); }
.rejection { flex:none; margin:0 20px 12px; padding:8px 10px; border-left:2px solid #e5b56d; border-radius:4px; background:#e5b56d0c; color:var(--nf-text); font-size:12px; line-height:1.4; overflow-wrap:anywhere; }
footer { display:flex; align-items:center; justify-content:space-between; gap:16px; border-top:1px solid var(--nf-line); padding:15px 20px; }
.selection { min-width:0; } .selection small { margin-top:4px; overflow-wrap:anywhere; }
.actions { display:flex; gap:8px; flex-shrink:0; }
.apply { color:white; background:var(--nf-accent); border-color:transparent; }
@media(max-width:580px) {
dialog { width:calc(100vw - 16px); height:calc(100dvh - 32px); border-radius:12px; }
header { padding:16px; } .search-bar { padding:12px; gap:8px; } .fixed { padding:0 12px 8px; }
.tree { margin:0 8px; } .node { gap:6px; padding-left:calc(2px + var(--depth)*18px); }
.node small { display:none; } footer { padding:12px; flex-direction:column; align-items:stretch; } .actions { justify-content:flex-end; }
}
`];
}
if (!customElements.get("nf-symcon-object-picker")) customElements.define("nf-symcon-object-picker", SymconObjectPicker);
@@ -0,0 +1,69 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import type { SymconObject } from "../types.ts";
import { indexSymconTree, symconAncestors, symconTreeRows, SYMCON_SYSTEM_ROOT } from "./symcon-tree.ts";
const node = (object_id: number, parent_id: number, name: string, object_type = 0, position = 0): SymconObject =>
({ object_id, parent_id, name, object_type, position, path: name, hidden: false, icon: "" });
test("native position, type and name order are kept, including empty categories and non-variable objects", () => {
const tree = indexSymconTree([node(4, 0, "Variable", 2), node(2, 0, "Zentrale", 1), node(3, 0, "Zweiter Ordner"), node(1, 0, "Erster Ordner"), node(5, 0, "Skript", 3, -1)]);
assert.deepEqual(symconTreeRows(tree, new Set()).map((row) => row.node.object_id), [5, 1, 3, 2, 4]);
});
test("equal names and a slash inside a name remain distinct native branches", () => {
const tree = indexSymconTree([node(1, 0, "Haus / Altbau"), node(2, 1, "Heizung", 1), node(3, 0, "Heizung", 1), node(4, 2, "Temperatur", 2), node(5, 3, "Temperatur", 2)]);
assert.deepEqual(symconAncestors(tree, 4), [2, 1]);
assert.deepEqual(symconAncestors(tree, 5), [3]);
assert.deepEqual(symconTreeRows(tree, new Set([1, 2])).map((row) => [row.node.object_id, row.depth]), [[1, 0], [2, 1], [4, 2], [3, 0]]);
});
test("search opens the original ancestors and never searches internal IDs", () => {
const tree = indexSymconTree([node(1, 0, "Haus"), node(2, 1, "Küche", 1), node(3, 2, "Temperatur", 2), node(4, 1, "Garten")]);
const expanded = new Set<number>();
assert.deepEqual(symconTreeRows(tree, expanded, "temperatur").map((row) => row.node.object_id), [1, 2, 3]);
assert.equal(expanded.size, 0, "search must not change manual expansion state");
assert.deepEqual(symconTreeRows(tree, expanded, "3"), []);
});
test("hidden categories and their variables stay in the main category without a visibility filter", () => {
const objects = [{ ...node(1, 0, "Versteckt"), hidden: true }, { ...node(2, 1, "Technik"), hidden: true }, { ...node(3, 2, "Temperatur", 2), entity_id: "sensor.3" }];
const tree = indexSymconTree(objects);
const rows = symconTreeRows(tree, new Set([1, 2]));
assert.deepEqual(rows.map((row) => row.node.object_id), [1, 2, 3]);
assert.equal(rows[0].node.hidden, true);
assert.equal(rows[1].node.hidden, true);
assert.equal(rows[2].node.entity_id, "sensor.3");
});
test("all six system module types move into virtual groups while devices stay in the main category", () => {
const objects = [node(1, 0, "Haus"), { ...node(2, 1, "Heizung", 1), module_type: 3 }, node(3, 2, "Temperatur", 2)];
const types = [1, 2, 0, 4, 5, 6];
for (const type of types) {
objects.push({ ...node(20 + type, 0, `Modul ${type}`, 1), module_type: type });
objects.push({ ...node(40 + type, 20 + type, "Wert", 2), entity_id: `sensor.${40 + type}` });
}
const original = structuredClone(objects);
const tree = indexSymconTree(objects);
assert.deepEqual(symconTreeRows(tree, new Set()).map((row) => row.node.name), ["Haus", "System"]);
assert.deepEqual((tree.children.get(SYMCON_SYSTEM_ROOT) ?? []).map((entry) => entry.name), ["I/O", "Splitter", "Kerninstanzen", "Konfiguratoren", "Discovery", "Visualisierungen"]);
assert.equal(tree.nodes.get(2)?.parent_id, 1);
for (const type of types) {
assert.equal(tree.nodes.get(20 + type)?.parent_id, -10 - type);
assert.deepEqual(symconAncestors(tree, 40 + type), [20 + type, -10 - type, SYMCON_SYSTEM_ROOT]);
assert.equal(tree.nodes.get(40 + type)?.entity_id, `sensor.${40 + type}`);
}
assert.deepEqual(objects, original, "grouping must never mutate native parents or object data");
assert.ok([...tree.nodes.values()].filter((entry) => entry.virtual).every((entry) => !entry.entity_id && entry.object_id < 0));
});
test("system subtrees remain intact and searchable, including native folders already named System", () => {
const objects = [node(1, 0, "System"), { ...node(2, 1, "LAN", 1), module_type: 1 }, { ...node(3, 2, "Splitter", 1), module_type: 2 },
{ ...node(4, 3, "Betriebsstunden", 2), hidden: true, entity_id: "sensor.4" }];
const tree = indexSymconTree(objects);
assert.equal(tree.nodes.get(1)?.parent_id, 0, "an actual user category named System must not be merged or moved");
assert.equal(tree.nodes.get(3)?.parent_id, 2, "nested instances stay with their original parent");
assert.deepEqual(symconTreeRows(tree, new Set(), "System I/O Betriebsstunden").map((row) => row.node.object_id), [SYMCON_SYSTEM_ROOT, -11, 2, 3, 4]);
assert.equal(tree.nodes.get(4)?.hidden, true);
assert.equal(tree.nodes.get(4)?.path, "System / I/O / LAN / Splitter / Betriebsstunden");
});
+131
View File
@@ -0,0 +1,131 @@
import type { SymconObject } from "../types.ts";
export interface SymconTree {
nodes: Map<number, SymconObject>;
children: Map<number, SymconObject[]>;
}
export interface SymconTreeRow {
node: SymconObject;
depth: number;
hasChildren: boolean;
expanded: boolean;
index: number;
siblings: number;
}
// Symcon orders siblings by position, then object type, then name (IPS_SetPosition).
const collator = new Intl.Collator("de", { numeric: true, sensitivity: "base" });
export const SYMCON_SYSTEM_ROOT = -1;
const SYSTEM_GROUPS = [
{ type: 1, name: "I/O" },
{ type: 2, name: "Splitter" },
{ type: 0, name: "Kerninstanzen" },
{ type: 4, name: "Konfiguratoren" },
{ type: 5, name: "Discovery" },
{ type: 6, name: "Visualisierungen" },
] as const;
const isSystemInstance = (node: SymconObject): boolean => node.object_type === 1 && SYSTEM_GROUPS.some((group) => group.type === node.module_type);
/** Show the main category's objects first and tuck the logical console's system branches away.
* Hidden categories are never filtered; only this display copy is regrouped, never the native tree. */
function projectSymconObjects(objects: readonly SymconObject[]): readonly SymconObject[] {
const native = new Map(objects.map((node) => [node.object_id, node]));
const roots = objects.filter((node) => {
if (!isSystemInstance(node)) return false;
const seen = new Set([node.object_id]);
let parent = native.get(node.parent_id);
while (parent && !seen.has(parent.object_id)) {
if (isSystemInstance(parent)) return false; // Keep its entire native subtree together.
seen.add(parent.object_id);
parent = native.get(parent.parent_id);
}
return true;
});
if (!roots.length) return objects;
const projected = new Map(native);
const children = new Map<number, SymconObject[]>();
for (const node of objects) {
const siblings = children.get(node.parent_id) ?? [];
siblings.push(node);
children.set(node.parent_id, siblings);
}
const virtualCategory = (id: number, parent: number, name: string, path: string, position: number): SymconObject => ({
object_id: id, parent_id: parent, name, path, position, object_type: 0, hidden: false, icon: "", virtual: true,
});
projected.set(SYMCON_SYSTEM_ROOT, virtualCategory(SYMCON_SYSTEM_ROOT, 0, "System", "System", Number.MAX_SAFE_INTEGER));
const moved = new Set<number>();
const moveBranch = (node: SymconObject, parent: number, parentPath: string): void => {
if (moved.has(node.object_id)) return;
moved.add(node.object_id);
const copy = { ...node, parent_id: parent, path: `${parentPath} / ${node.name}` };
projected.set(node.object_id, copy);
for (const child of children.get(node.object_id) ?? []) moveBranch(child, node.object_id, copy.path);
};
SYSTEM_GROUPS.forEach((group, index) => {
const instances = roots.filter((node) => node.module_type === group.type);
if (!instances.length) return;
const id = -10 - group.type;
const path = `System / ${group.name}`;
projected.set(id, virtualCategory(id, SYMCON_SYSTEM_ROOT, group.name, path, index));
for (const instance of instances) moveBranch(instance, id, path);
});
return [...projected.values()];
}
export function indexSymconTree(objects: readonly SymconObject[]): SymconTree {
const projected = projectSymconObjects(objects);
const nodes = new Map(projected.map((node) => [node.object_id, node]));
const children = new Map<number, SymconObject[]>();
for (const node of projected) {
const parent = nodes.has(node.parent_id) ? node.parent_id : 0;
const siblings = children.get(parent) ?? [];
siblings.push(node);
children.set(parent, siblings);
}
for (const siblings of children.values()) siblings.sort((a, b) => a.position - b.position || a.object_type - b.object_type || collator.compare(a.name, b.name));
return { nodes, children };
}
/** Display ancestor IDs, including virtual system groups, without splitting names into paths. */
export function symconAncestors(tree: SymconTree, objectId: number): number[] {
const result: number[] = [];
const seen = new Set([objectId]);
let parent = tree.nodes.get(objectId)?.parent_id;
while (parent && !seen.has(parent) && tree.nodes.has(parent)) {
result.push(parent);
seen.add(parent);
parent = tree.nodes.get(parent)?.parent_id;
}
return result;
}
/** Search retains each match's displayed ancestors and opens that path without changing manual expansion. */
export function symconTreeRows(tree: SymconTree, expanded: ReadonlySet<number>, query = ""): SymconTreeRow[] {
const words = query.trim().toLocaleLowerCase("de").split(/\s+/).filter(Boolean);
const matches = words.length ? new Set<number>() : null;
if (matches) {
for (const node of tree.nodes.values()) {
if (words.every((word) => `${node.name} ${node.path}`.toLocaleLowerCase("de").includes(word))) {
matches.add(node.object_id);
for (const id of symconAncestors(tree, node.object_id)) matches.add(id);
}
}
}
const rows: SymconTreeRow[] = [];
const visited = new Set<number>();
const visit = (parent: number, depth: number) => {
const siblings = (tree.children.get(parent) ?? []).filter((node) => !matches || matches.has(node.object_id));
siblings.forEach((node, i) => {
if (visited.has(node.object_id)) return;
visited.add(node.object_id);
const hasChildren = (tree.children.get(node.object_id)?.length ?? 0) > 0;
const open = hasChildren && (!!matches || expanded.has(node.object_id));
rows.push({ node, depth, hasChildren, expanded: open, index: i + 1, siblings: siblings.length });
if (open) visit(node.object_id, depth + 1);
});
};
visit(0, 0);
return rows;
}
+40
View File
@@ -0,0 +1,40 @@
import { css, html, LitElement, nothing } from "lit";
import type { HomeAssistant } from "../types.ts";
import { loggedEntities } from "../trend-data.ts";
declare const __NF_TREND_HASH__: string;
let loaded: Promise<typeof import("./trend-dialog.ts")> | undefined;
/** Small shared trigger; the chart and its controls load only after the first click. */
class NfTrendButton extends LitElement {
static properties = { hass: { attribute: false }, ids: { attribute: false }, label: { attribute: false }, busy: { state: true }, error: { state: true } };
declare hass: HomeAssistant;
declare ids: string[];
declare label: string;
private declare busy: boolean;
private declare error: string;
constructor() { super(); this.ids = []; this.label = ""; this.busy = false; this.error = ""; }
private async open(event: Event) {
event.stopPropagation(); this.busy = true; this.error = "";
try {
const url = new URL(`./nextfloor-trend.js?v=${__NF_TREND_HASH__}`, import.meta.url).href;
const mod = await (loaded ??= import(/* @vite-ignore */ url).catch((error) => { loaded = undefined; throw error; }));
await mod.openTrend(this.hass, this.ids, this.label);
} catch (error) { this.error = error instanceof Error ? error.message : String(error); }
finally { this.busy = false; }
}
render() {
if (!loggedEntities(this.hass, this.ids).length) return nothing;
const title = this.label ? `Trend anzeigen: ${this.label}` : "Trend anzeigen";
return html`<button type="button" title=${title} aria-label=${title} aria-haspopup="dialog" ?disabled=${this.busy} @pointerdown=${(e: Event) => e.stopPropagation()} @click=${(e: Event) => void this.open(e)}>
<svg width="12" height="12" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M3 2v15h15M5 13l4-5 4 2 4-6"/></svg>
</button>${this.error ? html`<span role="alert">${this.error}</span>` : nothing}`;
}
static styles = css`:host{position:relative;display:inline-flex;flex:0 0 18px;width:18px;height:18px;vertical-align:middle;margin-left:3px;font-weight:normal;line-height:0}button{display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;width:18px;height:18px;padding:2px;border:0;border-radius:3px;background:transparent;color:var(--nf-accent,#40c8ff);opacity:.8;cursor:pointer}svg{display:block;flex-shrink:0}button:hover,button:focus-visible{opacity:1;background:#40c8ff18}button:focus-visible{outline:1px solid currentColor;outline-offset:1px}button:disabled{opacity:.4}span{position:absolute;right:0;top:22px;z-index:10;box-sizing:border-box;width:200px;padding:8px;border:1px solid #ff9b9b50;border-radius:6px;background:var(--nf-chrome-solid,#1c1c1c);font:12px/1.4 system-ui;color:#ff9b9b;white-space:normal}`;
}
if (!customElements.get("nf-trend-button")) customElements.define("nf-trend-button", NfTrendButton);
export function trendButton(hass: HomeAssistant | undefined, ids: readonly string[], label = "") {
const logged = loggedEntities(hass, ids);
return logged.length ? html`<nf-trend-button .hass=${hass} .ids=${logged} .label=${label}></nf-trend-button>` : nothing;
}
+257
View File
@@ -0,0 +1,257 @@
import { css, html, LitElement, nothing, svg } from "lit";
import type { HomeAssistant } from "../types.ts";
import { tokens } from "../styles.ts";
import { localDateTime, loggedEntities, TREND_RESOLUTIONS, trendBounds, trendCsv, type TrendPoint, type TrendResolution, type TrendSeries } from "../trend-data.ts";
import "./help-popup.ts";
const COLORS = ["#4ec9ff", "#ffbe69", "#ae9bff", "#72deb0", "#ff87aa", "#ebde72"];
const entityName = (hass: HomeAssistant, id: string) => String(hass.states[id]?.attributes.friendly_name || id);
const errorText = (e: unknown) => ({ variable_not_logged: "Die Variable wird nicht mehr geloggt.", trend_range_too_large_for_resolution: "Bitte für diesen Zeitraum eine gröbere Auflösung wählen.", invalid_trend_range: "Bitte einen gültigen Zeitraum wählen." } as Record<string, string>)[String(e instanceof Error ? e.message : e)] || String(e instanceof Error ? e.message : e);
/** Lazy, read-only archive viewer, shared by designer and tile iframe. */
export class NfTrendDialog extends LitElement {
static properties = {
hass: { attribute: false }, ids: { attribute: false }, label: { attribute: false },
from: { state: true }, to: { state: true }, resolution: { state: true }, chartStyle: { state: true }, field: { state: true },
min: { state: true }, max: { state: true }, zero: { state: true }, band: { state: true }, live: { state: true },
series: { state: true }, hiddenSeries: { state: true }, loading: { state: true }, errors: { state: true }, hover: { state: true }, width: { state: true }, plotHeight: { state: true }, page: { state: true },
};
declare hass: HomeAssistant;
declare ids: string[];
declare label: string;
private declare from: number;
private declare to: number;
private declare resolution: TrendResolution;
private declare chartStyle: "auto" | "line" | "step" | "bar" | "table";
private declare field: "v" | "min" | "max";
private declare min: string;
private declare max: string;
private declare zero: boolean;
private declare band: boolean;
private declare live: boolean;
private declare series: TrendSeries[];
// Avoid HTMLElement.hidden: this collection controls individual chart series only.
private declare hiddenSeries: Set<string>;
private declare loading: boolean;
private declare errors: string[];
private declare hover: number | null;
private declare width: number;
private declare plotHeight: number;
private declare page: number;
private request = 0;
private drag: number | null = null;
private timer?: ReturnType<typeof setInterval>;
private observer?: ResizeObserver;
private resize = () => { this.plotHeight = Math.round(Math.min(600, Math.max(220, window.innerHeight * (window.innerWidth < 600 ? .52 : .65)))); };
constructor() {
super(); this.ids = []; this.label = "";
this.to = Math.floor(Date.now() / 1000); this.from = this.to - 86400;
this.resolution = "auto"; this.chartStyle = "auto"; this.field = "v"; this.min = ""; this.max = "";
this.zero = false; this.band = true; this.live = false; this.series = []; this.hiddenSeries = new Set();
this.loading = false; this.errors = []; this.hover = null; this.width = 900; this.plotHeight = 400; this.page = 0;
}
async open() {
await this.updateComplete;
this.renderRoot.querySelector<HTMLDialogElement>("dialog")!.showModal();
this.observer = new ResizeObserver(([e]) => { this.width = Math.max(280, Math.floor(e.contentRect.width)); });
this.observer.observe(this.renderRoot.querySelector(".body")!);
this.resize(); window.addEventListener("resize", this.resize);
this.timer = setInterval(() => { if (this.live && !this.loading) { const span = this.to - this.from; this.to = Math.floor(Date.now() / 1000); this.from = this.to - span; void this.load(); } }, 30000);
await this.load();
}
disconnectedCallback() { super.disconnectedCallback(); ++this.request; clearInterval(this.timer); this.observer?.disconnect(); window.removeEventListener("resize", this.resize); }
private async load() {
const request = ++this.request, start = this.from, end = this.to;
this.errors = []; this.series = []; this.hover = null; this.page = 0;
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 1 || end <= start) { this.errors = ["Das Ende muss nach dem Beginn des Zeitraums liegen."]; this.loading = false; return; }
this.loading = true;
const series: TrendSeries[] = [], errors: string[] = [];
// Keep archive reads bounded even when the value is linked to many variables.
for (let i = 0; i < this.ids.length && request === this.request; i += 3) {
const ids = this.ids.slice(i, i + 3);
const results = await Promise.allSettled(ids.map((entity_id) => this.hass.callWS<TrendSeries>({ type: "nextfloor/archive/trend", entity_id, start, end, aggregation: this.resolution })));
results.forEach((r, index) => r.status === "fulfilled" ? series.push(r.value) : errors.push(`${entityName(this.hass, ids[index])}: ${errorText(r.reason)}`));
}
if (request !== this.request || !this.isConnected) return;
this.series = series; this.errors = errors; this.loading = false;
}
private range(from: number, to: number) { this.from = Math.max(1, Math.floor(from)); this.to = Math.max(this.from + 1, Math.floor(to)); this.live = false; void this.load(); }
private zoom(factor: number, anchor = .5) { const span = Math.max(60, Math.min(315576000, (this.to - this.from) * factor)), at = this.from + (this.to - this.from) * anchor; this.range(at - span * anchor, at + span * (1 - anchor)); }
private stamp(t: number) { return new Date(t * 1000).toLocaleString(this.hass.language, { dateStyle: "short", timeStyle: "medium" }); }
private number(v: number) { return v.toLocaleString(this.hass.language, { maximumFractionDigits: Math.abs(v) < .01 && v !== 0 ? 5 : 2 }); }
private unit(id: string) { return String(this.hass.states[id]?.attributes.unit_of_measurement ?? ""); }
private selected() { return this.series.filter((s) => !this.hiddenSeries.has(s.entity_id)); }
private value(p: TrendPoint) { const value = this.field === "v" ? p.v : p[this.field] ?? p.v; return typeof value === "number" && Number.isFinite(value) ? value : null; }
private color(id: string) { return COLORS[this.ids.indexOf(id) % COLORS.length]; }
private ratio(event: PointerEvent | WheelEvent) { const r = (event.currentTarget as SVGSVGElement).getBoundingClientRect(); return Math.max(0, Math.min(1, ((event.clientX - r.left) / r.width * this.width - 64) / (this.width - 80))); }
private exportCsv() {
const names = Object.fromEntries(this.ids.map((id) => [id, String(this.hass.states[id]?.attributes.symcon_path || entityName(this.hass, id))]));
const url = URL.createObjectURL(new Blob([trendCsv(this.selected(), names)], { type: "text/csv;charset=utf-8" }));
const link = document.createElement("a"); link.href = url; link.download = "Symcon-Trend.csv"; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);
}
private plot(series: TrendSeries[], unit: string) {
const numbers = series.flatMap((s) => s.points.flatMap((p) => { const v = this.value(p); return v === null ? [] : this.band && !s.counter ? [v, p.min ?? v, p.max ?? v] : [v]; }));
if (!numbers.length) return html`<p class="note">Keine numerischen Archivwerte in diesem Zeitraum.</p>`;
let low: number, high: number;
try { [low, high] = trendBounds(numbers, this.min, this.max, this.zero || this.chartStyle === "bar" || series.some((s) => s.type === 0) || (this.chartStyle === "auto" && series.some((s) => s.counter && s.aggregation !== "raw"))); }
catch (e) { return html`<p role="alert">${errorText(e)}</p>`; }
const groups = new Set(this.selected().filter((s) => s.type !== 3).map((s) => this.unit(s.entity_id))).size;
const height = Math.max(200, Math.round(this.plotHeight / Math.max(1, Math.min(groups, 2))));
const left = 64, right = this.width - 16, top = 14, bottom = height - 32;
const x = (t: number) => left + (t - this.from) / (this.to - this.from) * (right - left);
const y = (v: number) => bottom - (v - low) / (high - low) * (bottom - top);
const point = (p: TrendPoint, field = this.field) => Number(field === "v" ? p.v : p[field] ?? p.v);
const path = (s: TrendSeries, field = this.field) => {
const ps = s.points.filter((p) => typeof p.v === "number");
const stepped = this.chartStyle === "step" || (this.chartStyle === "auto" && s.type === 0);
return ps.map((p, i) => `${i ? stepped ? `H${x(p.t).toFixed(1)}V` : "L" : "M"}${stepped && i ? y(point(p, field)).toFixed(1) : `${x(p.t).toFixed(1)},${y(point(p, field)).toFixed(1)}`}`).join("") + (ps.length ? stepped ? `H${right}` : s.aggregation === "raw" ? `L${right},${y(point(ps[ps.length - 1], field)).toFixed(1)}` : "" : "");
};
const ticks = this.width < 480 ? 2 : 5;
return html`<section class="chart-group"><h3>${unit || "Wert"}</h3><svg class="plot" viewBox=${`0 0 ${this.width} ${height}`} role="img" aria-label=${`Trend ${unit}`} @wheel=${(e: WheelEvent) => { e.preventDefault(); this.zoom(e.deltaY > 0 ? 1.5 : 1 / 1.5, this.ratio(e)); }}
@pointerdown=${(e: PointerEvent) => { this.drag = this.ratio(e); (e.currentTarget as Element).setPointerCapture(e.pointerId); }}
@pointerup=${(e: PointerEvent) => { if (this.drag === null) return; const start = this.drag, end = this.ratio(e); this.drag = null; if (Math.abs(start - end) > .02) { const span = this.to - this.from; this.range(this.from + span * Math.min(start, end), this.from + span * Math.max(start, end)); } }}
@pointercancel=${() => { this.drag = null; }} @pointermove=${(e: PointerEvent) => { this.hover = this.from + (this.to - this.from) * this.ratio(e); }}>
<defs><clipPath id="plot-clip"><rect x=${left} y=${top} width=${right - left} height=${bottom - top}/></clipPath></defs>
${[0, 1, 2, 3, 4].map((i) => { const v = low + (high - low) * i / 4; return svg`<line class="grid" x1=${left} x2=${right} y1=${y(v)} y2=${y(v)}/><text x=${left - 7} y=${y(v) + 4} text-anchor="end">${this.number(v)}</text>`; })}
${Array.from({ length: ticks }, (_, i) => { const t = this.from + (this.to - this.from) * i / (ticks - 1); return svg`<text x=${x(t)} y=${height - 8} text-anchor=${i === 0 ? "start" : i === ticks - 1 ? "end" : "middle"}>${new Date(t * 1000).toLocaleString(this.hass.language, { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" })}</text>`; })}
<g clip-path="url(#plot-clip)">${series.map((s) => {
const bars = this.chartStyle === "bar" || (this.chartStyle === "auto" && s.counter && s.aggregation !== "raw");
const color = this.color(s.entity_id);
if (bars) return s.points.filter((p) => this.value(p) !== null).map((p) => svg`<rect fill=${color} opacity=".65" x=${x(p.t)} y=${Math.min(y(this.value(p)!), y(0))} width=${Math.max(1, Math.min(right, x(p.t + Math.max(1, p.d))) - x(p.t) - 1)} height=${Math.max(1, Math.abs(y(this.value(p)!) - y(0)))}/>`);
return svg`${this.band && s.aggregation !== "raw" && !s.counter ? svg`<path d=${path(s, "min")} fill="none" stroke=${color} opacity=".3"/><path d=${path(s, "max")} fill="none" stroke=${color} opacity=".3"/>` : nothing}<path d=${path(s)} fill="none" stroke=${color} stroke-width="2" vector-effect="non-scaling-stroke"/>${s.points.length === 1 ? svg`<circle cx=${x(s.points[0].t)} cy=${y(point(s.points[0]))} r="3" fill=${color}/>` : nothing}`;
})}${this.hover !== null ? svg`<line x1=${x(this.hover)} x2=${x(this.hover)} y1=${top} y2=${bottom} stroke="currentColor" stroke-dasharray="3 4" opacity=".5"/>` : nothing}</g>
</svg></section>`;
}
private table(series: TrendSeries[]) {
const rows = series.flatMap((s) => s.points.map((p) => ({ id: s.entity_id, ...p }))).sort((a, b) => b.t - a.t);
const pages = Math.max(1, Math.ceil(rows.length / 100)), page = Math.min(this.page, pages - 1);
return html`<div class="table"><table><thead><tr><th>Zeit</th><th>Variable</th><th>Wert</th></tr></thead><tbody>${rows.slice(page * 100, (page + 1) * 100).map((p) => html`<tr><td>${this.stamp(p.t)}</td><td>${entityName(this.hass, p.id)}</td><td>${typeof p.v === "number" ? this.number(p.v) : p.v} ${this.unit(p.id)}</td></tr>`)}</tbody></table></div><div class="actions"><button ?disabled=${!page} @click=${() => { this.page = page - 1; }}>Zurück</button><span>${page + 1} / ${pages}</span><button ?disabled=${page >= pages - 1} @click=${() => { this.page = page + 1; }}>Weiter</button></div>`;
}
render() {
const selected = this.selected(), allString = selected.length > 0 && selected.every((s) => s.type === 3);
const text = this.hover === null ? "Letzter Wert" : this.stamp(this.hover);
return html`<dialog aria-label="Variablentrend" @close=${() => this.remove()} @keydown=${(e: KeyboardEvent) => {
e.stopPropagation();
const settings = this.renderRoot.querySelector<HTMLDetailsElement>(".settings");
if (e.key === "Escape" && settings?.open) { e.preventDefault(); settings.open = false; }
}} @click=${(e: Event) => { const settings = this.renderRoot.querySelector<HTMLDetailsElement>(".settings"); if (settings?.open && !e.composedPath().includes(settings)) settings.open = false; }}>
<header><div><h2>${this.label || "Variablentrend"}</h2><span class="range">${new Date(this.from * 1000).toLocaleString(this.hass.language, { dateStyle: "short", timeStyle: "short" })} – ${new Date(this.to * 1000).toLocaleString(this.hass.language, { dateStyle: "short", timeStyle: "short" })}</span></div><button aria-label="Schließen" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>("dialog")?.close()}>×</button></header>
<div class="body"><div class="toolbar"><div class="presets">${[["1 h", 3600], ["6 h", 21600], ["24 h", 86400], ["7 Tage", 604800], ["30 Tage", 2592000], ["1 Jahr", 31536000]].map(([label, seconds]) => html`<button aria-pressed=${this.to - this.from === seconds} @click=${() => { const end = Math.floor(Date.now() / 1000); this.range(end - Number(seconds), end); }}>${label}</button>`)}</div>
<div class="navigation"><button aria-label="Vorheriger Zeitraum" title="Vorheriger Zeitraum" @click=${() => this.range(this.from - (this.to - this.from), this.from)}>←</button><button aria-label="Nächster Zeitraum" title="Nächster Zeitraum" @click=${() => this.range(this.to, this.to + (this.to - this.from))}>→</button><button aria-label="Hineinzoomen" title="Hineinzoomen" @click=${() => this.zoom(.5)}>+</button><button aria-label="Herauszoomen" title="Herauszoomen" @click=${() => this.zoom(2)}>−</button><button aria-label="Aktualisieren" title="Aktualisieren" aria-busy=${this.loading} @click=${() => void this.load()} ?disabled=${this.loading}>↻</button></div>
<label class="live-toggle" title="Alle 30 Sekunden aktualisieren"><input type="checkbox" .checked=${this.live} @change=${(e: Event) => { this.live = (e.target as HTMLInputElement).checked; }}/> Live</label>
<details class="settings"><summary aria-label="Trend-Einstellungen" title="Zeitraum, Auflösung und Darstellung">⚙︎</summary><div class="settings-panel">
<form @submit=${(e: Event) => { e.preventDefault(); void this.load(); }}><div class="fields time-fields">
<label>Von<input type="datetime-local" .value=${localDateTime(this.from)} @change=${(e: Event) => { this.from = Math.floor(new Date((e.target as HTMLInputElement).value).getTime() / 1000); this.live = false; void this.load(); }}/></label>
<label>Bis<input type="datetime-local" .value=${localDateTime(this.to)} @change=${(e: Event) => { this.to = Math.floor(new Date((e.target as HTMLInputElement).value).getTime() / 1000); this.live = false; void this.load(); }}/></label>
<label>Auflösung<select .value=${this.resolution} @change=${(e: Event) => { this.resolution = (e.target as HTMLSelectElement).value as TrendResolution; void this.load(); }}>${Object.entries(TREND_RESOLUTIONS).map(([id, label]) => html`<option value=${id}>${label}</option>`)}</select></label>
<button type="submit" ?disabled=${this.loading}>${this.loading ? "Lädt …" : "Anzeigen"}</button>
</div></form>
<div class="display-settings"><b class="group-title">Darstellung und Wertebereich</b><div class="fields display-fields">
<label>Darstellung<select .value=${this.chartStyle} @change=${(e: Event) => { this.chartStyle = (e.target as HTMLSelectElement).value as typeof this.chartStyle; }}>${Object.entries({ auto: "Automatisch", line: "Linie", step: "Stufen", bar: "Balken", table: "Tabelle" }).map(([id, label]) => html`<option value=${id}>${label}</option>`)}</select></label>
<label>Aggregierter Wert<select .value=${this.field} @change=${(e: Event) => { this.field = (e.target as HTMLSelectElement).value as typeof this.field; }}><option value="v">Mittelwert / Verbrauch</option><option value="min">Minimum</option><option value="max">Maximum</option></select></label>
<label>Y-Minimum<input type="number" step="any" placeholder="Automatisch" .value=${this.min} @input=${(e: Event) => { this.min = (e.target as HTMLInputElement).value; }}/></label>
<label>Y-Maximum<input type="number" step="any" placeholder="Automatisch" .value=${this.max} @input=${(e: Event) => { this.max = (e.target as HTMLInputElement).value; }}/></label>
</div><div class="checks"><label><input type="checkbox" .checked=${this.zero} @change=${(e: Event) => { this.zero = (e.target as HTMLInputElement).checked; }}/> Nullpunkt einbeziehen</label><label><input type="checkbox" .checked=${this.band} @change=${(e: Event) => { this.band = (e.target as HTMLInputElement).checked; }}/> Min/Max anzeigen</label></div></div>
<div class="actions"><button @click=${() => this.exportCsv()} ?disabled=${!selected.length}>CSV</button>
<nf-help-popup .text=${"Zeitraum und Auflösung lesen die originalen Symcon-Archivdaten. Rohdaten zeigen gespeicherte Änderungen; ein zuvor bekannter Wert wird zum Beginn fortgeführt. Bei Zählern sind aggregierte Werte der Verbrauch pro Intervall, bei Messwerten der Mittelwert. Mehrere Variablen werden einzeln dargestellt; unterschiedliche Einheiten erhalten eigene Diagramme. Zoomen: +/−, Mausrad oder im Diagramm einen Zeitraum ziehen. Eigene Y-Grenzen gelten für alle Diagramme. Begrenzte Rohdatenabfragen werden gekennzeichnet; wähle dann einen kürzeren Zeitraum oder eine Aggregation."}></nf-help-popup>
</div></div></details></div>
<div class="legend">${this.ids.map((id) => html`<label title=${String(this.hass.states[id]?.attributes.symcon_path || entityName(this.hass, id))}><input type="checkbox" .checked=${!this.hiddenSeries.has(id)} @change=${(e: Event) => { const set = new Set(this.hiddenSeries); if ((e.target as HTMLInputElement).checked) set.delete(id); else set.add(id); this.hiddenSeries = set; this.requestUpdate(); }}/><i style=${`background:${this.color(id)}`}></i>${entityName(this.hass, id)}</label>`)}</div>
${this.errors.map((e) => html`<p class="error" role="alert">${e}</p>`)}${this.loading ? html`<p class="note" role="status">Archivwerte werden geladen …</p>` : nothing}
${selected.filter((s) => s.truncated).map((s) => html`<p class="error" role="status">${entityName(this.hass, s.entity_id)}: Die Abfrage ist auf ${(s.limit ?? 10000).toLocaleString(this.hass.language)} Einträge begrenzt. Bitte Zeitraum verkürzen oder Auflösung ändern.</p>`)}
${selected.some((s) => s.counter && s.aggregation !== "raw") ? html`<p class="note">Zähler: Verbrauch pro Intervall</p>` : nothing}
<div class="charts" style=${`min-height:${this.plotHeight}px`}>
${this.chartStyle === "table" || allString ? this.table(selected) : [...new Set(selected.filter((s) => s.type !== 3).map((s) => this.unit(s.entity_id)))].map((unit) => this.plot(selected.filter((s) => s.type !== 3 && this.unit(s.entity_id) === unit), unit))}
${selected.some((s) => s.type === 3) && !allString && this.chartStyle !== "table" ? this.table(selected.filter((s) => s.type === 3)) : nothing}
${!this.loading && selected.length && selected.every((s) => !s.points.length) ? html`<p class="note">Keine Archivwerte in diesem Zeitraum.</p>` : nothing}
</div>
<div class="cursor"><b>${text}</b>${selected.map((s) => { let p = s.points.at(-1); if (this.hover !== null) { let lo = 0, hi = s.points.length; while (lo < hi) { const mid = (lo + hi) >>> 1; if (s.points[mid].t <= this.hover) lo = mid + 1; else hi = mid; } p = s.points[lo - 1]; } return html`<span style=${`color:${this.color(s.entity_id)}`}>${entityName(this.hass, s.entity_id)}: ${p ? typeof p.v === "number" ? `${this.number(this.value(p)!)} ${this.unit(s.entity_id)}` : p.v : "–"}</span>`; })}</div>
</div>
</dialog>`;
}
static styles = [tokens, css`
:host { font:13px/1.4 system-ui,sans-serif; color:var(--nf-text); }
dialog { box-sizing:border-box; width:min(1080px,calc(100vw - 24px)); max-height:92vh; max-height:92dvh; padding:0; border:1px solid var(--nf-line); border-radius:12px; background:var(--nf-chrome-solid,#1c1c1c); color:inherit; box-shadow:var(--nf-shadow); overflow:auto; }
dialog::backdrop { background:#050b16a8; }
header { display:flex; justify-content:space-between; align-items:center; gap:12px; padding:8px 12px; border-bottom:1px solid var(--nf-line); position:sticky; top:0; z-index:3; background:var(--nf-chrome-solid,#1c1c1c); }
header>div { display:flex; align-items:baseline; flex-wrap:wrap; gap:3px 14px; min-width:0; }
h2 { font-size:15px; margin:0; }
.range { font-size:11px; color:var(--nf-muted); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
header button { width:26px; height:26px; font-size:19px; padding:0; flex-shrink:0; }
.body { padding:8px 12px; }
.toolbar { position:relative; display:flex; align-items:center; flex-wrap:wrap; gap:5px 10px; margin-bottom:6px; }
.presets,.navigation { display:flex; align-items:center; gap:3px; }
button,input,select { box-sizing:border-box; color:var(--nf-text); font:inherit; }
button,select,input:not([type=checkbox]),summary { border:1px solid var(--nf-line); border-radius:5px; padding:4px 7px; background:var(--nf-fill,#292929); min-width:0; }
button { cursor:pointer; font-size:12px; }
button:disabled { opacity:.45; }
button:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible { outline:2px solid var(--nf-accent); outline-offset:2px; }
.toolbar button,.toolbar summary { height:26px; }
.navigation button { width:26px; padding:0; font-size:16px; }
.presets button { padding:3px 6px; font-size:11px; }
.presets button[aria-pressed=true],.settings[open]>summary { border-color:var(--nf-accent); background:color-mix(in srgb,var(--nf-accent) 16%,var(--nf-fill)); }
.live-toggle { display:flex; align-items:center; gap:3px; font-size:11px; white-space:nowrap; }
input[type=checkbox] { margin:0; }
.settings { margin-left:auto; }
.settings:not([open])>.settings-panel { display:none; }
summary { display:flex; align-items:center; justify-content:center; width:28px; padding:0; list-style:none; font-size:17px; cursor:pointer; }
summary::-webkit-details-marker { display:none; }
.settings-panel { position:absolute; z-index:2; top:calc(100% + 5px); right:0; box-sizing:border-box; width:min(620px,100%); max-height:min(62vh,480px); overflow:auto; padding:10px 12px; border:1px solid var(--nf-line); border-radius:8px; background:var(--nf-chrome-solid,#1c1c1c); box-shadow:var(--nf-shadow); }
.fields { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); align-items:end; gap:7px 10px; margin:0 0 10px; }
.fields label { display:grid; gap:3px; color:var(--nf-muted); font-size:11px; }
.fields input,.fields select { height:28px; width:100%; font-size:12px; }
.time-fields button { justify-self:start; }
.display-settings { padding-top:8px; border-top:1px solid var(--nf-line); }
.group-title { display:block; margin-bottom:6px; font-size:12px; }
.actions,.checks,.legend,.cursor { display:flex; align-items:center; flex-wrap:wrap; gap:6px 10px; }
.checks { margin:0 0 6px; }
.checks label,.legend label { display:flex; align-items:center; gap:4px; font-size:11px; }
.legend { margin:4px 0 0; }
.legend i { display:inline-block; width:8px; height:8px; border-radius:50%; flex-shrink:0; }
.legend label { max-width:100%; overflow-wrap:anywhere; }
.plot { display:block; width:100%; touch-action:none; user-select:none; }
.plot text { fill:var(--nf-muted); font:11px system-ui; }
.grid { stroke:var(--nf-line); }
h3 { font-size:11px; color:var(--nf-muted); margin:3px 0 0; }
.chart-group { margin-bottom:4px; }
.cursor { font-size:11px; align-items:baseline; border-top:1px solid var(--nf-line); padding-top:6px; }
.cursor>b { color:var(--nf-muted); font-weight:normal; }
.cursor span { overflow-wrap:anywhere; }
.note,.error { font-size:12px; margin:6px 0; }
.note { color:var(--nf-muted); }
.error { color:#ffa5a5; }
.table { overflow:auto; max-height:60vh; margin:8px 0; }
table { width:100%; border-collapse:collapse; font-size:12px; }
td,th { text-align:left; padding:5px; border-bottom:1px solid var(--nf-line); overflow-wrap:anywhere; }
td:first-child { white-space:nowrap; }
th { position:sticky; top:0; background:var(--nf-chrome-solid,#1c1c1c); }
@media(max-width:500px) {
header { padding:7px 9px; }
header>div { display:grid; gap:1px; }
h2 { font-size:14px; }
.body { padding:7px 9px; }
.toolbar { gap:4px 6px; }
.presets { gap:2px; }
.presets button { padding:3px 5px; }
.settings-panel { padding:9px; }
input[type=datetime-local] { font-size:11px; padding:3px; }
}
`];
}
// Each lazy bundle has its own Lit copy; use an existing registration when another host loaded it first.
if (!customElements.get("nf-trend-dialog")) customElements.define("nf-trend-dialog", NfTrendDialog);
export async function openTrend(hass: HomeAssistant, ids: string[], label: string) {
const logged = loggedEntities(hass, ids);
if (!logged.length) return;
const dialog = document.createElement("nf-trend-dialog") as NfTrendDialog;
Object.assign(dialog, { hass, ids: logged, label }); document.body.append(dialog);
try { await dialog.open(); } catch (e) { dialog.remove(); throw e; }
}
@@ -0,0 +1,94 @@
import { css, html, LitElement, nothing } from "lit";
import { UTILITY_KINDS, type Floor } from "../model.ts";
import type { HomeAssistant } from "../types.ts";
import { buildingUtilityReadings, floorUtilityAreas, floorUtilityReadings, UTILITY_ICONS, UTILITY_LABELS, utilityMetricLabel, utilityText, type UtilityReading } from "../utilities.ts";
import { trendButton } from "./trend-button.ts";
/** Building → floors, floor → native areas → rooms → placed devices with a linked power value. */
class NfUtilityOverview extends LitElement {
static properties = { hass: { attribute: false }, floors: { attribute: false }, floorId: { attribute: false }, inline: { type: Boolean, reflect: true }, compact: { type: Boolean }, folded: { state: true } };
declare hass: HomeAssistant;
declare floors: readonly Floor[];
declare floorId: string | null;
declare inline: boolean;
declare compact: boolean;
private declare folded: boolean | null;
constructor() { super(); this.floors = []; this.floorId = null; this.inline = false; this.compact = false; this.folded = null; }
private value(row: UtilityReading | undefined) {
return row ? html`<span class="value" title=${`${utilityMetricLabel(row)}${row.manual ? " · eigener Zähler" : ""}`}><b>${utilityText(this.hass, row)}</b>${row.period !== "total" ? html`<small>${({ day: "heute", month: "Monat", year: "Jahr" })[row.period]}</small>` : nothing}${trendButton(this.hass, row.sources, `${UTILITY_LABELS[row.kind]} · ${utilityMetricLabel(row)}`)}</span>` : nothing;
}
private open(id: string, room: boolean) { this.dispatchEvent(new CustomEvent("utility-open", { detail: { floorId: room ? this.floorId : id, roomId: room ? id : null }, bubbles: true, composed: true })); }
private rows(readings: UtilityReading[]) {
return UTILITY_KINDS.map((kind) => {
const powers = readings.filter((r) => r.kind === kind && r.metric === "power"), energies = readings.filter((r) => r.kind === kind && r.metric === "energy");
return Array.from({ length: Math.max(powers.length, energies.length) }, (_, i) => html`<div class="row"><span class="kind" title=${UTILITY_LABELS[kind]}>${i ? "" : `${UTILITY_ICONS[kind]} ${UTILITY_LABELS[kind]}`}</span>${powers[i] ? this.value(powers[i]) : html`<span></span>`}${energies[i] ? this.value(energies[i]) : html`<span></span>`}</div>`);
});
}
render() {
if (!this.hass) return nothing;
const rooms = this.floors.flatMap((f) => f.rooms), floor = this.floors.find((f) => f.id === this.floorId);
if (this.inline) {
const rows = floor ? floorUtilityReadings(this.hass, floor, rooms) : buildingUtilityReadings(this.hass, this.floors);
return html`${UTILITY_KINDS.map((kind) => {
const readings = rows.filter((r) => r.kind === kind);
return readings.length ? html`<div class="meter" aria-label=${`${floor?.name || "Gesamtgebäude"} · ${UTILITY_LABELS[kind]}`}><span class="medium" title=${floor?.name || "Gesamtgebäude"}>${UTILITY_ICONS[kind]} ${UTILITY_LABELS[kind]}</span><div class="values">${readings.map((r) => this.value(r))}</div></div>` : nothing;
})}`;
}
const entries = floor ? floorUtilityAreas(this.hass, floor, rooms, true).map((area) => ({ ...area, hasDetails: area.rooms.length > 0 }))
: [...this.floors].sort((a, b) => b.elevation - a.elevation).map((f) => ({ id: f.id, name: f.name, path: "", readings: floorUtilityReadings(this.hass, f, rooms), rooms: [], hasDetails: floorUtilityAreas(this.hass, f, rooms, true).length > 0 }));
const shown = entries.filter((e) => e.readings.length || e.hasDetails);
if (!shown.length) return nothing;
const folded = this.folded ?? this.compact;
return html`<section class="panel" aria-label=${floor ? "Bereichszähler" : "Stockwerkszähler"}>
<button class="heading" aria-expanded=${!folded} @click=${() => { this.folded = !folded; }}><span>${floor ? "Bereiche" : "Stockwerke"}<small>${floor?.name || "Gesamtgebäude"}</small></span><span aria-hidden="true">${folded ? "+" : "−"}</span></button>
${folded ? nothing : html`<div class="entries"><div class="columns"><span></span><span title="Leistung bzw. Durchfluss">Leistung</span><span>Energie / Verbrauch</span></div>
${shown.map((entry) => html`<section class="entry" data-area=${floor ? entry.id : nothing}>
${floor ? html`<div class="entry-name area-name" title=${entry.path || entry.name}>${entry.name}</div>` : html`<button class="entry-name" title=${entry.name} @click=${() => this.open(entry.id, false)}>${entry.name}</button>`}
${this.rows(entry.readings)}
${entry.rooms.map((room) => html`<section class="room-entry" data-room=${room.id}><button class="entry-name" title=${room.name} @click=${() => this.open(room.id, true)}><span aria-hidden="true">↳</span> ${room.name}</button>${this.rows(room.readings)}
${room.devices.map((device) => html`<section class="device-entry" data-device=${device.id}><div class="entry-name device-name" title=${device.name}><span aria-hidden="true">↳</span> ${device.name}</div>${this.rows(device.readings)}</section>`)}
</section>`)}
</section>`)}
</div>`}
</section>`;
}
static styles = css`
:host { display:flex; width:100%; min-height:0; max-height:100%; color:var(--nf-text); font:12px/1.4 system-ui,sans-serif; pointer-events:auto; }
:host([inline]) { display:flex; flex-wrap:wrap; align-items:stretch; gap:6px; width:auto; max-width:100%; }
.meter { padding:5px 9px; border-radius:10px; background:var(--nf-chrome); border-left:2px solid var(--nf-line); backdrop-filter:blur(6px); }
.medium { font-size:11px; color:var(--nf-muted); }
.medium small { font-size:10px; }
.values { display:flex; flex-wrap:wrap; gap:3px 10px; }
.value { display:inline-flex; align-items:center; justify-content:flex-end; gap:3px; min-width:0; white-space:nowrap; font-variant-numeric:tabular-nums; }
.value b { font-size:12px; font-weight:600; }
.value small { color:var(--nf-muted); font-size:9px; }
nf-trend-button { margin-left:0; }
.panel { display:flex; flex-direction:column; box-sizing:border-box; width:100%; max-height:100%; border:1px solid var(--nf-line); border-radius:12px; background:var(--nf-chrome); backdrop-filter:blur(8px); overflow:hidden; }
button { color:inherit; font:inherit; border:0; background:none; cursor:pointer; text-align:left; }
button:focus-visible { outline:2px solid var(--nf-accent); outline-offset:-2px; }
.heading { display:flex; flex-shrink:0; align-items:center; justify-content:space-between; gap:12px; width:100%; padding:8px 10px; font-weight:600; }
.heading small { display:block; color:var(--nf-muted); font-size:10px; font-weight:normal; }
.entries { min-height:0; max-height:min(50vh,480px); overflow:auto; padding:0 10px 8px; }
.columns,.row { display:grid; grid-template-columns:54px minmax(0,1fr) minmax(0,1.2fr); align-items:center; gap:5px; }
.columns { color:var(--nf-muted); font-size:9px; text-align:right; margin-bottom:2px; }
.entry { border-top:1px solid var(--nf-line); padding:6px 0; }
.entry:last-child { padding-bottom:0; }
.entry-name { display:block; width:100%; padding:0 0 3px; font-size:11px; font-weight:600; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; }
.entry-name:hover { color:var(--nf-accent); }
.area-name:hover { color:inherit; }
.room-entry { margin-top:5px; padding-top:4px; border-top:1px dotted var(--nf-line); }
.room-entry>.entry-name { padding-left:12px; color:var(--nf-muted); font-weight:normal; }
.device-entry { margin-top:4px; }
.device-entry>.device-name { padding-left:24px; color:var(--nf-muted); font-weight:normal; }
.device-name:hover { color:var(--nf-muted); }
.row { min-height:20px; }
.kind { color:var(--nf-muted); font-size:10px; white-space:nowrap; }
.row .value b { font-size:11px; font-weight:normal; }
@media(max-width:600px) { .entries { max-height:32vh; } }
`;
}
if (!customElements.get("nf-utility-overview")) customElements.define("nf-utility-overview", NfUtilityOverview);
+35
View File
@@ -0,0 +1,35 @@
import { css, html, LitElement } from "lit";
import { UTILITY_KINDS } from "../model.ts";
import type { HomeAssistant } from "../types.ts";
import { UTILITY_ICONS, UTILITY_LABELS, utilityMetricLabel, utilityText, type UtilityReading } from "../utilities.ts";
import { trendButton } from "./trend-button.ts";
/** The same metered readings in the room panel and the floor overview. */
class NfUtilityReport extends LitElement {
static properties = { hass: { attribute: false }, readings: { attribute: false } };
declare hass: HomeAssistant;
declare readings: UtilityReading[];
constructor() { super(); this.readings = []; }
render() {
return html`${UTILITY_KINDS.filter((kind) => this.readings.some((r) => r.kind === kind)).map((kind) => html`<section aria-label=${UTILITY_LABELS[kind]}>
<h4>${UTILITY_ICONS[kind]} ${UTILITY_LABELS[kind]}</h4>
${this.readings.filter((r) => r.kind === kind).map((r) => html`<div class="reading" title=${`${r.manual ? "Eigener Zähler" : "Bereichszähler"}${r.incomplete ? " · Err: Mindestens ein Wert fehlt; angezeigt wird die Summe der verfügbaren Werte." : ""}\n${r.sources.map((id) => this.hass.states[id]?.attributes.symcon_path || this.hass.states[id]?.attributes.friendly_name || id).join("\n")}`}>
<span>${utilityMetricLabel(r)}${r.manual ? html` <small>· Zähler</small>` : ""}</span><b>${utilityText(this.hass, r)}${trendButton(this.hass, r.sources, `${UTILITY_LABELS[r.kind]} · ${utilityMetricLabel(r)}`)}</b>
</div>`)}
</section>`)}`;
}
static styles = css`
:host { display:block; color:var(--nf-text); font:inherit; }
section { padding:10px 0; border-bottom:1px solid var(--nf-line,#ffffff20); }
section:last-child { border:0; }
h4 { font:inherit; font-weight:600; margin:0 0 6px; }
.reading { display:flex; justify-content:space-between; gap:16px; margin:4px 0; }
.reading span { color:var(--nf-muted,#aaa); }
b { white-space:nowrap; font-variant-numeric:tabular-nums; }
small { font-size:.85em; }
`;
}
if (!customElements.get("nf-utility-report")) customElements.define("nf-utility-report", NfUtilityReport);
+157 -33
View File
@@ -30,6 +30,10 @@ import { gateStates } from "../entities/gates.ts";
import { weatherEntity } from "../weather.ts"; import { weatherEntity } from "../weather.ts";
import { chosenEffects, readSkyWeather, withDensity } from "../live/sky-weather.ts"; import { chosenEffects, readSkyWeather, withDensity } from "../live/sky-weather.ts";
import { energyPicture, houseHub, type EnergyPicture } from "../live/energy-flow.ts"; 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 { loadWeek, type WeekBars } from "../live/week-bars.ts";
import { binsDue, loadToday, sortDay, type TodayItem } from "../live/today.ts"; import { binsDue, loadToday, sortDay, type TodayItem } from "../live/today.ts";
import { forecastDays, loadForecast } from "../live/forecast.ts"; import { forecastDays, loadForecast } from "../live/forecast.ts";
@@ -38,6 +42,7 @@ import { isHeatPump, readHeatPump, type HeatPumpInfo } from "../live/heat-pump.t
import { coverageColor, isAccessPoint, networkHealth, readAccessPoint } from "../live/wifi.ts"; import { coverageColor, isAccessPoint, networkHealth, readAccessPoint } from "../live/wifi.ts";
import type { FurnitureColors } from "../furniture-colors.ts"; import type { FurnitureColors } from "../furniture-colors.ts";
import { renderLhCards, liveCardStyles, unstackLhCards, type LiveCard } from "../live/cards.ts"; import { renderLhCards, liveCardStyles, unstackLhCards, type LiveCard } from "../live/cards.ts";
import { cardDetail, cardVisibleAtZoom } from "../live/card-visibility.ts";
import { readCar, type CarInfo } from "../live/car.ts"; import { readCar, type CarInfo } from "../live/car.ts";
import { mediaNow, multiroom, type MediaNow } from "../live/media.ts"; import { mediaNow, multiroom, type MediaNow } from "../live/media.ts";
import { SHOW_PRESENCE } from "../flags.ts"; import { SHOW_PRESENCE } from "../flags.ts";
@@ -48,6 +53,14 @@ import { load3d } from "../load3d.ts";
import { scaleGlow, buildMarkers, openMoreInfo, stateText, toggleEntity, withPluginPatch } from "../markers.ts"; import { scaleGlow, buildMarkers, openMoreInfo, stateText, toggleEntity, withPluginPatch } from "../markers.ts";
import { fanSpin } from "../entities/fans.ts"; import { fanSpin } from "../entities/fans.ts";
import { fixtureGlow } from "../entities/kinds.ts"; import { fixtureGlow } from "../entities/kinds.ts";
import { coverTiltEntity } from "../entities/covers.ts";
import { isSymcon, isSymconVariable, nativeBool, nativeText } from "../entities/symcon-values.ts";
import { WEATHER_VARIABLE_LABELS } from "../symcon-weather.ts";
import { floorUtilityAreas, floorUtilityReadings, utilityText } from "../utilities.ts";
import "./utility-report.ts";
import "./utility-overview.ts";
import { trendButton } from "./trend-button.ts";
import { deviceValuesText } from "../entities/device-values.ts";
import { furnitureShown, hiddenFurniture, withoutHidden } from "../entities/visibility.ts"; import { furnitureShown, hiddenFurniture, withoutHidden } from "../entities/visibility.ts";
import { pictureUrl } from "../entities/pictures.ts"; import { pictureUrl } from "../entities/pictures.ts";
import { fetchImage } from "../api.ts"; import { fetchImage } from "../api.ts";
@@ -117,6 +130,7 @@ export class NfView3d extends LitElement {
_liveCards: { state: true }, _liveCards: { state: true },
_liveCardOn: { state: true }, _liveCardOn: { state: true },
_houseFolded: { state: true }, _houseFolded: { state: true },
_utilityOverviewVisible: { state: true },
_swipe: { state: true }, _swipe: { state: true },
_menu: { state: true }, _menu: { state: true },
_pluginWindow: { state: true }, _pluginWindow: { state: true },
@@ -154,6 +168,7 @@ export class NfView3d extends LitElement {
_locked: { state: true }, _locked: { state: true },
_now: { state: true }, _now: { state: true },
roomLabels: { attribute: false }, roomLabels: { attribute: false },
roomNamesButton: { attribute: false },
floorStack: { attribute: false }, floorStack: { attribute: false },
panelOpen: { attribute: false }, panelOpen: { attribute: false },
alerts: { attribute: false }, alerts: { attribute: false },
@@ -301,6 +316,8 @@ export class NfView3d extends LitElement {
private clockTimer: ReturnType<typeof setInterval> | undefined; private clockTimer: ReturnType<typeof setInterval> | undefined;
/** Room names in 3D (cards can switch them off). */ /** Room names in 3D (cards can switch them off). */
declare roomLabels: boolean; declare roomLabels: boolean;
/** Cards expose the room-name switch in their own 3D top bar. The designer has its toolbar switch. */
declare roomNamesButton: boolean;
/** Floors below an opened floor: dimmed, stacked (the house up to it) or hidden. */ /** Floors below an opened floor: dimmed, stacked (the house up to it) or hidden. */
declare floorStack: FloorStack; declare floorStack: FloorStack;
private declare _thumbs: { floorId: string; url: string }[]; private declare _thumbs: { floorId: string; url: string }[];
@@ -395,8 +412,12 @@ export class NfView3d extends LitElement {
private declare _liveCardOn: boolean; private declare _liveCardOn: boolean;
/** The house card folded to its ring by the small corner button; remembered in this browser. */ /** The house card folded to its ring by the small corner button; remembered in this browser. */
private declare _houseFolded: boolean; private declare _houseFolded: boolean;
/** Visibility of the right utility overview, remembered independently of the top totals. */
private declare _utilityOverviewVisible: boolean;
private viewer: NextFloorViewer | null = null; private viewer: NextFloorViewer | null = null;
private hydronicModule: Awaited<ReturnType<typeof loadHydronics>> | null = null;
private hydronicGeneration = 0;
private starting = false; private starting = false;
/** States of the placed entities as last sent to the viewer. */ /** States of the placed entities as last sent to the viewer. */
private shownStates = new Map<string, HassEntity | undefined>(); private shownStates = new Map<string, HassEntity | undefined>();
@@ -443,6 +464,8 @@ export class NfView3d extends LitElement {
this._liveCards = []; this._liveCards = [];
this._liveCardOn = localStorage.getItem("nextfloor.cards") !== "0"; this._liveCardOn = localStorage.getItem("nextfloor.cards") !== "0";
this._houseFolded = localStorage.getItem("nextfloor.house_card_folded") === "1"; this._houseFolded = localStorage.getItem("nextfloor.house_card_folded") === "1";
try { this._utilityOverviewVisible = localStorage.getItem("nextfloor.utility_overview") !== "0"; }
catch { this._utilityOverviewVisible = true; }
this.selectedFurniture = null; this.selectedFurniture = null;
this.selectedDevice = null; this.selectedDevice = null;
this._sky = 0; this._sky = 0;
@@ -487,6 +510,7 @@ export class NfView3d extends LitElement {
} }
})(); })();
this.roomLabels = true; this.roomLabels = true;
this.roomNamesButton = false;
this.floorStack = "dim"; this.floorStack = "dim";
this._low = false; this._low = false;
this.panelOpen = false; this.panelOpen = false;
@@ -530,6 +554,7 @@ export class NfView3d extends LitElement {
disconnectedCallback(): void { disconnectedCallback(): void {
super.disconnectedCallback(); super.disconnectedCallback();
this.hydronicGeneration++; this.hydronicModule?.closeHydronic();
this.stopPlugins?.(); this.stopPlugins?.();
this.stopPlugins = null; this.stopPlugins = null;
this.listenToAnnouncements(false); this.listenToAnnouncements(false);
@@ -689,7 +714,7 @@ export class NfView3d extends LitElement {
if (changed.has("building") || changed.has("theme") || changed.has("floorThumbs") || changed.has("packs")) this.scheduleThumbs(); if (changed.has("building") || changed.has("theme") || changed.has("floorThumbs") || changed.has("packs")) this.scheduleThumbs();
// markers shown by kind outside the opened room change with the room // markers shown by kind outside the opened room change with the room
const byRoom = this.markersOutside ? ["markersOutside", "floorId", "roomId"] : ["markersOutside"]; const byRoom = this.markersOutside ? ["markersOutside", "floorId", "roomId"] : ["markersOutside"];
const forced = this.pluginsDirty || ["building", "markerMode", "heatMode", "flows", "alerts", "dimmed", ...byRoom].some((k) => changed.has(k)); const forced = this.pluginsDirty || ["building", "markerMode", "heatMode", "flows", "alerts", "dimmed", "holograms", "roomLabels", "floorId", "roomId", ...byRoom].some((k) => changed.has(k));
this.pluginsDirty = false; this.pluginsDirty = false;
if (forced || changed.has("hass")) this.syncDevices(forced); if (forced || changed.has("hass")) this.syncDevices(forced);
if (changed.has("autoOrbit")) v.setAutoOrbit(this.autoOrbit ? 0.06 : 0); if (changed.has("autoOrbit")) v.setAutoOrbit(this.autoOrbit ? 0.06 : 0);
@@ -840,6 +865,7 @@ export class NfView3d extends LitElement {
// a piece shown only while a helper is on (seasonal decoration) comes and goes with it // 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)); 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.shownStates = new Map(this.watched.map((id) => [id, hass.states[id]]));
this.syncHydronics(v, b, hass);
this.refreshToday(b); this.refreshToday(b);
this.refreshForecast(b); this.refreshForecast(b);
@@ -968,7 +994,7 @@ export class NfView3d extends LitElement {
playing.filter((m) => m.rings > 0).map((m) => ({ id: m.entity, at: m.at, color: m.color, level: m.volume ?? 0.5, size: m.rings })), playing.filter((m) => m.rings > 0).map((m) => ({ id: m.entity, at: m.at, color: m.color, level: m.volume ?? 0.5, size: m.rings })),
multiroom(playing).map(([a, c]) => [a.at, c.at]), multiroom(playing).map(([a, c]) => [a.at, c.at]),
); );
this.syncLhCards(v, b, livePic, liveCars, playing); this.syncLhCards(v, b, livePic, liveCars, playing, hass);
// TV screens: a TV or monitor linked to a media player that runs shows what runs // TV screens: a TV or monitor linked to a media player that runs shows what runs
v.setLiveScreens(this.dimmed ? [] : liveScreens(hass, b, this.furnitureLinks)); v.setLiveScreens(this.dimmed ? [] : liveScreens(hass, b, this.furnitureLinks));
v.setPictures(this.framePictures(hass, b)); v.setPictures(this.framePictures(hass, b));
@@ -1126,7 +1152,7 @@ export class NfView3d extends LitElement {
for (const floor of b.floors) for (const floor of b.floors)
for (const room of floor.rooms) { for (const room of floor.rooms) {
const st = room.floor_heating ? hass.states[room.floor_heating] : undefined; const st = room.floor_heating ? hass.states[room.floor_heating] : undefined;
const heats = st && (st.entity_id.startsWith("climate.") ? st.attributes.hvac_action === "heating" : st.state === "on" || st.state === "open"); const heats = st && (isSymcon(hass) ? nativeBool(st) === true : st.entity_id.startsWith("climate.") ? st.attributes.hvac_action === "heating" : st.state === "on" || st.state === "open");
if (heats) (tint ??= new Map()).set(room.id, [0.55, 0.24, 0.08]); if (heats) (tint ??= new Map()).set(room.id, [0.55, 0.24, 0.08]);
} }
} }
@@ -1234,7 +1260,7 @@ export class NfView3d extends LitElement {
const deviceTemp = !isCooling(f.type) ? deviceTempOf(hass, f.temp_entity) : null; const deviceTemp = !isCooling(f.type) ? deviceTempOf(hass, f.temp_entity) : null;
const deviceTempText = deviceTemp === null ? "" : `🌡 ${formatNumber(hass, fromCelsius(hass, deviceTemp), 1)} ${tempUnit(hass)}`; const deviceTempText = deviceTemp === null ? "" : `🌡 ${formatNumber(hass, fromCelsius(hass, deviceTemp), 1)} ${tempUnit(hass)}`;
const extraRef = f.type === "home_battery" ? f.soc : f.type === "wallbox" ? f.status : temps ? (f.temp_entity && f.temp_entity !== "none" ? f.temp_entity : f.temp_entity2) : deviceTemp !== null ? f.temp_entity : null; const extraRef = f.type === "home_battery" ? f.soc : f.type === "wallbox" ? f.status : temps ? (f.temp_entity && f.temp_entity !== "none" ? f.temp_entity : f.temp_entity2) : deviceTemp !== null ? f.temp_entity : null;
const extra = extraRef && extraRef !== "none" ? extraRef : null; const extra = extraRef && extraRef !== "none" ? extraRef : (f.values ?? []).find((v) => v.entity && v.entity !== "none")?.entity ?? null;
const link = linked ?? (extra ? { entity: null, power: null } : undefined); const link = linked ?? (extra ? { entity: null, power: null } : undefined);
if (!link) continue; if (!link) continue;
// a battery goes by its charge first: its power sensor is often placed on its own as well // a battery goes by its charge first: its power sensor is often placed on its own as well
@@ -1328,6 +1354,7 @@ export class NfView3d extends LitElement {
? formatPower(hass, Math.max(0, power)) ? formatPower(hass, Math.max(0, power))
: "", : "",
deviceTempText, deviceTempText,
deviceValuesText(hass, f.values),
] ]
.filter(Boolean) .filter(Boolean)
.join(" · "), .join(" · "),
@@ -1339,7 +1366,7 @@ export class NfView3d extends LitElement {
// inverter, battery, wallbox: their own text (watts, charge, status) is always worth a pin // inverter, battery, wallbox: their own text (watts, charge, status) is always worth a pin
energyDevice: f.type === "inverter" || f.type === "home_battery" || f.type === "wallbox" || f.type === "meter", energyDevice: f.type === "inverter" || f.type === "home_battery" || f.type === "wallbox" || f.type === "meter",
// a fridge's temperatures are worth a pin, like an energy device's values // a fridge's temperatures are worth a pin, like an energy device's values
readout: !!temps || undefined, readout: !!temps || !!f.values?.some((v) => v.entity && v.entity !== "none") || undefined,
show: f.marker ?? undefined, show: f.marker ?? undefined,
fromFurniture: true, fromFurniture: true,
}); });
@@ -1360,6 +1387,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 // 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); 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; 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}`); 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 // one without a pin of its own gets one above it, like a device's, that does the same
@@ -1561,7 +1589,7 @@ export class NfView3d extends LitElement {
} }
/** A lamp: its 3D model glows with the linked light and is tapped directly. */ /** A lamp: its 3D model glows with the linked light and is tapped directly. */
private lampMarker(hass: HomeAssistant, floor: Building["floors"][number], f: Furniture, entity: string | null): DeviceMarker & { fromFurniture: boolean } { private lampMarker(hass: HomeAssistant, floor: Building["floors"][number], f: Furniture, entity: string | null): DeviceMarker & { fromFurniture: boolean; readout?: boolean } {
const st = entity ? hass.states[entity] : undefined; const st = entity ? hass.states[entity] : undefined;
// further bulbs of the same fixture (a night light, an ambient ring): the lamp glows with them while its main light is off // further bulbs of the same fixture (a night light, an ambient ring): the lamp glows with them while its main light is off
const others = (f.extra_lights ?? []).map((id) => hass.states[id]).filter((s): s is HassEntity => !!s); const others = (f.extra_lights ?? []).map((id) => hass.states[id]).filter((s): s is HassEntity => !!s);
@@ -1605,7 +1633,7 @@ export class NfView3d extends LitElement {
bollard: base + f.h + 0.25, bollard: base + f.h + 0.25,
garden: base + f.h + 0.25, garden: base + f.h + 0.25,
}[model]; }[model];
const marker: DeviceMarker & { fromFurniture: boolean } = { const marker: DeviceMarker & { fromFurniture: boolean; readout?: boolean } = {
// a lamp without a light keeps a key of its own (it is drawn, but not tappable) // a lamp without a light keeps a key of its own (it is drawn, but not tappable)
id: entity ?? `lamp:${f.id}`, id: entity ?? `lamp:${f.id}`,
floorId: floor.id, floorId: floor.id,
@@ -1615,7 +1643,8 @@ export class NfView3d extends LitElement {
y, y,
icon: iconSvg("light"), icon: iconSvg("light"),
name: f.name || (entity ? entityName(hass, entity) : furnitureName(hass, f.type)), name: f.name || (entity ? entityName(hass, entity) : furnitureName(hass, f.type)),
text: st && (isActive(st) || !otherOn) ? stateText(hass, st) : otherOn ? entityName(hass, otherOn.entity_id) : "", text: [st && (isActive(st) || !otherOn) ? stateText(hass, st) : otherOn ? entityName(hass, otherOn.entity_id) : "", deviceValuesText(hass, f.values)].filter(Boolean).join(" · "),
readout: !!f.values?.some((v) => v.entity && v.entity !== "none"),
active: (st ? isActive(st) : false) || !!otherOn, active: (st ? isActive(st) : false) || !!otherOn,
unavailable: st ? isUnavailable(st) : false, unavailable: st ? isUnavailable(st) : false,
glow: st || others.length ? scaleGlow(fixtureGlow(st, others, f.color_entity && f.color_entity !== "none" ? hass.states[f.color_entity] : undefined), f.glow_scale) : null, glow: st || others.length ? scaleGlow(fixtureGlow(st, others, f.color_entity && f.color_entity !== "none" ? hass.states[f.color_entity] : undefined), f.glow_scale) : null,
@@ -2282,6 +2311,7 @@ export class NfView3d extends LitElement {
.presets=${(this.building?.settings.media_presets ?? []).filter((p) => !p.speakers?.length || p.speakers.includes(m.entity))} .presets=${(this.building?.settings.media_presets ?? []).filter((p) => !p.speakers?.length || p.speakers.includes(m.entity))}
?confirmSwitch=${this.confirmSet.has(m.entity)} ?confirmSwitch=${this.confirmSet.has(m.entity)}
.myPosition=${this.myPositionOf(m.entity)} .myPosition=${this.myPositionOf(m.entity)}
.tiltEntity=${coverTiltEntity(this.hass, this.building?.floors ?? [], m.entity)}
@close=${() => (this._menu = null)} @close=${() => (this._menu = null)}
></nf-quick-menu>`; ></nf-quick-menu>`;
} }
@@ -2301,6 +2331,11 @@ export class NfView3d extends LitElement {
if (entityId.startsWith("lamp:")) return; if (entityId.startsWith("lamp:")) return;
// in the past nothing is switched // in the past nothing is switched
if (this._travel) return; 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); const ownTap = entityId.startsWith("tap:") ? entityId.slice(4) : this.tapPins.get(entityId);
if (ownTap) { if (ownTap) {
const f = this.building?.floors.flatMap((fl) => fl.furniture).find((it) => it.id === ownTap); const f = this.building?.floors.flatMap((fl) => fl.furniture).find((it) => it.id === ownTap);
@@ -2512,15 +2547,15 @@ export class NfView3d extends LitElement {
</section>`; </section>`;
} }
private renderToday() { private renderToday(utilities: ReturnType<NfView3d["utilityOverview"]>) {
const b = this.building; const b = this.building;
const hass = this.hass; const hass = this.hass;
// the room panel (a room, or Outside) takes the right side; the Today card would lie under it and catch its taps (#83) // the room panel (a room, or Outside) takes the right side; the Today card would lie under it and catch its taps (#83)
if (!b || !hass || this.clean || this.roomId || this.panelOpen) return nothing; if (!b || !hass || this.clean || this.roomId || this.panelOpen) return nothing;
const forecast = this.renderForecast("top_right"); const forecast = this.renderForecast("top_right");
const today = this.today === false ? nothing : this.renderTodayCard(b, hass); const today = this.today === false ? nothing : this.renderTodayCard(b, hass);
if (today === nothing && forecast === nothing) return nothing; if (today === nothing && forecast === nothing && utilities === nothing) return nothing;
return html`<div class="nf-right-col" style=${this.clock === "top_right" ? "top: 78px" : ""}>${today}${forecast}</div>`; return html`<div class="nf-right-col ${utilities !== nothing ? "nf-utility-right" : ""}" style=${this.clock === "top_right" ? "top: 78px" : ""}>${utilities}${today}${forecast}</div>`;
} }
private renderTodayCard(b: Building, hass: HomeAssistant) { private renderTodayCard(b: Building, hass: HomeAssistant) {
@@ -2586,10 +2621,11 @@ export class NfView3d extends LitElement {
const hass = this.hass; const hass = this.hass;
const rows: { icon: string; label: string; value: string }[] = []; const rows: { icon: string; label: string; value: string }[] = [];
const floor = this.floorId ? b.floors.find((f) => f.id === this.floorId) : undefined; const floor = this.floorId ? b.floors.find((f) => f.id === this.floorId) : undefined;
const floorPower = floor?.power_entity ? readPower(hass?.states[floor.power_entity]) : null; const meter = floor && isSymcon(hass) ? floorUtilityReadings(hass, floor, b.floors.flatMap((f) => f.rooms)).find((r) => r.kind === "electricity" && r.metric === "power" && r.unit === "W") : undefined;
if (floor && floorPower !== null) { const floorPower = isSymcon(hass) ? meter?.value ?? null : floor?.power_entity ? readPower(hass?.states[floor.power_entity]) : null;
const share = consumption && consumption > 0 ? ` · ${translate(hass, "floor_power_share", { n: Math.round((Math.max(0, floorPower) / consumption) * 100) })}` : ""; if (floor && (meter || floorPower !== null)) {
rows.push({ icon: "⚡", label: floor.name, value: `${powerText(hass, floorPower)}${share}` }); const share = !meter?.incomplete && floorPower !== null && consumption && consumption > 0 ? ` · ${translate(hass, "floor_power_share", { n: Math.round((Math.max(0, floorPower) / consumption) * 100) })}` : "";
rows.push({ icon: "⚡", label: floor.name, value: `${meter ? utilityText(hass, meter) : powerText(hass, floorPower!)}${share}` });
} }
for (const [key, icon, label] of [["gas", "🔥", "energy_gas_short"], ["water", "💧", "energy_water_short"]] as const) { for (const [key, icon, label] of [["gas", "🔥", "energy_gas_short"], ["water", "💧", "energy_water_short"]] as const) {
const id = b.energy[key]; const id = b.energy[key];
@@ -2616,7 +2652,19 @@ export class NfView3d extends LitElement {
.catch(() => (this.dayCurves = null)); .catch(() => (this.dayCurves = null));
} }
private syncLhCards(v: NextFloorViewer, b: Building, pic: EnergyPicture, cars: ReturnType<NfView3d["liveCars"]>, media: MediaNow[]): void { 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 cards: LiveCard[] = [];
const s = pic.summary; const s = pic.summary;
const hasEnergy = s.solar !== null || s.grid !== null || s.battery !== null || s.consumption !== null; const hasEnergy = s.solar !== null || s.grid !== null || s.battery !== null || s.consumption !== null;
@@ -2637,20 +2685,40 @@ export class NfView3d extends LitElement {
for (const p of this.liveHeatPumps(b)) cards.push({ kind: "heatpump", at: p.at, name: p.name, pump: p.pump }); for (const p of this.liveHeatPumps(b)) cards.push({ kind: "heatpump", at: p.at, name: p.name, pump: p.pump });
for (const m of media) cards.push({ kind: "media", at: { ...m.at, y: m.at.y + 0.5 }, media: m }); for (const m of media) cards.push({ kind: "media", at: { ...m.at, y: m.at.y + 0.5 }, media: m });
} }
if (this.liveCardsOn && !this.dimmed) {
cards.push(...roomClimateCards(hass, b, this.floorId, this.roomId));
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; if (JSON.stringify(cards) !== JSON.stringify(this._liveCards)) this._liveCards = cards;
v.setLiveAnchors( v.setLiveAnchors(
cards.map((c) => c.at), cards.map((c) => c.at),
cards.length ? (i, x, y, visible) => this.placeLhCard(i, x, y, visible) : null, cards.length ? (i, x, y, visible, density) => this.placeLhCard(i, x, y, visible, density) : null,
); );
} }
/** Called by the viewer after every frame: moves a card to its point without a Lit render. */ /** Called by the viewer after every frame: moves a card to its point without a Lit render. */
private placeLhCard(i: number, x: number, y: number, visible: boolean): void { private placeLhCard(i: number, x: number, y: number, visible: boolean, density: number): void {
const el = this.renderRoot.querySelector<HTMLElement>(`.live-card[data-i="${i}"]`); const el = this.renderRoot.querySelector<HTMLElement>(`.live-card[data-i="${i}"]`);
if (!el) return; if (!el) return;
const card = this._liveCards[i], key = `${card.kind}:${card.at.floorId}:${card.at.x}:${card.at.z}`;
const wasVisible = el.dataset.zoomKey === key && el.dataset.zoomVisible === "1";
const active = this.shadowRoot?.activeElement;
const focused = !!active && el.contains(active);
const zoomVisible = focused || cardVisibleAtZoom(card, density, wasVisible);
el.dataset.zoomKey = key;
el.dataset.zoomVisible = zoomVisible ? "1" : "0";
el.dataset.density = String(Math.round(density));
el.dataset.priority = String(focused ? 110 : cardDetail(card).priority);
el.dataset.focused = focused ? "1" : "0";
el.dataset.x = String(x); el.dataset.x = String(x);
el.dataset.y = String(y); el.dataset.y = String(y);
el.style.visibility = visible ? "visible" : "hidden"; el.style.visibility = visible && zoomVisible ? "visible" : "hidden";
// the last card of the frame: lay them all out so none covers another // the last card of the frame: lay them all out so none covers another
if (i === this._liveCards.length - 1) unstackLhCards(this.renderRoot); if (i === this._liveCards.length - 1) unstackLhCards(this.renderRoot);
} }
@@ -2687,7 +2755,13 @@ export class NfView3d extends LitElement {
const own = this.ownSensors(); const own = this.ownSensors();
const e = this._liveEnergy?.summary; 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 energy = !!e && !this.roomId && this.showEnergy && !!this.hass && !(e.consumption === null && e.grid === null && e.solar === null && e.battery === null);
if (!energy) return own.length ? html`<div class="nf-energy" aria-live="off">${own}</div>` : nothing; const climate = this.building?.floors.some((f) => f.rooms.some((r) => r.climate_card) || 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;
this.dispatchEvent(new CustomEvent("room-names-change", { detail: { value: this.roomLabels }, bubbles: true, composed: true }));
}}><span>${translate(this.hass, "room_names_short")}</span><b aria-hidden="true">Aa</b></button>` : nothing;
if (!energy) return own.length || climateToggle !== nothing || roomNames !== nothing ? html`<div class="nf-energy" aria-live="off">${roomNames}${own}${climateToggle}</div>` : nothing;
const t = (k: Parameters<typeof translate>[1]) => translate(this.hass, k); const t = (k: Parameters<typeof translate>[1]) => translate(this.hass, k);
const items: { cls: string; label: string; value: string }[] = []; const items: { cls: string; label: string; value: string }[] = [];
if (e.solar !== null) items.push({ cls: "solar", label: t("energy_solar"), value: formatPower(this.hass, e.solar) }); if (e.solar !== null) items.push({ cls: "solar", label: t("energy_solar"), value: formatPower(this.hass, e.solar) });
@@ -2704,31 +2778,57 @@ export class NfView3d extends LitElement {
if (e.tariff) items.push({ cls: "tariff", label: t("energy_tariff"), value: `${formatNumber(this.hass, e.tariff.value, 3)} ${e.tariff.unit}`.trim() }); if (e.tariff) items.push({ cls: "tariff", label: t("energy_tariff"), value: `${formatNumber(this.hass, e.tariff.value, 3)} ${e.tariff.unit}`.trim() });
if (this.building) for (const m of this.meterRows(this.building)) items.push({ cls: "meter", label: `${m.icon} ${m.label}`, value: m.value }); if (this.building) for (const m of this.meterRows(this.building)) items.push({ cls: "meter", label: `${m.icon} ${m.label}`, value: m.value });
return html`<div class="nf-energy" aria-live="off"> return html`<div class="nf-energy" aria-live="off">
${roomNames}
${this.liveCardsOn && this._liveCards.some((c) => c.kind === "house") ? nothing : items.map((i) => html`<div class="nf-energy-item nf-energy-${i.cls}"><span>${i.label}</span><b>${i.value}</b></div>`)} ${this.liveCardsOn && this._liveCards.some((c) => c.kind === "house") ? nothing : items.map((i) => html`<div class="nf-energy-item nf-energy-${i.cls}"><span>${i.label}</span><b>${i.value}</b></div>`)}
${this.flows !== null ${this.flows !== null
? nothing ? nothing
: html`<button class="nf-energy-item nf-flow-toggle" aria-pressed=${this._flows} title=${t("flows_hint")} aria-label=${t("flows")} @click=${() => this.toggleFlows()}> : html`<button class="nf-energy-item nf-flow-toggle" aria-pressed=${this._flows} title=${t("flows_hint")} aria-label=${t("flows")} @click=${() => this.toggleFlows()}>
<span>${t("flows")}</span><b>⚡</b> <span>${t("flows")}</span><b>⚡</b>
</button>`} </button>`}
${this.holograms !== null ${this.renderCardToggle()}
? nothing
: html`<button class="nf-energy-item nf-flow-toggle" aria-pressed=${this._liveCardOn} title=${t("holos_hint")} aria-label=${t("holos")} @click=${() => this.toggleLhCards()}>
<span>${t("holos")}</span><b>◫</b>
</button>`}
${own} ${own}
</div>`; </div>`;
} }
/** The plan's own sensors at the top (outside temperature, the alarm…): their name and state; a tap opens their details. */ private renderCardToggle() {
return this.holograms !== null ? nothing : html`<button class="nf-energy-item nf-flow-toggle nf-card-toggle" aria-pressed=${this._liveCardOn} title=${translate(this.hass, "holos_hint")} aria-label=${translate(this.hass, "holos")} @click=${() => this.toggleLhCards()}>
<span>${translate(this.hass, "holos")}</span><b>◫</b>
</button>`;
}
/** Native utility readings for the current building/floor scope. */
private utilityOverview(inline: boolean) {
const b = this.building;
if (!b || !isSymcon(this.hass) || !this.showEnergy || this.clean || this.roomId || this.panelOpen || (!inline && !this._utilityOverviewVisible)) return nothing;
const rooms = b.floors.flatMap((f) => f.rooms), floors = this.floorId ? b.floors.filter((f) => f.id === this.floorId) : b.floors;
if (!floors.some((f) => floorUtilityReadings(this.hass, f, rooms).length || floorUtilityAreas(this.hass, f, rooms, true).length)) return nothing;
return html`<nf-utility-overview ?inline=${inline} .hass=${this.hass} .floors=${b.floors} .floorId=${this.floorId} .compact=${this._narrowStage}
@utility-open=${(e: CustomEvent<{ floorId: string; roomId: string | null }>) => { e.stopPropagation(); if (e.detail.roomId) this.openRoom(e.detail.floorId, e.detail.roomId); else this.fire("floor-tap", { floorId: e.detail.floorId }); }}></nf-utility-overview>`;
}
/** The plan's own sensors and utility controls at the top. */
private ownSensors() { private ownSensors() {
const summary = this.utilityOverview(true);
const overviewToggle = summary === nothing ? nothing : html`<button class="nf-energy-item nf-flow-toggle nf-utility-overview-toggle" aria-label="Rechte Übersicht" aria-pressed=${this._utilityOverviewVisible} title=${this._utilityOverviewVisible ? "Rechte Übersicht ausblenden" : "Rechte Übersicht einblenden"} @click=${() => {
this._utilityOverviewVisible = !this._utilityOverviewVisible;
try { localStorage.setItem("nextfloor.utility_overview", this._utilityOverviewVisible ? "1" : "0"); } catch { /* Keep the choice for this view when storage is unavailable. */ }
}}><span>Übersicht</span><b aria-hidden="true"><svg width="18" height="16" viewBox="0 0 20 16" fill="none" stroke="currentColor" stroke-width="1.3"><rect x="1" y="1" width="18" height="14" rx="2"/><path d="M12 1v14m2-10h3m-3 3h3m-3 3h3"/></svg></b></button>`;
const ids = this.sensorBar && this.hass ? (this.building?.settings.status_entities ?? []) : []; const ids = this.sensorBar && this.hass ? (this.building?.settings.status_entities ?? []) : [];
return ids const people = isSymcon(this.hass) ? (this.building?.presence ?? []).filter((link) => isSymconVariable(this.hass, link.person, [0])).map((link) => html`<div class="nf-energy-item nf-presence-state"><span>${link.name || entityName(this.hass, link.person)}</span><b>${nativeBool(this.hass.states[link.person]) === null ? "–" : nativeBool(this.hass.states[link.person]) ? "Anwesend" : "Abwesend"}${trendButton(this.hass, [link.person], link.name || "Anwesenheit")}</b></div>`) : [];
const weather = isSymcon(this.hass) ? Object.entries(this.building?.settings.weather_variables ?? {}).filter((entry): entry is [keyof typeof WEATHER_VARIABLE_LABELS, string] => !!entry[1] && entry[1] !== "none").map(([key, id]) => [WEATHER_VARIABLE_LABELS[key] || key, id]) : [];
if (isSymcon(this.hass) && this.building?.settings.rain_sensor && this.building.settings.rain_sensor !== "none") weather.push(["Regensensor", this.building.settings.rain_sensor]);
const weatherValues = weather.length ? html`<button class="nf-energy-item nf-flow-toggle nf-weather-values" aria-label="Wetterwerte anzeigen" title="Wetterwerte anzeigen" aria-haspopup="dialog" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>(".nf-weather-dialog")?.showModal()}><span>Wetter</span><b aria-hidden="true">⛅</b></button>
<dialog class="nf-weather-dialog" aria-label="Wetterwerte" @keydown=${(event: KeyboardEvent) => event.stopPropagation()}><header><b>Wetter</b><button type="button" class="nf-chip" aria-label="Schließen" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>(".nf-weather-dialog")?.close()}>×</button></header>${weather.map(([label, id]) => html`<p><span>${label}</span><b>${nativeText(this.hass.states[id])}${trendButton(this.hass, [id], label)}</b></p>`)}</dialog>` : nothing;
const floors = isSymcon(this.hass) ? (this.building?.floors ?? []).filter((f) => !this.floorId || f.id === this.floorId).map((f) => ({ floor: f, readings: floorUtilityReadings(this.hass, f, this.building?.floors.flatMap((x) => x.rooms)) })).filter((f) => f.readings.length) : [];
const utilities = floors.length ? html`<button class="nf-energy-item nf-flow-toggle nf-utility-toggle" aria-label="Stockwerkszähler anzeigen" title="Stockwerkszähler anzeigen" aria-haspopup="dialog" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>(".nf-utility-dialog")?.showModal()}><span>Stockwerkszähler</span><b aria-hidden="true">⚡ 💧</b></button>
<dialog class="nf-weather-dialog nf-utility-dialog" aria-label="Stockwerkszähler" @keydown=${(event: KeyboardEvent) => event.stopPropagation()}><header><b>Stockwerkszähler</b><button type="button" class="nf-chip" aria-label="Schließen" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>(".nf-utility-dialog")?.close()}>×</button></header>${floors.map(({ floor, readings }) => html`<h3>${floor.name}</h3><nf-utility-report .hass=${this.hass} .readings=${readings}></nf-utility-report>`)}</dialog>` : nothing;
return [overviewToggle, summary, ...people, weatherValues, utilities, ...ids
.filter((id) => this.hass.states[id]) .filter((id) => this.hass.states[id])
.map( .map(
(id) => html`<button class="nf-energy-item nf-own-sensor" title=${entityName(this.hass, id)} @click=${() => openMoreInfo(this, id)}> (id) => html`<button class="nf-energy-item nf-own-sensor" title=${entityName(this.hass, id)} @click=${() => openMoreInfo(this, id)}>
<span>${entityName(this.hass, id)}</span><b>${stateText(this.hass, this.hass.states[id])}</b> <span>${entityName(this.hass, id)}</span><b>${stateText(this.hass, this.hass.states[id])}</b>
</button>`, </button>${trendButton(this.hass, [id], entityName(this.hass, id))}`,
); )];
} }
/** The map's credit while a real map lies under the plan (OpenStreetMap asks for it). */ /** The map's credit while a real map lies under the plan (OpenStreetMap asks for it). */
@@ -2785,17 +2885,18 @@ export class NfView3d extends LitElement {
} }
protected render() { protected render() {
const utilities = this.utilityOverview(false);
const sky = this._sky; const sky = this._sky;
const mix = (a: number[], b: number[]) => `rgb(${a.map((v, i) => Math.round(v + (b[i] - v) * sky)).join(",")})`; const mix = (a: number[], b: number[]) => `rgb(${a.map((v, i) => Math.round(v + (b[i] - v) * sky)).join(",")})`;
const stage = STAGE[this.theme] ?? STAGE.neon; const stage = STAGE[this.theme] ?? STAGE.neon;
const style = `--nf-sky:${mix(stage.night[0], stage.day[0])};--nf-ground:${mix(stage.night[1], stage.day[1])}` + backdropStyle(this.building?.settings.backdrop); const style = `--nf-sky:${mix(stage.night[0], stage.day[0])};--nf-ground:${mix(stage.night[1], stage.day[1])}` + backdropStyle(this.building?.settings.backdrop);
return html`<div return html`<div
class="nf-stage ${this.roomLabels ? "" : "nf-no-room-names"} ${this._low ? "nf-low" : ""} ${this.panelOpen ? "nf-panel-open" : ""} ${this._alerts.length ? "nf-has-alerts" : ""} ${this._narrowStage ? "nf-narrow" : ""}" class="nf-stage ${this.roomLabels ? "" : "nf-no-room-names"} ${this._low ? "nf-low" : ""} ${this.panelOpen ? "nf-panel-open" : ""} ${this._alerts.length ? "nf-has-alerts" : ""} ${this._narrowStage ? "nf-narrow" : ""} ${utilities !== nothing ? "nf-has-utility-overview" : ""}"
style=${style} style=${style}
> >
${this._error ? html`<p class="nf-error">${this._error}</p>` : nothing} ${this.renderTopLeft()} ${renderLhCards(this.hass, this.roomId || this.panelOpen ? [] : this._liveCards, (domain, service, entity, data) => this.hass?.callService(domain, service, { entity_id: entity, ...data }), { folded: this._houseFolded, toggle: () => this.toggleHouseFold() })} ${this.clean ? nothing : this.renderLegend()} ${this.renderMapCredit()} ${this._error ? html`<p class="nf-error">${this._error}</p>` : nothing} ${this.renderTopLeft()} ${renderLhCards(this.hass, this._liveCards, (domain, service, entity, data) => this.hass?.callService(domain, service, { entity_id: entity, ...data }), { folded: this._houseFolded, toggle: () => this.toggleHouseFold() }, !!this.roomId || this.panelOpen)} ${this.clean ? nothing : this.renderLegend()} ${this.renderMapCredit()}
${this.renderAlerts()} ${this.renderAnnouncement()} ${this.clean ? nothing : html`${this.renderThumbs()} ${this.renderScenes()} ${this.renderFind()} ${this.renderCentral()}`} ${this.renderSwipe()} ${this.renderAlerts()} ${this.renderAnnouncement()} ${this.clean ? nothing : html`${this.renderThumbs()} ${this.renderScenes()} ${this.renderFind()} ${this.renderCentral()}`} ${this.renderSwipe()}
${this.renderMenu()} ${this.renderPlate()} ${this.renderEye()} ${this.renderLock()} ${this.renderWalk()} ${this.renderTravel()} ${this.renderClock()} ${this.renderToday()} ${this.renderLayers()} ${this.renderPluginWindow()} ${this.renderMenu()} ${this.renderPlate()} ${this.renderEye()} ${this.renderLock()} ${this.renderWalk()} ${this.renderTravel()} ${this.renderClock()} ${this.renderToday(utilities)} ${this.renderLayers()} ${this.renderPluginWindow()}
${this.showStats && this._stats ${this.showStats && this._stats
? html`<span class="nf-stats" ? html`<span class="nf-stats"
><b>${this._stats.fps ? translate(this.hass, "stats_fps", { fps: this._stats.fps, ms: this._stats.worstMs }) : translate(this.hass, "stats_idle")}</b> ><b>${this._stats.fps ? translate(this.hass, "stats_fps", { fps: this._stats.fps, ms: this._stats.worstMs }) : translate(this.hass, "stats_idle")}</b>
@@ -3137,7 +3238,7 @@ export class NfView3d extends LitElement {
.nf-person[hidden] { .nf-person[hidden] {
display: none; display: none;
} }
.nf-no-room-names .nf-pin { .nf-no-room-names .nf-pin[data-room] {
display: none !important; display: none !important;
} }
/* tablet level: blur over the canvas and glowing shadows are expensive on weak GPUs */ /* tablet level: blur over the canvas and glowing shadows are expensive on weak GPUs */
@@ -3377,6 +3478,24 @@ export class NfView3d extends LitElement {
.nf-right-col > * { .nf-right-col > * {
pointer-events: auto; pointer-events: auto;
} }
.nf-utility-right {
height: calc(100% - 140px);
}
.nf-has-utility-overview:not(.nf-narrow) > .nf-energy,
.nf-has-utility-overview:not(.nf-narrow) > .nf-topleft {
max-width: calc(100% - 316px);
}
.nf-has-utility-overview .nf-energy {
align-items: flex-start;
}
.nf-narrow .nf-utility-right {
top: auto !important;
bottom: 64px;
height: 42%;
max-height: 42%;
justify-content: flex-end;
width: min(280px, calc(100% - 24px));
}
.nf-has-alerts .nf-right-col { .nf-has-alerts .nf-right-col {
top: 58px; top: 58px;
} }
@@ -4242,6 +4361,11 @@ export class NfView3d extends LitElement {
text-align: left; text-align: left;
font: inherit; font: inherit;
} }
.nf-weather-dialog { pointer-events:auto; width:min(380px,calc(100vw - 32px)); max-height:75dvh; overflow:auto; box-sizing:border-box; padding:16px; background:var(--nf-chrome-solid); color:var(--nf-text); font:14px/1.5 system-ui,sans-serif; border:1px solid var(--nf-line); border-radius:12px; box-shadow:var(--nf-shadow); }
.nf-weather-dialog::backdrop { background:#0008; }
.nf-weather-dialog header,.nf-weather-dialog p { display:flex; justify-content:space-between; gap:16px; margin:8px 0; }
.nf-weather-dialog p span { color:var(--nf-muted); }
.nf-weather-dialog p b { font-size:13px; white-space:nowrap; }
.nf-own-sensor { .nf-own-sensor {
pointer-events: auto; pointer-events: auto;
cursor: pointer; cursor: pointer;
@@ -37,7 +37,28 @@ test("the sensors of the rooms' areas are only watched when the heat map or room
}); });
test("opening links bring their blinds, contacts and positions along", () => { test("opening links bring their blinds, contacts and positions along", () => {
const links = new Map([["o1", { cover: "cover.blind", contact: "binary_sensor.window", tilt: null, contact2: "binary_sensor.second", position: "sensor.pos" }]]); const links = new Map([["o1", { cover: "cover.blind", coverTilt: "cover.slats", cover2Tilt: "cover.slats2", contact: "binary_sensor.window", tilt: null, contact2: "binary_sensor.second", position: "sensor.pos" }]]);
const ids = watchedEntities(inputs({ openingLinks: links as never })); const ids = watchedEntities(inputs({ openingLinks: links as never }));
for (const id of ["cover.blind", "binary_sensor.window", "binary_sensor.second", "sensor.pos"]) assert.ok(ids.includes(id), id); for (const id of ["cover.blind", "cover.slats", "cover.slats2", "binary_sensor.window", "binary_sensor.second", "sensor.pos"]) assert.ok(ids.includes(id), id);
});
test("a standalone blind's separate slat position is watched", () => {
const b = building();
b.floors[0].placements.push({ entity_id: "cover.blind", cover_tilt: "cover.slats", x: 2, z: 2, y: null });
assert.ok(watchedEntities(inputs({ building: b })).includes("cover.slats"));
});
test("all custom device and furniture readings are watched", () => {
const b = building();
b.floors[0].placements[0].values = [{ id: "a", entity: "sensor.inside" }, { id: "b", entity: "sensor.outside" }];
b.floors[0].furniture[0].values = [{ id: "c", entity: "sensor.lux" }];
const ids = watchedEntities(inputs({ building: b, needsRoomSensors: false }));
for (const id of ["sensor.inside", "sensor.outside", "sensor.lux"]) assert.ok(ids.includes(id));
});
test("room cards watch explicitly chosen values outside the area, including a source that is temporarily missing", () => {
const b = building();
Object.assign(b.floors[0].rooms[0], { climate_card: true, climate: { humidity: "cover.knx", temperature: "sensor.missing", co2: "sensor.other_room" } });
const ids = watchedEntities(inputs({ building: b, needsRoomSensors: false }));
for (const id of ["cover.knx", "sensor.missing", "sensor.other_room"]) assert.ok(ids.includes(id), id);
}); });
+15 -4
View File
@@ -2,7 +2,7 @@
// everything it shows: devices and their power sensors, openings and their contacts, energy, presence, heat, weather, and so on. // everything it shows: devices and their power sensors, openings and their contacts, energy, presence, heat, weather, and so on.
import { alertEntities, type AlertSources } from "../../alerts.ts"; import { alertEntities, type AlertSources } from "../../alerts.ts";
import { carWatched, deviceSiblings, kindOf, robotRoomSensor, type FurnitureLinks, type OpeningEntities, roomEntities } from "../../devices.ts"; import { carWatched, deviceSiblings, kindOf, robotRoomSensor, roomClimateSensors, type FurnitureLinks, type OpeningEntities, roomEntities } from "../../devices.ts";
import { powerSensorFor } from "../../energy.ts"; import { powerSensorFor } from "../../energy.ts";
import { placedEntities } from "../../markers.ts"; import { placedEntities } from "../../markers.ts";
import type { Building } from "../../model.ts"; import type { Building } from "../../model.ts";
@@ -10,6 +10,9 @@ import { parkingEntities } from "../../parking.ts";
import { pluginWatched } from "../../plugins/registry.ts"; import { pluginWatched } from "../../plugins/registry.ts";
import type { HomeAssistant } from "../../types.ts"; import type { HomeAssistant } from "../../types.ts";
import { weatherEntity } from "../../weather.ts"; import { weatherEntity } from "../../weather.ts";
import { utilityWatched } from "../../utilities.ts";
import { hydronicRefs } from "../../hydronic-model.ts";
import { chargingRefs } from "../../charging-station.ts";
export interface WatchInputs { export interface WatchInputs {
hass: HomeAssistant; hass: HomeAssistant;
@@ -30,7 +33,7 @@ const furnitureOf = (b: Building) => b.floors.flatMap((f) => f.furniture);
/** The sensors and entities behind the openings: blinds, contacts, tilt, positions. */ /** The sensors and entities behind the openings: blinds, contacts, tilt, positions. */
function openingIds(links: WatchInputs["openingLinks"]): MaybeId[] { function openingIds(links: WatchInputs["openingLinks"]): MaybeId[] {
return [...links.values()].flatMap((e) => [e.cover, e.cover2, e.contact, e.tilt, e.contact2, e.tilt2, e.position, e.tiltAngle]); return [...links.values()].flatMap((e) => [e.cover, e.cover2, e.coverTilt, e.cover2Tilt, e.contact, e.tilt, e.contact2, e.tilt2, e.position, e.tiltAngle]);
} }
/** What furniture is linked to besides its device: state lights, doors and thermometers of a fridge, battery, status, charge, export, pictures. */ /** What furniture is linked to besides its device: state lights, doors and thermometers of a fridge, battery, status, charge, export, pictures. */
@@ -42,7 +45,9 @@ function furnitureIds(inputs: WatchInputs): MaybeId[] {
...pieces.flatMap((m) => [m.state_entity, m.state_entity2, m.color_entity, ...(m.gang_entities ?? []), ...(m.extra_lights ?? []), m.cover_entity, m.care_entity, m.room_sensor, m.show_when?.entity, m.picture && /^[a-z_]+\.[a-z0-9_]+$/.test(m.picture) ? m.picture : null]), ...pieces.flatMap((m) => [m.state_entity, m.state_entity2, m.color_entity, ...(m.gang_entities ?? []), ...(m.extra_lights ?? []), m.cover_entity, m.care_entity, m.room_sensor, m.show_when?.entity, m.picture && /^[a-z_]+\.[a-z0-9_]+$/.test(m.picture) ? m.picture : null]),
// a washer's, dryer's or dishwasher's time left comes from a sensor next to its switch // 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.filter((m) => m.type === "washer" || m.type === "dryer" || m.type === "dishwasher").flatMap((m) => deviceSiblings(hass, furnitureLinks.get(m.id)?.entity ?? furnitureLinks.get(m.id)?.power).filter((id) => id.startsWith("sensor."))),
...pieces.flatMap((m) => [m.door_left, m.door_right, m.soc, m.status, m.charge, m.export, m.temp_entity, m.temp_entity2]), ...pieces.flatMap((m) => [m.door_left, m.door_right, m.soc, m.status, m.charge, m.export, m.temp_entity, m.temp_entity2, ...(m.values ?? []).map((v) => v.entity)]),
...pieces.flatMap(hydronicRefs),
...pieces.flatMap(chargingRefs),
...pieces.filter((m) => m.type === "robot_vacuum").map((m) => robotRoomSensor(hass, furnitureLinks.get(m.id)?.entity ?? null, m.room_sensor)), ...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)] : [])])), ...pieces.flatMap((m) => (m.pictures ?? []).flatMap((rule) => [rule.entity, ...(rule.image.startsWith("camera:") ? [rule.image.slice("camera:".length)] : [])])),
]; ];
@@ -59,9 +64,13 @@ export function watchedEntities(inputs: WatchInputs): string[] {
const placed = placedEntities(b); const placed = placedEntities(b);
const energy = b.energy; const energy = b.energy;
const lightsOfRooms = roomsOf(b).flatMap((r) => roomEntities(hass, r).filter((id) => kindOf(id) === "light")); const lightsOfRooms = roomsOf(b).flatMap((r) => roomEntities(hass, r).filter((id) => kindOf(id) === "light"));
const sensorsOfRooms = inputs.needsRoomSensors ? roomsOf(b).flatMap((r) => roomEntities(hass, r).filter((id) => id.startsWith("sensor.") || id.startsWith("climate."))) : []; const sensorsOfRooms = b.floors.flatMap((f) => f.rooms.flatMap((r) => inputs.needsRoomSensors || r.climate_card
? [...roomEntities(hass, r).filter((id) => id.startsWith("sensor.") || id.startsWith("climate.")), ...Object.values(r.climate ?? {}).flat(), ...(["temperature", "humidity", "co2", "illuminance"] as const).flatMap((key) => roomClimateSensors(hass, f, r, key))]
: []));
const ids: MaybeId[] = [ const ids: MaybeId[] = [
...placed, ...placed,
...utilityWatched(hass, b.floors),
...b.floors.flatMap((f) => f.placements.flatMap((p) => [p.cover_tilt, p.position, ...(p.values ?? []).map((v) => v.entity)])),
...openingIds(inputs.openingLinks), ...openingIds(inputs.openingLinks),
...placed.map((id) => powerSensorFor(hass, id)), ...placed.map((id) => powerSensorFor(hass, id)),
// what plugins draw for a device may follow further entities (a camera's motion sensor) // what plugins draw for a device may follow further entities (a camera's motion sensor)
@@ -79,6 +88,8 @@ export function watchedEntities(inputs: WatchInputs): string[] {
...b.presence.flatMap((p) => [p.person, p.sensor]), ...b.presence.flatMap((p) => [p.person, p.sensor]),
...lightsOfRooms, ...lightsOfRooms,
...roomsOf(b).map((r) => r.floor_heating), ...roomsOf(b).map((r) => r.floor_heating),
...roomsOf(b).flatMap((r) => Object.values(r.hvac ?? {}).flat()),
...Object.values(b.settings.weather_variables ?? {}),
...b.floors.flatMap((f) => (f.outdoor ?? []).flatMap((a) => [a.temp_entity, a.pump_entity])), ...b.floors.flatMap((f) => (f.outdoor ?? []).flatMap((a) => [a.temp_entity, a.pump_entity])),
...sensorsOfRooms, ...sensorsOfRooms,
...(inputs.alertSources ? alertEntities(inputs.alertSources) : []), ...(inputs.alertSources ? alertEntities(inputs.alertSources) : []),
+3 -2
View File
@@ -6,6 +6,7 @@ import { entityAreaId, isHubDevice, powerSensorsOf } from "./devices.ts";
import { generateWalls } from "./geometry/walls.ts"; import { generateWalls } from "./geometry/walls.ts";
import type { Building, EnergySettings, Furniture } from "./model.ts"; import type { Building, EnergySettings, Furniture } from "./model.ts";
import type { HassEntity, HomeAssistant } from "./types.ts"; import type { HassEntity, HomeAssistant } from "./types.ts";
import { nativeNumber } from "./entities/symcon-values.ts";
export interface EnergySummary { export interface EnergySummary {
/** Grid power in W: positive is import, negative is export. */ /** Grid power in W: positive is import, negative is export. */
@@ -231,8 +232,8 @@ export function proposeEnergySensors(hass: HomeAssistant, prefs: EnergyPrefs): P
/** A power state in watts (kW and MW are converted), optionally with the sign flipped. Null when it is no number. */ /** A power state in watts (kW and MW are converted), optionally with the sign flipped. Null when it is no number. */
export function readPower(st: HassEntity | undefined, invert = false): number | null { export function readPower(st: HassEntity | undefined, invert = false): number | null {
const value = st ? Number(st.state) : NaN; const value = st?.attributes.symcon_id ? nativeNumber(st) : st ? Number(st.state) : null;
if (!Number.isFinite(value)) return null; if (value === null || !Number.isFinite(value)) return null;
const factor = { kW: 1e3, MW: 1e6 }[String(st!.attributes.unit_of_measurement ?? "W")] ?? 1; const factor = { kW: 1e3, MW: 1e6 }[String(st!.attributes.unit_of_measurement ?? "W")] ?? 1;
return invert ? -value * factor : value * factor; return invert ? -value * factor : value * factor;
} }
@@ -0,0 +1,112 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { box, entity, floorWith, hassOf, opening } from "./fixtures.ts";
import { openingEntities, openingState } from "./openings.ts";
import { isPositionVariable, positionPercent } from "./position-value.ts";
import { withCoverControls } from "./cover-controls.ts";
import { stateText } from "../markers.ts";
test("Symcon position feedback accepts numeric actuator domains and respects native integer/float ranges", () => {
const h = hassOf([
entity("cover.feedback", "open", { symcon_id: 1, symcon_variable_type: 1, symcon_numeric_value: 128, symcon_min: 0, symcon_max: 255 }),
entity("light.fraction", "on", { symcon_id: 2, symcon_variable_type: 2, symcon_numeric_value: 0.4, symcon_min: 0, symcon_max: 1 }),
entity("cover.one", "open", { symcon_id: 3, symcon_variable_type: 1, symcon_numeric_value: 1, symcon_min: 0, symcon_max: 100 }),
entity("sensor.text", "50", { symcon_id: 4, symcon_variable_type: 3 }),
]);
assert.equal(isPositionVariable(h, "cover.feedback"), true);
assert.equal(isPositionVariable(h, "light.fraction"), true);
assert.equal(isPositionVariable(h, "sensor.text"), false);
assert.equal(positionPercent(h, "cover.feedback"), 128 / 255 * 100);
assert.equal(positionPercent(h, "light.fraction"), 40);
assert.equal(positionPercent(h, "cover.one"), 1, "integer 1 is one percent, not a normalized float at full travel");
});
test("blind and slat inversions affect only 3D, retaining readings and slider, button and grouped command values", async () => {
for (const inverted of [false, true]) for (const tiltInverted of [false, true]) {
const calls: unknown[] = [];
const raw = hassOf([entity("cover.height", "open", { current_position: 5 }), entity("cover.slats", "open", { current_position: 30, symcon_id: 9 }), entity("cover.feedback", "open", { symcon_numeric_value: 40, symcon_min: 0, symcon_max: 100 }), entity("cover.normal", "open", { current_position: 90 })], {}, { callService: async (domain: string, service: string, data: unknown) => { calls.push([domain, service, data]); } });
const floor = floorWith([box("r", 0, 0, 4, 4)], { openings: [opening("w", "r", "window", { cover: "cover.height", cover_tilt: "cover.slats", position: "cover.feedback", cover_inverted: inverted, cover_tilt_inverted: tiltInverted })] });
const view = withCoverControls(raw, [floor]);
assert.equal(view.states["cover.height"].attributes.current_position, 40);
assert.equal(view.states["cover.height"].attributes.current_tilt_position, 30);
assert.equal(stateText(view, view.states["cover.height"]), "40 %");
const links = openingEntities(raw, [floor]).get("w")!;
const fromRaw = openingState(raw, links), fromView = openingState(view, links);
assert.ok(Math.abs(fromView.cover! - (inverted ? 0.4 : 0.6)) < 1e-9);
assert.equal(fromView.slats, tiltInverted ? 0.7 : 0.3);
assert.equal(fromRaw.cover, fromView.cover, "3D feedback cannot be inverted twice");
assert.equal(fromRaw.slats, fromView.slats);
await view.callService("cover", "set_cover_position", { entity_id: "cover.height", position: 75 });
await view.callService("cover", "set_cover_tilt_position", { entity_id: "cover.height", tilt_position: 20 });
await view.callService("cover", "open_cover", { entity_id: ["cover.height", "cover.normal"] });
assert.deepEqual(calls, [
["cover", "set_cover_position", { entity_id: "cover.height", position: 75 }],
["cover", "set_cover_tilt_position", { entity_id: "cover.slats", tilt_position: 20 }],
["cover", "open_cover", { entity_id: "cover.height" }],
["cover", "open_cover", { entity_id: "cover.normal" }],
]);
assert.equal(raw.states["cover.height"].attributes.current_position, 5, "the native state remains unchanged");
}
});
test("standalone feedback inversion is visual only, including facade reuse and changed settings", async () => {
const raw = hassOf([entity("cover.height", "closed", { current_position: 0, current_tilt_position: 20 }), entity("sensor.feedback", "25", { unit_of_measurement: "%" })]);
const floor = floorWith([], { placements: [{ entity_id: "cover.height", x: 1, z: 1, y: null, position: "sensor.feedback", position_inverted: true, cover_tilt_inverted: true }] });
const floors = [floor];
const first = withCoverControls(raw, floors);
assert.equal(first.states["cover.height"].attributes.current_position, 25);
assert.equal(first.states["cover.height"].attributes.current_tilt_position, 20);
assert.equal(withCoverControls(first, floors), first, "nested views cannot invert an already adapted facade again");
const next = withCoverControls(first, [{ ...floor, placements: [{ ...floor.placements[0], cover_inverted: true }] }]);
assert.equal(next.states["cover.height"].attributes.current_position, 25);
});
test("zero and full travel stay unchanged in values and commands, while each blind half reverses only its geometry", async () => {
for (const value of [0, 100]) for (const inverted of [false, true]) for (const tiltInverted of [false, true]) {
const calls: unknown[] = [];
const raw = hassOf([
entity("cover.main", value ? "open" : "closed", { current_position: value, current_tilt_position: value, symcon_id: 1 }),
entity("cover.second", value ? "open" : "closed", { current_position: value, current_tilt_position: value, symcon_id: 2 }),
], {}, { callService: async (domain: string, service: string, data: unknown) => { calls.push([domain, service, data]); } });
const floors = [floorWith([box("r", 0, 0, 4, 4)], { openings: [opening("w", "r", "window", { cover: "cover.main", cover2: "cover.second", cover_inverted: inverted, cover_tilt_inverted: tiltInverted, cover2_inverted: inverted, cover2_tilt_inverted: tiltInverted })] })];
const controls = withCoverControls(raw, floors);
const visual = openingState(controls, openingEntities(controls, floors).get("w")!);
const fraction = value / 100;
assert.equal(visual.cover, inverted ? fraction : 1 - fraction);
assert.equal(visual.cover2, visual.cover);
assert.equal(visual.slats, tiltInverted ? 1 - fraction : fraction);
assert.equal(visual.slats2, visual.slats);
assert.equal(stateText(controls, controls.states["cover.main"]), `${value} %`);
for (const id of ["cover.main", "cover.second"]) {
assert.equal(controls.states[id].attributes.current_tilt_position, value);
await controls.callService("cover", "set_cover_position", { entity_id: id, position: value });
await controls.callService("cover", "set_cover_tilt_position", { entity_id: id, tilt_position: value });
await controls.callService("cover", "close_cover", { entity_id: id });
await controls.callService("cover", "open_cover_tilt", { entity_id: id });
await controls.callService("cover", "stop_cover", { entity_id: id });
}
assert.deepEqual(calls, ["cover.main", "cover.second"].flatMap((id) => [
["cover", "set_cover_position", { entity_id: id, position: value }],
["cover", "set_cover_tilt_position", { entity_id: id, tilt_position: value }],
["cover", "close_cover", { entity_id: id }],
["cover", "open_cover_tilt", { entity_id: id }],
["cover", "stop_cover", { entity_id: id }],
]));
}
});
test("a reversed feedback sensor changes only 3D, not the value shown on the cover", () => {
const raw = hassOf([entity("cover.main", "closed", { current_position: 0 }), entity("sensor.feedback", "0", { unit_of_measurement: "%" })]);
const floors = [floorWith([box("r", 0, 0, 4, 4)], { openings: [opening("w", "r", "window", { cover: "cover.main", position: "sensor.feedback", position_inverted: true })] })];
const controls = withCoverControls(raw, floors);
assert.equal(controls.states["cover.main"].attributes.current_position, 0);
assert.equal(stateText(controls, controls.states["cover.main"]), "0 %");
assert.equal(openingState(controls, openingEntities(controls, floors).get("w")!).cover, 0);
});
test("unavailable slat feedback does not substitute the blind height in 3D", () => {
const raw = hassOf([entity("cover.main", "open", { current_position: 40 }), entity("cover.slats", "unavailable")]);
const floors = [floorWith([box("r", 0, 0, 4, 4)], { openings: [opening("w", "r", "window", { cover: "cover.main", cover_tilt: "cover.slats", cover_tilt_inverted: true })] })];
const controls = withCoverControls(raw, floors);
assert.equal(openingState(controls, openingEntities(controls, floors).get("w")!).slats, undefined);
});
+72
View File
@@ -0,0 +1,72 @@
// Combine live cover feedback and separate slat controls without changing values or command direction.
import type { Floor } from "../model.ts";
import type { HassEntity, HomeAssistant } from "../types.ts";
import { openingEntities } from "./openings.ts";
import { positionPercent } from "./position-value.ts";
interface Binding {
tilt?: string | null;
position?: string | null;
}
const cache = new WeakMap<HomeAssistant, WeakMap<readonly Floor[], HomeAssistant>>();
const sources = new WeakMap<HomeAssistant, HomeAssistant>();
export function withCoverControls(hass: HomeAssistant, floors: readonly Floor[]): HomeAssistant {
const raw = sources.get(hass) ?? hass;
const memo = cache.get(raw) ?? new WeakMap<readonly Floor[], HomeAssistant>();
cache.set(raw, memo);
const existing = memo.get(floors);
if (existing) return existing;
const bindings = new Map<string, Binding>();
for (const f of floors) for (const p of f.placements) if (p.entity_id.startsWith("cover.")) {
bindings.set(p.entity_id, { tilt: p.cover_tilt === "none" ? null : p.cover_tilt, position: p.position });
}
for (const e of openingEntities(raw, floors).values()) {
if (e.cover && !bindings.has(e.cover)) bindings.set(e.cover, { tilt: e.coverTilt, position: e.position });
if (e.cover2 && !bindings.has(e.cover2)) bindings.set(e.cover2, { tilt: e.cover2Tilt });
}
const states = { ...raw.states };
for (const [id, b] of bindings) {
const st = raw.states[id];
if (!st) continue;
const a: Record<string, unknown> = { ...st.attributes, nf_cover_control: true };
let position = positionPercent(raw, b.position);
if (position === null) position = typeof st.attributes.current_position === "number" ? st.attributes.current_position : null;
if (position !== null) a.current_position = position;
const tiltState = b.tilt ? raw.states[b.tilt] : st;
const tilt = typeof tiltState?.attributes.current_tilt_position === "number" ? tiltState.attributes.current_tilt_position : b.tilt ? positionPercent(raw, b.tilt) : null;
if (tilt !== null) {
a.current_tilt_position = tilt;
a.supported_features = Number(a.supported_features ?? 0) | 128;
}
let state = st.state;
if (typeof a.current_position === "number" && state !== "unavailable" && state !== "unknown" && state !== "opening" && state !== "closing") state = a.current_position > 0 ? "open" : "closed";
states[id] = { ...st, state, attributes: a } satisfies HassEntity;
}
const result: HomeAssistant = { ...raw, states, callService: async (domain, service, data = {}) => {
if (domain !== "cover") return raw.callService(domain, service, data);
const ids = Array.isArray(data.entity_id) ? data.entity_id : [data.entity_id];
const send = async (id: unknown) => {
const b = typeof id === "string" ? bindings.get(id) : undefined;
if (!b) return raw.callService(domain, service, { ...data, entity_id: id });
const payload: Record<string, unknown> = { ...data, entity_id: id };
let command = service;
if (command === "toggle" || command === "toggle_cover") command = states[String(id)]?.state === "closed" ? "open_cover" : "close_cover";
const tilt = command.includes("tilt");
if (tilt && b.tilt) payload.entity_id = b.tilt;
// A separate HA position-only cover controls its slats through its position service.
const target = b.tilt ? raw.states[b.tilt] : undefined;
if (tilt && b.tilt && !target?.attributes.symcon_id && typeof target?.attributes.current_tilt_position !== "number") {
if (command === "set_cover_tilt_position") { command = "set_cover_position"; payload.position = payload.tilt_position; delete payload.tilt_position; }
else if (command === "open_cover_tilt") command = "open_cover";
else if (command === "close_cover_tilt") command = "close_cover";
}
return raw.callService(domain, command, payload);
};
return Array.isArray(data.entity_id) ? Promise.all(ids.map(send)) : send(ids[0]);
} };
sources.set(result, raw);
memo.set(floors, result);
return result;
}
+15 -2
View File
@@ -1,10 +1,23 @@
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { test } from "node:test"; import { test } from "node:test";
import { entity, hassOf } from "./fixtures.ts"; import { box, entity, floorWith, hassOf, opening } from "./fixtures.ts";
import { coverPosition, coverReaches } from "./covers.ts"; import { coverPosition, coverReaches, coverTiltEntity, coverWithTilt } from "./covers.ts";
import { emptyBuilding, newFloor, type Furniture } from "../model.ts"; import { emptyBuilding, newFloor, type Furniture } from "../model.ts";
import { setPacks, type PackItem } from "../packs.ts"; import { setPacks, type PackItem } from "../packs.ts";
test("separate slat sources are resolved per blind and enrich only its control state", () => {
const hass = hassOf([entity("cover.height", "open", { current_position: 40, supported_features: 4 }), entity("cover.slats", "open", { current_position: 75 })]);
const floor = floorWith([box("r", 0, 0, 4, 4)], { openings: [opening("w", "r", "window", { cover: "cover.height", cover_tilt: "cover.slats" })] });
assert.equal(coverTiltEntity(hass, [floor], "cover.height"), "cover.slats");
const state = coverWithTilt(hass, hass.states["cover.height"], "cover.slats");
assert.equal(state.attributes.current_position, 40);
assert.equal(state.attributes.current_tilt_position, 75);
assert.equal(state.attributes.supported_features, 132);
assert.equal(hass.states["cover.height"].attributes.current_tilt_position, undefined, "one opening's mapping must not mutate a shared source");
const placed = floorWith([], { placements: [{ entity_id: "cover.height", cover_tilt: "cover.slats", x: 1, z: 1, y: null }] });
assert.equal(coverTiltEntity(hass, [placed], "cover.height"), "cover.slats", "standalone placed blinds also support a separate slat variable");
});
test("a cover's position comes from its attribute, else from open / closed", () => { test("a cover's position comes from its attribute, else from open / closed", () => {
const hass = hassOf([ const hass = hassOf([
entity("cover.a", "open", { current_position: 40 }), entity("cover.a", "open", { current_position: 40 }),
+22 -2
View File
@@ -1,9 +1,29 @@
// Pack items with moving parts (curtains, roller screens, awnings, gates) and the cover entity they follow. // Pack items with moving parts (curtains, roller screens, awnings, gates) and the cover entity they follow.
import type { Building } from "../model.ts"; import type { Building, Floor } from "../model.ts";
import { coverReach, hasMovingParts, packItem } from "../packs.ts"; import { coverReach, hasMovingParts, packItem } from "../packs.ts";
import type { HomeAssistant } from "../types.ts"; import type { HassEntity, HomeAssistant } from "../types.ts";
import { isUnavailable } from "./kinds.ts"; import { isUnavailable } from "./kinds.ts";
import { openingEntities } from "./openings.ts";
/** The separately selected slat variable of either blind of an opening. */
export function coverTiltEntity(hass: HomeAssistant, floors: readonly Floor[], id: string): string | null {
for (const f of floors) for (const p of f.placements) if (p.entity_id === id && p.cover_tilt && p.cover_tilt !== "none") return p.cover_tilt;
for (const e of openingEntities(hass, floors).values()) {
if (e.cover === id && e.coverTilt) return e.coverTilt;
if (e.cover2 === id && e.cover2Tilt) return e.cover2Tilt;
}
return null;
}
export function coverWithTilt(hass: HomeAssistant, st: HassEntity, tilt: string | null | undefined): HassEntity {
if (st.attributes.nf_cover_control) return st;
if (!tilt) return st;
const a = hass.states[tilt]?.attributes;
const position = a?.current_tilt_position ?? a?.current_position;
if (typeof position !== "number") return st;
return { ...st, attributes: { ...st.attributes, current_tilt_position: position, supported_features: Number(st.attributes.supported_features ?? 0) | 128 } };
}
/** How far open a cover is in percent: its position, else 100 / 0 from open / closed (moving counts half). Null when unknown. */ /** How far open a cover is in percent: its position, else 100 / 0 from open / closed (moving counts half). Null when unknown. */
export function coverPosition(hass: HomeAssistant, id: string | null | undefined): number | null { export function coverPosition(hass: HomeAssistant, id: string | null | undefined): number | null {
@@ -0,0 +1,27 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { entity, hassOf } from "./fixtures.ts";
import { deviceValueReadouts, deviceValuesText } from "./device-values.ts";
test("several temperatures and other device values keep independent symbols, labels and native readings", () => {
const h = hassOf([
entity("cover.temp", "open", { symcon_numeric_value: 22.7, unit_of_measurement: "°C", device_class: "temperature" }),
entity("sensor.out", "48.5", { unit_of_measurement: "°C", friendly_name: "Ausgang", device_class: "temperature" }),
entity("sensor.humidity", "55", { unit_of_measurement: "%", device_class: "humidity" }),
entity("sensor.status", "normal", {}),
]);
const links = [{ id: "a", entity: "cover.temp", icon: "❄", label: "Innen" }, { id: "b", entity: "sensor.out", icon: "🔥" }, { id: "c", entity: "sensor.humidity" }, { id: "d", entity: "sensor.status", icon: "✓" }];
const rows = deviceValueReadouts(h, links);
assert.deepEqual(rows.map((v) => v.icon), ["❄", "🔥", "💧", "✓"]);
assert.equal(rows[0].text, "22.7 °C", "an inferred actuator domain cannot replace the numeric reading with an on/off state");
assert.equal(rows[1].label, "Ausgang");
assert.equal(rows[3].text, "normal");
assert.match(deviceValuesText(h, links), /❄ Innen: 22.7 °C.*🔥 48.5 °C.*💧 55 %/);
assert.equal(deviceValueReadouts(h, [links[1]])[0].id, "b", "removing one link keeps the others intact");
});
test("unassigned values stay hidden and linked unavailable readings retain a dash", () => {
const h = hassOf([entity("sensor.offline", "unavailable"), entity("sensor.native", "on", { symcon_formatted: "Ein" })]);
const rows = deviceValueReadouts(h, [{ id: "empty", entity: null }, { id: "none", entity: "none" }, { id: "offline", entity: "sensor.offline" }, { id: "native", entity: "sensor.native" }]);
assert.deepEqual(rows.map((v) => v.text), ["–", "Ein"]);
});
+31
View File
@@ -0,0 +1,31 @@
import type { DeviceValueLink } from "../model.ts";
import type { HassEntity, HomeAssistant } from "../types.ts";
import { formatNumber } from "../i18n.ts";
import { entityName, isUnavailable } from "./kinds.ts";
export function valueSymbol(st: HassEntity | undefined): string {
const a = st?.attributes;
return ({ temperature: "🌡", humidity: "💧", carbon_dioxide: "☁", illuminance: "☀", power: "⚡", energy: "⚡" } as Record<string, string>)[String(a?.device_class)] ?? (a?.unit_of_measurement === "°C" ? "🌡" : "◉");
}
export function deviceValueReadouts(hass: HomeAssistant, links: readonly DeviceValueLink[] = []): { id: string; entity: string; icon: string; label: string; text: string }[] {
return links.flatMap((link) => {
if (!link.entity || link.entity === "none") return [];
const st = hass.states[link.entity];
let text = "–";
if (st && !isUnavailable(st)) {
const a = st.attributes;
if (typeof a.symcon_formatted === "string" && a.symcon_formatted.trim()) text = a.symcon_formatted;
else {
const raw = a.symcon_numeric_value ?? st.state;
const n = typeof raw === "number" || (typeof raw === "string" && raw.trim()) ? Number(raw) : NaN;
text = Number.isFinite(n) ? `${formatNumber(hass, n, hass.entities?.[link.entity]?.display_precision ?? (a.symcon_variable_type === 1 ? 0 : 1))}${a.unit_of_measurement ? ` ${a.unit_of_measurement}` : ""}` : String(raw ?? "–");
}
}
return [{ id: link.id, entity: link.entity, icon: link.icon?.trim() || valueSymbol(st), label: link.label?.trim() || entityName(hass, link.entity), text }];
});
}
export function deviceValuesText(hass: HomeAssistant, links: readonly DeviceValueLink[] = []): string {
return deviceValueReadouts(hass, links).map((v) => `${v.icon} ${v.label && links.find((l) => l.id === v.id)?.label ? `${v.label}: ` : ""}${v.text}`).join(" · ");
}
+1 -1
View File
@@ -248,7 +248,7 @@ export function roomPanelEntities(hass: HomeAssistant, floor: Floor, room: Room)
.filter((o) => o.room_id === room.id) .filter((o) => o.room_id === room.id)
.flatMap((o) => { .flatMap((o) => {
const e = openingLinks.get(o.id); const e = openingLinks.get(o.id);
return e ? [e.cover, e.contact, e.tilt, e.contact2] : []; return e ? [e.cover, e.cover2, e.contact, e.tilt, e.contact2] : [];
}), }),
...(room.panel ?? []), ...(room.panel ?? []),
]; ];
+3 -2
View File
@@ -192,8 +192,9 @@ export const tempUnit = (hass: HomeAssistant): "°C" | "°F" => (hass.config?.un
/** A reading in its unit (°F, K, anything else counts as °C) converted to °C. */ /** A reading in its unit (°F, K, anything else counts as °C) converted to °C. */
export function toCelsius(value: number, unit: unknown): number { export function toCelsius(value: number, unit: unknown): number {
if (unit === "°F") return ((value - 32) * 5) / 9; const normalized = String(unit ?? "").replace(/\s/g, "").toLowerCase();
if (unit === "K") return value - 273.15; if (normalized === "°f" || normalized === "℉") return ((value - 32) * 5) / 9;
if (normalized === "k") return value - 273.15;
return value; return value;
} }
+13
View File
@@ -184,3 +184,16 @@ test("a wide window's second blind and a venetian blind's slats", () => {
assert.equal(state.slats, 0.3); assert.equal(state.slats, 0.3);
assert.equal(openingState(hass, { cover: "cover.right", contact: null, tilt: null }).cover2, undefined, "no second blind"); assert.equal(openingState(hass, { cover: "cover.right", contact: null, tilt: null }).cover2, undefined, "no second blind");
}); });
test("a separate integer slat variable changes the 3D slats independently of the blind height", () => {
const hass = hassOf([
entity("cover.height", "open", { current_position: 40 }),
entity("cover.slats", "open", { current_position: 75 }),
]);
const state = openingState(hass, { cover: "cover.height", coverTilt: "cover.slats", contact: null, tilt: null });
assert.equal(state.cover, 0.6);
assert.equal(state.slats, 0.75);
const double = openingState(hass, { cover: "cover.height", coverTilt: "cover.slats", cover2: "cover.slats", cover2Tilt: "cover.height", contact: null, tilt: null });
assert.equal(double.slats, 0.75);
assert.equal(double.slats2, 0.4);
});
+40 -17
View File
@@ -4,9 +4,13 @@ import type { Floor, Opening } from "../model.ts";
import type { HassEntity, HomeAssistant } from "../types.ts"; import type { HassEntity, HomeAssistant } from "../types.ts";
import { isUnavailable, kindOf } from "./kinds.ts"; import { isUnavailable, kindOf } from "./kinds.ts";
import { roomEntities } from "./registry.ts"; import { roomEntities } from "./registry.ts";
import { positionPercent } from "./position-value.ts";
export interface OpeningEntities { export interface OpeningEntities {
cover: string | null; cover: string | null;
coverTilt?: string | null;
coverInverted?: boolean;
coverTiltInverted?: boolean;
contact: string | null; contact: string | null;
tilt: string | null; tilt: string | null;
/** Contact and tilt sensor of the second leaf of a double door or window. */ /** Contact and tilt sensor of the second leaf of a double door or window. */
@@ -28,6 +32,9 @@ export interface OpeningEntities {
lock?: string | null; lock?: string | null;
/** A second blind of a wide window (its right half, seen from the room). */ /** A second blind of a wide window (its right half, seen from the room). */
cover2?: string | null; cover2?: string | null;
cover2Tilt?: string | null;
cover2Inverted?: boolean;
cover2TiltInverted?: boolean;
} }
const BLIND_CLASSES = new Set([undefined, "shutter", "blind", "awning", "shade", "curtain", "window"]); const BLIND_CLASSES = new Set([undefined, "shutter", "blind", "awning", "shade", "curtain", "window"]);
@@ -91,6 +98,12 @@ export function openingEntities(hass: HomeAssistant, floors: readonly Floor[]):
angled: o.type === "door" && !!o.open_angle, angled: o.type === "door" && !!o.open_angle,
lock: o.type === "door" ? unlessNone(o.lock) : null, lock: o.type === "door" ? unlessNone(o.lock) : null,
cover2: o.type === "garage" ? null : unlessNone(o.cover2), cover2: o.type === "garage" ? null : unlessNone(o.cover2),
coverTilt: unlessNone(o.cover_tilt),
cover2Tilt: unlessNone(o.cover2_tilt),
coverInverted: !!o.cover_inverted,
coverTiltInverted: !!o.cover_tilt_inverted,
cover2Inverted: !!o.cover2_inverted,
cover2TiltInverted: !!o.cover2_tilt_inverted,
}); });
} }
} }
@@ -127,38 +140,41 @@ export const DOOR_DEFAULT_OPEN = 0.5;
/** How far a blind is open according to a position sensor: a percentage or a 0-1 fraction. Null when unknown. */ /** How far a blind is open according to a position sensor: a percentage or a 0-1 fraction. Null when unknown. */
function reportedPosition(hass: HomeAssistant, id: string | null | undefined): number | null { function reportedPosition(hass: HomeAssistant, id: string | null | undefined): number | null {
const st = id ? hass.states[id] : undefined; const value = positionPercent(hass, id);
const value = st && !isUnavailable(st) ? Number(st.state) : NaN; return value === null ? null : value / 100;
if (!Number.isFinite(value)) return null;
const isPercent = st!.attributes.unit_of_measurement === "%" || value > 1;
return Math.min(1, Math.max(0, isPercent ? value / 100 : value));
} }
/** How closed the blind is (0 open, 1 closed) from the position sensor, else from the cover entity. Null without cover data. */ /** How closed the blind is (0 open, 1 closed) from the position sensor, else from the cover entity. Null without cover data. */
/** How far a cover entity is closed (0 up, 1 down), or null without one. */ /** How far a cover entity is closed (0 up, 1 down), or null without one. */
function coverClosed(hass: HomeAssistant, id: string | null | undefined): number | null { function coverClosed(hass: HomeAssistant, id: string | null | undefined, inverted = false): number | null {
const cover = id ? hass.states[id] : undefined; const cover = id ? hass.states[id] : undefined;
if (!cover || isUnavailable(cover)) return id ? 0 : null; if (!cover || isUnavailable(cover)) return id ? 0 : null;
const percent = cover.attributes.current_position; const percent = cover.attributes.current_position;
if (typeof percent === "number") return 1 - Math.min(100, Math.max(0, percent)) / 100; if (typeof percent === "number") { const closed = 1 - Math.min(100, Math.max(0, percent)) / 100; return inverted ? 1 - closed : closed; }
if (cover.state === "closed") return 1; if (cover.state === "closed") return inverted ? 0 : 1;
if (cover.state === "open") return inverted ? 1 : 0;
return cover.state === "opening" || cover.state === "closing" ? 0.5 : 0; return cover.state === "opening" || cover.state === "closing" ? 0.5 : 0;
} }
/** How far the slats of a venetian blind are open (0 shut, 1 level), from its tilt position; null when it reports none. */ /** How far the slats of a venetian blind are open (0 shut, 1 level), from its tilt position; null when it reports none. */
function slatsOpen(hass: HomeAssistant, id: string | null | undefined): number | null { function slatsOpen(hass: HomeAssistant, id: string | null | undefined, separate?: string | null, inverted = false): number | null {
const tilt = id ? hass.states[id]?.attributes.current_tilt_position : undefined; const main = hass.states[id || ""];
return typeof tilt === "number" ? Math.min(100, Math.max(0, tilt)) / 100 : null; const combined = !!main?.attributes.nf_cover_control;
const a = combined ? main!.attributes : hass.states[separate || id || ""]?.attributes;
const tilt = a?.current_tilt_position ?? (!combined && separate ? a?.current_position : undefined);
const value = typeof tilt === "number" ? Math.min(100, Math.max(0, tilt)) : separate ? positionPercent(hass, separate) : null;
return value === null ? null : (inverted ? 100 - value : value) / 100;
} }
function blindClosedFraction(hass: HomeAssistant, e: OpeningEntities): number | null { function blindClosedFraction(hass: HomeAssistant, e: OpeningEntities): number | null {
const reported = reportedPosition(hass, e.position); const reported = reportedPosition(hass, e.position);
if (reported !== null) return e.positionInverted ? reported : 1 - reported; if (reported !== null) { const closed = e.positionInverted ? reported : 1 - reported; return e.coverInverted ? 1 - closed : closed; }
const cover = e.cover ? hass.states[e.cover] : undefined; const cover = e.cover ? hass.states[e.cover] : undefined;
if (cover && !isUnavailable(cover)) { if (cover && !isUnavailable(cover)) {
const percent = cover.attributes.current_position; const percent = cover.attributes.current_position;
if (typeof percent === "number") return 1 - Math.min(100, Math.max(0, percent)) / 100; if (typeof percent === "number") return coverClosed(hass, e.cover, e.coverInverted);
if (cover.state === "closed") return 1; if (cover.state === "closed") return e.coverInverted ? 0 : 1;
if (cover.state === "open") return e.coverInverted ? 1 : 0;
return cover.state === "opening" || cover.state === "closing" ? 0.5 : 0; return cover.state === "opening" || cover.state === "closing" ? 0.5 : 0;
} }
return e.cover ? 0 : null; return e.cover ? 0 : null;
@@ -185,6 +201,7 @@ export interface OpeningState {
cover2?: number | null; cover2?: number | null;
/** Venetian blinds: how far the slats are open (0 shut, 1 level), from the cover's tilt position. */ /** Venetian blinds: how far the slats are open (0 shut, 1 level), from the cover's tilt position. */
slats?: number | null; slats?: number | null;
slats2?: number | null;
} }
/** /**
@@ -196,12 +213,19 @@ export function openingState(hass: HomeAssistant, e: OpeningEntities, type: Open
const isKnown = (id: string | null | undefined) => !!id && !!hass.states[id] && !isUnavailable(hass.states[id]); const isKnown = (id: string | null | undefined) => !!id && !!hass.states[id] && !isUnavailable(hass.states[id]);
const positionOf = (id: string | null | undefined) => (id ? windowPosition(hass.states[id]) : null); const positionOf = (id: string | null | undefined) => (id ? windowPosition(hass.states[id]) : null);
const cover = blindClosedFraction(hass, e); const cover = blindClosedFraction(hass, e);
const slats = slatsOpen(hass, e.cover, e.coverTilt, e.coverTiltInverted);
const slats2 = slatsOpen(hass, e.cover2, e.cover2Tilt, e.cover2TiltInverted);
const blindState = {
...(e.cover2 ? { cover2: coverClosed(hass, e.cover2, e.cover2Inverted) } : {}),
...(slats !== null ? { slats } : {}),
...(slats2 !== null ? { slats2 } : {}),
};
if (type === "door") { if (type === "door") {
// a door with a roller shutter (front door, patio door): the blind comes down over it // a door with a roller shutter (front door, patio door): the blind comes down over it
const leaf = positionOf(e.contact); const leaf = positionOf(e.contact);
const open = leaf === null ? (e.shut ? 0 : e.angled ? 1 : DOOR_DEFAULT_OPEN) : leaf === "closed" ? 0 : 1; const open = leaf === null ? (e.shut ? 0 : e.angled ? 1 : DOOR_DEFAULT_OPEN) : leaf === "closed" ? 0 : 1;
return { open, open2: positionOf(e.contact2) === "open" ? 1 : 0, tilt: 0, tilt2: 0, cover, sensed: leaf !== null || cover !== null, unlocked: isUnlocked(hass, e.lock), assumed: leaf === null }; return { open, open2: positionOf(e.contact2) === "open" ? 1 : 0, tilt: 0, tilt2: 0, cover, ...blindState, sensed: leaf !== null || cover !== null, unlocked: isUnlocked(hass, e.lock), assumed: leaf === null };
} }
if (type === "garage") { if (type === "garage") {
// a garage door without a cover shows its contact: open or closed; so does one whose cover cannot tell (a remote without // a garage door without a cover shows its contact: open or closed; so does one whose cover cannot tell (a remote without
@@ -231,7 +255,6 @@ export function openingState(hass: HomeAssistant, e: OpeningEntities, type: Open
tilt2: secondTilted ? 1 : 0, tilt2: secondTilted ? 1 : 0,
cover, cover,
sensed: isKnown(e.contact) || isKnown(e.tilt) || Number.isFinite(rawAngle), sensed: isKnown(e.contact) || isKnown(e.tilt) || Number.isFinite(rawAngle),
...(e.cover2 ? { cover2: coverClosed(hass, e.cover2) } : {}), ...blindState,
...(slatsOpen(hass, e.cover) !== null ? { slats: slatsOpen(hass, e.cover) } : {}),
}; };
} }
+28
View File
@@ -0,0 +1,28 @@
import type { HomeAssistant } from "../types.ts";
import { symconPercent } from "../symcon-controls.ts";
import { isUnavailable } from "./kinds.ts";
/** A feedback variable can be numeric even when its inferred entity domain is an actuator. */
export function isPositionVariable(hass: HomeAssistant | undefined, id: string): boolean {
const st = hass?.states[id];
if (!st) return false;
const a = st.attributes;
if (typeof a.symcon_id === "number") return a.symcon_variable_type === 1 || a.symcon_variable_type === 2;
return typeof a.current_position === "number" || (/^(sensor|number|input_number)\./.test(id) && !!st.state.trim() && Number.isFinite(Number(st.state)));
}
/** Percent open, using native Symcon ranges before considering plain 0–100 or 0–1 sensors. */
export function positionPercent(hass: HomeAssistant, id: string | null | undefined): number | null {
const st = id ? hass.states[id] : undefined;
if (!st || isUnavailable(st)) return null;
const a = st.attributes;
if (a.nf_cover_control && typeof a.current_position === "number") return a.current_position;
const native = symconPercent(st);
if (native !== null) return native;
if (typeof a.current_position === "number") return Math.max(0, Math.min(100, a.current_position));
if (!st.state.trim()) return null;
const value = Number(st.state);
if (!Number.isFinite(value)) return null;
const percent = a.unit_of_measurement === "%" || value > 1 || value < 0 ? value : value * 100;
return Math.max(0, Math.min(100, percent));
}
+32 -1
View File
@@ -2,7 +2,38 @@ import assert from "node:assert/strict";
import { test } from "node:test"; import { test } from "node:test";
import { entity, floorWith, box, hassOf } from "./fixtures.ts"; import { entity, floorWith, box, hassOf } from "./fixtures.ts";
import { registerPlugin, resetPlugins } from "../plugins/registry.ts"; import { registerPlugin, resetPlugins } from "../plugins/registry.ts";
import { areaEntities, entityAreaId, entityKind, groupByDevice, isHubDevice, isRelevant, isRoomClimateSensor, otherAreaEntities, powerSensorsOf, primaryEntities, roomClimateSensors, roomClimateValue, unassignedEntities } from "./registry.ts"; import { areaEntities, entityAreaId, entityKind, groupByDevice, isClimateValueSensor, isHubDevice, isRelevant, isRoomClimateSensor, otherAreaEntities, powerSensorsOf, primaryEntities, roomClimateSensors, roomClimateValue, unassignedEntities } from "./registry.ts";
test("a KNX numeric temperature remains selectable and readable even with an inferred actuator domain", () => {
const hass = hassOf([
entity("climate.12345", "heat", { symcon_id: 12345, symcon_variable_type: 2, symcon_numeric_value: 21.75, unit_of_measurement: "°C" }),
entity("sensor.23456", "22.5", { symcon_id: 23456, symcon_variable_type: 2, unit_of_measurement: " °C " }),
entity("sensor.power", "12", { device_class: "power", unit_of_measurement: "W" }),
entity("light.lamp", "on", { unit_of_measurement: "°C" }),
entity("sensor.fahrenheit", "68", { unit_of_measurement: "℉" }),
]);
assert.equal(isClimateValueSensor(hass, "climate.12345", "temperature"), true);
assert.equal(isClimateValueSensor(hass, "sensor.23456", "temperature"), true);
assert.equal(isClimateValueSensor(hass, "sensor.power", "temperature"), false);
assert.equal(isClimateValueSensor(hass, "light.lamp", "temperature"), false);
const room = { ...box("room", 0, 0, 4, 4), climate: { temperature: "climate.12345" } };
assert.equal(roomClimateValue(hass, null, room, "temperature"), 21.75);
assert.equal(roomClimateValue(hass, null, { ...room, climate: { temperature: "sensor.fahrenheit" } }, "temperature"), 20);
});
test("manual Symcon climate assignment accepts unclassified numeric values without relaxing automatic detection", () => {
const h = hassOf([
entity("cover.knx", "open", { symcon_id: 12, symcon_variable_type: 2, symcon_numeric_value: 48.5 }),
entity("sensor.percent", "50", { unit_of_measurement: "%" }),
entity("sensor.soil", "50", { device_class: "moisture", unit_of_measurement: "%" }),
entity("sensor.text", "50", { symcon_id: 13, symcon_variable_type: 3, unit_of_measurement: "%" }),
]);
assert.equal(isClimateValueSensor(h, "cover.knx", "humidity", true), true);
assert.equal(isClimateValueSensor(h, "cover.knx", "humidity"), false);
assert.equal(isClimateValueSensor(h, "sensor.percent", "humidity"), true);
assert.equal(isClimateValueSensor(h, "sensor.soil", "humidity"), false);
assert.equal(isClimateValueSensor(h, "sensor.text", "humidity", true), false);
});
const lounge = hassOf( const lounge = hassOf(
[ [
+24 -4
View File
@@ -206,9 +206,26 @@ export const primaryEntities = (hass: HomeAssistant, ids: readonly string[]): st
// ---------------------------------------------------------------- room climate // ---------------------------------------------------------------- room climate
/** Device classes of the three room values. */ /** Device classes of the three room values. */
export const CLIMATE_CLASSES = { temperature: "temperature", humidity: "humidity", co2: "carbon_dioxide" } as const; export const CLIMATE_CLASSES = { temperature: "temperature", humidity: "humidity", co2: "carbon_dioxide", illuminance: "illuminance" } as const;
export type ClimateKey = keyof typeof CLIMATE_CLASSES; export type ClimateKey = keyof typeof CLIMATE_CLASSES;
/** Numeric room values, including Symcon readings whose legacy domain was inferred from a parent name. */
export function isClimateValueSensor(hass: HomeAssistant, id: string, key: ClimateKey, manual = false): boolean {
const a = hass.states[id]?.attributes;
if (!a) return false;
const symconNumber = (a.symcon_variable_type === 1 || a.symcon_variable_type === 2) && typeof a.symcon_id === "number";
if (typeof a.symcon_id === "number" && !symconNumber) return false;
if (!symconNumber && !/^(sensor|input_number|number)\./.test(id)) return false;
// An explicit assignment gives an otherwise unclassified Symcon number its meaning.
if (manual && symconNumber) return true;
const unit = String(a.unit_of_measurement ?? "").replace(/\s/g, "").toLowerCase();
if (key === "temperature" && ["°c", "°f", "℃", "℉", "k"].includes(unit)) return true;
if (key === "humidity" && !a.device_class && ["%", "%rh", "%r.h.", "%rf", "%r.f."].includes(unit)) return true;
if (key === "co2" && unit === "ppm" && /co[₂2]/i.test(String(a.friendly_name ?? ""))) return true;
if (key === "illuminance" && ["lx", "lux"].includes(unit)) return true;
return a.device_class === CLIMATE_CLASSES[key];
}
/** A device with one of these domains is not a room sensor: a heat pump, a printer, a TV. */ /** A device with one of these domains is not a room sensor: a heat pump, a printer, a TV. */
const APPLIANCE_DOMAINS = new Set(["climate", "water_heater", "switch", "button", "camera", "media_player", "vacuum", "light", "fan", "lawn_mower"]); const APPLIANCE_DOMAINS = new Set(["climate", "water_heater", "switch", "button", "camera", "media_player", "vacuum", "light", "fan", "lawn_mower"]);
/** Words in a name (English and German) that mark a temperature that is not the room's: pipes, printers, chips, outdoors, cold appliances. */ /** Words in a name (English and German) that mark a temperature that is not the room's: pipes, printers, chips, outdoors, cold appliances. */
@@ -245,20 +262,23 @@ export function roomClimateSensors(hass: HomeAssistant, floor: Floor | null, roo
const inside = placedSensors.filter((p) => pointInPolygon([p.x, p.z], room.points)).map((p) => p.entity_id); const inside = placedSensors.filter((p) => pointInPolygon([p.x, p.z], room.points)).map((p) => p.entity_id);
const insideElsewhere = new Set(placedSensors.filter((p) => !pointInPolygon([p.x, p.z], room.points)).map((p) => p.entity_id)); const insideElsewhere = new Set(placedSensors.filter((p) => !pointInPolygon([p.x, p.z], room.points)).map((p) => p.entity_id));
const candidates = new Set([...roomEntities(hass, room).filter((id) => !insideElsewhere.has(id)), ...inside]); const candidates = new Set([...roomEntities(hass, room).filter((id) => !insideElsewhere.has(id)), ...inside]);
return [...candidates].filter((id) => id.startsWith("sensor.") && hass.states[id]?.attributes.device_class === CLIMATE_CLASSES[key] && isRoomClimateSensor(hass, id)); return [...candidates].filter((id) => id.startsWith("sensor.") && isClimateValueSensor(hass, id, key) && isRoomClimateSensor(hass, id));
} }
/** The average of the room's sensors, or null when none reports. Temperatures are always °C, whatever the sensor's unit. */ /** The average of the room's sensors, or null when none reports. Temperatures are always °C, whatever the sensor's unit. */
export function roomClimateValue(hass: HomeAssistant, floor: Floor | null, room: Room, key: ClimateKey): number | null { export function roomClimateValue(hass: HomeAssistant, floor: Floor | null, room: Room, key: ClimateKey): number | null {
const readings = roomClimateSensors(hass, floor, room, key) const readings = roomClimateSensors(hass, floor, room, key)
.map((id) => { .map((id) => {
const reading = Number(hass.states[id]?.state); const state = hass.states[id];
if (!state || isUnavailable(state) || (!state.state.trim() && state.attributes.symcon_numeric_value === undefined)) return NaN;
const reading = Number(state?.attributes.symcon_numeric_value ?? state?.state);
return key === "temperature" ? toCelsius(reading, hass.states[id]?.attributes.unit_of_measurement) : reading; return key === "temperature" ? toCelsius(reading, hass.states[id]?.attributes.unit_of_measurement) : reading;
}) })
.filter(Number.isFinite); .filter(Number.isFinite);
if (readings.length) return readings.reduce((sum, v) => sum + v, 0) / readings.length; if (readings.length) return readings.reduce((sum, v) => sum + v, 0) / readings.length;
if (room.climate?.[key]) return null;
// no room sensor: a thermostat of the room's area tells its temperature and humidity (heating curves, the heat map) // no room sensor: a thermostat of the room's area tells its temperature and humidity (heating curves, the heat map)
if (key === "co2" || room.climate?.[key] === "none") return null; if ((key !== "temperature" && key !== "humidity") || room.climate?.[key] === "none") return null;
const attr = key === "temperature" ? "current_temperature" : "current_humidity"; const attr = key === "temperature" ? "current_temperature" : "current_humidity";
const climates = roomEntities(hass, room) const climates = roomEntities(hass, room)
.filter((id) => id.startsWith("climate.")) .filter((id) => id.startsWith("climate."))
+10
View File
@@ -0,0 +1,10 @@
import type { RoomHvac } from "../model.ts";
export const ROOM_HVAC_FIELDS: readonly { key: Exclude<keyof RoomHvac, "schedules">; label: string; types: readonly number[]; control?: boolean }[] = [
{ key: "supply_vsr", label: "Zuluft-VSR", types: [0, 1, 2], control: true },
{ key: "extract_vsr", label: "Abluft-VSR", types: [0, 1, 2], control: true },
{ key: "supply_temperature", label: "Zulufttemperatur", types: [1, 2] },
{ key: "extract_temperature", label: "Ablufttemperatur", types: [1, 2] },
{ key: "reheat", label: "NHR (Nachheizregister)", types: [0, 1, 2], control: true },
{ key: "status", label: "Raumstatus", types: [1] },
];
+38
View File
@@ -0,0 +1,38 @@
import type { HassEntity, HomeAssistant } from "../types.ts";
export const isSymcon = (hass: HomeAssistant | undefined): boolean => hass?.symconObjects !== undefined;
/** Pick the original native variable, regardless of a guessed actuator domain. */
export function isSymconVariable(hass: HomeAssistant | undefined, id: string, types: readonly number[] = [0, 1, 2, 3]): boolean {
const a = hass?.states[id]?.attributes;
return !!a?.symcon_id && !a.symcon_source_entity && types.includes(Number(a.symcon_variable_type));
}
export function nativeValue(st: HassEntity | undefined): unknown {
if (!st || st.state === "unknown" || st.state === "unavailable") return null;
return st.attributes.symcon_value ?? st.attributes.symcon_numeric_value ?? st.state;
}
export function nativeNumber(st: HassEntity | undefined): number | null {
const value = nativeValue(st);
if (value === null || typeof value === "boolean" || value === "") return null;
const n = Number(value);
return Number.isFinite(n) ? n : null;
}
export function nativeBool(st: HassEntity | undefined): boolean | null {
const value = nativeValue(st);
if (value === null) return null;
if (typeof value === "boolean") return value;
if (typeof value === "number") return value > 0;
const word = String(value).trim().toLowerCase();
if (["on", "true", "1", "home", "open", "an", "ein", "ja", "regen", "rain", "wet", "nass"].includes(word)) return true;
if (["off", "false", "0", "not_home", "closed", "aus", "nein", "trocken", "dry"].includes(word)) return false;
const n = Number(word);
return word !== "" && Number.isFinite(n) ? n > 0 : null;
}
export function nativeText(st: HassEntity | undefined): string {
if (nativeValue(st) === null) return "–";
return String(st?.attributes.symcon_formatted ?? nativeValue(st));
}
+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
@@ -2,6 +2,7 @@
import { roomClimateValue } from "./devices.ts"; import { roomClimateValue } from "./devices.ts";
import { powerSensorFor, readPower } from "./energy.ts"; import { powerSensorFor, readPower } from "./energy.ts";
import { roomUtilityReadings } from "./utilities.ts";
import { roomSun } from "./live/sun-hours.ts"; import { roomSun } from "./live/sun-hours.ts";
import { comfortScore, isSummer, mouldRisk } from "./live/room-climate.ts"; import { comfortScore, isSummer, mouldRisk } from "./live/room-climate.ts";
import { pointInPolygon, type Building, type Floor, type Room } from "./model.ts"; import { pointInPolygon, type Building, type Floor, type Room } from "./model.ts";
@@ -93,7 +94,9 @@ export function heatColor(mode: HeatColorMode, value: number, summer = false): R
* What the devices of a room draw now, in watts: the power sensors of its device pins and of its furniture (a piece's own power * What the devices of a room draw now, in watts: the power sensors of its device pins and of its furniture (a piece's own power
* sensor, else the one on its entity's device), each counted once. Null when the room has none. The house's meters stay out. * sensor, else the one on its entity's device), each counted once. Null when the room has none. The house's meters stay out.
*/ */
export function roomPower(hass: HomeAssistant, building: Pick<Building, "energy">, floor: Floor, room: Room): number | null { export function roomPower(hass: HomeAssistant, building: Pick<Building, "energy"> & Partial<Pick<Building, "floors">>, floor: Floor, room: Room): number | null {
const metered = roomUtilityReadings(hass, room, building.floors?.flatMap((f) => f.rooms) ?? floor.rooms).filter((r) => r.kind === "electricity" && r.metric === "power");
if (metered.length) return metered.find((r) => r.unit === "W")?.value ?? null;
let sum: number | null = null; let sum: number | null = null;
for (const s of roomPowerSensors(hass, building, floor, room)) { for (const s of roomPowerSensors(hass, building, floor, room)) {
const w = readPower(hass.states[s]); const w = readPower(hass.states[s]);
@@ -103,7 +106,9 @@ export function roomPower(hass: HomeAssistant, building: Pick<Building, "energy"
} }
/** The power sensors of a room's device pins and furniture, each once, without the house's meters. */ /** The power sensors of a room's device pins and furniture, each once, without the house's meters. */
export function roomPowerSensors(hass: HomeAssistant, building: Pick<Building, "energy">, floor: Floor, room: Room): string[] { export function roomPowerSensors(hass: HomeAssistant, building: Pick<Building, "energy"> & Partial<Pick<Building, "floors">>, floor: Floor, room: Room): string[] {
const metered = roomUtilityReadings(hass, room, building.floors?.flatMap((f) => f.rooms) ?? floor.rooms).filter((r) => r.kind === "electricity" && r.metric === "power");
if (metered.length) return metered.filter((r) => r.unit === "W").flatMap((r) => r.sources);
const { grid, solar, battery } = building.energy; const { grid, solar, battery } = building.energy;
const meters = new Set([grid, solar, battery].filter(Boolean)); const meters = new Set([grid, solar, battery].filter(Boolean));
const sensors = new Set<string>(); const sensors = new Set<string>();
+49
View File
@@ -0,0 +1,49 @@
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);
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;
/** Mixing valve adds a return-side bypass; two-way valves stay in the flow only. */
valve_type?: "mixing" | "two_way";
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;
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 });
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([...(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, ...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))];
}
+72
View File
@@ -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);
});
+71
View File
@@ -0,0 +1,71 @@
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;
}
/** 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)),
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,
};
}
+108 -6
View File
@@ -23,6 +23,31 @@ const DE = {
needs_restart: "Eine neue Version von NextFloor ({frontend}) ist installiert, aber Home Assistant läuft noch mit {version}. Bitte Home Assistant neu starten – bis dahin kann das Speichern fehlschlagen.", needs_restart: "Eine neue Version von NextFloor ({frontend}) ist installiert, aber Home Assistant läuft noch mit {version}. Bitte Home Assistant neu starten – bis dahin kann das Speichern fehlschlagen.",
needs_reload: "Diese Seite zeigt noch NextFloor {frontend}, Home Assistant hat schon {backend}. Bitte die Seite neu laden; in der Companion-App: Einstellungen → Companion-App → Frontend-Cache zurücksetzen.", needs_reload: "Diese Seite zeigt noch NextFloor {frontend}, Home Assistant hat schon {backend}. Bitte die Seite neu laden; in der Companion-App: Einstellungen → Companion-App → Frontend-Cache zurücksetzen.",
reload_page: "Neu laden", reload_page: "Neu laden",
symcon_variables_reload: "Variablen neu laden",
symcon_cover_position: "Position (Behang)",
climate_card: "Raumklima als schwebende Karte",
climate_card_hint: "Zeigt Temperatur, Luftfeuchtigkeit und CO₂ über diesem Raum. In der 3D-Ansicht lassen sie sich über „Karten“ ein- und ausblenden.",
climate_card_missing: "Keine aktuellen Messwerte",
furniture_power_card: "Leistung als 3D-Kachel",
furniture_power_card_hint: "Zeigt den Leistungswert über diesem Möbelstück, auch ohne verknüpfte Schaltvariable. Die Kachel bleibt bei 0 W sichtbar. Bei archivierten Variablen öffnet das Trendsymbol den Verlauf. Der Schalter „Karten“ blendet die schwebenden Kacheln gemeinsam ein und aus.",
climate_illuminance: "Helligkeit",
device_values: "Zusätzliche Werte",
device_value: "Datenpunkt",
device_value_add: "Wert hinzufügen",
device_value_remove: "Wert entfernen",
device_value_icon: "Symbol",
device_value_label: "Bezeichnung (optional)",
device_values_hint: "Über + weitere Datenpunkte auswählen, zum Beispiel mehrere Temperaturen oder andere Messwerte. Als Symbol eignen sich Emojis oder kurze Zeichen wie 🌡, 💧, ☁ oder ⚡. Die Werte erscheinen am Gerät und im Raumfenster.",
cover_tilt_entity: "Lamellenposition",
cover_direction_invert: "Behang in 3D umkehren",
cover_tilt_direction_invert: "Lamellen in 3D umkehren",
cover2_direction_invert: "Zweiten Behang in 3D umkehren",
cover2_tilt_direction_invert: "Lamellen des zweiten Behangs in 3D umkehren",
cover_direction_hint: "Die Umkehrung betrifft nur die 3D-Darstellung. Zahlenwerte, Regler und Steuerbefehle bleiben unverändert: Ein empfangener Wert von 0 wird weiterhin als 0 angezeigt und ein eingestellter Wert von 0 als 0 gesendet.",
cover2_tilt_entity: "Lamellenposition (zweiter Behang)",
symcon_variables_loading: "Variablen werden geladen …",
symcon_variables_loaded: "Variablen und Objektbaum wurden neu geladen.",
symcon_variables_error: "Variablen konnten nicht neu geladen werden: {error}",
needs_restart_old: "Eine neue Version von NextFloor ist installiert, aber Home Assistant läuft noch mit einer älteren. Bitte Home Assistant neu starten – bis dahin schlägt das Speichern fehl.", needs_restart_old: "Eine neue Version von NextFloor ist installiert, aber Home Assistant läuft noch mit einer älteren. Bitte Home Assistant neu starten – bis dahin schlägt das Speichern fehl.",
draft_found: "Nicht gespeicherte Änderungen vom {time} gefunden.", draft_found: "Nicht gespeicherte Änderungen vom {time} gefunden.",
draft_restore: "Übernehmen und speichern", draft_restore: "Übernehmen und speichern",
@@ -746,6 +771,7 @@ const DE = {
sill_boards_inside: "Nur innen", sill_boards_inside: "Nur innen",
sill_boards_outside: "Nur außen", sill_boards_outside: "Nur außen",
room_names_short: "Raumnamen", room_names_short: "Raumnamen",
room_names_toggle_hint: "Raumnamen in der 3D-Ansicht ein- oder ausblenden",
floor_stack_short_dim: "Abgedunkelt", floor_stack_short_dim: "Abgedunkelt",
floor_stack_short_stacked: "Gestapelt", floor_stack_short_stacked: "Gestapelt",
floor_stack_short_single: "Einzeln", floor_stack_short_single: "Einzeln",
@@ -1101,12 +1127,17 @@ const DE = {
outdoor_opacity_hint: "100 = undurchsichtig. Weniger macht die Fläche durchsichtig, etwa eine Einfahrt über dem Keller; der Umriss bleibt.", outdoor_opacity_hint: "100 = undurchsichtig. Weniger macht die Fläche durchsichtig, etwa eine Einfahrt über dem Keller; der Umriss bleibt.",
outdoor_outline: "Umrisslinie zeigen", outdoor_outline: "Umrisslinie zeigen",
outdoor_outline_hint: "Ohne Haken zeichnet die Fläche keine Leuchtlinie an ihrem Rand – für große Grundstücke aus mehreren Rasenflächen.", outdoor_outline_hint: "Ohne Haken zeichnet die Fläche keine Leuchtlinie an ihrem Rand – für große Grundstücke aus mehreren Rasenflächen.",
outdoor_corners_hint: "Ecken: ein + auf einer Kante fügt eine Ecke hinzu, Ziehen formt die Fläche, × entfernt eine Ecke.", outdoor_corners_hint: "Ecken: ein + auf einer Kante fügt eine Ecke hinzu, Ziehen formt die Fläche, × entfernt eine Ecke. Beim Zeichnen und Verschieben rasten Flächen an benachbarten Ecken und Kanten ein. Alt unterdrückt das Einrasten.",
outdoor_hint: "Außenleuchten (Wegleuchte, Garten-Spot, Wandleuchte außen) beleuchten alle Außenflächen und die Fassade.", outdoor_hint: "Außenleuchten (Wegleuchte, Garten-Spot, Wandleuchte außen) beleuchten alle Außenflächen und die Fassade.",
out_lawn: "Rasen", out_lawn: "Rasen",
out_terrace: "Terrasse", out_terrace: "Terrasse",
out_path: "Weg", out_path: "Weg",
out_driveway: "Einfahrt", out_driveway: "Einfahrt",
out_street: "Straße",
out_sidewalk: "Gehweg",
out_gravel: "Schotterfläche",
out_river: "Fluss",
out_stream: "Bach",
out_pool: "Pool", out_pool: "Pool",
out_bed: "Beet", out_bed: "Beet",
out_hedge: "Hecke", out_hedge: "Hecke",
@@ -1129,7 +1160,7 @@ const DE = {
fence_gates_hint: "Ein Tor ist eine Lücke im Zaun mit Torpfosten und Flügel. Mit einem Antrieb (Cover, Schalter, Hilfsschalter, Schloss) und/oder Kontakt geht es in 3D auf: Garten- und Doppeltor schwingen nach innen, ein Schiebetor fährt hinter den Zaun.", fence_gates_hint: "Ein Tor ist eine Lücke im Zaun mit Torpfosten und Flügel. Mit einem Antrieb (Cover, Schalter, Hilfsschalter, Schloss) und/oder Kontakt geht es in 3D auf: Garten- und Doppeltor schwingen nach innen, ein Schiebetor fährt hinter den Zaun.",
outdoor_bracing: "X-Verstrebung", outdoor_bracing: "X-Verstrebung",
outdoor_cut: "Aus Flächen ausschneiden", outdoor_cut: "Aus Flächen ausschneiden",
outdoor_cut_hint: "Jede Fläche, in der diese ganz liegt, bekommt hier ein Loch – ein Pool in der Terrasse, ein Teich oder eine Wildfläche im Rasen. Die Reihenfolge beim Zeichnen spielt keine Rolle. Ein Pool schneidet sich von selbst aus.", outdoor_cut_hint: "Jede Fläche, in der diese ganz liegt, bekommt hier ein Loch – ein Pool in der Terrasse, ein Bach oder eine Wildfläche im Rasen. Die Reihenfolge beim Zeichnen spielt keine Rolle. Pool, Fluss und Bach schneiden sich von selbst aus.",
outdoor_area_hint: "Der Home-Assistant-Bereich dieser Fläche (Garten, Terrasse, Pool): seine Geräte und Sensoren stehen unter Draußen, und ein Pin auf der Fläche öffnet es.", outdoor_area_hint: "Der Home-Assistant-Bereich dieser Fläche (Garten, Terrasse, Pool): seine Geräte und Sensoren stehen unter Draußen, und ein Pin auf der Fläche öffnet es.",
pool_temp: "Wassertemperatur (optional)", pool_temp: "Wassertemperatur (optional)",
pool_pump: "Pumpe / Filter (optional)", pool_pump: "Pumpe / Filter (optional)",
@@ -1265,7 +1296,7 @@ const DE = {
cover_entity: "Rollladen", cover_entity: "Rollladen",
door_cover: "Antrieb (Tür oder Tor mit Motor)", door_cover: "Antrieb (Tür oder Tor mit Motor)",
cover_position_entity: "Positions-Sensor (live)", cover_position_entity: "Positions-Sensor (live)",
cover_position_invert: "Sensor zählt umgekehrt (0 = offen)", cover_position_invert: "Positionssensor in 3D umkehren (0 = offen)",
contact_entity: "Kontakt", contact_entity: "Kontakt",
sensor_kind: "Sensor-Art", sensor_kind: "Sensor-Art",
sensor_kind_contact: "Fensterkontakt (offen/zu)", sensor_kind_contact: "Fensterkontakt (offen/zu)",
@@ -1684,6 +1715,23 @@ const DE = {
furn_charge: "Ladeleistung (W, separater Sensor, optional)", furn_charge: "Ladeleistung (W, separater Sensor, optional)",
furn_charge_hint: "Meldet dein Speicher Laden und Entladen in zwei Sensoren (z. B. Anker Solix), nimm oben den Entlade-Sensor als Leistung und hier den Lade-Sensor. Ein Sensor mit Vorzeichen braucht das nicht.", furn_charge_hint: "Meldet dein Speicher Laden und Entladen in zwei Sensoren (z. B. Anker Solix), nimm oben den Entlade-Sensor als Leistung und hier den Lade-Sensor. Ein Sensor mit Vorzeichen braucht das nicht.",
furn_wallbox_status: "Status (lädt, angesteckt)", furn_wallbox_status: "Status (lädt, angesteckt)",
charging_data: "Ladedaten",
charging_card: "Ladestation als 3D-Kachel",
charging_hint: "Verknüpfte Ladedaten erscheinen in der 3D-Kachel und im Raummenü, auch ohne Leistungswert. Nicht verknüpfte Zeilen bleiben ausgeblendet. Zeitprofile und Integer-Aliase werden aus Symcon übernommen. Ohne Zeitprofil erkennt Automatisch Unix-Zeitstempel; numerische Ladezeiten ohne Einheit gelten als Sekunden. Die Formatwahl kann dies ändern. Die Werte dienen ausschließlich der Anzeige.",
charging_start: "Startzeit",
charging_end: "Endzeit",
charging_duration: "Ladezeit",
charging_energy: "Geladene Energie",
charging_lock: "Verriegelungsstatus",
charging_time_format: "Zeitformat",
charging_duration_unit: "Ladezeit-Einheit",
charging_auto: "Automatisch",
charging_value: "Symcon-Wert unverändert",
charging_seconds: "Sekunden",
charging_minutes: "Minuten",
charging_hours: "Stunden",
charging_unix_seconds: "Unix-Zeit (Sekunden)",
charging_unix_ms: "Unix-Zeit (Millisekunden)",
energy_only_note: "⚡ Energie: Hier lassen sich nur Solarfelder und Energiegeräte verschieben, Räume und Möbel sind gesperrt.", energy_only_note: "⚡ Energie: Hier lassen sich nur Solarfelder und Energiegeräte verschieben, Räume und Möbel sind gesperrt.",
roof_only_note: "🏠 Dach: Hier lassen sich nur Dachflächen und Dachfenster verschieben, Räume und Möbel sind gesperrt.", roof_only_note: "🏠 Dach: Hier lassen sich nur Dachflächen und Dachfenster verschieben, Räume und Möbel sind gesperrt.",
energy_devices_hint: "Stromzähler, Wechselrichter, Stromspeicher, Wallbox und Netzanschluss werden hier angelegt: auf der oben gewählten Etage, im Grundriss verschiebbar. Mit Leistungssensor zeigen sie ihre Watt; der Zähler bekommt den Netzsensor, beim Strang wählst du den Wechselrichter. Mehrere Wechselrichter und Speicher (etwa eine Balkonanlage dazu) gehen auch: Jeder bekommt seinen eigenen Sensor.", energy_devices_hint: "Stromzähler, Wechselrichter, Stromspeicher, Wallbox und Netzanschluss werden hier angelegt: auf der oben gewählten Etage, im Grundriss verschiebbar. Mit Leistungssensor zeigen sie ihre Watt; der Zähler bekommt den Netzsensor, beim Strang wählst du den Wechselrichter. Mehrere Wechselrichter und Speicher (etwa eine Balkonanlage dazu) gehen auch: Jeder bekommt seinen eigenen Sensor.",
@@ -1808,6 +1856,9 @@ const DE = {
furn_inverter: "Wechselrichter", furn_inverter: "Wechselrichter",
furn_home_battery: "Stromspeicher", furn_home_battery: "Stromspeicher",
furn_wallbox: "Wallbox", furn_wallbox: "Wallbox",
furn_heating_manifold: "Heiz-/Kühlkreisverteiler",
furn_buffer_tank: "Pufferspeicher",
furn_freshwater_station: "Frischwasserstation",
furn_entity: "Gerät (Schalter, Steckdose …)", furn_entity: "Gerät (Schalter, Steckdose …)",
furn_state_entity: "Zustand von (optional)", furn_state_entity: "Zustand von (optional)",
furn_state_entity2: "Zweiter Zustand (andere Hälfte)", furn_state_entity2: "Zweiter Zustand (andere Hälfte)",
@@ -2042,6 +2093,31 @@ const EN: Record<Key, string> = {
needs_restart: "A new version of NextFloor ({frontend}) is installed, but Home Assistant still runs {version}. Please restart Home Assistant – until then saving may fail.", needs_restart: "A new version of NextFloor ({frontend}) is installed, but Home Assistant still runs {version}. Please restart Home Assistant – until then saving may fail.",
needs_reload: "This page still shows NextFloor {frontend}, Home Assistant already has {backend}. Please reload the page; in the companion app: Settings → Companion app → Reset frontend cache.", needs_reload: "This page still shows NextFloor {frontend}, Home Assistant already has {backend}. Please reload the page; in the companion app: Settings → Companion app → Reset frontend cache.",
reload_page: "Reload", reload_page: "Reload",
symcon_variables_reload: "Reload variables",
symcon_cover_position: "Blind position",
climate_card: "Room climate as a floating card",
climate_card_hint: "Shows temperature, humidity and CO₂ over this room. Toggle them with “Cards” in the 3D view.",
climate_card_missing: "No current readings",
furniture_power_card: "Power as a floating 3D card",
furniture_power_card_hint: "Shows the power reading above this furniture, even without a linked switch. The card remains visible at 0 W. Logged variables offer a trend button. Use the Cards switch to show or hide floating cards together.",
climate_illuminance: "Illuminance",
device_values: "Additional values",
device_value: "Data point",
device_value_add: "Add value",
device_value_remove: "Remove value",
device_value_icon: "Symbol",
device_value_label: "Label (optional)",
device_values_hint: "Use + to select additional data points, such as several temperatures or other readings. Symbols can be emoji or short characters such as 🌡, 💧, ☁ or ⚡. Values appear on the device and in the room panel.",
cover_tilt_entity: "Slat position",
cover_direction_invert: "Reverse blind in 3D",
cover_tilt_direction_invert: "Reverse slats in 3D",
cover2_direction_invert: "Reverse second blind in 3D",
cover2_tilt_direction_invert: "Reverse second blind slats in 3D",
cover_direction_hint: "Reversal affects only the 3D appearance. Numeric values, sliders and control commands stay unchanged: a received value of 0 is still displayed as 0, and a chosen value of 0 is sent as 0.",
cover2_tilt_entity: "Slat position (second blind)",
symcon_variables_loading: "Loading variables …",
symcon_variables_loaded: "Variables and object tree reloaded.",
symcon_variables_error: "Could not reload variables: {error}",
needs_restart_old: "A new version of NextFloor is installed, but Home Assistant still runs an older one. Please restart Home Assistant – until then saving fails.", needs_restart_old: "A new version of NextFloor is installed, but Home Assistant still runs an older one. Please restart Home Assistant – until then saving fails.",
draft_found: "Unsaved changes from {time} found.", draft_found: "Unsaved changes from {time} found.",
draft_restore: "Restore and save", draft_restore: "Restore and save",
@@ -2765,6 +2841,7 @@ const EN: Record<Key, string> = {
sill_boards_inside: "Inside only", sill_boards_inside: "Inside only",
sill_boards_outside: "Outside only", sill_boards_outside: "Outside only",
room_names_short: "Room names", room_names_short: "Room names",
room_names_toggle_hint: "Show or hide room names in the 3D view",
floor_stack_short_dim: "Dimmed", floor_stack_short_dim: "Dimmed",
floor_stack_short_stacked: "Stacked", floor_stack_short_stacked: "Stacked",
floor_stack_short_single: "Alone", floor_stack_short_single: "Alone",
@@ -3120,12 +3197,17 @@ const EN: Record<Key, string> = {
outdoor_opacity_hint: "100 = solid. Less makes the area see-through, such as a driveway above a cellar; the outline stays.", outdoor_opacity_hint: "100 = solid. Less makes the area see-through, such as a driveway above a cellar; the outline stays.",
outdoor_outline: "Show the outline", outdoor_outline: "Show the outline",
outdoor_outline_hint: "Unticked, the area draws no glowing line along its edge – for large plots made of several lawns.", outdoor_outline_hint: "Unticked, the area draws no glowing line along its edge – for large plots made of several lawns.",
outdoor_corners_hint: "Corners: a + on an edge adds a corner, dragging shapes the area, × removes a corner.", outdoor_corners_hint: "Corners: a + on an edge adds a corner, dragging shapes the area, × removes a corner. Drawing and moving snap to nearby corners and edges. Hold Alt to bypass snapping.",
outdoor_hint: "Outdoor lights (path light, garden spot, outdoor wall light) light all outdoor areas and the facade.", outdoor_hint: "Outdoor lights (path light, garden spot, outdoor wall light) light all outdoor areas and the facade.",
out_lawn: "Lawn", out_lawn: "Lawn",
out_terrace: "Terrace", out_terrace: "Terrace",
out_path: "Path", out_path: "Path",
out_driveway: "Driveway", out_driveway: "Driveway",
out_street: "Street",
out_sidewalk: "Sidewalk",
out_gravel: "Gravel",
out_river: "River",
out_stream: "Stream",
out_pool: "Pool", out_pool: "Pool",
out_bed: "Flower bed", out_bed: "Flower bed",
out_hedge: "Hedge", out_hedge: "Hedge",
@@ -3148,7 +3230,7 @@ const EN: Record<Key, string> = {
fence_gates_hint: "A gate is a gap in the fence with gate posts and a leaf. With a motor (cover, switch, input_boolean, lock) and/or a contact it opens in 3D: garden and double gates swing inwards, a sliding gate runs along the fence.", fence_gates_hint: "A gate is a gap in the fence with gate posts and a leaf. With a motor (cover, switch, input_boolean, lock) and/or a contact it opens in 3D: garden and double gates swing inwards, a sliding gate runs along the fence.",
outdoor_bracing: "X-bracing", outdoor_bracing: "X-bracing",
outdoor_cut: "Cut out of surrounding areas", outdoor_cut: "Cut out of surrounding areas",
outdoor_cut_hint: "Every area that contains this one whole gets a hole here – a pool in the terrace, a pond or a wild patch in the lawn. The drawing order does not matter. A pool cuts itself out on its own.", outdoor_cut_hint: "Every area that contains this one whole gets a hole here – a pool in the terrace, a stream or a wild patch in the lawn. The drawing order does not matter. Pools, rivers and streams cut themselves out by default.",
outdoor_area_hint: "The Home Assistant area of this surface (garden, terrace, pool): its devices and sensors are listed under Outside, and a pin on the surface opens it.", outdoor_area_hint: "The Home Assistant area of this surface (garden, terrace, pool): its devices and sensors are listed under Outside, and a pin on the surface opens it.",
pool_temp: "Water temperature (optional)", pool_temp: "Water temperature (optional)",
pool_pump: "Pump / filter (optional)", pool_pump: "Pump / filter (optional)",
@@ -3284,7 +3366,7 @@ const EN: Record<Key, string> = {
cover_entity: "Blind", cover_entity: "Blind",
door_cover: "Drive (motorised door or gate)", door_cover: "Drive (motorised door or gate)",
cover_position_entity: "Position sensor (live)", cover_position_entity: "Position sensor (live)",
cover_position_invert: "Sensor counts the other way round (0 = open)", cover_position_invert: "Reverse position sensor in 3D (0 = open)",
contact_entity: "Contact", contact_entity: "Contact",
sensor_kind: "Sensor type", sensor_kind: "Sensor type",
sensor_kind_contact: "Window contact (open/closed)", sensor_kind_contact: "Window contact (open/closed)",
@@ -3699,6 +3781,23 @@ const EN: Record<Key, string> = {
furn_charge: "Charging power (W, separate sensor, optional)", furn_charge: "Charging power (W, separate sensor, optional)",
furn_charge_hint: "If your battery reports charging and discharging in two sensors (e.g. Anker Solix), take the discharging sensor as power above and the charging sensor here. A signed sensor does not need this.", furn_charge_hint: "If your battery reports charging and discharging in two sensors (e.g. Anker Solix), take the discharging sensor as power above and the charging sensor here. A signed sensor does not need this.",
furn_wallbox_status: "Status (charging, plugged in)", furn_wallbox_status: "Status (charging, plugged in)",
charging_data: "Charging data",
charging_card: "Charging station as a floating 3D card",
charging_hint: "Linked charging data appears on the floating card and in the room menu, even without a power reading. Unlinked rows stay hidden. Native date/time profiles and Integer associations retain their Symcon display. Auto detects Unix timestamps without a time profile; numeric durations without a unit use seconds. Change the format to override this. These readings are display-only.",
charging_start: "Start time",
charging_end: "End time",
charging_duration: "Charging duration",
charging_energy: "Charged energy",
charging_lock: "Lock status",
charging_time_format: "Time format",
charging_duration_unit: "Duration unit",
charging_auto: "Automatic",
charging_value: "Unchanged Symcon value",
charging_seconds: "Seconds",
charging_minutes: "Minutes",
charging_hours: "Hours",
charging_unix_seconds: "Unix time (seconds)",
charging_unix_ms: "Unix time (milliseconds)",
energy_only_note: "⚡ Energy: only solar fields and energy devices can be moved here; rooms and furniture are locked.", energy_only_note: "⚡ Energy: only solar fields and energy devices can be moved here; rooms and furniture are locked.",
roof_only_note: "🏠 Roof: only roof sections and roof windows can be moved here; rooms and furniture are locked.", roof_only_note: "🏠 Roof: only roof sections and roof windows can be moved here; rooms and furniture are locked.",
energy_devices_hint: "Meter, inverters, home batteries, wallboxes and the grid connection are added here: on the floor chosen above, movable in the plan. With a power sensor they show their watts; the meter takes the grid sensor, a string picks its inverter. Several inverters and batteries (say a balcony plant on top) work too: each gets its own sensor.", energy_devices_hint: "Meter, inverters, home batteries, wallboxes and the grid connection are added here: on the floor chosen above, movable in the plan. With a power sensor they show their watts; the meter takes the grid sensor, a string picks its inverter. Several inverters and batteries (say a balcony plant on top) work too: each gets its own sensor.",
@@ -3823,6 +3922,9 @@ const EN: Record<Key, string> = {
furn_inverter: "Solar inverter", furn_inverter: "Solar inverter",
furn_home_battery: "Home battery", furn_home_battery: "Home battery",
furn_wallbox: "Wallbox", 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_kitchen: "Kitchen",
furn_group_sleeping: "Sleeping", furn_group_sleeping: "Sleeping",
furn_group_bath: "Bath & laundry", furn_group_bath: "Bath & laundry",
+1 -1
View File
@@ -164,7 +164,7 @@ test("one shared effect timer stops for no participants, hidden views/document,
assert.equal(lamps, 2); assert.equal(lamps, 2);
viewer.scheduleEffects(); viewer.scheduleEffects();
const noop = { dispose() {}, disconnect() {}, remove() {} }; 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.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 }; viewer.renderer = { dispose() {}, forceContextLoss() {}, domElement: noop };
const previousCancel = globalThis.cancelAnimationFrame; const previousCancel = globalThis.cancelAnimationFrame;
+41
View File
@@ -0,0 +1,41 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import type { FurniturePowerCard } from "./furniture-power-card.ts";
import type { HouseCard, HydronicCard } from "./cards.ts";
import { cardDetail, cardVisibleAtZoom } from "./card-visibility.ts";
const power=(w: number|null): FurniturePowerCard=>({kind:"power",id:"wallbox",name:"Wallbox",powerEntity:"sensor.power",power:w,at:{floorId:"f",x:0,y:1,z:0}});
const house: HouseCard={kind:"house",at:{floorId:"f",x:0,y:5,z:0},summary:{grid:0,solar:0,battery:null,soc:null,tariff:null,consumption:0},autarky:null};
const hydraulic: HydronicCard={kind:"hydronic",at:{floorId:"f",x:0,y:2,z:0},readOnly:false,item:{id:"h",type:"heating_manifold",x:0,z:0,w:1.5,d:.35,h:1.1,rotation:0,variant:null}};
test("distant views retain the summary while small device cards wait for more zoom",()=>{
assert.equal(cardVisibleAtZoom(house,0,false),true);
for(const card of [power(0),power(7400),hydraulic]) assert.equal(cardVisibleAtZoom(card,15,false),false);
assert.equal(cardVisibleAtZoom(hydraulic,50,false),true);
assert.equal(cardVisibleAtZoom(power(7400),60,false),true);
assert.equal(cardVisibleAtZoom(power(0),60,false),false);
assert.equal(cardVisibleAtZoom(power(0),90,false),true);
});
test("live consumption and export appear before idle devices, without discarding the zero value",()=>{
assert.ok(cardDetail(power(7400)).priority>cardDetail(power(0)).priority);
assert.equal(cardVisibleAtZoom(power(-1500),60,false),true);
assert.equal(cardVisibleAtZoom(power(0),90,false),true);
assert.equal(power(0).power,0);
assert.equal(cardVisibleAtZoom(power(null),40,false),false);
});
test("hysteresis keeps a visible card stable near its boundary and restores it after zooming back in",()=>{
const c=power(0),threshold=cardDetail(c).density;
assert.equal(cardVisibleAtZoom(c,threshold,false),false);
assert.equal(cardVisibleAtZoom(c,threshold,true),true);
assert.equal(cardVisibleAtZoom(c,threshold*.85,true),false);
assert.equal(cardVisibleAtZoom(c,threshold*1.15,false),true);
for(const density of [NaN,Infinity,-1,0]) assert.equal(cardVisibleAtZoom(c,density,true),false);
});
test("charging telemetry follows detail zoom even without a power link",()=>{
const c={...power(null),powerEntity:null,readings:[{id:"soc",entity:"sensor.soc",label:"SoC",icon:"🔋",text:"0 %"}]};
assert.equal(cardVisibleAtZoom(c,30,false),false);
assert.equal(cardVisibleAtZoom(c,70,false),true);
});
+25
View File
@@ -0,0 +1,25 @@
import type { LiveCard } from "./cards.ts";
/** Screen pixels per plan metre at the anchor, independent of building size and camera angle. */
export function cardDetail(card: LiveCard): { density: number; priority: number } {
switch (card.kind) {
case "house": return { density:0,priority:100 };
case "roomclimate": return { density:24,priority:80 };
case "hydronic": return { density:42,priority:45 };
case "power": {
const active=card.power!==null&&Math.abs(card.power)>1;
return active ? {density:48,priority:60} : card.readings?.length ? {density:56,priority:30} : {density:card.power===null?64:72,priority:20};
}
case "car": return {density:card.car.charging?36:60,priority:card.car.charging?60:20};
case "printer": return {density:card.printer.printing?36:60,priority:card.printer.printing?60:20};
case "heatpump": return {density:card.pump.mode!=="idle"?36:60,priority:card.pump.mode!=="idle"?60:20};
case "media": return {density:48,priority:40};
}
}
/** A small dead band prevents cards flickering at a zoom boundary. Summary cards keep their existing visibility. */
export function cardVisibleAtZoom(card: LiveCard, density: number, previouslyVisible: boolean): boolean {
const limit=cardDetail(card).density;
if (!limit) return true;
return Number.isFinite(density) && density >= limit * (previouslyVisible ? .88 : 1.12);
}
+92 -6
View File
@@ -18,6 +18,12 @@ import { curvePath } from "./day-curves.ts";
import type { PrinterInfo } from "./printer.ts"; import type { PrinterInfo } from "./printer.ts";
import type { HeatPumpInfo } from "./heat-pump.ts"; import type { HeatPumpInfo } from "./heat-pump.ts";
import type { PlanPoint } from "../viewer/live-energy.ts"; import type { PlanPoint } from "../viewer/live-energy.ts";
import type { RoomClimateCard } from "./room-climate-card.ts";
import { fromCelsius, tempUnit } from "../devices.ts";
import { trendButton } from "../components/trend-button.ts";
import { loggedEntities } from "../trend-data.ts";
import type { FurniturePowerCard } from "./furniture-power-card.ts";
import type { Furniture } from "../model.ts";
export interface HouseCard { export interface HouseCard {
kind: "house"; kind: "house";
@@ -60,7 +66,8 @@ export interface HeatPumpCard {
pump: HeatPumpInfo; pump: HeatPumpInfo;
} }
export type LiveCard = HouseCard | CarCard | MediaCard | PrinterCard | HeatPumpCard; 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). */ /** 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; export type LiveCardAction = (domain: string, service: string, entity: string, data?: Record<string, unknown>) => void;
@@ -239,10 +246,11 @@ function mediaCard(hass: HomeAssistant | undefined, c: MediaCard, i: number, act
* before it (lower on screen first) moves up above it. Its thread to the anchor stretches. * before it (lower on screen first) moves up above it. Its thread to the anchor stretches.
*/ */
export function unstackLhCards(root: ParentNode): void { export function unstackLhCards(root: ParentNode): void {
const cards = [...root.querySelectorAll<HTMLElement>(".live-card")].filter((el) => el.style.visibility !== "hidden"); const cards = [...root.querySelectorAll<HTMLElement>(".live-card")].filter((el) => el.style.visibility !== "hidden" && el.offsetWidth > 0);
const placed: { x0: number; x1: number; y0: number; y1: number }[] = []; 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 // 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 width = cards[0]?.parentElement?.clientWidth ?? 0;
const height = cards[0]?.parentElement?.clientHeight ?? 0;
const items = cards const items = cards
.map((el) => { .map((el) => {
const [anchor, w] = [Number(el.dataset.x), el.offsetWidth]; const [anchor, w] = [Number(el.dataset.x), el.offsetWidth];
@@ -250,17 +258,35 @@ export function unstackLhCards(root: ParentNode): void {
el.style.setProperty("--live-dx", `${Math.round(anchor - x)}px`); el.style.setProperty("--live-dx", `${Math.round(anchor - x)}px`);
return { el, x, y: Number(el.dataset.y), w, h: el.offsetHeight }; return { el, x, y: Number(el.dataset.y), w, h: el.offsetHeight };
}) })
.sort((a, b) => b.y - a.y); .sort((a, b) => Number(b.el.dataset.priority || 0) - Number(a.el.dataset.priority || 0) || b.y - a.y);
for (const it of items) { for (const it of items) {
let bottom = it.y; let bottom = it.y;
// Multi-reading equipment cards use nearby free columns before stacking out of view.
if ((it.el.classList.contains("live-card-hydronic") || it.el.classList.contains("live-card-charging")) && 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++) { 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 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); 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);
if (!hit) break; if (!hit) break;
bottom = hit.y0 - 8; bottom = hit.y0 - 8;
} }
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; const lift = it.y - bottom;
// Device details wait for a closer view instead of forming long towers or leaving the stage.
const detail = !it.el.classList.contains("live-card-house") && !it.el.classList.contains("live-card-roomclimate") && it.el.dataset.focused !== "1";
const multi = it.el.classList.contains("live-card-hydronic") || it.el.classList.contains("live-card-charging");
if (detail && height > 0 && (bottom-it.h < 8 || bottom > height-8 || (!multi && Math.abs(lift) > Math.max(100,Math.min(180,height*.25))))) {
it.el.style.visibility="hidden"; continue;
}
placed.push({ x0: it.x - it.w / 2, x1: it.x + it.w / 2, y0: bottom - it.h, y1: 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.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`); it.el.style.setProperty("--live-thread", `${Math.round(18 + lift)}px`);
} }
@@ -312,14 +338,43 @@ function heatPumpCard(hass: HomeAssistant | undefined, c: HeatPumpCard, i: numbe
</div>`; </div>`;
} }
export function renderLhCards(hass: HomeAssistant | undefined, cards: readonly LiveCard[], act: LiveCardAction, fold?: LiveCardFold): TemplateResult | typeof nothing { function roomClimateCard(hass: HomeAssistant | undefined, c: RoomClimateCard, i: number): TemplateResult {
const value = (n: number | null, digits: number, unit: string) => n === null ? "–" : `${formatNumber(hass, n, digits)} ${unit}`;
const trends = Object.values(c.sources ?? {}).some((ids) => loggedEntities(hass, ids).length > 0);
return html`<div class="live-card live-card-roomclimate ${trends ? "live-climate-trends" : ""}" data-i=${i} data-room=${c.roomId} role="group" aria-label=${`${c.name || translate(hass, "room")} · ${translate(hass, "climate")}`}>
${c.showTemperature ? html`<div class="live-row live-climate-temperature"><span title=${translate(hass, "climate_temperature")} aria-label=${translate(hass, "climate_temperature")}>🌡</span><b>${value(c.temperature === null ? null : hass ? fromCelsius(hass, c.temperature) : c.temperature, 1, hass ? tempUnit(hass) : "°C")}</b>${trendButton(hass, c.sources?.temperature ?? [], translate(hass, "climate_temperature"))}</div>` : nothing}
${c.showHumidity ? html`<div class="live-row live-climate-humidity"><span title=${translate(hass, "climate_humidity")} aria-label=${translate(hass, "climate_humidity")}>💧</span><b>${value(c.humidity, 0, "%")}</b>${trendButton(hass, c.sources?.humidity ?? [], translate(hass, "climate_humidity"))}</div>` : nothing}
${c.showCo2 ? html`<div class="live-row live-climate-co2"><span title=${translate(hass, "climate_co2")} aria-label=${translate(hass, "climate_co2")}>☁</span><b>${value(c.co2, 0, "ppm")}</b>${trendButton(hass, c.sources?.co2 ?? [], translate(hass, "climate_co2"))}</div>` : nothing}
${c.showIlluminance ? html`<div class="live-row live-climate-illuminance"><span title=${translate(hass, "climate_illuminance")} aria-label=${translate(hass, "climate_illuminance")}>☀</span><b>${value(c.illuminance, 0, "lx")}</b>${trendButton(hass, c.sources?.illuminance ?? [], translate(hass, "climate_illuminance"))}</div>` : nothing}
</div>`;
}
function furniturePowerCard(hass: HomeAssistant | undefined, c: FurniturePowerCard, i: number): TemplateResult {
const power = c.power === null ? "–" : `${c.power < 0 ? "−" : ""}${watts(hass, c.power)}`;
return html`<div class="live-card live-card-power ${(c.readings ?? []).length ? "live-card-charging" : ""}" data-i=${i} data-furniture=${c.id} role="group" aria-label=${c.name}>
<div class="live-power-name">${c.name}</div>${c.powerEntity ? html`<div class="live-row"><span aria-hidden="true">⚡</span><b>${power}</b>${trendButton(hass, [c.powerEntity], c.name)}</div>` : nothing}
${(c.readings ?? []).map((r) => html`<div class="live-row live-charging-row" data-reading=${r.id}><span class="live-charging-label" title=${r.label}><span aria-hidden="true">${r.icon}</span> ${r.label}</span><b title=${r.text}>${r.text}</b>${trendButton(hass, [r.entity], r.label)}</div>`)}
</div>`;
}
export function renderLhCards(hass: HomeAssistant | undefined, cards: readonly LiveCard[], act: LiveCardAction, fold?: LiveCardFold, climateOnly = false): TemplateResult | typeof nothing {
if (!cards.length) return nothing; if (!cards.length) return nothing;
return html`<div class="live-cards"> return html`<div class="live-cards">
${cards.map((c, i) => (c.kind === "house" ? houseCard(hass, c, i, fold) : c.kind === "car" ? carCard(hass, c, i, act) : c.kind === "printer" ? printerCard(hass, c, i) : c.kind === "heatpump" ? heatPumpCard(hass, c, i) : mediaCard(hass, c, i, act)))} ${cards.map((c, i) => (c.kind === "roomclimate" ? roomClimateCard(hass, c, i) : 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>`; </div>`;
} }
export const liveCardStyles = css` export const liveCardStyles = css`
.live-card.live-card-power { display:grid; gap:4px; min-width:90px; max-width:220px; box-sizing:border-box; }
.live-power-name { font-size:11px; color:var(--nf-muted); overflow:hidden; text-overflow:ellipsis; }
.live-card-power .live-row { align-items:center; gap:6px; }
.live-card-power .live-row b { margin-left:auto; color:color-mix(in srgb,#ffca8a 80%,var(--nf-text)); font-variant-numeric:tabular-nums; }
.live-card-power nf-trend-button { margin-left:0; }
.live-card-power.live-card-charging { max-width:min(320px,calc(100vw - 24px)); }
.live-card-power .live-charging-row { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1.4fr) 18px; align-items:center; column-gap:6px; min-height:18px; }
.live-charging-label { color:var(--nf-muted); font-size:10px; overflow:hidden; text-overflow:ellipsis; }
.live-charging-row b { font-size:11px; overflow:hidden; text-overflow:ellipsis; }
.live-charging-row nf-trend-button { grid-column:3; }
.live-cards { .live-cards {
position: absolute; position: absolute;
inset: 0; inset: 0;
@@ -418,6 +473,37 @@ export const liveCardStyles = css`
gap: 2px; gap: 2px;
min-width: 150px; min-width: 150px;
} }
.live-card-roomclimate {
display: grid;
gap: 4px;
min-width: 96px;
max-width: calc(100vw - 24px);
box-sizing: border-box;
}
.live-card-roomclimate .live-row {
display: grid;
grid-template-columns: 14px minmax(0, 1fr);
align-items: center;
column-gap: 6px;
min-height: 18px;
}
.live-climate-trends .live-row {
grid-template-columns: 14px minmax(0, 1fr) 18px;
}
.live-card-roomclimate .live-row b {
justify-self: end;
white-space: nowrap;
line-height: 18px;
font-variant-numeric: tabular-nums;
}
.live-card-roomclimate nf-trend-button {
grid-column: 3;
margin-left: 0;
}
.live-climate-temperature b { color: color-mix(in srgb, #ffca8a 80%, var(--nf-text)); }
.live-climate-humidity b { color: color-mix(in srgb, #7dd3fc 80%, var(--nf-text)); }
.live-climate-co2 b { color: color-mix(in srgb, #c4b5fd 80%, var(--nf-text)); }
.live-climate-illuminance b { color: color-mix(in srgb, #fde68a 80%, var(--nf-text)); }
.live-row { .live-row {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
@@ -0,0 +1,64 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { box, entity, floorWith, hassOf } from "../entities/fixtures.ts";
import { emptyBuilding, FURNITURE_TYPES, normalizeBuilding, type Furniture } from "../model.ts";
import { furnitureEntities } from "../entities/furniture-links.ts";
import { isElectric, setPacks } from "../packs.ts";
import { furniturePowerCards } from "./furniture-power-card.ts";
const item = (id: string, extra: Partial<Furniture> = {}): Furniture => ({ id, type: "wallbox", x: 2, z: 2, w: .3, d: .3, h: .4, rotation: 0, variant: null, power: "cover.knx", power_card: true, ...extra });
const native = (value: number, unit = "W") => entity("cover.knx", "open", { symcon_id: 123, symcon_variable_type: 2, symcon_numeric_value: value, unit_of_measurement: unit });
const plan = (...items: Furniture[]) => ({ ...emptyBuilding(), floors: [floorWith([box("garage", 0, 0, 5, 5)], { furniture: items })] });
test("power-only native links work for every electric built-in and a pack wallbox with a status light", () => {
setPacks([{ id: "test", name: "Test", publisher: "test", items: [{ id: "wallbox", name: { de: "Wallbox" }, size: [.3, .3, .4], light: "wall", parts: [] }] }]);
try {
const types = [...FURNITURE_TYPES.filter(isElectric), "pack:test:wallbox"];
const b = plan(...types.map((type, n) => item(String(n), { type, entity: null })));
const h = hassOf([native(11, "kW")]);
const cards = furniturePowerCards(h, b, furnitureEntities(h, b.floors), null, null);
assert.equal(cards.length, types.length);
assert.ok(cards.every((c) => c.power === 11000 && c.powerEntity === "cover.knx"));
assert.equal(cards.at(-1)?.name, "Wallbox");
} finally { setPacks([]); }
});
test("zero, export, unavailable and missing values retain their meaning and update live", () => {
const b = plan(item("wallbox")), h = hassOf([native(0)]);
const read = () => furniturePowerCards(h, b, new Map(), null, null)[0].power;
assert.equal(read(), 0);
h.states["cover.knx"] = native(-2.5, "kW");
assert.equal(read(), -2500);
h.states["cover.knx"] = entity("cover.knx", "unavailable", { symcon_id: 123, symcon_numeric_value: 1234 });
assert.equal(read(), null);
delete h.states["cover.knx"];
assert.equal(read(), null);
});
test("cards are opt-in, respect explicit none and use automatic links including the native source of aliases", () => {
const b = plan(item("default", { power_card: undefined }), item("none", { power: "none" }), item("unlinked", { power: null }), item("auto", { power: null }), item("explicit"));
const h = hassOf([native(250), entity("light.alias", "on", { symcon_source_entity: "cover.knx" })]);
const links = new Map([ ["none", { entity: null, power: "cover.knx" }], ["auto", { entity: null, power: "light.alias" }] ]);
assert.deepEqual(furniturePowerCards(h, b, links, null, null).map((c) => [c.id, c.powerEntity, c.power]), [["auto", "cover.knx", 250], ["explicit", "cover.knx", 250]]);
});
test("floor, room and furniture visibility filter cards while anchors follow mounting and pin offsets", () => {
const b = plan(item("garage", { name: "Meine Wallbox", mount_y: .9, pin_offset: { x: .1, y: .2, z: -.3 } }), item("outside", { x: 7 }), item("hidden", { show_when: { entity: "binary_sensor.visible" } }));
b.floors.push(floorWith([box("office", 0, 0, 5, 5)], { id: "upper", furniture: [item("upper")] }));
const h = hassOf([native(500), entity("binary_sensor.visible", "off")]);
const read = (floor: string | null, room: string | null) => furniturePowerCards(h, b, new Map(), floor, room);
assert.deepEqual(read(null, null).map((c) => c.id), ["garage", "outside", "upper"]);
assert.deepEqual(read("upper", null).map((c) => c.id), ["upper"]);
assert.deepEqual(read(null, "garage").map((c) => c.id), ["garage"]);
assert.deepEqual(read("upper", "garage"), []);
assert.equal(read(null, "garage")[0].name, "Meine Wallbox");
const at = read(null, "garage")[0].at;
assert.deepEqual([at.floorId, at.x, at.z], [b.floors[0].id, 2.1, 1.7]);
assert.ok(Math.abs(at.y - 1.85) < 1e-10);
});
test("the setting and links survive plan normalization and JSON persistence", () => {
const b = normalizeBuilding(JSON.parse(JSON.stringify(plan(item("wallbox")))));
assert.equal(b.floors[0].furniture[0].power_card, true);
assert.equal(furniturePowerCards(hassOf([native(100)]), b, new Map(), null, null)[0].power, 100);
});
+42
View File
@@ -0,0 +1,42 @@
import { mountBase } from "../packs.ts";
import { pointInPolygon, type Building } from "../model.ts";
import { furnitureName } from "../furniture-names.ts";
import { furnitureShown } from "../entities/visibility.ts";
import type { FurnitureLinks } from "../entities/furniture-links.ts";
import type { HomeAssistant } from "../types.ts";
import { readPower } from "../energy.ts";
import type { PlanPoint } from "../viewer/live-energy.ts";
import { chargingReadouts, type ChargingReadout } from "../charging-station.ts";
export interface FurniturePowerCard {
kind: "power";
id: string;
name: string;
powerEntity: string | null;
power: number | null;
readings?: ChargingReadout[];
at: PlanPoint;
}
/** Power-only links are enough: never require a switch, a special furniture type, or a positive reading. */
export function furniturePowerCards(hass: HomeAssistant, building: Building, links: ReadonlyMap<string, FurnitureLinks>, floorId: string | null, roomId: string | null): FurniturePowerCard[] {
const cards: FurniturePowerCard[] = [];
for (const floor of building.floors) {
if (floorId && floor.id !== floorId) continue;
const room = roomId ? floor.rooms.find((r) => r.id === roomId) : null;
if (roomId && !room) continue;
for (const item of floor.furniture) {
if (!item.power_card || !furnitureShown(hass, item)) continue;
if (room && !pointInPolygon([item.x, item.z], room.points)) continue;
const candidate = item.power === "none" ? null : item.power || links.get(item.id)?.power;
const source = candidate && candidate !== "none" ? candidate : null;
const readings = chargingReadouts(hass, item);
if (!source && !readings.length) continue;
const powerEntity = source ? String(hass.states[source]?.attributes.symcon_source_entity || source) : null;
const offset = item.pin_offset;
cards.push({ kind: "power", id: item.id, name: item.name || furnitureName(hass, item.type), powerEntity,
power: powerEntity ? readPower(hass.states[powerEntity]) : null, readings, at: { floorId: floor.id, x: item.x + (offset?.x ?? 0), z: item.z + (offset?.z ?? 0), y: mountBase(floor, item) + item.h + .35 + (offset?.y ?? 0) } });
}
}
return cards;
}
@@ -0,0 +1,54 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { box, entity, floorWith, hassOf } from "../entities/fixtures.ts";
import { emptyBuilding, normalizeBuilding, pointInPolygon } from "../model.ts";
import { roomClimateCards } from "./room-climate-card.ts";
test("enabled room cards use explicit numeric sensors, averages and temperature conversion", () => {
const b = emptyBuilding();
const room = { ...box("living", 0, 0, 4, 4), name: "Wohnzimmer", climate_card: true, climate: { temperature: ["sensor.c", "sensor.f"], humidity: "cover.knx", co2: "sensor.co2", illuminance: "sensor.lux" } };
b.floors = [floorWith([room, box("disabled", 5, 0, 8, 4)])];
const h = hassOf([
entity("sensor.c", "20", { unit_of_measurement: "°C" }), entity("sensor.f", "68", { unit_of_measurement: "°F" }),
entity("cover.knx", "open", { symcon_numeric_value: 48.5 }), entity("sensor.co2", "780"), entity("sensor.lux", "320", { unit_of_measurement: "lx" }),
]);
const cards = roomClimateCards(h, normalizeBuilding(b), b.floors[0].id, null);
assert.equal(cards.length, 1);
assert.deepEqual([cards[0].temperature, cards[0].humidity, cards[0].co2], [20, 48.5, 780]);
assert.equal(cards[0].name, "Wohnzimmer");
assert.equal(cards[0].illuminance, 320);
assert.equal(cards[0].showIlluminance, true);
assert.ok(pointInPolygon([cards[0].at.x, cards[0].at.z], room.points));
h.states["cover.knx"] = entity("cover.knx", "open", { symcon_numeric_value: 55 });
assert.equal(roomClimateCards(h, b, b.floors[0].id, null)[0].humidity, 55, "a fresh state updates the card values");
});
test("floor/room navigation filters cards and concave rooms keep their anchor inside", () => {
const b = emptyBuilding();
const room = { ...box("u", 0, 0, 6, 6), climate_card: true, climate: { temperature: "sensor.pending" }, points: [[0, 0], [6, 0], [6, 6], [4, 6], [4, 2], [2, 2], [2, 6], [0, 6]] as [number, number][] };
const upper = { ...floorWith([{ ...box("upper", 0, 0, 4, 4), climate_card: true, climate: { temperature: "sensor.pending" } }]), id: "upper" };
b.floors = [floorWith([room]), upper];
const h = hassOf([]);
assert.deepEqual(roomClimateCards(h, b, null, null), [], "all-floors view never shows room climate cards");
const [card] = roomClimateCards(h, b, b.floors[0].id, null);
assert.ok(pointInPolygon([card.at.x, card.at.z], room.points));
assert.deepEqual(roomClimateCards(h, b, "upper", null).map((c) => c.roomId), ["upper"]);
assert.deepEqual(roomClimateCards(h, b, null, "u").map((c) => c.roomId), ["u"]);
});
test("missing, unavailable and disabled readings stay missing rather than becoming zero or another thermostat", () => {
const b = emptyBuilding();
b.floors = [floorWith([{ ...box("r", 0, 0, 4, 4, "a"), climate_card: true, climate: { temperature: "sensor.offline", humidity: "sensor.empty", co2: "none" } }])];
const h = hassOf([entity("sensor.offline", "unavailable"), entity("sensor.empty", ""), entity("climate.other", "heat", { current_temperature: 30 })], { "climate.other": { area_id: "a" } });
const [card] = roomClimateCards(h, b, b.floors[0].id, null);
assert.deepEqual([card.temperature, card.humidity, card.co2], [null, null, null]);
assert.deepEqual([card.showTemperature, card.showHumidity, card.showCo2], [true, true, false]);
});
test("unlinked metrics are hidden and an entirely unlinked room has no empty card", () => {
const b = emptyBuilding();
b.floors = [floorWith([{ ...box("r", 0, 0, 4, 4), climate_card: true, climate: { temperature: "sensor.t", humidity: "none", co2: "none" } }, { ...box("empty", 5, 0, 9, 4), climate_card: true }])];
const [card, ...rest] = roomClimateCards(hassOf([entity("sensor.t", "22.7", { unit_of_measurement: "°C" })]), b, b.floors[0].id, null);
assert.equal(rest.length, 0);
assert.deepEqual([card.showTemperature, card.showHumidity, card.showCo2], [true, false, false]);
});
+53
View File
@@ -0,0 +1,53 @@
import { roomClimateSensors, roomClimateValue, type ClimateKey } from "../devices.ts";
import { centroid, pointInPolygon, spotGrid, type Building } from "../model.ts";
import type { HomeAssistant } from "../types.ts";
import type { PlanPoint } from "../viewer/live-energy.ts";
export interface RoomClimateCard {
kind: "roomclimate";
at: PlanPoint;
roomId: string;
name: string;
/** Celsius internally, converted to the display unit when rendered. */
temperature: number | null;
humidity: number | null;
co2: number | null;
showTemperature: boolean;
showHumidity: boolean;
showCo2: boolean;
illuminance: number | null;
showIlluminance: boolean;
sources?: Partial<Record<ClimateKey, string[]>>;
}
/** Opt-in room cards for an opened floor/room; the all-floors overview stays clear. */
export function roomClimateCards(hass: HomeAssistant, building: Building, floorId: string | null, roomId: string | null): RoomClimateCard[] {
if (!floorId && !roomId) return [];
const cards: RoomClimateCard[] = [];
for (const floor of building.floors) {
if (floorId && floor.id !== floorId) continue;
for (const room of floor.rooms) {
if (!room.climate_card || room.points.length < 3 || (roomId && room.id !== roomId)) continue;
const temperature = roomClimateValue(hass, floor, room, "temperature");
const humidity = roomClimateValue(hass, floor, room, "humidity");
const co2 = roomClimateValue(hass, floor, room, "co2");
const illuminance = roomClimateValue(hass, floor, room, "illuminance");
const linked = (key: ClimateKey, value: number | null) => {
const chosen = room.climate?.[key];
if (chosen === "none") return false;
return (chosen ? [chosen].flat().some((id) => !!id && id !== "none") : false) || roomClimateSensors(hass, floor, room, key).length > 0 || value !== null;
};
const showTemperature = linked("temperature", temperature), showHumidity = linked("humidity", humidity), showCo2 = linked("co2", co2);
const showIlluminance = linked("illuminance", illuminance);
if (!showTemperature && !showHumidity && !showCo2 && !showIlluminance) continue;
const middle = centroid(room.points);
const [x, z] = pointInPolygon(middle, room.points) ? middle : spotGrid(room, 9, 9).sort((a, b) => Math.hypot(a[0] - middle[0], a[1] - middle[1]) - Math.hypot(b[0] - middle[0], b[1] - middle[1]))[0] ?? room.points[0];
cards.push({ kind: "roomclimate", roomId: room.id, name: room.name,
at: { floorId: floor.id, x, z, y: (room.ceiling ?? floor.height) + 0.4 },
temperature, humidity, co2, illuminance, showTemperature, showHumidity, showCo2, showIlluminance,
sources: Object.fromEntries((["temperature", "humidity", "co2", "illuminance"] as const).map((key) => [key, roomClimateSensors(hass, floor, room, key)])),
});
}
}
return cards;
}
+2 -2
View File
@@ -62,8 +62,8 @@ export function bearing(v: unknown): number | null {
/** The weather to draw from an entity, or null when it is missing or reports nothing usable. */ /** The weather to draw from an entity, or null when it is missing or reports nothing usable. */
export function readSkyWeather(hass: HomeAssistant, entity: string | null): SkyWeather | null { export function readSkyWeather(hass: HomeAssistant, entity: string | null): SkyWeather | null {
const st = entity ? hass.states[entity] : undefined; const st = entity ? hass.states[entity] : undefined;
if (!st || st.state === "unavailable" || st.state === "unknown") return null; if (!st || st.state === "unavailable" || (st.state === "unknown" && !st.attributes.nf_symcon_weather)) return null;
const look = LOOK[st.state]; const look = LOOK[st.state] ?? (st.attributes.nf_symcon_weather ? {} : undefined);
if (!look) return null; if (!look) return null;
const a = st.attributes as Record<string, unknown>; const a = st.attributes as Record<string, unknown>;
const w: SkyWeather = { const w: SkyWeather = {
+6
View File
@@ -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; });
}
+12
View File
@@ -90,6 +90,18 @@ test("toggling uses the service of the entity's own domain", async () => {
assert.deepEqual(hass.calls[0], ["switch", "toggle", { entity_id: "switch.pump" }]); assert.deepEqual(hass.calls[0], ["switch", "toggle", { entity_id: "switch.pump" }]);
}); });
test("a placed blind reverses its 3D marker without changing its zero reading", () => {
const building = emptyBuilding();
const floor = newFloor("g", "Ground", 0);
floor.placements = [{ entity_id: "cover.a", x: 1, z: 1, y: null, cover_inverted: true }];
building.floors = [floor];
const hass = hassOf([state("cover.a", "closed", { current_position: 0 })]);
const [marker] = buildMarkers(hass, building);
assert.equal(marker.text, "0 %");
assert.equal(marker.active, true);
assert.equal(hass.states["cover.a"].attributes.current_position, 0);
});
test("a wall button (event entity) shows when it was last pressed, and a dash before its first press", () => { test("a wall button (event entity) shows when it was last pressed, and a dash before its first press", () => {
const hass = hassOf([]); const hass = hassOf([]);
const now = new Date(2026, 10, 1, 18, 0); const now = new Date(2026, 10, 1, 18, 0);
+3 -2
View File
@@ -6,6 +6,7 @@ import { formatNumber, translate, type I18nKey } from "./i18n.ts";
import { iconSvg, mdiIcon } from "./icons.ts"; import { iconSvg, mdiIcon } from "./icons.ts";
import { ceilingAt, offsetAt, pointInPolygon, type Building, type Floor, type Placement, type Room } from "./model.ts"; import { ceilingAt, offsetAt, pointInPolygon, type Building, type Floor, type Placement, type Room } from "./model.ts";
import type { HassEntity, HomeAssistant } from "./types.ts"; import type { HassEntity, HomeAssistant } from "./types.ts";
import { deviceValuesText } from "./entities/device-values.ts";
import type { DeviceMarker } from "./viewer/viewer3d.ts"; import type { DeviceMarker } from "./viewer/viewer3d.ts";
import { lightAnimation } from "./light-effects.ts"; import { lightAnimation } from "./light-effects.ts";
import { pluginFloorWedge, pluginKind, pluginMarkerPatch } from "./plugins/registry.ts"; import { pluginFloorWedge, pluginKind, pluginMarkerPatch } from "./plugins/registry.ts";
@@ -135,8 +136,8 @@ function markerFor(hass: HomeAssistant, floor: Floor, placed: Placement): Device
name: placed.name || entityName(hass, placed.entity_id, areaName), name: placed.name || entityName(hass, placed.entity_id, areaName),
ownName: placed.name || undefined, ownName: placed.name || undefined,
showName: !!placed.show_name, showName: !!placed.show_name,
text: stateText(hass, st), text: [stateText(hass, st), deviceValuesText(hass, placed.values)].filter(Boolean).join(" · "),
active: isActive(st), active: kind === "cover" && (!!placed.cover_inverted !== (!!placed.position && !!placed.position_inverted)) && !isUnavailable(st) ? !isActive(st) : isActive(st),
unavailable: isUnavailable(st), unavailable: isUnavailable(st),
glow: kind === "light" ? scaleGlow(lightGlow(st), placed.glow_scale) : null, glow: kind === "light" ? scaleGlow(lightGlow(st), placed.glow_scale) : null,
effect: kind === "light" ? lightAnimation(placed, st) : undefined, effect: kind === "light" ? lightAnimation(placed, st) : undefined,
+74 -5
View File
@@ -8,22 +8,54 @@ import type { StairConfig } from "./geometry/stairs.ts";
import type { LampModel } from "./viewer/viewer3d.ts"; import type { LampModel } from "./viewer/viewer3d.ts";
import type { FurnitureColors } from "./furniture-colors.ts"; import type { FurnitureColors } from "./furniture-colors.ts";
import type { ShowWhen } from "./entities/visibility.ts"; import type { ShowWhen } from "./entities/visibility.ts";
import type { HydronicConfig } from "./hydronic-model.ts";
export type Vec2 = [number, number]; export type Vec2 = [number, number];
export const UTILITY_KINDS = ["electricity", "water", "gas", "heating", "cooling"] as const;
export type UtilityKind = typeof UTILITY_KINDS[number];
export interface UtilityMeterRefs { power?: EntityRef; energy?: EntityRef }
/** Sensors a room's climate is read from (null = automatic, "none" = no value). */ /** Sensors a room's climate is read from (null = automatic, "none" = no value). */
export interface RoomClimate { export interface RoomClimate {
temperature?: string | string[] | null; temperature?: string | string[] | null;
humidity?: string | string[] | null; humidity?: string | string[] | null;
co2?: string | string[] | null; co2?: string | string[] | null;
illuminance?: string | string[] | null;
} }
/** Additional readouts attached to a device; entity references always come from the picker. */
export interface DeviceValueLink {
id: string;
entity: EntityRef;
icon?: string | null;
label?: string | null;
}
export interface RoomHvac {
supply_vsr?: EntityRef;
extract_vsr?: EntityRef;
supply_temperature?: EntityRef;
extract_temperature?: EntityRef;
reheat?: EntityRef;
status?: EntityRef;
schedules?: string[];
}
export const WEATHER_VARIABLE_KEYS = ["condition", "temperature", "humidity", "pressure", "wind_speed", "wind_gust_speed", "wind_bearing", "cloud_coverage", "precipitation", "precipitation_total", "illuminance", "uv_index", "visibility", "snow", "fog", "lightning"] as const;
export type WeatherVariableKey = typeof WEATHER_VARIABLE_KEYS[number];
/** A wall height on a room edge, or one per part of a split edge. */ /** A wall height on a room edge, or one per part of a split edge. */
export type WallHeight = number | null | (number | null)[]; export type WallHeight = number | null | (number | null)[];
export interface Room { export interface Room {
/** Room temperature, humidity and CO2: chosen sensors instead of the automatic pick. */ /** Room temperature, humidity and CO2: chosen sensors instead of the automatic pick. */
climate?: RoomClimate | null; climate?: RoomClimate | null;
/** Show temperature, humidity and CO2 in a floating glass card over this room. */
climate_card?: boolean;
hvac?: RoomHvac | null;
/** Explicit room meters; area meters are shown once for their linked native category. */
utility_meters?: Partial<Record<UtilityKind, UtilityMeterRefs>> | null;
id: string; id: string;
name: string; name: string;
area_id: string | null; area_id: string | null;
@@ -158,8 +190,16 @@ export interface Opening {
/** Ask before moving the blind or garage door; it then does not follow a swipe either. */ /** Ask before moving the blind or garage door; it then does not follow a swipe either. */
confirm?: boolean; confirm?: boolean;
cover: EntityRef; cover: EntityRef;
/** Separate numeric control for the venetian blind's slat position. */
cover_tilt?: EntityRef;
/** Reverse only the 3D appearance; displayed positions and control commands keep their original direction. */
cover_inverted?: boolean;
cover_tilt_inverted?: boolean;
/** Windows and doors: a second blind for the right half (seen from the room) of a wide window. */ /** Windows and doors: a second blind for the right half (seen from the room) of a wide window. */
cover2?: string | null; cover2?: string | null;
cover2_tilt?: EntityRef;
cover2_inverted?: boolean;
cover2_tilt_inverted?: boolean;
/** The kind of blind: a roller shutter outside (null, default), a venetian blind (Raffstore) outside with slats, or a roller blind inside. */ /** The kind of blind: a roller shutter outside (null, default), a venetian blind (Raffstore) outside with slats, or a roller blind inside. */
blind?: "roller" | "venetian" | "inside" | null; blind?: "roller" | "venetian" | "inside" | null;
/** The favourite position of the blind (%, open = 100) – Somfy's "My": a button in its menu moves it there. */ /** The favourite position of the blind (%, open = 100) – Somfy's "My": a button in its menu moves it there. */
@@ -190,6 +230,7 @@ export interface ScreenPicture {
} }
export interface Furniture extends LightEffectConfig { 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. */ /** 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; tap?: Pick<CustomButton, "action" | "target" | "data"> | null;
/** Fixed against moving by accident. */ /** Fixed against moving by accident. */
@@ -226,9 +267,14 @@ export interface Furniture extends LightEffectConfig {
entity?: EntityRef; entity?: EntityRef;
/** Power sensor (null = automatic: the linked entity's device or a matching name). */ /** Power sensor (null = automatic: the linked entity's device or a matching name). */
power?: EntityRef; power?: EntityRef;
/** Show this furniture's linked power reading as its own floating 3D card. */
power_card?: boolean;
/** Charging station telemetry; read-only links retain native values and Integer aliases. */
charging?: import("./charging-station.ts").ChargingStationConfig | null;
/** Fridges and freezers: a temperature sensor of the fridge (temp_entity) and one of the freezer compartment; the marker shows them and warns when too warm. Any other device: its own thermometer, shown on its pin (#112). */ /** Fridges and freezers: a temperature sensor of the fridge (temp_entity) and one of the freezer compartment; the marker shows them and warns when too warm. Any other device: its own thermometer, shown on its pin (#112). */
temp_entity?: string | null; temp_entity?: string | null;
temp_entity2?: string | null; temp_entity2?: string | null;
values?: DeviceValueLink[];
/** Smart fridge: door sensors of the left (freezer) and right (fridge) door; the doors open in 3D while they report open. */ /** Smart fridge: door sensors of the left (freezer) and right (fridge) door; the doors open in 3D while they report open. */
door_left?: EntityRef; door_left?: EntityRef;
door_right?: EntityRef; door_right?: EntityRef;
@@ -336,6 +382,14 @@ export interface Placement extends LightEffectConfig {
confirm?: boolean; confirm?: boolean;
/** Lights: only the switch in the room panel, without brightness, colour temperature and colours. */ /** Lights: only the switch in the room panel, without brightness, colour temperature and colours. */
simple?: boolean; simple?: boolean;
/** A placed blind's separate slat position control. */
cover_tilt?: EntityRef;
values?: DeviceValueLink[];
/** Visual direction only; values and commands are unchanged. */
cover_inverted?: boolean;
cover_tilt_inverted?: boolean;
position?: EntityRef;
position_inverted?: boolean;
/** Its marker in 3D: automatic (null), always shown, shown without watts, or hidden. */ /** Its marker in 3D: automatic (null), always shown, shown without watts, or hidden. */
marker?: MarkerShow | null; marker?: MarkerShow | null;
/** An own symbol for the marker: a Material Design icon name without "mdi:" (null = by kind). */ /** An own symbol for the marker: a Material Design icon name without "mdi:" (null = by kind). */
@@ -397,6 +451,8 @@ export interface Floor {
layer?: boolean; layer?: boolean;
/** The floor's own meter: a power sensor whose use shows on the floor label and, in this floor's view, on the house card. */ /** The floor's own meter: a power sensor whose use shows on the floor label and, in this floor's view, on the house card. */
power_entity?: string | null; power_entity?: string | null;
/** Native meters override the matching room sum, independently for each medium and metric. */
utility_meters?: Partial<Record<UtilityKind, UtilityMeterRefs>> | null;
/** Notes pinned to a spot of the floor ("filter due in March", "fuse 12"), shown in 3D and found by the search. */ /** Notes pinned to a spot of the floor ("filter due in March", "fuse 12"), shown in 3D and found by the search. */
notes?: PlanNote[]; notes?: PlanNote[];
/** Paint of this floor's outer walls in the solid wall view ("#rrggbb"; null = the building's outside colour): a plinth, a garage (#110). */ /** Paint of this floor's outer walls in the solid wall view ("#rrggbb"; null = the building's outside colour): a plinth, a garage (#110). */
@@ -671,6 +727,7 @@ export interface BleTag {
} }
export interface BuildingSettings { export interface BuildingSettings {
weather_variables?: Partial<Record<WeatherVariableKey, EntityRef>> | null;
/** Bluetooth tags located by room (the sensor and the editor's learning by walking). */ /** Bluetooth tags located by room (the sensor and the editor's learning by walking). */
ble?: { tags: BleTag[] } | null; ble?: { tags: BleTag[] } | null;
/** Stations and playlists for the speakers' quick menu (Klang). */ /** Stations and playlists for the speakers' quick menu (Klang). */
@@ -852,7 +909,7 @@ export type WeatherEffect = (typeof WEATHER_EFFECTS)[number];
/** The effects shown when the plan does not say: everything but fog (fog greys the whole scene). */ /** The effects shown when the plan does not say: everything but fog (fog greys the whole scene). */
export const DEFAULT_WEATHER_EFFECTS: WeatherEffect[] = ["rain", "snow", "clouds", "lightning", "sky"]; export const DEFAULT_WEATHER_EFFECTS: WeatherEffect[] = ["rain", "snow", "clouds", "lightning", "sky"];
export const OUTDOOR_TYPES = ["lawn", "terrace", "path", "driveway", "pool", "bed", "wild", "hedge", "fence", "pergola"] as const; export const OUTDOOR_TYPES = ["lawn", "terrace", "path", "driveway", "street", "sidewalk", "gravel", "river", "stream", "pool", "bed", "wild", "hedge", "fence", "pergola"] as const;
export type OutdoorType = (typeof OUTDOOR_TYPES)[number]; export type OutdoorType = (typeof OUTDOOR_TYPES)[number];
/** Top of each kind of outdoor area above ground level (pool: its water, below). */ /** Top of each kind of outdoor area above ground level (pool: its water, below). */
@@ -861,6 +918,11 @@ export const OUTDOOR_TOP: Record<OutdoorType, number> = {
terrace: 0.12, terrace: 0.12,
path: 0.02, path: 0.02,
driveway: 0.02, driveway: 0.02,
street: 0.02,
sidewalk: 0.12,
gravel: 0.018,
river: 0.008,
stream: 0.006,
pool: -0.25, pool: -0.25,
bed: 0.15, bed: 0.15,
wild: 0.03, wild: 0.03,
@@ -956,7 +1018,7 @@ export interface OutdoorArea {
open?: boolean; open?: boolean;
/** Pergola: diagonal X-bracing on every side. */ /** Pergola: diagonal X-bracing on every side. */
bracing?: boolean; bracing?: boolean;
/** This area is cut out of every other area that contains it whole (a wild patch or pond inside a lawn). A pool does this by itself unless this is false. */ /** This area is cut out of every other area that contains it whole. Pools, rivers and streams do this by default unless this is false. */
cut?: boolean; cut?: boolean;
/** Fences: gates in the fence (gaps with a leaf that follows an entity). */ /** Fences: gates in the fence (gaps with a leaf that follows an entity). */
gates?: FenceGate[]; gates?: FenceGate[];
@@ -979,8 +1041,8 @@ export interface FenceGate {
open?: boolean; open?: boolean;
} }
/** Whether an area leaves a hole in the areas around it: set by hand, and on by default for a pool. */ /** Whether an area leaves a hole in the areas around it: water areas default to on. */
export const cutsOut = (a: OutdoorArea): boolean => a.cut ?? a.type === "pool"; export const cutsOut = (a: OutdoorArea): boolean => a.cut ?? (a.type === "pool" || a.type === "river" || a.type === "stream");
/** Energy flow: meter position and power sensors (W). Grid positive = import, battery positive = discharging. */ /** Energy flow: meter position and power sensors (W). Grid positive = import, battery positive = discharging. */
export interface EnergySettings { export interface EnergySettings {
@@ -1032,6 +1094,7 @@ export interface Circuit {
/** A person and the sensor whose state names the room they are in (ESPresense, Bermuda, …). */ /** A person and the sensor whose state names the room they are in (ESPresense, Bermuda, …). */
export interface PresenceLink { export interface PresenceLink {
name?: string | null;
/** A person, or any entity that is "home" / "on" while someone is in (an input_boolean, a device tracker). */ /** A person, or any entity that is "home" / "on" while someone is in (an input_boolean, a device tracker). */
person: string; person: string;
sensor: string | null; sensor: string | null;
@@ -1202,6 +1265,9 @@ export const FURNITURE_TYPES = [
"grid_point", "grid_point",
"parking", "parking",
"fridge_smart", "fridge_smart",
"heating_manifold",
"buffer_tank",
"freshwater_station",
"stairwell", "stairwell",
] as const; ] as const;
@@ -1213,7 +1279,7 @@ export const FURNITURE_GROUPS: Record<string, FurnitureType[]> = {
kitchen: ["kitchen", "kitchen_wall", "kitchen_tall", "island", "worktop", "sink", "stove", "dishwasher", "fridge"], kitchen: ["kitchen", "kitchen_wall", "kitchen_tall", "island", "worktop", "sink", "stove", "dishwasher", "fridge"],
sleeping: ["bed", "bunk_bed", "nightstand", "wardrobe", "dresser"], sleeping: ["bed", "bunk_bed", "nightstand", "wardrobe", "dresser"],
bath: ["bathtub", "shower", "wc", "washbasin", "washer", "dryer"], 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"], vehicles: ["parking"],
}; };
@@ -1405,6 +1471,9 @@ export const FURNITURE_SIZE: Record<FurnitureType, [number, number, number]> = {
inverter: [0.5, 0.2, 0.65], inverter: [0.5, 0.2, 0.65],
home_battery: [0.6, 0.25, 1.1], home_battery: [0.6, 0.25, 1.1],
wallbox: [0.3, 0.15, 0.42], 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 // the meter cabinet hangs on the wall as well
meter: [0.55, 0.21, 1.1], meter: [0.55, 0.21, 1.1],
// the grid connection: a small street cabinet at the edge of the plot // the grid connection: a small street cabinet at the edge of the plot
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff. Show more