Compare commits

..
32 Commits
Author SHA1 Message Date
jhartworks dde3f4027b fix: follow topology in utility summaries and breakdowns 2026-11-19 15:44:24 +01:00
jhartworks 9374ac9e35 feat: add branch overviews scoped outdoor plans and complete room moves 2026-11-19 15:12:11 +01:00
jhartworks 0cc4b35995 fix: separate hierarchy management from selected building editing 2026-11-19 09:46:31 +01:00
jhartworks 5090c400c2 feat: add location and branch topology with scoped navigation 2026-11-17 14:46:48 +01:00
jhartworks e0ea779fcc fix: remove Home Assistant version notices from Symcon 2026-11-17 14:02:56 +01:00
jhartworks 8965a649d2 fix: serialize native account form lists and refresh user grants 2026-11-17 13:40:23 +01:00
jhartworks f58e0125cd feat: add native status bindings for hydraulic circuits and freshwater stations 2026-11-16 16:48:46 +01:00
jhartworks aa42a1003b fix: preserve scoped utility topology and refresh sessions across tabs 2026-11-16 16:38:10 +01:00
jhartworks a3c211d8df feat: add scoped user accounts, password login and garden paving materials 2026-11-16 16:30:47 +01:00
jhartworks f6bc7b27bc feat: configure outdoor texture scale and rotation per area 2026-11-16 13:57:52 +01:00
jhartworks 57f7933d80 feat: add outdoor snapping, terrain types and procedural textures 2026-11-16 13:02:18 +01:00
jhartworks 02232f3b33 feat: add fresh-water cascades with independent stations and buffer links 2026-11-12 16:16:01 +01:00
jhartworks 9ab5f7f63d feat: reveal device cards progressively with camera zoom 2026-11-12 15:41:35 +01:00
jhartworks 1b69f8d8f4 fix: rebuild hydronic circuits around correct inline pipework 2026-11-12 15:27:17 +01:00
jhartworks 66e1c5e73e feat: add native charging station telemetry and aliased lock status 2026-11-12 14:55:18 +01:00
jhartworks a918f6e695 feat: show metered devices below rooms in utility overview 2026-11-12 14:44:02 +01:00
jhartworks 3a59d50c8b feat: add 3D hydronic manifolds buffer tanks and fresh water stations 2026-11-12 14:28:30 +01:00
jhartworks 082511a02b fix: group utility overview by area and show explicit room meters 2026-11-12 12:09:21 +01:00
jhartworks 876187761e fix: select native variables by datatype and explain rejected links 2026-11-12 10:14:19 +01:00
jhartworks 4e8d8d5fa7 feat: add floating power cards for all powered furniture 2026-11-11 16:24:52 +01:00
jhartworks a435907043 feat: toggle and remember right utility overview visibility 2026-11-11 13:00:36 +01:00
jhartworks ac97c24953 feat: show scoped utility overviews and compact trend controls 2026-11-11 12:33:54 +01:00
jhartworks fd20e8d411 fix: keep compact trend icons aligned beside room values 2026-11-11 12:15:37 +01:00
jhartworks 9276d1c28a feat: add native Symcon archive trends and explicit room naming 2026-11-11 12:00:51 +01:00
jhartworks a4d195ba10 fix: show incomplete Symcon utility sums with Err prefix 2026-11-11 10:08:20 +01:00
jhartworks 2e965fa7ea feat: discover Symcon room utility meters and sum floor consumption 2026-11-11 09:55:26 +01:00
jhartworks f0be3d2cb4 feat: add native Symcon room climate, schedules, weather and presence 2026-11-11 09:34:26 +01:00
jhartworks 0fed9dc5e5 fix: retain Symcon webhook registration and show configured view title 2026-11-10 12:39:30 +01:00
jhartworks 28dd3880b5 fix: hide room climate cards in all-floors overview 2026-11-10 12:32:59 +01:00
jhartworks e3d02bbd58 feat: add room name switches to 3D view and editor toolbars 2026-11-10 10:41:07 +01:00
jhartworks aa834d0727 fix: restrict blind direction reversal to 3D appearance 2026-11-10 10:31:41 +01:00
jhartworks badd4ee7e3 fix: keep Symcon binding paths compact and allow direct unlinking 2026-11-10 10:00:01 +01:00
25 changed files with 4927 additions and 1774 deletions

No files matched your search

File diff suppressed because it is too large. Load diff
+24 -24
View File
@@ -1,28 +1,28 @@
/*! 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,V=Symbol(),me=new WeakMap,R=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==V)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,V),U=(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,V)},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:Ve}=Object,C=globalThis,ge=C.trustedTypes,Ue=ge?ge.emptyScript:"",je=C.reactiveElementPolyfillSupport,F=(i,e)=>i,q={toAttribute(i,e){switch(e){case Boolean:i=i?Ue: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=Ve(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
\f\r]`,W=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ye=/-->/g,Se=/>/g,S=RegExp(`>|${J}(?:([^\\s"'>=/]+)(${J}*=${J}*(?:[^
\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=W;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===W?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??W,_=-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=W:(a=S,r=void 0);let k=a===S&&i[s+1].startsWith("/>")?" ":"";o+=a===W?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],x()),A.nextNode(),h.push({type:2,index:++o});r.append(_[g],x())}}}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=H(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),H(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&&H(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(x()),this.O(x()),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
<input type="checkbox" .checked=${e} @change=${o=>r(nt(o))} />
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,x=(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(x("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(x("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(x("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]`,F=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Se=/-->/g,Ae=/>/g,S=RegExp(`>|${X}(?:([^\\s"'>=/]+)(${X}*=${X}*(?:[^
\f\r"'\`<>=]|("|')|))|$)`,"g"),De=/'/g,ze=/"/g,xe=/^(?: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 Fe(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=F;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===F?p[1]==="!--"?a=Se:p[1]!==void 0?a=Ae:p[2]!==void 0?(xe.test(p[2])&&(r=RegExp("</"+p[2],"g")),a=S):p[3]!==void 0&&(a=S):a===S?p[0]===">"?(a=r??F,_=-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=F:(a=S,r=void 0);let k=a===S&&i[s+1].startsWith("/>")?" ":"";o+=a===F?h+Je:_>=0?(n.push(u),h.slice(0,_)+Te+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,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(xe.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(Fe(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(rt(o))} />
<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)}
<select @change=${o=>i.set(e,O(o))}>
${n.map(([o,a])=>l`<option value=${o} ?selected=${o===r}>${i.t(a)}</option>`)}
</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)}
<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>`)}
</select>
</label>`}function I(i,e,t,n=""){return l`<label class="field wide"
>${i.t(t)}
<input type="text" placeholder=${n} .value=${i.value[e]??""} @change=${r=>i.set(e,tt(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"
<input type="text" placeholder=${n} .value=${i.value[e]??""} @change=${r=>i.set(e,nt(r).trim()||void 0)} />
</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)}
<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>`)}
</select>
</label>`}var Pe=U`
</label>`}var Le=j`
:host {
display: block;
color: var(--primary-text-color);
@@ -115,29 +115,29 @@ var p={cs:"4be67fcd522e",da:"0fe66a82bf2a",es:"bd89dffd1355",fi:"9a17bc084f56",f
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,xe(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>
<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>`)}
</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.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.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,"controls_hide_after","card_controls_hide_after",a)}
${le(e,"marker_names","card_marker_names","card_marker_names_hint")} ${le(e,"controls_hidden","card_controls_hidden","card_controls_hidden_hint")}
${he(e,"controls_hide_after","card_controls_hide_after",a)}
${n?l`<div class="sub">
${$.map(s=>l`<label class="chip">
${L.map(s=>l`<label class="chip">
<input
type="checkbox"
.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}`)}
</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 class="grid">
${le(e,"idle_return","card_idle_return",r)}
${he(e,"idle_return","card_idle_return",r)}
<label class="field"
>${e.t("card_night")}
<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>`)}
</select>
</label>
${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)?d:c(e,"announcements","card_announcements","card_announcements_hint")}
${!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")}
${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")}
<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>
${t.map(n=>l`<option value=${n} ?selected=${n===e.value.weather_entity}>${String(this.hass?.states[n]?.attributes.friendly_name??n)}</option>`)}
</select>
</label>
</label>`}
<label class="field"
>${e.t("card_weather_density")}
<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}
<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>
${He.map(r=>l`<label class="field"
${Be.map(r=>l`<label class="field"
>${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}
</label>`)}
</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">
${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)}
${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>
${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,"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:
@lit/reactive-element/css-tag.js:
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+257
View File
@@ -0,0 +1,257 @@
/*! NextFloor, MIT licence. Includes three.js (MIT) and Lit (BSD-3-Clause); see LICENSE and THIRD_PARTY_NOTICES.md */
var G=globalThis,Q=G.ShadowRoot&&(G.ShadyCSS===void 0||G.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,it=Symbol(),wt=new WeakMap,j=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==it)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(Q&&t===void 0){let i=n!==void 0&&n.length===1;i&&(t=wt.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&wt.set(n,t))}return t}toString(){return this.cssText}},At=r=>new j(typeof r=="string"?r:r+"",void 0,it),y=(r,...t)=>{let n=r.length===1?r[0]:t.reduce((i,e,s)=>i+(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)+r[s+1],r[0]);return new j(n,r,it)},St=(r,t)=>{if(Q)r.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(let n of t){let i=document.createElement("style"),e=G.litNonce;e!==void 0&&i.setAttribute("nonce",e),i.textContent=n.cssText,r.appendChild(i)}},rt=Q?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let n="";for(let i of t.cssRules)n+=i.cssText;return At(n)})(r):r;var{is:Xt,defineProperty:Yt,getOwnPropertyDescriptor:Gt,getOwnPropertyNames:Qt,getOwnPropertySymbols:te,getPrototypeOf:ee}=Object,tt=globalThis,Et=tt.trustedTypes,ne=Et?Et.emptyScript:"",ie=tt.reactiveElementPolyfillSupport,B=(r,t)=>r,st={toAttribute(r,t){switch(t){case Boolean:r=r?ne: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}},kt=(r,t)=>!Xt(r,t),Ht={attribute:!0,type:String,converter:st,reflect:!1,useDefault:!1,hasChanged:kt};Symbol.metadata??=Symbol("metadata"),tt.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=Ht){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&&Yt(this.prototype,t,e)}}static getPropertyDescriptor(t,n,i){let{get:e,set:s}=Gt(this.prototype,t)??{get(){return this[n]},set(o){this[n]=o}};return{get:e,set(o){let c=e?.call(this);s?.call(this,o),this.requestUpdate(t,c,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Ht}static _$Ei(){if(this.hasOwnProperty(B("elementProperties")))return;let t=ee(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(B("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(B("properties"))){let n=this.properties,i=[...Qt(n),...te(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(rt(e))}else t!==void 0&&n.push(rt(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 s=(i.converter?.toAttribute!==void 0?i.converter:st).toAttribute(n,i.type);this._$Em=t,s==null?this.removeAttribute(e):this.setALine truncated
\f\r]`,I=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Nt=/-->/g,Pt=/>/g,k=RegExp(`>|${ot}(?:([^\\s"'>=/]+)(${ot}*=${ot}*(?:[^
\f\r"'\`<>=]|("|')|))|$)`,"g"),Mt=/'/g,Tt=/"/g,Ut=/^(?:script|style|textarea|title)$/i,ft=r=>(t,...n)=>({_$litType$:r,strings:t,values:n}),d=ft(1),ve=ft(2),xe=ft(3),N=Symbol.for("lit-noChange"),a=Symbol.for("lit-nothing"),Ot=new WeakMap,C=R.createTreeWalker(R,129);function Lt(r,t){if(!pt(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return Rt!==void 0?Rt.createHTML(t):t}var oe=(r,t)=>{let n=r.length-1,i=[],e,s=t===2?"<svg>":t===3?"<math>":"",o=I;for(let c=0;c<n;c++){let l=r[c],h,p,u=-1,g=0;for(;g<l.length&&(o.lastIndex=g,p=o.exec(l),p!==null);)g=o.lastIndex,o===I?p[1]==="!--"?o=Nt:p[1]!==void 0?o=Pt:p[2]!==void 0?(Ut.test(p[2])&&(e=RegExp("</"+p[2],"g")),o=k):p[3]!==void 0&&(o=k):o===k?p[0]===">"?(o=e??I,u=-1):p[1]===void 0?u=-2:(u=o.lastIndex-p[2].length,h=p[1],o=p[3]===void 0?k:p[3]==='"'?Tt:Mt):o===Tt||o===Mt?o=k:o===Nt||o===Pt?o=I:(o=k,e=void 0);let $=o===k&&r[c+1].startsWith("/>")?" ":"";s+=o===I?l+re:u>=0?(i.push(h),l.slice(0,u)+Ft+l.slice(u)+S+$):l+S+(u===-2?c:$)}return[Lt(r,s+(r[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]},q=class r{constructor({strings:t,_$litType$:n},i){let e;this.parts=[];let s=0,o=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(Ft)){let g=p[o++],$=e.getAttribute(u).split(S),_=/([.?@])?(.*)/.exec(g);l.push({type:1,index:s,name:_[2],strings:$,ctor:_[1]==="."?lt:_[1]==="?"?ct:_[1]==="@"?ut:T}),e.removeAttribute(u)}else u.startsWith(S)&&(l.push({type:6,index:s}),e.removeAttribute(u));if(Ut.test(e.tagName)){let u=e.textContent.split(S),g=u.length-1;if(g>0){e.textContent=et?et.emptyScript:"";for(let $=0;$<g;$++)e.append(u[$],K()),C.nextNode(),l.push({type:2,index:++s});e.append(u[g],K())}}}else if(e.nodeType===8)if(e.data===zt)l.push({type:2,index:s});else{let u=-1;for(;(u=e.data.indexOf(S,u+1))!==-1;)l.push({type:7,index:s}),u+=S.length-1}s++}}static createElement(t,n){let i=R.createElement("template");return i.innerHTML=t,i}};function M(r,t,n=r,i){if(t===N)return t;let e=i!==void 0?n._$Co?.[i]:n._$Cl,s=W(t)?void 0:t._$litDirective$;return e?.constructor!==s&&(e?._$AO?.(!1),s===void 0?e=void 0:(e=new s(r),e._$AT(r,n,i)),i!==void 0?(n._$Co??=[])[i]=e:n._$Cl=e),e!==void 0&&(t=M(r,e._$AS(r,t.values),e,i)),t}var at=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 s=C.nextNode(),o=0,c=0,l=i[0];for(;l!==void 0;){if(o===l.index){let h;l.type===2?h=new Z(s,s.nextSibling,this,t):l.type===1?h=new l.ctor(s,l.name,l.strings,this,t):l.type===6&&(h=new dt(s,this,t)),this._$AV.push(h),l=i[++c]}o!==l?.index&&(s=C.nextNode(),o++)}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++}},Z=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=M(this,t,n),W(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):se(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&&W(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=q.createElement(Lt(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===e)this._$AH.p(n);else{let s=new at(e,this),o=s.u(this.options);s.p(n),this.T(o),this._$AH=s}}_$AC(t){let n=Ot.get(t.strings);return n===void 0&&Ot.set(t.strings,n=new q(t)),n}k(t){pt(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,i,e=0;for(let s of t)e===n.length?n.push(i=new r(this.O(K()),this.O(K()),this,this.options)):i=n[e],i._$AI(s),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=Ct(t).nextSibling;Ct(t).remove(),t=i}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},T=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,n,i,e,s){this.type=1,this._$AH=a,this._$AN=void 0,this.element=t,this.name=n,this._$AM=e,this.options=s,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);
}
`,je=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;
}
`,Be=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 bt(r,t){let n=new Set;return t.flatMap(i=>{let e=String(r?.states[i]?.attributes.symcon_source_entity||i),s=r?.states[e]?.attributes,o=Number(s?.symcon_id);return!o||!s?.symcon_archive||n.has(o)?[]:(n.add(o),[e])})}var jt,yt=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(jt??=import(n).catch(e=>{throw jt=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(!bt(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",yt);function D(r,t,n=""){let i=bt(r,t);return i.length?d`<nf-trend-button .hass=${r} .ids=${i} .label=${n}></nf-trend-button>`:a}var fe={heating_manifold:"Heiz-/K\xFChlkreisverteiler",buffer_tank:"Pufferspeicher",freshwater_station:"Frischwasserstation"},It=r=>r.name||fe[r.type],Kt=r=>r.name||{heating:"Heizkreis",cooling:"K\xFChlkreis",changeover:"Heizen / K\xFChlen",pump:"Vorschubpumpe"}[r.kind],Wt=(r,t)=>t.kind==="pump"?"Pumpenkreis":t.kind==="cooling"?"K\xFChlen":t.kind==="heating"?"Heizen":f(t.mode_entity)&&b(r.states[t.mode_entity])===null?"Betriebsart \u2013":Number(f(t.mode_entity)?b(r.states[t.mode_entity]):0)===(t.cooling_value??1)?"K\xFChlen":"Heizen",nt=(r,t,n)=>[m(r,"Vorlauf",t),m(r,"R\xFCcklauf",n)].filter(i=>i!==null),vt=(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 qt(r,t){let n=z(t),i=t.type==="freshwater_station"?[]:nt(r,n.flow,n.return);if(t.type==="buffer_tank"&&i.unshift(...[...n.sensors??[]].sort((e,s)=>s.level-e.level).flatMap(e=>{let s=m(r,e.name||"F\xFChler",e.entity);return s?[s]:[]})),t.type==="freshwater_station"){let e=m(r,"Zirkulation",n.circulation_temperature);e&&i.push(e)}for(let e of t.values??[]){let s=m(r,e.label||String(e.entity&&r.states[e.entity]?.attributes.friendly_name||"Wert"),e.entity);s&&i.push({...s,icon:e.icon})}return i}function Zt(r,t){return[...nt(r,t.flow,t.return),...[["Kaltwasser",t.cold_water],["Trinkwarmwasser",t.hot_water],["Pumpenleistung",t.power]].flatMap(([n,i])=>{let e=m(r,n,i);return e?[e]:[]})]}var xt=(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}${D(r,[t.id],t.label)}</b></div>`,P=(r,t,n="Status")=>{let i=m(r,n,t);return i?d`<div class="reading status-reading" data-source=${i.id}><span>${n}</span><b><span class="status-text" title=${i.text}>${i.text}</span>${D(r,[i.id],n)}</b></div>`:a};function V(r,t,n){let i=A(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>${L(r.states[i.id])}${D(r,[i.id],t)}</b></div>`:a}var Jt=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}
.status-reading{grid-template-columns:auto minmax(0,1fr)}.status-reading b{min-width:0}.status-text{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.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}
`,$t=class extends v{static properties={hass:{attribute:!1},item:{attribute:!1},readOnly:{type:Boolean}};render(){if(!this.hass||!this.item)return a;let t=z(this.item),n=qt(this.hass,this.item),i=this.item.type==="freshwater_station"?F(this.item):[];return d`<button class="title" @click=${()=>Bt(this.hass,this.item,this.readOnly)} aria-haspopup="dialog">${It(this.item)} ⚙</button><div class="content">${P(this.hass,t.status,"Anlagenstatus")}
${this.item.type==="heating_manifold"?(t.circuits??[]).map(e=>d`<section class="circuit"><div class="circuit-name">${Kt(e)} <small>${Wt(this.hass,e)}</small></div>${P(this.hass,e.status)}${J(e)?V(this.hass,"Pumpe",e.pump):a}${X(e)?V(this.hass,"Ventil",e.valve):a}${nt(this.hass,e.flow,e.return).map(s=>H(this.hass,s))}${m(this.hass,"Leistung",e.power)?H(this.hass,m(this.hass,"Leistung",e.power)):a}</section>`):a}
${i.length>1?d`<small class="cascade-count">Kaskade · ${i.length} Stationen</small>${i.map((e,s)=>{let o=A(this.hass,e.pump),c=m(this.hass,"Trinkwarmwasser",e.hot_water)||m(this.hass,"Vorlauf",e.flow);return d`<div class="station-summary" data-station=${e.id}><button class="station-name" @click=${()=>Bt(this.hass,this.item,this.readOnly,e.id)}><i class="lamp" title=${`Pumpe: ${o.id?L(this.hass.states[o.id]):"\u2013"}`} style=${`background:${o.running===null?"#888":o.running?"#6fe1a2":"#a82638"}`}></i>${xt(e,s)}</button><b>${c?.text||"\u2013"}</b>${c?D(this.hass,[c.id],`${xt(e,s)} \xB7 ${c.label}`):a}${P(this.hass,e.status)}</div>`})}`:i.map(e=>d`<section class="circuit">${P(this.hass,e.status)}${Zt(this.hass,e).map(s=>H(this.hass,s))}${V(this.hass,"Ladepumpe",e.pump)}${O(e)?V(this.hass,"Kaskadenventil",e.valve):a}</section>`)}
${n.map(e=>H(this.hass,e))}${this.item.type==="freshwater_station"?V(this.hass,"Zirkulationspumpe",t.circulation):a}
${this.item.type!=="heating_manifold"&&this.item.type!=="freshwater_station"&&!n.length&&!f(t.status)?d`<p class="empty">Noch keine Fühler verknüpft</p>`:a}
</div>`}static styles=[gt,Jt,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>.status-reading{grid-column:1/-1}.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(!f(n?.command)&&!f(n?.feedback))return a;let i=f(n?.command)?n.command:null,e=i?this.hass.states[i]:void 0,s=e?.attributes,o=b(e),c=!!i&&!!s?.symcon_has_action&&o!==null&&!this.readOnly&&!this.pending.has(i),l=Number(s?.symcon_min??0),h=Number(s?.symcon_max??100),p=Number(s?.symcon_step||(s?.symcon_variable_type===1?1:.1)),u=U(e),g=$=>{let _=$.target;i&&_.value.trim()&&_.checkValidity()&&Number.isFinite(_.valueAsNumber)&&this.send(i,_.valueAsNumber)};return d`<fieldset data-control=${t}><legend>${t}</legend>${V(this.hass,t,n)}
${i?d`<div class="reading"><span>Befehl / Sollwert</span><b>${L(e)}${D(this.hass,[i],`${t} \xB7 Sollwert`)}</b></div>
${s?.symcon_variable_type===0?d`<div class="command"><button data-command=${i} ?disabled=${!c} @click=${()=>{this.send(i,!Y(e))}}>${Y(e)?"Ausschalten / Schlie\xDFen":"Einschalten / \xD6ffnen"}</button></div>`:[1,2].includes(Number(s?.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=${g}/><input type="number" aria-label=${`${t} nativer Sollwert`} min=${l} max=${h} step=${p} .value=${u===null?"":String(u)} ?disabled=${!c} @change=${g}/></div>`:a}
${this.readOnly?d`<p class="readonly">Historische Ansicht · nur Anzeige</p>`:s?.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=z(this.item),n=qt(this.hass,this.item),i=this.item.type==="freshwater_station"?F(this.item):[];return d`<dialog @close=${()=>{this.remove(),x===this&&(x=null)}} @keydown=${e=>e.stopPropagation()}><header><h2>${It(this.item)}</h2><button aria-label="Schließen" @click=${()=>this.shadowRoot.querySelector("dialog").close()}>×</button></header><div class="body">${P(this.hass,t.status,"Anlagenstatus")}
${this.item.type==="heating_manifold"?(t.circuits??[]).map(e=>d`<section class="circuit" data-circuit=${e.id}><h3>${Kt(e)} <small>${Wt(this.hass,e)}</small></h3>${P(this.hass,e.status)}${J(e)?this.control("Pumpe",e.pump):a}${X(e)?this.control("Ventil",e.valve):a}${nt(this.hass,e.flow,e.return).map(s=>H(this.hass,s))}${vt(this.hass,e.flow,e.return)}${m(this.hass,"Pumpenleistung",e.power)?H(this.hass,m(this.hass,"Pumpenleistung",e.power)):a}</section>`):a}
${i.map((e,s)=>d`<details class="freshwater-unit" data-station=${e.id} ?open=${s===0||this.focusStation===e.id}><summary>${xt(e,s)}</summary>${P(this.hass,e.status)}${Zt(this.hass,e).map(o=>H(this.hass,o))}${vt(this.hass,e.flow,e.return)}${this.control("Ladepumpe",e.pump)}${O(e)?this.control("Kaskadenventil",e.valve):a}</details>`)}
${n.map(e=>H(this.hass,e))}${this.item.type==="buffer_tank"?vt(this.hass,t.flow,t.return):a}
${this.item.type==="freshwater_station"?this.control("Zirkulationspumpe",t.circulation):a}
${!n.length&&!f(t.status)&&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=[gt,Jt,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 nn(){x?.remove(),x=null}async function Bt(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 rn(r,t,n=!1){if(!x)return;let i=t.floors.flatMap(e=>e.furniture).find(e=>e.id===x.item.id);if(!i||!Vt(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",$t);customElements.get("nf-hydronic-dialog")||customElements.define("nf-hydronic-dialog",_t);export{nn as closeHydronic,pe as hydronicVisual,Bt as openHydronic,rn 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
*)
*/
+354
View File
@@ -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
*)
*/
+3 -7
View File
@@ -5,10 +5,6 @@
"type": "ValidationTextBox",
"name": "Title",
"caption": "Name der Visualisierung"
},
{
"type": "Label",
"label": "Der Designer wird als eigener Tab in der IP-Symcon-Konsole geöffnet. Variablen werden dort ausschließlich über den Objektbaum ausgewählt; Objekt-IDs müssen nicht eingegeben werden."
}
],
"actions": [
@@ -20,16 +16,16 @@
},
{
"type": "Button",
"caption": "Designer in der Konsole öffnen",
"caption": "Designer im Browser öffnen",
"onClick": "echo NFSC_OpenDesigner($id);",
"link": true
},
{
"type": "Button",
"caption": "Neuen Designer-Zugang erzeugen",
"caption": "Alle Anmeldungen beenden und Designer öffnen",
"onClick": "echo NFSC_RotateAccessToken($id);",
"link": true,
"confirm": "Alle aktuell offenen Designer- und Kachelansichten dieser Instanz müssen danach neu geladen werden. Fortfahren?"
"confirm": "Alle Benutzer dieser Instanz werden abgemeldet. Der Designer wird anschließend im Browser neu geöffnet. Fortfahren?"
}
],
"status": [
+200
View File
@@ -0,0 +1,200 @@
<?php
declare(strict_types=1);
/** Instance-local accounts and revocable HttpOnly sessions. Console actions are never exposed through the WebHook API. */
trait NextFloorAccess
{
private ?array $requestUser = null;
private ?array $requestScope = null;
private const SESSION_TTL = 43200;
private const SESSION_IDLE = 7200;
private function accessLock(callable $operation): mixed
{
$name = 'NextFloorAccess_' . $this->InstanceID;
$native = function_exists('IPS_SemaphoreEnter');
if ($native && !IPS_SemaphoreEnter($name, 3000)) throw new RuntimeException('access_busy');
try { return $operation(); }
finally { if ($native) IPS_SemaphoreLeave($name); }
}
private function accounts(): array { return $this->jsonAttribute('Accounts', []); }
/** A short-lived, single-use console ticket; no reusable admin credential in browser URLs. */
private function consoleUrl(): string
{
$ticket = $this->newToken();
$this->accessLock(function () use ($ticket): void {
$tickets = array_filter($this->jsonAttribute('ConsoleTickets', []), static fn(array $t): bool => $t['expires'] > time());
$tickets = array_slice($tickets, -19, null, true);
$tickets[hash('sha256', $ticket)] = ['expires' => time() + 90, 'epoch' => $this->ensureAccessToken()];
$this->writeJsonAttribute('ConsoleTickets', $tickets);
});
return '/hook/' . $this->hookPath() . '/designer?mode=designer&ticket=' . rawurlencode($ticket);
}
private function sessionCookie(): string { return 'NFSC_Session_' . $this->InstanceID; }
private function loginCookie(): string { return 'NFSC_Login_' . $this->InstanceID; }
private function accessCookie(string $name, string $value, int $expires = 0): void
{
setcookie($name, $value, ['expires' => $expires, 'path' => '/hook/' . $this->hookPath() . '/',
'secure' => $this->secureRequest(), 'httponly' => true, 'samesite' => 'Strict']);
}
private function secureRequest(): bool
{
// A proxy header can only strengthen cookie protection, never turn native HTTPS off.
return (($_SERVER['HTTPS'] ?? '') !== '' && ($_SERVER['HTTPS'] ?? '') !== 'off') || ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https';
}
private function createSession(string $accountID, array $account, bool $remember = false): array
{
$token = $this->newToken();
$id = hash('sha256', $token);
$session = ['account' => $accountID, 'epoch' => $account['epoch'], 'csrf' => $this->newToken(),
'expires' => time() + ($remember ? 2592000 : self::SESSION_TTL), 'idle' => $remember ? 604800 : self::SESSION_IDLE, 'seen' => time()];
// Called inside accessLock, including ticket exchange and password login.
$sessions = array_filter($this->jsonAttribute('Sessions', []), static fn(array $s): bool => $s['expires'] > time() && $s['seen'] > time() - ($s['idle'] ?? self::SESSION_IDLE));
if (count($sessions) >= 128) throw new RuntimeException('session_limit');
$sessions[$id] = $session;
$this->writeJsonAttribute('Sessions', $sessions);
$this->accessCookie($this->sessionCookie(), $token, $remember ? $session['expires'] : 0);
return [...$account, 'id' => $accountID, 'session_id' => $id, 'csrf' => $session['csrf']];
}
private function resolveSession(): ?array
{
$token = $_COOKIE[$this->sessionCookie()] ?? '';
if (!is_string($token) || preg_match('/^[a-f0-9]{64}$/D', $token) !== 1) return null;
return $this->accessLock(function () use ($token): ?array {
$id = hash('sha256', $token);
$sessions = $this->jsonAttribute('Sessions', []);
$s = $sessions[$id] ?? null;
if (!$s || $s['expires'] <= time() || $s['seen'] <= time() - ($s['idle'] ?? self::SESSION_IDLE)) return null;
$account = $s['account'] === '__console__' ? ['name' => 'Symcon-Konsole', 'role' => 'admin', 'enabled' => true, 'epoch' => $this->ensureAccessToken()]
: ($this->accounts()[$s['account']] ?? null);
if (!$account || !$account['enabled'] || !hash_equals((string) $account['epoch'], (string) $s['epoch'])) return null;
if ($s['seen'] < time() - 60) {
$sessions[$id]['seen'] = time();
$this->writeJsonAttribute('Sessions', $sessions);
}
return [...$account, 'id' => $s['account'], 'session_id' => $id, 'csrf' => $s['csrf']];
});
}
private function exchangeConsoleTicket(string $ticket): bool
{
if (preg_match('/^[a-f0-9]{64}$/D', $ticket) !== 1) return false;
return $this->accessLock(function () use ($ticket): bool {
$tickets = $this->jsonAttribute('ConsoleTickets', []);
$key = hash('sha256', $ticket);
$grant = $tickets[$key] ?? null;
unset($tickets[$key]);
$this->writeJsonAttribute('ConsoleTickets', $tickets);
if (!$grant || $grant['expires'] <= time() || !hash_equals($this->ensureAccessToken(), $grant['epoch'])) return false;
$this->requestUser = $this->createSession('__console__', ['name' => 'Symcon-Konsole', 'role' => 'admin', 'enabled' => true, 'epoch' => $grant['epoch']]);
return true;
});
}
private function safeMode(): string { return ($_GET['mode'] ?? '') === 'tile' ? 'tile' : 'designer'; }
private function entryUrl(string $tail = 'designer'): string { return '/hook/' . $this->hookPath() . '/' . $tail . '?mode=' . $this->safeMode(); }
private function accessRedirect(string $url): void { header('Location: ' . $url, true, 303); header('Cache-Control: no-store'); }
private function validOrigin(): bool
{
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if ($origin === '') return true; // non-browser clients still require the CSRF value and session cookie
$parts = parse_url($origin);
if (!is_array($parts) || ($parts['scheme'] ?? '') !== ($this->secureRequest() ? 'https' : 'http')) return false;
$authority = strtolower((string) ($parts['host'] ?? '') . (isset($parts['port']) ? ':' . $parts['port'] : ''));
return $authority !== '' && hash_equals(strtolower((string) ($_SERVER['HTTP_HOST'] ?? '')), $authority);
}
private function validCsrf(): bool
{
$value = $_SERVER['HTTP_X_NEXTFLOOR_CSRF'] ?? $_POST['csrf'] ?? '';
return $this->requestUser !== null && is_string($value) && $value !== '' && $this->validOrigin()
&& hash_equals($this->requestUser['csrf'], $value);
}
/** Login stays a regular HTML form, including with JavaScript disabled and on small touch screens. */
private function loginPage(string $error = '', int $status = 200): void
{
$csrf = $this->newToken();
$this->accessCookie($this->loginCookie(), $csrf);
$escape = static fn(string $s): string => htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
http_response_code($status);
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store');
$configured = count(array_filter($this->accounts(), static fn(array $a): bool => $a['enabled'])) > 0;
echo '<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
. '<title>Anmelden · ' . $escape($this->viewTitle()) . '</title><style>html{color-scheme:dark}body{margin:0;min-height:100dvh;display:grid;place-items:center;background:#0c1320;color:#e6edf5;font:16px/1.5 system-ui}main{box-sizing:border-box;width:min(420px,calc(100% - 32px));padding:32px;background:#1b2432;border:1px solid #344255;border-radius:18px;box-shadow:0 16px 60px #0005}h1{margin:0 0 4px;font-size:25px}p{color:#aebdce}label{display:block;margin:18px 0 6px}input,button{box-sizing:border-box;width:100%;padding:12px 14px;border-radius:9px;border:1px solid #465872;font:inherit}input{background:#101a28;color:inherit}button{margin-top:24px;background:#1bb8e8;color:#061624;font-weight:700;cursor:pointer}input:focus,button:focus{outline:2px solid #45d0ff;outline-offset:3px}[role=alert]{padding:10px;background:#82353555;border-radius:8px;color:#ffc4c4}.note{font-size:13px}</style></head><body><main><h1>'
. $escape($this->viewTitle()) . '</h1><p>Mit deinem NextFloor-Konto anmelden.</p>'
. ($error !== '' ? '<p role="alert">' . $escape($error) . '</p>' : '')
. ($configured ? '<form method="post" action="' . $escape($this->entryUrl('login')) . '"><input type="hidden" name="csrf" value="' . $csrf . '">'
. '<label for="username">Benutzername</label><input id="username" name="username" autocomplete="username" required maxlength="64" autofocus>'
. '<label for="password">Passwort</label><input id="password" name="password" type="password" autocomplete="current-password" required maxlength="72">'
. '<label style="display:flex;gap:9px;align-items:center;font-size:14px"><input style="width:auto" type="checkbox" name="remember" value="1">Angemeldet bleiben (30 Tage)</label><button type="submit">Anmelden</button></form><p class="note">Passwort vergessen? Der Symcon-Administrator kann es in der NextFloor-Instanz zurücksetzen.</p>'
: '<p role="status">Noch kein Benutzer eingerichtet. Lege in der Symcon-Konfiguration der NextFloor-Instanz zuerst einen Benutzer mit Passwort an.</p>')
. '</main></body></html>';
}
private function passwordLogin(): void
{
$csrf = $_POST['csrf'] ?? '';
$nonce = $_COOKIE[$this->loginCookie()] ?? '';
if (!$this->validOrigin() || !is_string($csrf) || !is_string($nonce) || strlen($nonce) !== 64 || !hash_equals($nonce, $csrf)) {
$this->loginPage('Die Anmeldung ist abgelaufen. Bitte erneut versuchen.', 403);
return;
}
$name = is_string($_POST['username'] ?? null) ? mb_strtolower(trim($_POST['username'])) : '';
$password = is_string($_POST['password'] ?? null) ? $_POST['password'] : '';
$result = $this->accessLock(function () use ($name, $password): string {
$now = time();
$limits = array_filter($this->jsonAttribute('LoginThrottle', []), static fn(array $v): bool => $v['until'] > time());
$ipKey = 'ip:' . hash('sha256', (string) ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
$nameKey = 'name:' . hash('sha256', $name);
if (($limits[$ipKey]['count'] ?? 0) >= 40 || ($limits[$nameKey]['count'] ?? 0) >= 8) return 'limited';
$found = null;
foreach ($this->accounts() as $id => $a) if (mb_strtolower($a['name']) === $name) { $found = [$id, $a]; break; }
// Use the same platform algorithm/cost for an unknown username as for real accounts.
$hash = $found[1]['password'] ?? $this->ReadAttributeString('LoginDummyHash');
$valid = strlen($password) <= 72 && !str_contains($password, "\0") && password_verify($password, $hash);
if (!$valid || !$found || !$found[1]['enabled']) {
foreach ([$ipKey, $nameKey] as $key) $limits[$key] = ['count' => ($limits[$key]['count'] ?? 0) + 1, 'until' => $limits[$key]['until'] ?? $now + 900];
$this->writeJsonAttribute('LoginThrottle', array_slice($limits, -1024, null, true));
return 'invalid';
}
unset($limits[$nameKey]);
$this->writeJsonAttribute('LoginThrottle', $limits);
$this->requestUser = $this->createSession($found[0], $found[1], ($_POST['remember'] ?? '') === '1');
return 'ok';
});
if ($result !== 'ok') { $this->loginPage($result === 'limited' ? 'Zu viele Anmeldeversuche. Bitte in 15 Minuten erneut versuchen.' : 'Benutzername oder Passwort ist ungültig.', $result === 'limited' ? 429 : 401); return; }
$this->accessCookie($this->loginCookie(), '', time() - 3600);
$this->accessRedirect($this->entryUrl());
}
private function logoutSession(): void
{
$id = $this->requestUser['session_id'] ?? '';
$this->accessLock(function () use ($id): void {
$sessions = $this->jsonAttribute('Sessions', []); unset($sessions[$id]); $this->writeJsonAttribute('Sessions', $sessions);
});
$this->accessCookie($this->sessionCookie(), '', time() - 3600);
$this->requestUser = null;
$this->accessRedirect($this->entryUrl('login'));
}
private function publicAccess(): array
{
$admin = $this->requestUser['role'] === 'admin';
$canControl = $admin || ($this->requestUser['control_all'] ?? false);
foreach (['rooms', 'devices', 'objects'] as $group) foreach ($this->requestUser[$group] ?? [] as $g) if (($g['access'] ?? '') === 'control') $canControl = true;
return ['id' => $this->requestUser['id'], 'name' => $this->requestUser['name'], 'is_admin' => $admin,
'view_all' => $admin || ($this->requestUser['view_all'] ?? false), 'control_all' => $admin || ($this->requestUser['control_all'] ?? false), 'can_control' => $canControl];
}
}
+327
View File
@@ -0,0 +1,327 @@
<?php
declare(strict_types=1);
class NextFloorDenied extends RuntimeException {}
/** Deny by default; project geometry and live data are separate capabilities. */
trait NextFloorPermissions
{
private const REF_FIELDS = ['entity', 'entity_id', 'device', 'tracker', 'power', 'energy', 'temperature', 'humidity', 'co2', 'illuminance',
'supply_vsr', 'extract_vsr', 'supply_temperature', 'extract_temperature', 'reheat', 'status', 'schedules',
'floor_heating', 'clean_entity', 'panel', 'hidden', 'no_state', 'cover', 'cover2', 'cover_tilt', 'cover2_tilt',
'contact', 'contact2', 'tilt', 'tilt2', 'position', 'tilt_angle', 'lock', 'door_left', 'door_right', 'soc', 'charge', 'export',
'gang_entities', 'flow', 'return', 'command', 'feedback', 'circulation_temperature', 'hot_water', 'cold_water',
'start', 'end', 'duration', 'start_time', 'end_time', 'charging_time', 'charged_energy', 'lock_status', 'range', 'charging', 'plugged', 'departure',
'grid', 'solar', 'battery', 'battery_soc', 'consumption', 'tariff', 'meter', 'favorites', 'condition', 'pressure', 'wind_speed', 'wind_gust_speed', 'wind_bearing',
'cloud_coverage', 'precipitation', 'precipitation_total', 'uv_index', 'visibility', 'snow', 'fog', 'lightning'];
private const REF_GROUPS = ['climate', 'hvac', 'utility_meters', 'electricity', 'water', 'gas', 'heating', 'cooling',
'values', 'charging', 'hydronic', 'circuits', 'sensors', 'stations', 'pump', 'valve', 'circulation', 'show_when', 'car', 'gates', 'settings', 'presence', 'weather_variables'];
private function refKey(string $key): bool { return in_array($key, self::REF_FIELDS, true) || preg_match('/_(?:entit(?:y\d*|ies)|sensor\d*)$/D', $key) === 1; }
private function entityRefs(array $node): array
{
$ids = [];
foreach ($node as $key => $value) {
if (!is_int($key) && !$this->refKey($key) && !in_array($key, self::REF_GROUPS, true)) continue;
if (is_string($value) && $this->variableIdForEntity($value) !== null) $ids[] = $this->variableIdForEntity($value);
if (is_array($value)) $ids = [...$ids, ...$this->entityRefs($value)];
}
return array_values(array_unique($ids));
}
private function planKey(string $kind, array $floor, string $id): string { return $kind . ':' . rawurlencode((string) $floor['id']) . ':' . rawurlencode($id); }
/** Keep existing grants on uniquely identified rooms/devices when an admin moves them to another floor. */
private function migrateMovedPlanGrants(array $before, array $after): void
{
$index = function (array $plan): array {
$result = [];
foreach ($plan['floors'] ?? [] as $floor) foreach (['rooms', 'furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $item) {
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
if ($id === '') continue;
$kind = $group === 'rooms' ? 'room' : $group;
$result[$kind . ':' . $id][] = $this->planKey($kind, $floor, $id);
}
return $result;
};
$old = $index($before); $new = $index($after); $moves = [];
foreach ($old as $id => $keys) if (count($keys) === 1 && count($new[$id] ?? []) === 1 && $keys[0] !== $new[$id][0]) $moves[$keys[0]] = $new[$id][0];
if ($moves === []) return;
$accounts = $this->accounts(); $changed = false;
foreach ($accounts as &$account) foreach (['rooms', 'devices'] as $group) {
$rows = [];
foreach ($account[$group] ?? [] as $row) {
$target = (string) $row['target'];
if (isset($moves[$target])) { $target = $moves[$target]; $changed = true; }
$level = $row['access'] === 'control' || ($rows[$target]['access'] ?? '') === 'control' ? 'control' : 'view';
$rows[$target] = ['target' => $target, 'access' => $level];
}
$account[$group] = array_values($rows);
}
unset($account);
if ($changed) { $this->writeJsonAttribute('Accounts', $accounts); $this->requestScope = null; }
}
private function accessCatalog(): array
{
$rooms = []; $devices = [];
$building = $this->building();
$topology = $building['topology'] ?? [];
$find = static function (string $group, ?string $id) use ($topology): array {
foreach ($topology[$group] ?? [] as $row) if ($row['id'] === $id) return $row;
return [];
};
foreach ($building['floors'] ?? [] as $floor) {
$group = $find('buildings', $floor['outdoor_building_id'] ?? $floor['building_id'] ?? null);
$branch = $find('branches', $floor['outdoor_branch_id'] ?? $group['branch_id'] ?? null);
$location = $find('locations', $floor['outdoor_location_id'] ?? $branch['location_id'] ?? null);
$parts = [$location['name'] ?? '', $branch['name'] ?? '', $group['name'] ?? '', $floor['name'] ?? 'Etage'];
$prefix = implode(' / ', array_filter($parts, static fn(string $v): bool => $v !== '')) . ' / ';
foreach ($floor['rooms'] ?? [] as $room) $rooms[] = ['caption' => $prefix . ($room['name'] ?? $room['id']), 'value' => $this->planKey('room', $floor, (string) $room['id'])];
foreach (['furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $item) {
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
if ($id === '') continue;
$room = $this->itemRoom($floor, $item);
$label = trim((string) ($item['name'] ?? ''));
if ($label === '' && ($native = $this->variableIdForEntity($id)) !== null && IPS_ObjectExists($native)) {
$parts = []; $at = $native; $seen = [];
while ($at > 0 && IPS_ObjectExists($at) && count($parts) < 3 && !isset($seen[$at])) {
$seen[$at] = true; array_unshift($parts, IPS_GetName($at)); $at = (int) IPS_GetObject($at)['ParentID'];
}
$label = implode(' / ', $parts);
}
if ($label === '') $label = str_replace('_', ' ', (string) ($item['type'] ?? 'Gerät'));
$devices[] = ['caption' => $prefix . ($room ? ($room['name'] ?? '') . ' / ' : '') . $label, 'value' => $this->planKey($group, $floor, $id)];
}
}
return ['rooms' => $rooms, 'devices' => $devices];
}
private function insideRoom(float $x, float $z, array $points): bool
{
$inside = false; $count = count($points);
for ($i = 0, $j = $count - 1; $i < $count; $j = $i++) {
[$xi, $zi] = $points[$i]; [$xj, $zj] = $points[$j];
if (($zi > $z) !== ($zj > $z) && $x < ($xj - $xi) * ($z - $zi) / ($zj - $zi) + $xi) $inside = !$inside;
}
return $inside;
}
private function itemRoom(array $floor, array $item): ?array
{
foreach ($floor['rooms'] ?? [] as $room) {
if (isset($item['room_id']) ? $item['room_id'] === $room['id'] : (isset($item['x'], $item['z']) && $this->insideRoom((float) $item['x'], (float) $item['z'], $room['points'] ?? []))) return $room;
}
return null;
}
private function grantMap(array $grants): array
{
$map = [];
foreach ($grants as $g) if (in_array($g['access'] ?? '', ['view', 'control'], true)) $map[(string) $g['target']] = $g['access'];
return $map;
}
private function isAdministrator(): bool { return ($this->requestUser['role'] ?? '') === 'admin'; }
private function scope(?array $tree = null): array
{
if ($this->requestScope !== null) return $this->requestScope;
if ($this->requestUser === null) throw new NextFloorDenied('authentication_required');
$user = $this->requestUser;
$all = $this->isAdministrator();
$scope = ['view_all' => $all || ($user['view_all'] ?? false) || ($user['control_all'] ?? false), 'control_all' => $all || ($user['control_all'] ?? false),
'read' => [], 'write' => [], 'native_read' => [], 'entities' => [], 'rooms' => $this->grantMap($user['rooms'] ?? []), 'devices' => $this->grantMap($user['devices'] ?? [])];
if ($all) return $this->requestScope = $scope;
$tree ??= $this->objectTree();
$parents = []; $native = [];
foreach ($tree['objects'] as $o) $parents[(int) $o['object_id']] = (int) $o['parent_id'];
foreach ($tree['variables'] as $v) {
$native[(int) $v['attributes']['symcon_id']] = true;
$scope['entities'][(int) $v['attributes']['symcon_id']] = $v['entity_id'];
}
$descendantCache = [];
$descendants = static function (int $root) use ($native, $parents, &$descendantCache): array {
if (isset($descendantCache[$root])) return $descendantCache[$root];
$ids = [];
foreach ($native as $id => $_) {
$at = $id; $seen = [];
while ($at > 0 && !isset($seen[$at])) {
if ($at === $root) { $ids[] = $id; break; }
$seen[$at] = true; $at = $parents[$at] ?? 0;
}
}
return $descendantCache[$root] = $ids;
};
$allow = static function (array $ids, string $level, bool $explicit = false) use (&$scope, $native): void {
foreach ($ids as $id) if (isset($native[$id])) {
$scope['read'][$id] = true;
if ($level === 'control') $scope['write'][$id] = true;
if ($explicit) $scope['native_read'][$id] = true;
}
};
foreach ($user['objects'] ?? [] as $g) {
$target = (int) $g['target']; $seen = [];
while (IPS_ObjectExists($target) && (int) IPS_GetObject($target)['ObjectType'] === 6 && !isset($seen[$target])) {
$seen[$target] = true; $target = (int) IPS_GetLink($target)['TargetID'];
}
$allow($descendants($target), $g['access'], true);
}
foreach ($this->building()['floors'] ?? [] as $floor) {
foreach ($floor['rooms'] ?? [] as $room) {
$key = $this->planKey('room', $floor, (string) $room['id']);
$own = $scope['rooms'][$key] ?? null;
$level = $scope['control_all'] || $own === 'control' ? 'control' : ($scope['view_all'] ? 'view' : $own);
if ($level === null) continue;
$scope['rooms'][$key] = $level;
$allow($this->entityRefs($room), $level);
foreach ([$room['area_id'] ?? '', ...($room['sub_areas'] ?? [])] as $area) if (preg_match('/^symcon-category-(\d+)$/D', (string) $area, $m) === 1) $allow($descendants((int) $m[1]), $level);
}
foreach (['furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $item) {
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
$own = $scope['devices'][$this->planKey($group, $floor, $id)] ?? null;
$room = $this->itemRoom($floor, $item);
$inherited = $room ? ($scope['rooms'][$this->planKey('room', $floor, (string) $room['id'])] ?? null) : null;
$level = $scope['control_all'] || $own === 'control' || $inherited === 'control' ? 'control' : ($own ?? $inherited ?? ($scope['view_all'] ? 'view' : null));
if ($level !== null) { $scope['devices'][$this->planKey($group, $floor, $id)] = $level; $allow($this->entityRefs($item), $level); }
}
if ($scope['view_all']) {
$allow($this->entityRefs($floor), $scope['control_all'] ? 'control' : 'view');
foreach ($floor['outdoor'] ?? [] as $area) $allow($this->entityRefs($area), $scope['control_all'] ? 'control' : 'view');
}
}
if ($scope['view_all']) $allow($this->entityRefs($this->building()), $scope['control_all'] ? 'control' : 'view');
return $this->requestScope = $scope;
}
private function allowedEntity(string $entity, bool $write): bool
{
$id = $this->variableIdForEntity($entity);
if ($id === null) return false;
$s = $this->scope();
return $this->isAdministrator() || ($write ? isset($s['write'][$id]) : isset($s['read'][$id]));
}
/** Authorize every target before the first write: mixed bulk commands cannot partially execute. */
private function authorizeApi(string $action, array $request): void
{
if ($this->requestUser === null) throw new NextFloorDenied('authentication_required');
$read = ['bootstrap', 'variables/snapshot', 'archive/trend', 'building/get', 'image/get', 'packs/list', 'transport/read', 'transport/release'];
if (!$this->isAdministrator() && !in_array($action, [...$read, 'variables/action'], true)) throw new NextFloorDenied('admin_required');
if ($action === 'archive/trend' && (!is_string($request['entity_id'] ?? null) || !$this->allowedEntity($request['entity_id'], false))) throw new NextFloorDenied('read_forbidden');
if ($action === 'variables/action') {
$targets = $request['data']['entity_id'] ?? [];
$targets = is_array($targets) ? $targets : [$targets];
if (!$targets || count($targets) > 256) throw new NextFloorDenied('invalid_targets');
foreach ($targets as $target) {
if (!is_string($target) || !$this->allowedEntity($target, true)) throw new NextFloorDenied('control_forbidden');
$id = $this->variableIdForEntity($target);
if (!$this->isAdministrator() && IPS_VariableExists($id)) {
$v = IPS_GetVariable($id); $actionID = (int) ($v['VariableCustomAction'] ?: $v['VariableAction']);
if ($actionID <= 0) throw new NextFloorDenied('variable_readonly');
}
}
}
if ($action === 'image/get' && !$this->isAdministrator()) {
$id = is_string($request['image_id'] ?? null) ? $request['image_id'] : '';
$images = [];
$visible = $this->visibleBuilding();
array_walk_recursive($visible, static function (mixed $value, mixed $key) use (&$images): void {
if (!is_string($value)) return;
if ($key === 'image_id') $images[] = $value;
elseif (is_string($key) && preg_match('/^(?:picture|image|url|.*_image)$/D', $key) && str_starts_with($value, 'image:')) $images[] = substr($value, 6);
});
if ($id === '' || !in_array($id, $images, true)) throw new NextFloorDenied('image_forbidden');
}
}
private function visibleTree(array $tree): array
{
if ($this->isAdministrator()) return $tree;
$scope = $this->scope($tree);
$variables = [];
foreach ($tree['variables'] as $v) {
$id = (int) $v['attributes']['symcon_id'];
if (!isset($scope['read'][$id])) continue;
$can = isset($scope['write'][$id]) && (($v['attributes']['symcon_schedule'] ?? false) || ($v['attributes']['symcon_has_action'] ?? false));
$v['attributes']['symcon_can_control'] = $can;
if (!$can) $v['attributes']['symcon_has_action'] = false;
$variables[] = $v;
}
$areaIDs = array_fill_keys(array_filter(array_column($variables, 'area_id'), 'is_string'), true);
$areas = array_filter($tree['areas'], static fn(array $a): bool => isset($areaIDs[$a['area_id']]));
// Utility discovery also needs topology (e.g. Büro / Strom / Leistung). Keep only permitted
// variable nodes and their ancestors; never expose unrelated branches or variable values.
$nodes = [];
foreach ($tree['objects'] as $node) $nodes[(int) $node['object_id']] = $node;
$keep = [];
foreach ($variables as $v) {
$at = (int) $v['attributes']['symcon_id'];
while ($at > 0 && isset($nodes[$at]) && !isset($keep[$at])) {
$keep[$at] = true; $at = (int) $nodes[$at]['parent_id'];
}
}
$objects = array_values(array_filter($tree['objects'], static fn(array $node): bool => isset($keep[(int) $node['object_id']])));
return ['variables' => $variables, 'areas' => array_values($areas), 'objects' => $objects];
}
private function maskRefs(array $node, array $allow): array
{
foreach ($node as $key => $v) {
// Strip unknown/legacy binding fields too. Geometry identifiers and captions are not live bindings.
if (in_array($key, ['id', 'name', 'type', 'label', 'icon', 'room_id', 'area_id', 'parent_meter', 'buffer_id'], true)) continue;
if (is_string($v) && ($id = $this->variableIdForEntity($v)) !== null && !isset($allow[$id])) $node[$key] = 'none';
elseif (is_array($v)) $node[$key] = $this->maskRefs($v, $allow);
}
return $node;
}
private function visibleBuilding(): array
{
$building = $this->building();
if ($this->isAdministrator()) return $building;
$s = $this->scope();
// Admin-owned executable UI configuration is never part of a user view.
$building['settings']['plugins'] = []; $building['settings']['buttons'] = [];
foreach (['custom_buttons', 'media_presets', 'announce_phrases'] as $key) unset($building['settings'][$key]);
foreach ($building['floors'] as &$floor) {
$panels = [];
foreach (['furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $i => $item) {
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
$granted = $s['view_all'] || isset($s['devices'][$this->planKey($group, $floor, $id)]);
$filtered = $granted ? $item : $this->maskRefs($item, $s['native_read']);
unset($filtered['tap']);
if (!$granted) {
unset($filtered['show_when'], $filtered['pictures'], $filtered['screen_pictures'], $filtered['picture']);
if (empty($item['entity'])) $filtered['entity'] = 'none';
if (!$this->entityRefs($filtered)) { $filtered['power_card'] = false; $filtered['hydronic']['card'] = false; }
}
$floor[$group][$i] = $filtered;
$room = $this->itemRoom($floor, $item);
if ($room) foreach ($this->entityRefs($filtered) as $native) $panels[$room['id']][$native] = true;
}
foreach ($floor['rooms'] as &$room) {
$key = $this->planKey('room', $floor, (string) $room['id']);
if ($s['view_all'] || isset($s['rooms'][$key])) continue;
$room = $this->maskRefs($room, []);
$room['area_id'] = null; $room['sub_areas'] = []; $room['climate_card'] = false;
$room['symcon_read_room'] = false;
$room['climate'] = ['temperature' => 'none', 'humidity' => 'none', 'co2' => 'none', 'illuminance' => 'none'];
$room['hvac'] = null; $room['utility_meters'] = null; $room['moods'] = []; $room['floor_heating'] = 'none';
$room['panel'] = array_values(array_filter(array_map(static fn(int $id): ?string => $s['entities'][$id] ?? null, array_keys($panels[$room['id']] ?? []))));
}
unset($room);
if (!$s['view_all']) { $floor['power_entity'] = 'none'; $floor['utility_meters'] = null; }
foreach ($floor['outdoor'] ?? [] as $i => $area) if (!$s['view_all']) {
$floor['outdoor'][$i] = $this->maskRefs($area, $s['native_read']); $floor['outdoor'][$i]['area_id'] = null;
}
}
unset($floor);
if (!$s['view_all']) {
$building['presence'] = []; $building['energy'] = []; $building['settings']['weather_variables'] = [];
foreach ($building['settings'] as $key => $value) if (is_string($value) && $this->variableIdForEntity($value) !== null) $building['settings'][$key] = 'none';
}
return $building;
}
}
+175
View File
@@ -0,0 +1,175 @@
<?php
declare(strict_types=1);
/** Native Symcon 9.0 configuration. Password fields are actions, never persistent module properties. */
trait NextFloorUsers
{
public function GetConfigurationForm(): string
{
$form = json_decode((string) file_get_contents(__DIR__ . '/../form.json'), true, 512, JSON_THROW_ON_ERROR);
$id = $this->ReadAttributeString('SelectedAccount');
$account = $this->accounts()[$id] ?? [];
$catalog = $this->accessCatalog();
$level = ['type' => 'Select', 'options' => [['caption' => 'Nur ansehen', 'value' => 'view'], ['caption' => 'Ansehen und bedienen', 'value' => 'control']]];
$grants = function (string $name, string $caption, array $options, array $values): array {
return ['type' => 'List', 'name' => $name, 'caption' => $caption, 'rowCount' => 5, 'add' => true, 'delete' => true, 'values' => $values,
'columns' => $this->planGrantColumns($options, $values)];
};
$userForm = ['type' => 'ExpansionPanel', 'caption' => 'Benutzer und Zugriffsrechte', 'expanded' => true, 'items' => [
['type' => 'ValidationTextBox', 'caption' => 'Direkter Zugang (an die Symcon-Adresse anhängen)', 'value' => '/hook/' . $this->hookPath() . '/', 'enabled' => false],
['type' => 'Button', 'caption' => 'Anmeldeseite öffnen', 'link' => true, 'onClick' => 'echo NFSC_OpenLogin($id);'],
['type' => 'Select', 'name' => 'AccountSelect', 'caption' => 'Benutzer auswählen', 'value' => $id, 'options' => $this->accountOptions(), 'onChange' => 'NFSC_SelectAccessUser($id, $AccountSelect);'],
['type' => 'ValidationTextBox', 'name' => 'AccountName', 'caption' => 'Benutzername', 'value' => $account['name'] ?? ''],
['type' => 'PasswordTextBox', 'name' => 'AccountPassword', 'caption' => 'Neues Passwort (leer = bestehendes behalten)', 'value' => ''],
['type' => 'Button', 'name' => 'AccountReset', 'caption' => 'Passwort zurücksetzen', 'enabled' => $id !== '', 'onClick' => 'echo NFSC_ResetUserPassword($id, $AccountSelect, $AccountPassword);'],
['type' => 'CheckBox', 'name' => 'AccountEnabled', 'caption' => 'Zugang aktiv', 'value' => $account['enabled'] ?? true],
['type' => 'Select', 'name' => 'AccountRole', 'caption' => 'Rolle', 'value' => $account['role'] ?? 'user', 'options' => [['caption' => 'Benutzer · Ansicht und freigegebene Bedienung', 'value' => 'user'], ['caption' => 'Admin · vollständiger Zugriff und Editor', 'value' => 'admin']]],
['type' => 'CheckBox', 'name' => 'AccountViewAll', 'caption' => 'Alle Zustände ansehen', 'value' => $account['view_all'] ?? false],
['type' => 'CheckBox', 'name' => 'AccountControlAll', 'caption' => 'Alles ansehen und bedienen', 'value' => $account['control_all'] ?? false],
$grants('AccountRooms', 'Einzelne Räume', $catalog['rooms'], $account['rooms'] ?? []),
$grants('AccountDevices', 'Einzelne Geräte im Plan', $catalog['devices'], $account['devices'] ?? []),
['type' => 'List', 'name' => 'AccountObjects', 'caption' => 'Weitere Symcon-Geräte / Datenpunkte (optional)', 'rowCount' => 4, 'add' => true, 'delete' => true, 'values' => $account['objects'] ?? [],
'columns' => [['name' => 'target', 'caption' => 'Objekt aus dem Objektbaum', 'width' => 'auto', 'add' => 0, 'edit' => ['type' => 'SelectObject']],
['name' => 'access', 'caption' => 'Recht', 'width' => '190px', 'add' => 'view', 'edit' => $level]]],
['type' => 'Button', 'caption' => 'Benutzer speichern', 'onClick' => [
// Native List variables implement iteration/ArrayAccess; direct JSON encoding does not serialize their rows.
'$rooms = []; foreach ($AccountRooms as $row) { $rooms[] = ["target" => $row["target"], "access" => $row["access"]]; }',
'$devices = []; foreach ($AccountDevices as $row) { $devices[] = ["target" => $row["target"], "access" => $row["access"]]; }',
'$objects = []; foreach ($AccountObjects as $row) { $objects[] = ["target" => $row["target"], "access" => $row["access"]]; }',
'echo NFSC_SaveAccessUser($id, $AccountSelect, $AccountName, $AccountRole, $AccountEnabled, $AccountViewAll, $AccountControlAll, json_encode($rooms), json_encode($devices), json_encode($objects), $AccountPassword);',
]],
['type' => 'Button', 'name' => 'AccountRevoke', 'caption' => 'Benutzer abmelden', 'enabled' => $id !== '', 'onClick' => 'echo NFSC_RevokeUserSessions($id, $AccountSelect);'],
['type' => 'Button', 'name' => 'AccountDelete', 'caption' => 'Benutzer löschen', 'enabled' => $id !== '', 'confirm' => 'Diesen NextFloor-Benutzer einschließlich seiner Zugänge löschen?', 'onClick' => 'echo NFSC_DeleteAccessUser($id, $AccountSelect);'],
['type' => 'PopupButton', 'caption' => 'ⓘ Rechte und Passwörter', 'popup' => ['caption' => 'Zugriffsrechte', 'items' => [
['type' => 'Label', 'caption' => 'Die Auswahl eines Benutzers lädt dessen Einstellungen und alle drei Freigabetabellen. Änderungen werden erst durch Benutzer speichern übernommen; beim Wechsel werden nicht gespeicherte Eingaben verworfen. Das Passwortfeld wird bei jedem Wechsel geleert.'],
['type' => 'Label', 'caption' => 'Admins dürfen den Editor und alle Geräte verwenden. Die Benutzerverwaltung bleibt ausschließlich in der Symcon-Konfiguration.'],
['type' => 'Label', 'caption' => 'Alle Zustände ansehen ohne weitere Bedienfreigabe ist ein Zugang nur zum Lesen. Einzelne Raum- und Gerätefreigaben ergänzen diese Grundrechte. Ohne Freigabe bleibt das Gebäude sichtbar, seine Zustände werden nicht übertragen.'],
['type' => 'Label', 'caption' => 'Eine Raumfreigabe umfasst seine verknüpften Werte, Geräte im Raum und die zugeordneten Bereichskategorien. Gerätefreigaben gelten für deren verknüpfte Datenpunkte. Bei automatischen Gerätezuordnungen die benötigten Symcon-Objekte zusätzlich auswählen oder feste Verknüpfungen im Editor setzen.'],
['type' => 'Label', 'caption' => 'Passwörter: 8–72 Bytes. Leer beim Speichern erhält das bisherige Passwort. Änderungen an Konto oder Rechten beenden bestehende Anmeldungen dieses Benutzers. Die Konsole kann jederzeit Passwörter zurücksetzen.'],
]]],
]];
$form['actions'][] = $userForm;
return json_encode($form, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
}
public function OpenLogin(): string { $this->requireWebHook(); return 'link:/hook/' . $this->hookPath() . '/login'; }
private function accountOptions(): array
{
$options = [['caption' => '+ Neuen Benutzer anlegen', 'value' => '']];
foreach ($this->accounts() as $id => $a) $options[] = ['caption' => $a['name'] . ($a['enabled'] ? '' : ' (gesperrt)'), 'value' => $id];
return $options;
}
private function planGrantColumns(array $options, array $values): array
{
foreach ($values as $v) if (!in_array($v['target'], array_column($options, 'value'), true)) $options[] = ['caption' => '(Nicht mehr im Plan) ' . $v['target'], 'value' => $v['target']];
return [['name' => 'target', 'caption' => 'Freigabe', 'width' => 'auto', 'add' => '', 'edit' => ['type' => 'Select', 'options' => [['caption' => 'Bitte auswählen', 'value' => ''], ...$options]]],
['name' => 'access', 'caption' => 'Recht', 'width' => '190px', 'add' => 'view', 'edit' => ['type' => 'Select', 'options' => [['caption' => 'Nur ansehen', 'value' => 'view'], ['caption' => 'Ansehen und bedienen', 'value' => 'control']]]]];
}
public function SelectAccessUser(string $UserID): void
{
$a = $this->accounts()[$UserID] ?? [];
if (!$a) $UserID = '';
$this->WriteAttributeString('SelectedAccount', $UserID);
$catalog = $this->accessCatalog();
$this->UpdateFormField('AccountSelect', 'options', json_encode($this->accountOptions()));
foreach (['AccountSelect' => $UserID, 'AccountName' => $a['name'] ?? '', 'AccountEnabled' => $a['enabled'] ?? true,
'AccountRole' => $a['role'] ?? 'user', 'AccountViewAll' => $a['view_all'] ?? false, 'AccountControlAll' => $a['control_all'] ?? false, 'AccountPassword' => ''] as $name => $value) $this->UpdateFormField($name, 'value', $value);
foreach (['AccountRooms' => 'rooms', 'AccountDevices' => 'devices', 'AccountObjects' => 'objects'] as $name => $key) {
if ($key !== 'objects') $this->UpdateFormField($name, 'columns', json_encode($this->planGrantColumns($catalog[$key], $a[$key] ?? [])));
$this->UpdateFormField($name, 'values', json_encode($a[$key] ?? []));
}
foreach (['AccountReset', 'AccountRevoke', 'AccountDelete'] as $name) $this->UpdateFormField($name, 'enabled', $UserID !== '');
}
private function passwordHash(string $password): string
{
if (strlen($password) < 8 || strlen($password) > 72 || str_contains($password, "\0")) throw new InvalidArgumentException('Das Passwort muss 8–72 Bytes lang sein.');
return password_hash($password, defined('PASSWORD_ARGON2ID') ? PASSWORD_ARGON2ID : PASSWORD_DEFAULT);
}
private function parseGrants(string $json, bool $objects = false): array
{
$rows = json_decode($json, true);
if (!is_array($rows) || !array_is_list($rows) || count($rows) > 256) throw new InvalidArgumentException('Ungültige Freigabeliste.');
$result = [];
foreach ($rows as $row) {
if (!is_array($row)) throw new InvalidArgumentException('Ungültige Freigabe.');
$target = $objects ? (int) ($row['target'] ?? 0) : (string) ($row['target'] ?? '');
if ($target === '' || $target === 0) continue;
if (!in_array($row['access'] ?? '', ['view', 'control'], true)) throw new InvalidArgumentException('Bitte für jede Freigabe ein Recht auswählen.');
if ($objects && (!IPS_ObjectExists($target) || !in_array((int) IPS_GetObject($target)['ObjectType'], [0, 1, 2, 4, 6], true))) throw new InvalidArgumentException('Das freigegebene Objekt existiert nicht oder ist kein Gerät, Datenpunkt, Ereignis oder Bereich.');
$key = (string) $target;
$level = $row['access'] === 'control' || ($result[$key]['access'] ?? '') === 'control' ? 'control' : 'view';
$result[$key] = ['target' => $target, 'access' => $level];
}
return array_values($result);
}
public function SaveAccessUser(string $UserID, string $Name, string $Role, bool $Enabled, bool $ViewAll, bool $ControlAll, string $Rooms, string $Devices, string $Objects, string $Password): string
{
try {
$Name = trim($Name);
if (preg_match('/^[\p{L}\p{N}][\p{L}\p{N}_.@ -]{1,63}$/uD', $Name) !== 1) throw new InvalidArgumentException('Benutzername: 2–64 Buchstaben, Zahlen, Leerzeichen oder . _ @ -');
if (!in_array($Role, ['admin', 'user'], true)) throw new InvalidArgumentException('Ungültige Rolle.');
$rooms = $this->parseGrants($Rooms); $devices = $this->parseGrants($Devices); $objects = $this->parseGrants($Objects, true);
$hash = $Password === '' ? null : $this->passwordHash($Password);
$id = $this->accessLock(function () use ($UserID, $Name, $Role, $Enabled, $ViewAll, $ControlAll, $rooms, $devices, $objects, $hash): string {
$accounts = $this->accounts();
if ($UserID !== '' && !isset($accounts[$UserID])) throw new InvalidArgumentException('Benutzer nicht gefunden.');
foreach ($accounts as $id => $a) if ($id !== $UserID && mb_strtolower($a['name']) === mb_strtolower($Name)) throw new InvalidArgumentException('Dieser Benutzername ist bereits vergeben.');
if ($UserID === '' && count($accounts) >= 128) throw new InvalidArgumentException('Maximal 128 Benutzer pro Instanz.');
if ($UserID === '' && $hash === null) throw new InvalidArgumentException('Für neue Benutzer bitte ein Passwort setzen.');
$id = $UserID ?: bin2hex(random_bytes(16));
$accounts[$id] = ['name' => $Name, 'role' => $Role, 'enabled' => $Enabled, 'view_all' => $ViewAll || $ControlAll,
'control_all' => $ControlAll, 'rooms' => $rooms, 'devices' => $devices, 'objects' => $objects,
'password' => $hash ?? $accounts[$id]['password'], 'epoch' => $this->newToken()];
$this->writeJsonAttribute('Accounts', $accounts);
$this->clearUserSessions($id);
return $id;
});
$this->SelectAccessUser($id);
return 'Benutzer gespeichert. Vorherige Anmeldungen dieses Benutzers wurden beendet.';
} catch (InvalidArgumentException $e) { return $e->getMessage(); }
}
private function clearUserSessions(string $id): void
{
$this->writeJsonAttribute('Sessions', array_filter($this->jsonAttribute('Sessions', []), static fn(array $s): bool => $s['account'] !== $id));
}
public function ResetUserPassword(string $UserID, string $Password): string
{
try {
$hash = $this->passwordHash($Password);
$this->accessLock(function () use ($UserID, $hash): void {
$accounts = $this->accounts();
if (!isset($accounts[$UserID])) throw new InvalidArgumentException('Bitte einen bestehenden Benutzer auswählen.');
$accounts[$UserID]['password'] = $hash; $accounts[$UserID]['epoch'] = $this->newToken();
$this->writeJsonAttribute('Accounts', $accounts); $this->clearUserSessions($UserID);
$limits = $this->jsonAttribute('LoginThrottle', []); unset($limits['name:' . hash('sha256', mb_strtolower($accounts[$UserID]['name']))]);
$this->writeJsonAttribute('LoginThrottle', $limits);
});
$this->UpdateFormField('AccountPassword', 'value', '');
return 'Passwort zurückgesetzt. Bestehende Anmeldungen dieses Benutzers sind beendet.';
} catch (InvalidArgumentException $e) { return $e->getMessage(); }
}
public function RevokeUserSessions(string $UserID): string
{
$this->accessLock(fn() => $this->clearUserSessions($UserID));
return 'Bestehende Anmeldungen dieses Benutzers wurden beendet.';
}
public function DeleteAccessUser(string $UserID): string
{
$this->accessLock(function () use ($UserID): void {
$accounts = $this->accounts(); unset($accounts[$UserID]); $this->writeJsonAttribute('Accounts', $accounts); $this->clearUserSessions($UserID);
});
$this->SelectAccessUser('');
return 'Benutzer gelöscht.';
}
}
+1 -1
View File
@@ -7,7 +7,7 @@
"aliases": [
"NextFloor Designer und 3D-Kachel"
],
"url": "https://git.portal.se-cloud.de/Hannes/NextFloor/src/branch/main/symcon/README.md",
"url": "https://git.portal.se-cloud.de/Hannes/NextFloor/src/branch/symcon/README.md",
"parentRequirements": [],
"childRequirements": [],
"implemented": [],
+282 -68
View File
@@ -2,15 +2,20 @@
declare(strict_types=1);
require_once __DIR__ . '/libs/Access.php';
require_once __DIR__ . '/libs/Users.php';
require_once __DIR__ . '/libs/Permissions.php';
/**
* NextFloor for IP-Symcon.
*
* One visualization instance owns a floor-plan project. Its protected WebHook serves the designer as
* a console tab and the same viewer in an HTML-SDK tile iframe. The frontend receives every variable
* in the object tree with a friendly path; it never asks an end user to type an object id.
* a browser tab and the same viewer in an HTML-SDK tile iframe. Admins receive the native object tree;
* user sessions receive only authorized live bindings. Object selections always use named choices.
*/
class NextFloor extends IPSModuleStrict
{
use NextFloorAccess, NextFloorUsers, NextFloorPermissions;
private const MAX_BUILDING_BYTES = 8_000_000;
private const MAX_IMAGE_BYTES = 8_000_000;
private const MAX_HISTORY = 20;
@@ -18,6 +23,8 @@ class NextFloor extends IPSModuleStrict
private const TRANSFER_CHUNK_BYTES = 128 * 1024;
private const MAX_TRANSFER_BYTES = 64 * 1024 * 1024;
private const TRANSFER_TTL = 120;
private const HOOK_RETRY_MS = 5000;
private const HOOK_MAINTENANCE_MS = 30000;
public function Create(): void
{
@@ -29,21 +36,31 @@ class NextFloor extends IPSModuleStrict
$this->RegisterAttributeString('Packs', '[]');
$this->RegisterAttributeString('History', '[]');
$this->RegisterAttributeString('AccessToken', '');
$this->RegisterAttributeString('Accounts', '{}');
$this->RegisterAttributeString('Sessions', '{}');
$this->RegisterAttributeString('ConsoleTickets', '{}');
$this->RegisterAttributeString('LoginThrottle', '{}');
$this->RegisterAttributeString('LoginDummyHash', '');
$this->RegisterAttributeString('SelectedAccount', '');
$this->RegisterAttributeString('StateHash', '');
$this->RegisterAttributeString('HookError', '');
$this->RegisterAttributeInteger('BuildingRevision', 0);
$this->RegisterAttributeInteger('StateRevision', 0);
$this->RegisterMessage(0, IPS_KERNELSTARTED);
$this->RegisterMessage(0, KR_READY);
$this->RegisterTimer('WebHookRetry', 0, 'NFSC_RetryWebHook($_IPS[\'TARGET\']);');
$this->ensureAccessToken();
if ($this->ReadAttributeString('LoginDummyHash') === '') $this->WriteAttributeString('LoginDummyHash', $this->passwordHash($this->newToken()));
$this->SetVisualizationType(1);
$this->ensureWebHook();
$this->ensureWebHook(true);
}
public function ApplyChanges(): void
{
parent::ApplyChanges();
$this->RegisterMessage(0, IPS_KERNELSTARTED);
$this->RegisterMessage(0, KR_READY);
$this->SetVisualizationType(1);
$this->ensureWebHook();
}
@@ -51,12 +68,12 @@ class NextFloor extends IPSModuleStrict
public function MessageSink(int $TimeStamp, int $SenderID, int $Message, array $Data): void
{
parent::MessageSink($TimeStamp, $SenderID, $Message, $Data);
if ($SenderID === 0 && $Message === IPS_KERNELSTARTED) {
if ($SenderID === 0 && ($Message === KR_READY || $Message === IPS_KERNELSTARTED)) {
$this->ensureWebHook();
}
}
/** Timer callback; stops itself as soon as the volatile hook has been restored. */
/** Keep the volatile route registered, including resets after successful startup or module reload. */
public function RetryWebHook(): void
{
$this->ensureWebHook();
@@ -71,7 +88,7 @@ class NextFloor extends IPSModuleStrict
return 'WebHook registriert: /hook/' . $this->hookPath() . '. Jetzt den Designer öffnen.';
}
/** URL returned to the console form. It opens in a console tab, as IPSView does. */
/** Browser link returned to the console form; link: does not create a native Pro Console tab. */
public function OpenDesigner(): string
{
$this->requireWebHook();
@@ -79,11 +96,13 @@ class NextFloor extends IPSModuleStrict
return 'link:' . $this->designerUrl('designer');
}
/** Invalidates links from copied browser history and returns a fresh designer URL. */
/** Revoke all logins and outstanding console tickets, then issue a fresh one-use designer link. */
public function RotateAccessToken(): string
{
$this->requireWebHook();
$this->WriteAttributeString('AccessToken', $this->newToken());
$this->WriteAttributeString('Sessions', '{}');
$this->WriteAttributeString('ConsoleTickets', '{}');
return 'link:' . $this->designerUrl('designer');
}
@@ -95,31 +114,60 @@ class NextFloor extends IPSModuleStrict
. htmlspecialchars($this->hookErrorMessage(), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</div>';
}
$src = htmlspecialchars($this->designerUrl('tile'), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$title = htmlspecialchars($this->viewTitle(), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
return '<style>html,body{margin:0;width:100%;height:100%;overflow:hidden}iframe{display:block;width:100%;height:100%;min-height:260px;border:0;background:#111}</style>'
. '<iframe title="NextFloor" src="' . $src . '" loading="eager" allow="fullscreen"></iframe>';
. '<iframe title="' . $title . '" src="' . $src . '" loading="eager" allow="fullscreen"></iframe>';
}
/** IP-Symcon calls this for /hook/nextfloor/<instance id>/... */
protected function ProcessHookData(): void
{
$this->requestUser = null;
$this->requestScope = null;
// Keep a same-origin Origin on native form POSTs; no-referrer can turn it into "null".
header('Referrer-Policy: same-origin');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header("Content-Security-Policy: frame-ancestors 'self'; object-src 'none'; base-uri 'none'");
$requestPath = (string) ($_SERVER['REQUEST_URI'] ?? '');
if ($requestPath === '') {
$requestPath = (string) ($_SERVER['SCRIPT_NAME'] ?? '');
}
$path = (string) (parse_url($requestPath, PHP_URL_PATH) ?? '');
$prefix = '/hook/' . $this->hookPath();
if (!str_starts_with($path, $prefix)) {
if ($path !== $prefix && !str_starts_with($path, $prefix . '/')) {
$this->sendError(404, 'not_found');
return;
}
if (!$this->hasValidToken()) {
$this->sendError(403, 'forbidden');
return;
}
$tail = trim(substr($path, strlen($prefix)), '/');
try {
$method = (string) ($_SERVER['REQUEST_METHOD'] ?? 'GET');
$this->requestUser = $this->resolveSession();
if ($tail === 'login') {
if ($method === 'POST') $this->passwordLogin();
elseif ($method !== 'GET') $this->sendError(405, 'method_not_allowed');
elseif ($this->requestUser !== null) $this->accessRedirect($this->entryUrl());
else $this->loginPage();
return;
}
if (($tail === 'designer' || $tail === '') && $method === 'GET' && isset($_GET['ticket'])) {
// Always exchange and remove a ticket, even if another user was already logged in.
if (is_string($_GET['ticket']) && $this->exchangeConsoleTicket($_GET['ticket'])) $this->accessRedirect($this->entryUrl());
else $this->loginPage('Der Konsolen-Link ist abgelaufen oder wurde schon verwendet. Bitte erneut in der Konsole öffnen.', 401);
return;
}
if ($this->requestUser === null) {
if ($tail === '' || $tail === 'designer') $this->accessRedirect($this->entryUrl('login'));
else $this->sendError(401, 'authentication_required');
return;
}
if ($tail === 'logout') {
if ($method !== 'POST' || !$this->validCsrf()) $this->sendError(403, 'csrf_invalid');
else $this->logoutSession();
return;
}
if ($tail === '' || $tail === 'designer') {
if ($method !== 'GET') { $this->sendError(405, 'method_not_allowed'); return; }
$this->sendDesignerPage();
return;
}
@@ -128,6 +176,8 @@ class NextFloor extends IPSModuleStrict
return;
}
if (str_starts_with($tail, 'assets/')) {
if ($method !== 'GET') { $this->sendError(405, 'method_not_allowed'); return; }
if (!$this->isAdministrator() && preg_match('#^assets/nextfloor-(?:editor|card-editor)\.js$#D', $tail)) { $this->sendError(403, 'admin_required'); return; }
$this->sendAsset(substr($tail, strlen('assets/')));
return;
}
@@ -140,13 +190,14 @@ class NextFloor extends IPSModuleStrict
// --------------------------------------------------------------------- WebHook pages
private function ensureWebHook(): bool
private function ensureWebHook(bool $duringCreate = false): bool
{
// Native hooks are volatile. Create/ApplyChanges can run before WebHook Control is ready;
// register again after the kernel has started and whenever a designer/tile link is requested.
if (IPS_GetKernelRunlevel() !== KR_READY) {
// Register in Create as documented, even while Symcon initializes. Re-register after
// startup/update and keep maintaining the route: WebHook Control can reset later too.
$ready = IPS_GetKernelRunlevel() === KR_READY;
if (!$ready && !$duringCreate) {
$this->SetStatus(104);
$this->SetTimerInterval('WebHookRetry', 5000);
$this->SetTimerInterval('WebHookRetry', self::HOOK_RETRY_MS);
return false;
}
try {
@@ -156,17 +207,27 @@ class NextFloor extends IPSModuleStrict
throw new RuntimeException('Symcon hat die Registrierung von /hook/' . $this->hookPath() . ' abgelehnt.');
}
} catch (Throwable $error) {
if (!$ready) {
$this->SetStatus(104);
$this->SetTimerInterval('WebHookRetry', self::HOOK_RETRY_MS);
return false;
}
$message = $error->getMessage();
if ($message !== $this->ReadAttributeString('HookError')) {
$this->LogMessage('WebHook-Registrierung fehlgeschlagen: ' . $message, KL_ERROR);
}
$this->WriteAttributeString('HookError', $message);
$this->SetStatus(200);
$this->SetTimerInterval('WebHookRetry', 5000);
$this->SetTimerInterval('WebHookRetry', self::HOOK_RETRY_MS);
return false;
}
if (!$ready) {
$this->SetStatus(104);
$this->SetTimerInterval('WebHookRetry', self::HOOK_RETRY_MS);
return false;
}
$this->WriteAttributeString('HookError', '');
$this->SetTimerInterval('WebHookRetry', 0);
$this->SetTimerInterval('WebHookRetry', self::HOOK_MAINTENANCE_MS);
$this->SetStatus(102);
return true;
}
@@ -192,9 +253,14 @@ class NextFloor extends IPSModuleStrict
return 'nextfloor/' . $this->InstanceID;
}
private function viewTitle(): string
{
return trim($this->ReadPropertyString('Title')) ?: 'NextFloor';
}
private function designerUrl(string $mode): string
{
return '/hook/' . $this->hookPath() . '/designer?mode=' . rawurlencode($mode) . '&token=' . rawurlencode($this->ensureAccessToken());
return $mode === 'tile' ? '/hook/' . $this->hookPath() . '/designer?mode=tile' : $this->consoleUrl();
}
private function ensureAccessToken(): string
@@ -212,55 +278,30 @@ class NextFloor extends IPSModuleStrict
return bin2hex(random_bytes(32));
}
private function hasValidToken(): bool
{
// The first HTML request carries the random URL token. It also sets an HttpOnly cookie
// below, so lazy ES-module imports (which cannot inherit a query string) stay protected.
$provided = (string) ($_GET['token'] ?? $_COOKIE[$this->cookieName()] ?? '');
return $provided !== '' && hash_equals($this->ensureAccessToken(), $provided);
}
private function cookieName(): string
{
return 'NFSC_' . $this->InstanceID;
}
private function setAccessCookie(): void
{
setcookie($this->cookieName(), $this->ensureAccessToken(), [
'expires' => 0,
'path' => '/hook/' . $this->hookPath() . '/',
'secure' => (($_SERVER['HTTPS'] ?? '') !== '' && ($_SERVER['HTTPS'] ?? '') !== 'off'),
'httponly' => true,
'samesite' => 'Strict'
]);
}
private function sendDesignerPage(): void
{
$this->setAccessCookie();
$config = [
'endpoint' => '/hook/' . $this->hookPath(),
'token' => $this->ensureAccessToken(),
'csrf' => $this->requestUser['csrf'],
'user' => $this->publicAccess(),
'language' => 'de',
'title' => $this->ReadPropertyString('Title') ?: 'NextFloor'
'title' => $this->viewTitle()
];
$asset = '/hook/' . $this->hookPath() . '/assets/nextfloor-designer.js?v=' . rawurlencode($this->moduleVersion())
. '&token=' . rawurlencode($this->ensureAccessToken());
$asset = '/hook/' . $this->hookPath() . '/assets/nextfloor-designer.js?v=' . rawurlencode($this->moduleVersion());
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store');
echo '<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
. '<title>' . htmlspecialchars($config['title'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</title>'
. '<style>html,body{width:100%;height:100%;margin:0;background:#111;color:#e1e1e1}body>nextfloor-panel,body>nextfloor-card{display:block;width:100%;height:100%}</style>'
. '<style>html,body{width:100%;height:100%;margin:0;background:#111;color:#e1e1e1}body{display:flex;flex-direction:column}body>nextfloor-panel,body>nextfloor-card{display:block;flex:1;min-height:0;width:100%}.nf-session-bar{display:flex;align-items:center;gap:10px;padding:5px 12px;font:12px/1.4 system-ui;background:#20252d;border-bottom:1px solid #ffffff15}.nf-session-bar span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.nf-session-bar form{margin:0 0 0 auto;flex-shrink:0}.nf-session-bar button{font:inherit;padding:5px 12px;border:1px solid #ffffff25;border-radius:7px;background:#ffffff0a;color:inherit;cursor:pointer}</style>'
. '</head><body><p style="padding:1rem;font-family:system-ui">NextFloor wird geladen …</p>'
. '<script>window.__NEXTFLOOR_SYMCON__=' . json_encode($config, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ';</script>'
. '<script>window.__NEXTFLOOR_SYMCON__=' . json_encode($config, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ';</script>'
. '<script type="module" src="' . htmlspecialchars($asset, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '"></script></body></html>';
}
private function sendAsset(string $asset): void
{
// Only build artifacts are public through the authenticated hook. No request can escape the module folder.
if (!preg_match('#^(?:nextfloor-(?:designer|3d|editor|card-editor)\\.js|lang/[a-z]{2}\\.json)$#', $asset)) {
if (!preg_match('#^(?:nextfloor-(?:designer|3d|editor|card-editor|trend|hydronics)\\.js|lang/[a-z]{2}\\.json)$#', $asset)) {
$this->sendError(404, 'asset_not_found');
return;
}
@@ -282,17 +323,23 @@ class NextFloor extends IPSModuleStrict
$this->sendError(405, 'method_not_allowed');
return;
}
$request = json_decode((string) file_get_contents('php://input'), true);
if (!$this->validCsrf()) { $this->sendError(403, 'csrf_invalid'); return; }
$limit = $this->isAdministrator() ? self::MAX_TRANSFER_BYTES : 65536;
$raw = (string) file_get_contents('php://input', false, null, 0, $limit + 1);
if (strlen($raw) > $limit) { $this->sendError(413, 'request_too_large'); return; }
$request = json_decode($raw, true);
if (!is_array($request) || !is_string($request['action'] ?? null)) {
$this->sendError(400, 'invalid_request');
return;
}
try {
$this->authorizeApi($request['action'], $request);
$result = match ($request['action']) {
'bootstrap' => $this->bootstrap(),
'variables/snapshot' => $this->variablesSnapshot((int) ($request['revision'] ?? -1)),
'building/get' => ['building' => $this->building(), 'revision' => $this->ReadAttributeInteger('BuildingRevision'), 'version' => $this->moduleVersion()],
'archive/trend' => $this->archiveTrend($request),
'building/get' => ['building' => $this->visibleBuilding(), 'revision' => $this->ReadAttributeInteger('BuildingRevision'), 'version' => $this->moduleVersion()],
'building/save' => ['revision' => $this->saveBuilding($this->arrayValue($request, 'building'))],
'image/get' => $this->imageGet((string) ($request['image_id'] ?? '')),
'image/set' => $this->imageSet((string) ($request['image_id'] ?? ''), (string) ($request['data'] ?? '')),
@@ -313,6 +360,8 @@ class NextFloor extends IPSModuleStrict
default => throw new RuntimeException('unknown_action')
};
$this->sendApiResult($result, ($request['transport'] ?? '') === 'nextfloor-chunks-v1');
} catch (NextFloorDenied $error) {
$this->sendError(403, $error->getMessage());
} catch (InvalidArgumentException $error) {
$this->sendError(400, $error->getMessage());
} catch (RuntimeException $error) {
@@ -322,9 +371,10 @@ class NextFloor extends IPSModuleStrict
private function bootstrap(): array
{
$objects = $this->objectTree();
$objects = $this->visibleTree($this->objectTree());
$stateRevision = $this->stateRevision($objects);
return [
'access' => $this->publicAccess(),
'state_revision' => $stateRevision,
'building_revision' => $this->ReadAttributeInteger('BuildingRevision'),
'variables' => $objects['variables'],
@@ -335,7 +385,7 @@ class NextFloor extends IPSModuleStrict
private function variablesSnapshot(int $knownRevision): array
{
$objects = $this->objectTree();
$objects = $this->visibleTree($this->objectTree());
$stateRevision = $this->stateRevision($objects);
$result = [
'state_revision' => $stateRevision,
@@ -358,10 +408,16 @@ class NextFloor extends IPSModuleStrict
foreach (IPS_GetChildrenIDs(0) as $child) {
$this->collectObjects($child, [], null, $variables, $areas, $nodes);
}
$archives = $this->archiveVariables();
$byVariable = [];
foreach ($variables as $variable) {
foreach ($variables as &$variable) {
$id = $variable['attributes']['symcon_id'];
if (isset($archives[$id]) && !isset($variable['attributes']['symcon_schedule'])) {
$variable['attributes']['symcon_archive'] = $archives[$id];
}
$byVariable[$variable['attributes']['symcon_id']] = $variable['entity_id'];
}
unset($variable);
// A link stays at its original position in the tree and selects its target variable.
foreach ($nodes as &$node) {
if ($node['object_type'] === 6) {
@@ -397,7 +453,9 @@ class NextFloor extends IPSModuleStrict
'icon' => (string) $object['ObjectIcon']
];
if ($type === 1) { // OBJECTTYPE_INSTANCE: the logical console view separates system modules.
$node['module_type'] = (int) IPS_GetInstance($objectID)['ModuleInfo']['ModuleType'];
$module = IPS_GetInstance($objectID)['ModuleInfo'];
$node['module_type'] = (int) $module['ModuleType'];
$node['module_id'] = (string) ($module['ModuleID'] ?? '');
}
if ($type === 0) { // OBJECTTYPE_CATEGORY
$nearestCategory = $objectID;
@@ -408,12 +466,41 @@ class NextFloor extends IPSModuleStrict
$variables[] = $variable;
$node['entity_id'] = $variable['entity_id'];
}
if ($type === 4 && function_exists('IPS_GetEvent')) {
$event = IPS_GetEvent($objectID);
if ((int) ($event['EventType'] ?? -1) === 2) {
$schedule = $this->describeSchedule($objectID, $name, implode(' / ', $path), $event);
$variables[] = $schedule;
$node['entity_id'] = $schedule['entity_id'];
}
}
$nodes[] = $node;
foreach (IPS_GetChildrenIDs($objectID) as $child) {
$this->collectObjects($child, $path, $nearestCategory, $variables, $areas, $nodes);
}
}
private function describeSchedule(int $eventID, string $name, string $path, array $event): array
{
// Export presentation only; action scripts and action parameters stay in Symcon.
$actions = array_map(static fn(array $action): array => [
'id' => (int) $action['ID'], 'name' => (string) $action['Name'], 'color' => (int) ($action['Color'] ?? 0)
], $event['ScheduleActions'] ?? []);
$groups = array_map(static fn(array $group): array => [
'id' => (int) $group['ID'], 'days' => (int) $group['Days'],
'points' => array_map(static fn(array $point): array => [
'id' => (int) $point['ID'], 'hour' => (int) $point['Start']['Hour'],
'minute' => (int) $point['Start']['Minute'], 'second' => (int) $point['Start']['Second'],
'action' => (int) $point['ActionID']
], $group['Points'] ?? [])
], $event['ScheduleGroups'] ?? []);
return ['entity_id' => 'schedule.' . $eventID, 'name' => $name, 'path' => $path,
'state' => ($event['EventActive'] ?? false) ? 'on' : 'off',
'attributes' => ['symcon_id' => $eventID, 'symcon_schedule' => true,
'groups' => $groups, 'actions' => $actions, 'next_run' => (int) ($event['NextRun'] ?? 0),
'next_action' => (int) ($event['NextActionID'] ?? 0), 'last_action' => (int) ($event['LastActionID'] ?? 0)]];
}
private function describeVariable(int $variableID, string $name, string $path, ?int $categoryID): array
{
$variable = IPS_GetVariable($variableID);
@@ -427,8 +514,9 @@ class NextFloor extends IPSModuleStrict
'symcon_path' => $path,
'symcon_profile' => $profile,
'symcon_variable_type' => (int) $variable['VariableType'],
'symcon_has_action' => ((int) ($variable['VariableCustomAction'] ?: $variable['VariableAction'])) !== 0,
'symcon_has_action' => ((int) ($variable['VariableCustomAction'] ?: $variable['VariableAction'])) > 0,
'symcon_formatted' => GetValueFormatted($variableID),
'symcon_value' => $value,
'device_class' => $this->deviceClassFor($profile, $name, $unit)
];
if ($unit !== '') {
@@ -587,6 +675,8 @@ class NextFloor extends IPSModuleStrict
private function stateRevision(array $objects): int
{
$hash = hash('sha256', $this->encodeResponse($objects));
// Distinct user scopes must not invalidate one global revision on every alternating poll.
if ($this->requestUser !== null && !$this->isAdministrator()) return (int) hexdec(substr($hash, 0, 12));
if (!hash_equals($this->ReadAttributeString('StateHash'), $hash)) {
$this->WriteAttributeString('StateHash', $hash);
$this->WriteAttributeInteger('StateRevision', $this->ReadAttributeInteger('StateRevision') + 1);
@@ -622,11 +712,14 @@ class NextFloor extends IPSModuleStrict
if (strlen($encoded) > self::MAX_BUILDING_BYTES) {
throw new InvalidArgumentException('building_too_large');
}
$this->WriteAttributeString('Building', $encoded);
$revision = $this->ReadAttributeInteger('BuildingRevision') + 1;
$this->WriteAttributeInteger('BuildingRevision', $revision);
$this->UpdateVisualizationValue(json_encode(['building_revision' => $revision]));
return $revision;
return $this->accessLock(function () use ($building, $encoded): int {
$this->migrateMovedPlanGrants($this->building(), $building);
$this->WriteAttributeString('Building', $encoded);
$revision = $this->ReadAttributeInteger('BuildingRevision') + 1;
$this->WriteAttributeInteger('BuildingRevision', $revision);
$this->UpdateVisualizationValue(json_encode(['building_revision' => $revision]));
return $revision;
});
}
private function imageGet(string $imageID): array
@@ -782,6 +875,87 @@ class NextFloor extends IPSModuleStrict
return is_array($history) ? array_values($history) : [];
}
// --------------------------------------------------------------------- archive trends (read-only)
/** One bulk metadata query per archive, never one query for every exported variable. */
private function archiveVariables(): array
{
if (!function_exists('AC_GetAggregationVariables') || !function_exists('IPS_GetInstanceListByModuleID')) return [];
$result = [];
foreach (IPS_GetInstanceListByModuleID('{43192F0B-135B-4CE7-A0A7-1475603F3060}') as $archiveID) {
try {
foreach (AC_GetAggregationVariables($archiveID, false) as $entry) {
if (!($entry['AggregationActive'] ?? false)) continue;
$id = (int) $entry['VariableID'];
$result[$id] ??= ['id' => (int) $archiveID, 'counter' => (int) $entry['AggregationType'] === 1,
'first' => (int) ($entry['FirstTime'] ?? 0), 'last' => (int) ($entry['LastTime'] ?? 0)];
}
} catch (Throwable) { /* An unavailable archive must not break live values or the designer. */ }
}
return $result;
}
/** Archive Control API: AC_GetLoggedValues / AC_GetAggregatedValues, bounded at 10,000 records. */
private function archiveTrend(array $request): array
{
if (!is_string($request['entity_id'] ?? null)) throw new InvalidArgumentException('invalid_trend_variable');
$id = $this->variableIdForEntity($request['entity_id']);
if ($id === null || !IPS_VariableExists($id)) throw new InvalidArgumentException('invalid_trend_variable');
$start = $request['start'] ?? null;
$end = $request['end'] ?? null;
if (!is_int($start) || !is_int($end) || $start < 1 || $end <= $start || $end > 253402300799) {
throw new InvalidArgumentException('invalid_trend_range');
}
$levels = ['minute' => 6, '5minutes' => 5, '15minutes' => 8, 'hour' => 0, 'day' => 1, 'week' => 2, 'month' => 3, 'year' => 4];
$mode = $request['aggregation'] ?? 'auto';
if (!is_string($mode) || !in_array($mode, ['auto', 'raw', ...array_keys($levels)], true)) throw new InvalidArgumentException('invalid_trend_aggregation');
$meta = $this->archiveVariables()[$id] ?? null;
if ($meta === null) throw new RuntimeException('variable_not_logged');
$type = (int) IPS_GetVariable($id)['VariableType'];
$span = $end - $start;
$automatic = $mode === 'auto';
if ($automatic) $mode = $span <= 172800 ? 'raw' : ($span <= 2678400 ? 'hour' : ($span <= 34560000 ? 'day' : 'month'));
if ($type === 3) $mode = 'raw';
$archive = $meta['id'];
$limit = $type === 3 ? 1000 : 10000;
// Bound expensive, computed minute aggregates and prevent silently truncated long requests.
$seconds = ['minute' => 60, '5minutes' => 300, '15minutes' => 900, 'hour' => 3600, 'day' => 86400, 'week' => 604800, 'month' => 2419200, 'year' => 31536000];
if ($mode !== 'raw' && $span / $seconds[$mode] > $limit - 2) throw new InvalidArgumentException('trend_range_too_large_for_resolution');
$rows = $mode === 'raw' ? AC_GetLoggedValues($archive, $id, $start, $end, $limit)
: AC_GetAggregatedValues($archive, $id, $levels[$mode], $start, $end, $limit);
if ($automatic && $type !== 3 && $mode === 'raw' && count($rows) >= $limit) {
$mode = 'minute';
$rows = AC_GetAggregatedValues($archive, $id, $levels[$mode], $start, $end, $limit);
}
$truncated = count($rows) >= $limit;
$points = [];
foreach ($rows as $row) {
$timestamp = (int) $row['TimeStamp'];
if ($timestamp < $start || $timestamp > $end) continue;
$raw = $mode === 'raw' ? $row['Value'] : $row['Avg'];
$value = $type === 3 ? mb_substr((string) $raw, 0, 4096) : (is_bool($raw) ? (int) $raw : (is_numeric($raw) ? (float) $raw : null));
if ($value === null || (is_float($value) && !is_finite($value))) continue;
$point = ['t' => $timestamp, 'v' => $value, 'd' => max(0, (int) ($row['Duration'] ?? 0))];
if ($mode !== 'raw' && is_numeric($row['Min'] ?? null) && is_numeric($row['Max'] ?? null)) {
$point['min'] = (float) $row['Min']; $point['max'] = (float) $row['Max'];
}
$points[] = $point;
}
// Raw archives only store changes. Carry the last known state into the requested range.
if ($mode === 'raw' && !$truncated && $start > 1) {
$previous = AC_GetLoggedValues($archive, $id, 0, $start - 1, 1);
if ($previous && !array_filter($points, static fn(array $p): bool => $p['t'] === $start)) {
$v = $previous[0]['Value'];
if ($type === 3 || is_bool($v) || is_numeric($v)) {
$points[] = ['t' => $start, 'v' => $type === 3 ? mb_substr((string) $v, 0, 4096) : (float) $v, 'd' => 0];
}
}
}
usort($points, static fn(array $a, array $b): int => $a['t'] <=> $b['t']);
return ['entity_id' => (string) $request['entity_id'], 'start' => $start, 'end' => $end,
'aggregation' => $mode, 'counter' => $meta['counter'], 'type' => $type, 'limit' => $limit, 'truncated' => $truncated, 'points' => $points];
}
// --------------------------------------------------------------------- variable actions
private function variableAction(string $domain, string $service, array $data): array
@@ -792,6 +966,14 @@ class NextFloor extends IPSModuleStrict
if (!is_string($entityID)) {
continue;
}
if ($domain === 'schedule' && $service === 'set_active') {
if (preg_match('/^schedule\.(\d+)$/', $entityID, $match) !== 1 || !IPS_EventExists((int) $match[1])
|| (int) IPS_GetEvent((int) $match[1])['EventType'] !== 2 || !is_bool($data['active'] ?? null)) {
throw new InvalidArgumentException('invalid_schedule');
}
if (!IPS_SetEventActive((int) $match[1], $data['active'])) throw new RuntimeException('schedule_update_failed');
continue;
}
$variableID = $this->variableIdForEntity($entityID);
if ($variableID === null || !IPS_VariableExists($variableID)) {
continue;
@@ -810,6 +992,20 @@ class NextFloor extends IPSModuleStrict
{
$variable = IPS_GetVariable($variableID);
$current = GetValue($variableID);
if ($domain === 'symcon' && $service === 'set_value') {
if ((int) ($variable['VariableCustomAction'] ?: $variable['VariableAction']) === 0) throw new InvalidArgumentException('variable_readonly');
$type = (int) $variable['VariableType'];
$value = $data['value'] ?? null;
if ($type === 0 && !is_bool($value)) throw new InvalidArgumentException('invalid_boolean');
if (in_array($type, [1, 2], true)) {
$meta = $this->variableMetadata($variableID, $variable);
if (!is_numeric($value) || !is_finite((float) $value) || (float) $value < $meta['min'] || (float) $value > $meta['max']
|| ($type === 1 && (float) $value !== floor((float) $value))) throw new InvalidArgumentException('invalid_value');
}
if ($type === 3 && !is_string($value)) throw new InvalidArgumentException('invalid_string');
$this->setVariable($variableID, $variable, $value);
return;
}
if ($domain === 'cover' && $service === 'stop_cover') {
throw new InvalidArgumentException('cover_stop_not_supported');
}
@@ -965,6 +1161,7 @@ class NextFloor extends IPSModuleStrict
if (preg_match('/^[a-f0-9]{32}\.json$/D', basename($file)) !== 1 || is_link($file)) continue;
if ((int) filemtime($file) < time() - self::TRANSFER_TTL) {
unlink($file);
if (is_file($file . '.owner') && !is_link($file . '.owner')) unlink($file . '.owner');
} else {
$active++;
}
@@ -988,15 +1185,32 @@ class NextFloor extends IPSModuleStrict
throw $error;
}
fclose($handle);
if (file_put_contents($file . '.owner', $this->transferOwner(), LOCK_EX) === false) {
unlink($file);
throw new RuntimeException('transfer_storage_unavailable');
}
chmod($file . '.owner', 0600);
return ['id' => $id, 'bytes' => $bytes, 'chunk_bytes' => self::TRANSFER_CHUNK_BYTES, 'chunks' => (int) ceil($bytes / self::TRANSFER_CHUNK_BYTES)];
}
private function transferOwner(): string
{
return hash('sha256', (string) ($this->requestUser['session_id'] ?? 'internal') . ':' . (string) ($this->requestUser['epoch'] ?? ''));
}
private function ownsTransfer(string $file): bool
{
$owner = $file . '.owner';
return is_file($owner) && !is_link($owner) && hash_equals($this->transferOwner(), (string) file_get_contents($owner));
}
private function readTransfer(string $id, int $index): array
{
$file = $this->transferFile($id);
if (!is_file($file) || is_link($file)) throw new RuntimeException('transfer_not_found');
if (!is_file($file) || is_link($file) || !$this->ownsTransfer($file)) throw new RuntimeException('transfer_not_found');
if ((int) filemtime($file) < time() - self::TRANSFER_TTL) {
unlink($file);
unlink($file . '.owner');
throw new RuntimeException('transfer_expired: Bitte erneut laden.');
}
$bytes = (int) filesize($file);
@@ -1019,7 +1233,7 @@ class NextFloor extends IPSModuleStrict
private function releaseTransfer(string $id): array
{
$file = $this->transferFile($id);
if (is_file($file) && !is_link($file)) unlink($file);
if (is_file($file) && !is_link($file) && $this->ownsTransfer($file)) { unlink($file); unlink($file . '.owner'); }
return [];
}
+483 -6
View File
@@ -1,10 +1,12 @@
# NextFloor für IP-Symcon 9.0
Dieses Verzeichnis ist eine vollständige IP-Symcon-Bibliothek. Der gleiche NextFloor-Designer
läuft damit in zwei Symcon-Oberflächen:
Dieses Verzeichnis ist eine vollständige IP-Symcon-Bibliothek. NextFloor lässt sich
über den Designer und die Kachel-Visualisierung verwenden:
- **Designer:** Die Instanzkonfiguration öffnet den Designer per geschütztem WebHook in einem
eigenen Konsolen-/Browser-Tab – derselbe Ansatz, den auch IPSView für seinen Designer nutzt.
Browser-Tab. Auch die installierte Pro-Konsole öffnet diesen Link im Standardbrowser.
IPSViews interner Designer-Tab ist speziell in Symcons Konsole integriert; die öffentliche
Modulschnittstelle von Symcon 9.0 bietet diesen Tab nicht für eigene Web-Oberflächen an.
- **Kachel-Visualisierung:** Die NextFloor-Instanz kann direkt in der Tile-Visualisierung als
HTML-SDK-Kachel abgelegt werden. Sie zeigt die 3D-Ansicht samt Bedienung.
@@ -16,9 +18,70 @@ In **Kerninstanzen → Modules** wird dieses Repository verwendet:
Im Zahnrad des Eintrags den Branch **`symcon`** wählen und auf Aktualisierungen prüfen.
`main` enthält die Quellen für die Entwicklung, `symcon` die installierbare Bibliothek.
Nach der Aktualisierung auf **0.2.7 / Build 10** die Konsole neu laden. Unter
Nach der Aktualisierung auf **0.4.3 / Build 41** die Konsole neu laden. Unter
**Instanz hinzufügen → Hersteller NextFloor** erscheint **„NextFloor Designer und 3D-Kachel“**.
## Hierarchie und Etagen
Im Editor oben **Hierarchie** öffnen. Bei einem bisherigen Plan dort auf
**Hierarchie einrichten** klicken.
Bestehende Stockwerke werden einem ersten Ort, einer Niederlassung und einem Gebäude
zugeordnet; ihre IDs, Geometrie, Datenpunkte und Benutzerfreigaben bleiben erhalten.
Im separaten Dialog Orte, Niederlassungen und Gebäude benennen und weitere anlegen.
Die drei Listen zeigen jeweils die Einträge der ausgewählten übergeordneten Ebene.
Beispiel: **Urbach / Zentrale / RAS19 / EG / IT**.
- Oben im Editor unter **Ansicht** einen **Ort**, eine **Niederlassung** oder ein
**Gebäude** auswählen. Ort und Niederlassung zeigen eine Gesamtübersicht ihrer
untergeordneten Pläne, auch in der 3D-Hälfte. Die Knöpfe darunter öffnen die nächste
Ebene. Eine Gesamtübersicht wählt keine Etage automatisch zur Bearbeitung aus.
Bei Auswahl eines Gebäudes erscheinen darunter nur seine Etagen und sein Außenplan.
**+ Etage** legt ein Stockwerk in genau diesem Gebäude an, mit eigener Höhenfolge.
Ein Gebäudewechsel ändert keine Zuordnung und erzeugt keine Etage. Ein leeres
Gebäude bleibt auch nach einem Neuladen der Daten ausgewählt und leer.
- Die rechte Leiste bleibt für Etagen-, Raum- und Geräteeigenschaften verfügbar.
Im ausgewählten Raum über **Bereich (Symcon)** die vorhandene Bereichskategorie
verknüpfen; Räume derselben Kategorie werden in der Raumliste zusammengefasst.
Der Raum gehört über seine Etage zum Gebäude. Die Auswahl verändert weder den
Symcon-Objektbaum noch den Raumnamen; dafür gibt es **Bereichsnamen übernehmen**.
- Zum Verschieben zuerst die betreffende Etage öffnen und oben
**Ausgewählte Etage verschieben…** wählen. Der Dialog nennt ihren vollständigen
Pfad. Erst die Schaltfläche **Etage „…“ verschieben** übernimmt das Zielgebäude;
eine bloße Zielauswahl oder das Schließen des Dialogs ändert nichts.
- Für einen einzelnen Raum rechts **Raum verschieben…** öffnen. Zielgebäude und
Zieletage auswählen, bei Bedarf die vorgeschlagene Position X/Z anpassen und erst
dann **Raum „…“ verschieben** drücken. Raumdaten, Datenpunktverknüpfungen,
Türen/Fenster, enthaltene Möbel, platzierte Geräte und Notizen ziehen mit um.
Der Dialog meldet Konflikte mit bereits vorhandenen Gerätekennungen. Vorhandene
Benutzerfreigaben folgen eindeutig identifizierbaren Räumen und Geräten, auch
beim Rückgängigmachen; Ansicht bleibt Ansicht und Bedienung bleibt Bedienung.
- Pro **Ort**, **Niederlassung** und **Gebäude** im Hierarchiedialog über
**Außenplan anlegen** einen eigenen Außenplan erstellen und im Editor wie
gewohnt Außenflächen, Geräte und Möbel platzieren.
Jeder Außenplan gehört direkt zur jeweiligen Ebene und erscheint dort auch in
der linken Navigation mit einer passenden Vorschau. Das Außen-Popup berücksichtigt
auch bisher auf untergeordneten Gebäudestockwerken platzierte Außen-Datenpunkte,
ohne Werte benachbarter Niederlassungen oder Gebäude einzumischen.
- Die linke Navigation in Designer und Kachel folgt der Topologie. Die kleinen
Pfadknöpfe führen zu den übergeordneten Ebenen zurück. Die Vorschaubilder zeigen
nur die Stockwerke des Eintrags; Raumvorschauen werden auf den Raum zugeschnitten.
- Die obere Raumleiste erscheint erst bei Auswahl eines Stockwerks. In Orts-,
Niederlassungs-, Gebäude- und Außenansichten bleibt sie ausgeblendet.
- Die rechte Verbrauchsübersicht folgt derselben Auswahl: **Ort → Niederlassungen**,
**Niederlassung → Gebäude**, **Gebäude → Stockwerke**, **Stockwerk → Bereiche**.
Oben stehen jeweils die Leistungen und Verbräuche der ausgewählten Gruppe.
Einträge öffnen die entsprechende Ebene. Eigene Außenpläne mit Zählern erscheinen
separat unter ihrem jeweiligen Besitzer. Alle fünf Medien, eigene Stockwerkszähler,
getrennte Verbrauchszeiträume, Trendknöpfe und „Err:“-Teilsummen bleiben erhalten.
- Stockwerksstapel und automatische Dächer werden pro Gebäude dargestellt.
Planpositionen bleiben unverändert. Bei Bedarf ein Gebäude über **Verschieben**
mit **Alle Stockwerke dieses Gebäudes mitnehmen** im gemeinsamen Grundriss anordnen.
Auch die Freigabe-Auswahl in der Symcon-Benutzerverwaltung zeigt die vollständigen
Pfade. Die Rechte bleiben an die bisherigen Stockwerks-, Raum- und Geräte-IDs gebunden.
Leere Gruppen können entfernt werden; Gruppen mit untergeordneten Einträgen sind geschützt.
Pläne ohne eingerichtete Topologie behalten ihre bisherige Navigation.
### Für die Entwicklung
IP-Symcon erwartet `library.json` im Wurzelverzeichnis eines Repositories. Das eigentliche
@@ -41,11 +104,425 @@ Danach in IP-Symcon unter **Kerninstanzen → Modules** den Git-Link des Forks h
im Zahnrad des Eintrags den Branch `symcon` wählen. Anschließend steht **NextFloor** bei
„Instanz hinzufügen“ zur Verfügung.
### Status von Heizkreisen und Frischwasserstationen
Im Editor lässt sich je Heizkreis und je FriWa-Station unter **Status (optional)** eine
Variable aus dem Symcon-Objektbaum auswählen. **Anlagenstatus (optional)** ergänzt einen
gemeinsamen Status für das gesamte Gerät. Integer-Variablen zeigen den in Symcon
hinterlegten Aliastext; Namen und Pfade begrenzen die Auswahl nicht. Die Statuswerte
erscheinen in der schwebenden 3D-Kachel und im Detailfenster, bei Kaskaden je Station.
Nicht verknüpfte Statuszeilen bleiben ausgeblendet. Die Anzeige ist schreibgeschützt.
Die Dateien unter `NextFloor/assets/` und `NextFloor/packs/` werden durch
`frontend` mit `npm run build` erzeugt beziehungsweise kopiert und gehören daher in den Branch.
Der Build prüft anschließend die Modulmetadaten und die installierbare Verzeichnisstruktur.
Dieselbe Prüfung lässt sich separat mit `node symcon/tests/validate-package.mjs` ausführen.
## Anmeldung und Benutzerrechte ab 0.3.0
1. In der NextFloor-Instanz **Benutzer und Zugriffsrechte** öffnen.
2. Unter **Benutzer auswählen → Neuen Benutzer anlegen** Namen und Passwort setzen.
3. Rolle und Freigaben auswählen, dann **Benutzer speichern**. Diese Aktionen
werden sofort gespeichert; das Passwortfeld wird danach geleert.
4. **Anmeldeseite öffnen** aufrufen und die Adresse als Lesezeichen verwenden.
Sie ist dauerhaft und enthält kein Zugangs-Token. Die Adresse steht außerdem
im Formular: `/hook/nextfloor/<Instanz-ID>/` an der Symcon-Serveradresse.
Das Passwortfeld steht direkt unter dem Benutzernamen. Beim Benutzerwechsel werden
Rolle, Schalter und alle drei Freigabetabellen mit den gespeicherten Werten dieses
Benutzers neu befüllt; das Passwortfeld wird geleert. Die Auswahl **Neuen Benutzer
anlegen** leert die Tabellen. Änderungen werden erst mit **Benutzer speichern**
übernommen; ein Wechsel verwirft noch nicht gespeicherte Eingaben. Seit 0.3.2 werden
die nativen Formularlisten zeilenweise übertragen, auch wenn sie leer sind oder
gerade keine Zeile ausgewählt ist.
Die Konten gehören zur jeweiligen NextFloor-Instanz. Die Benutzerverwaltung
bleibt ausschließlich in der Symcon-Konfiguration. **Designer im Browser
öffnen** ermöglicht dem Symcon-Administrator weiterhin den vollständigen Zugang,
auch wenn kein NextFloor-Admin mehr angemeldet ist oder alle Konten gesperrt sind.
Der dabei erzeugte Konsolen-Link gilt 90 Sekunden und kann einmal verwendet werden.
Als Lesezeichen wird stattdessen die dauerhafte Anmeldeseite verwendet.
| Einstellung | Zugriff |
| --- | --- |
| Admin | Komplette Visualisierung, Bedienung und Editor |
| Benutzer ohne Freigaben | Komplettes Gebäude als Geometrie, keine Zustände oder Bedienung |
| Alle Zustände ansehen | Alle Daten dieser Visualisierung, ohne Bedienung |
| Alles ansehen und bedienen | Daten und Bedienung dieser Visualisierung, ohne Editor |
| Raumfreigabe „Nur ansehen“ | Zustände des ausgewählten Raums und seiner Geräte |
| Raumfreigabe „Ansehen und bedienen“ | Zusätzlich Bedienung dieser Geräte |
| Gerätefreigabe | Nur das gewählte Gerät und seine verknüpften Werte, ohne den ganzen Raum freizugeben |
Einzelfreigaben ergänzen die Grundrechte. So kann ein Benutzer alles ansehen,
aber ausschließlich Büro 2 bedienen. „Alle“ bezieht sich auf die Visualisierung;
unverknüpfte Symcon-Variablen werden Benutzern nicht pauschal übertragen.
Ein Raum umfasst seine verknüpften Werte, die Geräte im Raum und die zugeordneten
Bereichskategorien einschließlich Unterkategorien. Freigaben für Geräte im Plan
verwenden deren feste Datenpunkt-Verknüpfungen. Automatisch zugeordnete Geräte
können über **Weitere Symcon-Geräte / Datenpunkte** ergänzt oder im Editor fest
verknüpft werden. Die Auswahl erfolgt aus dem Objektbaum; es müssen keine IDs
eingetippt werden. Eine hier ausgewählte Instanz oder Kategorie umfasst ihre
untergeordneten Datenpunkte. Ein ausgewählter Link gilt für sein Ziel.
Außerhalb freigegebener Räume bleiben die Gebäudegeometrie und Möbel sichtbar;
ihre Live-Verknüpfungen werden entfernt. Einzeln freigegebene Geräte bleiben
im jeweiligen Raum erreichbar, ohne dessen Raumklima freizugeben. Die Prüfung
gilt auch für direkte API-Aufrufe, native Rollen-Aliase, Trends und Datenübertragungen.
Benutzer erhalten weder den kompletten Objektbaum noch Projekt-Historie,
Backups, Uploads oder Editor-Funktionen. Schaltbefehle mit nicht freigegebenen
Zielen werden vor der ersten Aktion abgewiesen. Passive Variablen ohne native
Schaltaktion bleiben für Benutzer schreibgeschützt.
**Passwort zurücksetzen**, Sperren, Löschen und **Benutzer abmelden** funktionieren
in der Konsole. Änderungen an Konto oder Rechten beenden dessen bisherige
Anmeldungen sofort. Passwörter werden gehasht gespeichert. Anmeldungen verwenden
HttpOnly-Cookies und CSRF-Schutz; es gibt keine wiederverwendbaren Admin-Token
im Viewer-Link oder in der Kachel. Der normale Zugang gilt bis zu zwölf Stunden
mit maximal zwei Stunden Inaktivität. **Angemeldet bleiben** gilt bis zu 30 Tage
mit maximal sieben Tagen Inaktivität. Ein Passwort-Reset oder eine Sperre hebt
auch diese Anmeldungen auf. Für den Zugriff über das Internet die HTTPS-Adresse
des Symcon-Servers bzw. des eigenen HTTPS-Proxys verwenden.
Nach dem Update erfordert die Kachel-Visualisierung eine Anmeldung. Vorherige
Links mit `token=...` gelten nicht mehr als Admin-Zugang; der aktualisierte
Konsolen-Knopf und die neue Anmeldeseite bleiben verfügbar. Unsichere lokale
Browser-Entwürfe werden im Symcon-Zugang nicht zwischen Konten gespeichert.
## Änderungen in 0.3.0
- Passwort-Anmeldung und vollständige Benutzerverwaltung mit Raum- und
Gerätefreigaben in der Symcon-Konfiguration (siehe oben).
- **Pflastersteine**, **Trittplatten** und **Natursteinweg** als weitere
Außenflächenarten: strukturierte Pflastersteine, einzelne Gartenplatten mit
grünen Zwischenräumen und unregelmäßige Natursteinplatten. Texturmaßstab und
Drehung sind wie bei den vorhandenen Arten pro Fläche einstellbar.
## Änderungen in 0.2.30
- Jede Außenfläche erhält **Texturmaßstab (%)** und **Texturdrehung (°)** direkt
unter der Auswahl der Flächenart. 100 % ist die bisherige Größe, 200 % macht
das Muster doppelt so groß und 50 % halb so groß. Der Bereich ist 5–2000 %;
Drehungen werden auf eine volle Umdrehung normalisiert (auch negative Eingaben
sind möglich).
- Die Einstellungen betreffen ausschließlich das Muster der ausgewählten Fläche,
gelten auch bei Gefälle und Transparenz und bleiben beim Speichern, Laden und
Duplizieren erhalten. Bestehende Flächen behalten 100 % / 0°.
- Eine Erklärung zu Maßstab und Drehung steht hinter dem Infosymbol.
## Änderungen in 0.2.29
- **Außenflächen einrasten:** Beim Zeichnen, Verschieben und Bearbeiten der Ecken
rasten Flächen an benachbarten Außenflächen und Hauskanten ein. Ganze Flächen
behalten dabei ihre Form. Mit **Alt** lässt sich das Einrasten unterdrücken.
- **Neue Untergründe:** Straße, Gehweg, Schotterfläche, Fluss und Bach.
Fluss und Bach schneiden sich standardmäßig aus einer umgebenden Fläche aus;
Höhenversatz, Gefälle, Transparenz und die Option für Ausschnitte bleiben einstellbar.
- **3D-Texturen:** Gras, Pflaster/Platten, Asphalt, Schotter, Erde, Wasser, Hecken
und Holz bekommen passende, lokal erzeugte Texturen. Sie folgen dem Metermaß
der Szene statt beim Vergrößern einer Fläche zu verzerren, funktionieren auch
auf geneigten und transparenten Flächen und benötigen keine externen Bilder.
## Änderungen in 0.2.28
- **Frischwasserstation und Kaskade:** Das 3D-Modell zeigt getrennte Primär-
und Trinkwasserkreise mit Plattenwärmetauscher. Vorlauf ist rot, Rücklauf
blau, Trinkwarmwasser orange, Kaltwasser grün und Zirkulation violett.
- Mit **+ Station hinzufügen** lassen sich bis zu 16 parallele Stationen
anlegen. Jede erhält eigene Vorlauf-/Rücklauf-, Kaltwasser-/Warmwasser-
und Leistungsvariablen sowie separate Pumpen- und Kaskadenventil-Bindungen.
Die Datenpunkte werden ohne Namensfilter aus dem Symcon-Objektbaum gewählt.
Neue Stationen beginnen ohne Datenpunkt-Verknüpfungen. Die Breite wird beim
Hinzufügen und Entfernen passend angepasst.
- Die Kaskade hat gemeinsame Sammelleitungen und eine gemeinsame optionale
Zirkulationspumpe. Eine kompakte schwebende Kachel zeigt die Stationen;
ein Klick auf eine Station öffnet ihre Einzelwerte und nativen Bedienelemente.
Die vorhandene zoomabhängige Kachelanzeige bleibt wirksam.
- Unter **Pufferspeicher im Plan** kann ein Puffer desselben Stockwerks
zugeordnet werden. Zwei Primärleitungen verbinden die gemeinsame Kaskade
mit dem oberen und unteren Pufferanschluss. Die Trinkwasserseite bleibt
getrennt. Die Darstellung folgt Position, Drehung, Montagehöhe und Stockwerk;
beim Entfernen des Puffers verschwinden seine Verbindungsleitungen.
- Der Puffer zeigt eine Temperaturschichtung anhand seiner verknüpften Fühler.
Die Farben zwischen den Messhöhen werden interpoliert. Ohne Messwerte bleibt
die Oberfläche neutral. Vorhandene Einzelstationen behalten ihre Verknüpfungen.
Das Anlegen einer Kaskade löst keine Gerätebefehle aus.
## Änderungen in 0.2.27
- Gerätekacheln werden abhängig von der tatsächlichen Zoomstufe ein- und
ausgeblendet. In der Fernansicht bleiben die Summen erhalten; Raumwerte,
Anlagen und einzelne Geräte erscheinen mit zunehmender Nähe.
- Geräte mit laufendem Verbrauch bzw. Einspeisung erscheinen früher als
0-W-Kacheln. Verknüpfte Nullwerte bleiben erhalten und werden in der
Nahansicht wieder sichtbar. Gebäudesummen und die obere Zählerleiste werden
durch diese Auswahl nicht verändert.
- Dichte Gerätegruppen bilden keine langen Kachelsäulen mehr. Details, für
die am Bildrand oder in einem engen Stapel kein Platz ist, bleiben zunächst
ausgeblendet. Heranzoomen und das Verschieben des Ausschnitts zeigen sie
wieder. Ein Übergangsbereich verhindert Flackern an den Zoomgrenzen.
- Die automatische Auswahl gilt auch für schmale Kacheln und Mobilgeräte.
Der vorhandene Schalter **Karten** steuert weiterhin alle schwebenden Karten.
## Änderungen in 0.2.26
- Heiz-/Kühlkreise in 3D folgen jetzt der Anordnung eines realen Mischerkreises:
Vorlauf und Rücklauf als getrennte Steigleitungen, beide Sammelleitungen unten,
das Ventil unter der Pumpe und die Temperaturfühler oberhalb der Pumpe.
Die Bauteile sitzen direkt auf den zugehörigen Leitungen.
- Ein **Mischer (Dreiwegeventil)** erhält eine Querverbindung vom Rücklauf.
Unter **Ventilbauart** kann stattdessen ein **Durchgangsventil (Zweiwege)**
ohne Beimischung gewählt werden. Vorschubpumpen bleiben ohne Ventil und ohne
künstliche Verbindung zwischen Vor- und Rücklauf.
- Die Pumpenfront zeigt gemeldeten Betrieb grün, Stillstand rot und fehlende
Rückmeldung grau. Der Rotor bewegt sich bei gemeldetem Betrieb, der
Ventilzeiger folgt der Stellung. Vorhandene Verknüpfungen, native Werte,
Bedienbereiche und die rein visuelle Ventilumkehrung bleiben erhalten.
- Falsch ausgerichtete Flächen liegender Zylinder sind korrigiert, damit
Pumpengehäuse, Fühler und andere runde Bauteile geschlossen dargestellt werden.
## Änderungen in 0.2.25
- Ladestationen, einschließlich der Wallboxen aus den Möbelpaketen, erhalten
einen eigenen Abschnitt **Ladedaten** mit Objektbaum-Auswahl für SoC,
Startzeit, Endzeit, Ladezeit, geladene Energie und Verriegelungsstatus.
- Der Verriegelungsstatus verwendet eine Integer-Variable und zeigt deren
native Symcon-Aliase unverändert an. Die Felder filtern nach Datentyp,
ohne Einschränkungen durch Variablennamen, Pfad oder vermuteten Gerätetyp.
- Die verknüpften Daten erscheinen in der optionalen 3D-Kachel und im
Raummenü, auch ohne Leistungs- oder Schaltvariable. Unverknüpfte Zeilen
bleiben ausgeblendet, Nullwerte sichtbar. Archivierte Werte bieten Trends.
- Start und Ende übernehmen native Zeitprofile; alternativ können Unix-Zeit
in Sekunden/Millisekunden oder unveränderte Werte gewählt werden. Ladezeiten
unterstützen Sekunden, Minuten, Stunden und native Textanzeigen. Automatisch
nutzt vorhandene Einheiten und interpretiert einheitenlose Zahlen als Sekunden.
Die verknüpften Variablen werden ausschließlich gelesen.
## Änderungen in 0.2.24
- Die rechte Stockwerksübersicht zeigt **Bereich → Raum → Gerät**, wenn ein
im Raum platziertes Gerät einen Leistungswert hat. Das gilt auch für Möbel
wie Wallboxen und für die Pumpen der Heiz-/Kühlkreisverteiler.
- Ohne eigenen Raumzähler dient der Raum nur als eingerückte Überschrift.
Der Leistungswert steht am Gerät; direkt verknüpfte Raumzähler bleiben am
Raum sichtbar. Gerätewerte werden nicht zusätzlich zu Bereichs-,
Stockwerks- oder Gebäudesummen addiert.
- Nullwerte, Live-Updates und Archivsymbole bleiben erhalten. Auch ohne
Bereichs- oder Stockwerkszähler lassen sich die Geräte in der Übersicht
anzeigen; fehlende übergeordnete Werte werden nicht erfunden.
## Änderungen in 0.2.23
- **Heiz-/Kühlkreisverteiler:** Neues 3D-Bauteil in der Möbelbibliothek mit bis zu
32 frei benennbaren Kreisen. Heizkreise, Kühlkreise und umschaltbare Kreise
unterstützen jeweils optionale Pumpen, Ventile, Vorlauf-/Rücklauffühler und
Pumpenleistung. Einspeise- bzw. Vorschubpumpen sind eigene Kreise ohne Ventil.
Eine gemeinsame Vorschubpumpe mit mehreren ventilbestückten Kreisen ist damit
ebenfalls möglich. Umschaltbare Kreise verwenden einen explizit verknüpften
Boolean-/Integer-Wert und den konfigurierten Wert für Kühlbetrieb.
- **Pufferspeicher:** Neues 3D-Bauteil mit sieben Fühlerplätzen von oben nach
unten sowie separatem Vorlauf und Rücklauf. Es können bis zu 64 Plätze angelegt,
benannt, entfernt und frei in ihrer Höhe positioniert werden. Die Anzeige
sortiert die verknüpften Fühler nach ihrer Höhe; unzugewiesene Plätze bleiben
in der Werteliste ausgeblendet.
- **Frischwasserstation:** Neues 3D-Bauteil mit Vorlauf, Rücklauf,
Zirkulationstemperatur und Trinkwarmwasser. Lade- und Zirkulationspumpe lassen
sich getrennt verknüpfen und bedienen.
- Alle Datenpunkte werden aus dem echten Objektbaum ausgewählt, nach ihrem
nativen Datentyp und ohne Namens-/Pfadfilter. Pumpen und Ventile haben getrennte
Befehls- und Rückmeldevariablen. Eine zugewiesene Rückmeldung bestimmt die
3D-Anzeige auch dann, wenn sie nicht verfügbar ist; nur ohne Rückmeldung wird
der Sollwert verwendet. Ventilumkehrung gilt ausschließlich für die Darstellung.
Zahlen und Befehle behalten ihren nativen Wert und Wertebereich.
- Pumpenrotoren zeigen gemeldeten Betrieb, Ventilzeiger die gemeldete Position
und Speicherfühler ihre Temperaturfarbe. Optionale schwebende Karten und ein
Bedienfenster zeigen die Werte, geloggte Datenpunkte bieten Archivtrends.
Die Spreizung wird als **Vorlauf minus Rücklauf** in Kelvin angezeigt.
Nur Befehlsvariablen mit Symcon-Schaltaktion sind bedienbar; Rückmeldungen und
historische Ansichten bleiben reine Anzeigen. Die Zusatzoberfläche lädt erst,
wenn tatsächlich ein Hydraulikbauteil im Plan vorhanden ist.
## Änderungen in 0.2.22
- **Bereiche statt mehrfacher Raumkopien:** Die rechte Übersicht eines Stockwerks
listet die verknüpften Symcon-Bereichskategorien mit ihren eigenen Namen und
Werten jeweils einmal auf. Mehrere Planräume mit demselben Bereich wiederholen
dessen Leistung und Verbrauch nicht mehr.
- **Eigene Raumzähler:** Im Raumeditor können unter diesem Punkt Leistung bzw.
Durchfluss und Energie bzw. Verbrauch für alle fünf Medien direkt aus dem
Objektbaum zugewiesen werden. Nur solche Räume erscheinen leicht eingerückt
unter ihrem Bereich, mit ausschließlich ihren eigenen zugewiesenen Werten.
Das Entfernen der letzten Zuweisung entfernt auch die Raumzeile. Raumzeilen
öffnen weiterhin das Raummenü; geloggte Werte bieten Archivtrends.
- Ein vorhandener Bereichszähler enthält die Raumwerte bereits. Sie werden
deshalb nicht zusätzlich auf die Bereichs- oder Stockwerkssumme addiert.
Fehlt eine passende Bereichsgröße, werden dafür die eigenen Raumzähler
summiert. Eigene Stockwerkszähler behalten Vorrang. Räume ohne Bereich stehen
mit eigenen Zählern unter „Nicht zugeordnet“.
## Änderungen in 0.2.21
- **Keine Namensfilter bei der manuellen Variablenauswahl:** Maßgeblich ist der
native Datentyp, unabhängig von Namen, Pfad, Profil oder einer geratenen
Geräteklasse. Boolean-Werte aus „Garage“ und „Treppenhaus“ lassen sich
gleichermaßen als Licht/Schalter verknüpfen. Boolean-Lichter erhalten keinen
Helligkeitsregler. Vorhandene Verknüpfungen behalten ihre Referenzen.
- **Begründung im Datenpunktfenster:** Beim Anklicken eines unpassenden Objekts
erscheint eine kurze Meldung, etwa „Boolean statt Integer oder Float“,
„Instanz statt Variable“, „Schaltuhr bereits verknüpft“ oder ein Hinweis auf
noch nicht geladene Variablen. Eine abgelehnte Auswahl verändert die
bestehende Verknüpfung nicht; „Übernehmen“ bleibt dann deaktiviert.
## Änderungen in 0.2.20
- **Leistungskacheln für Möbel:** Bei jedem Möbel mit Leistungszuordnung lässt
sich **Leistung als 3D-Kachel** einschalten, auch bei Wallboxen aus Möbelpaketen.
Der Leistungswert allein genügt; eine Schaltvariable ist nicht erforderlich.
Die kleine Kachel zeigt Namen und Leistung über dem Möbel, auch bei 0 W.
Fehlende Werte erscheinen als Strich und geloggte Variablen erhalten ein
Trendsymbol. Der Schalter **Karten** blendet die Kacheln gemeinsam ein oder aus.
- Native Integer- und Float-Variablen lassen sich unabhängig von einer erkannten
Geräteklasse im Objektbaum als Leistung verknüpfen. Die Markereinstellungen
erscheinen auch bei Paketleuchten, denen nur ein Leistungswert zugeordnet ist.
## Änderungen in 0.2.19
- Der Schalter **Rechte Übersicht** oben blendet die Stockwerks- beziehungsweise
Raumübersicht vollständig ein oder aus. Die Summen oben bleiben sichtbar; beim
Ausblenden wird der Platz für die Leiste wieder freigegeben. Die Auswahl wird
im Browser gespeichert und beim nächsten Öffnen wiederhergestellt.
## Änderungen in 0.2.18
- **Kompakteres Trend-Popup:** Kleine Zeitraum-, Zoom- und Aktualisierungsknöpfe
bilden eine schmale Leiste. Eigene Zeiten, Auflösung, Darstellung, Wertebereich
und CSV liegen hinter dem Zahnrad. Der Graph passt seine Höhe an das Fenster an
und erhält den größten Teil des Popups. Die Einstellungen überlagern ihn bei
Bedarf; sie verkleinern das Diagramm nicht.
- **Gebäude- und Stockwerksübersicht:** Bei „Alle Etagen“ stehen oben die
Leistungen und Verbräuche des Gesamtgebäudes, rechts eine dezente Kachel mit den
Stockwerken. Im geöffneten Stockwerk zeigt die Leiste dessen Summen und die
rechte Kachel die einzelnen Räume/Bereiche. Namen öffnen das jeweilige Stockwerk
oder den Raum. Die Kachel ist einklappbar und startet auf schmalen Ansichten
eingeklappt. Medien, Einheiten, Zeiträume, eigene Stockwerkszähler, Trends und
die Kennzeichnung unvollständiger Summen bleiben erhalten. Gemeinsam verknüpfte
Variablen werden im Gebäude nur einmal gezählt.
## Änderungen in 0.2.17
- Das Trendsymbol ist kleiner und ohne Rahmen. In Raumklimakacheln sitzt es in
einer eigenen Spalte. Messwerte bleiben rechtsbündig untereinander ausgerichtet,
auch wenn nur einzelne Variablen geloggt werden; die Zeilen werden nicht höher.
## Änderungen in 0.2.16
- **Archivtrends:** Bei geloggten Variablen erscheint neben Raumklima-, Geräte-,
Heizungs-, Wetter- und Zählerwerten ein kleines Diagrammsymbol. Es öffnet ein
Popup mit Zeitraumvorgaben, eigenen Von-/Bis-Zeiten, Auflösung (Rohdaten bis
Jahreswerte), Zoom und Zeitnavigation, Linien/Stufen/Balken/Tabelle, Min/Max,
frei einstellbarer Y-Achse, Live-Aktualisierung und CSV-Export. Diagramme werden
erst beim Öffnen geladen und funktionieren auch im Kachel-iframe.
- Es werden die originalen Archivdaten gelesen, einschließlich Boolean- und
String-Aufzeichnungen. Zähler zeigen bei Aggregation den Verbrauch des
Intervalls. Mehrere Quellen bleiben als einzelne Kurven erkennbar;
unterschiedliche Einheiten bekommen getrennte Diagramme. Begrenzte Abfragen,
leere Zeiträume und Archivfehler werden angezeigt. Das Logging wird nicht verändert.
Grundlage sind die offiziellen APIs
[AC_GetLoggedValues](https://www.symcon.de/de/service/dokumentation/modulreferenz/kern-instanzen/archive-control/ac-getloggedvalues/) und
[AC_GetAggregatedValues](https://www.symcon.de/de/service/dokumentation/modulreferenz/kern-instanzen/archive-control/ac-getaggregatedvalues/).
- Die Auswahl einer Bereichskategorie ändert den Raumnamen nicht mehr.
**Bereichsnamen übernehmen** kopiert auf Wunsch nur den Namen der letzten
Kategorie aus dem echten Objektbaum.
## Änderungen in 0.2.15
- Fehlen einzelne Zählerwerte, wird die Summe der verfügbaren Werte mit **Err:**
davor angezeigt, zum Beispiel **Err: 1,5 kW**. Das gilt für Raum- und
Stockwerksübersichten sowie deren Leistungsanzeigen. Sind alle Quellen
ausgefallen, steht dort **Err: –**. Sobald wieder alle Werte verfügbar sind,
verschwindet die Kennzeichnung automatisch.
## Änderungen in 0.2.14
- Verknüpfte Raum-Bereichskategorien werden einschließlich ausgeblendeter Objekte
nach Kategorien und Dummy-Modulen namens **Elektro/Strom, Wasser, Gas, Heizen
und Kühlen** durchsucht. Daraus werden **Leistung/Durchfluss** und
**Energie/Verbrauch** aus numerischen Variablen gelesen und im Raummenü angezeigt.
Passende Einheiten werden umgerechnet; verschiedene Einheiten und Tages-,
Monats-, Jahres- und Gesamtverbräuche bleiben getrennt. Ein übergeordneter
Zählerstand ersetzt seine Unterzähler; Variablenlinks zählen nicht doppelt.
- Der Knopf **Stockwerkszähler** in der 3D-Ansicht zeigt die Raumsummen je Medium.
Unter **Stockwerke → Stockwerkszähler** können für jedes Medium eigene
Leistungs-/Durchfluss- und Energie-/Verbrauchszähler aus dem Objektbaum gewählt
werden. Jeder eigene Zähler ersetzt nur die entsprechende Raumsumme. **×**
kehrt zur automatischen Summe zurück; bestehende Stockwerks-Leistungszähler
bleiben verknüpft. Unvollständige Teilsummen werden gekennzeichnet.
Die Stromleistung wird auch in Raum- und Stockwerksanzeigen genutzt.
## Änderungen in 0.2.13
- Im Raum liegt **Fußbodenheizung** unter **Raumklima**. Dort lassen sich auch
**Zuluft-VSR, Abluft-VSR, Zulufttemperatur, Ablufttemperatur, NHR (Nachheizregister)**
und ein **Raumstatus** verknüpfen. Die Auswahl richtet sich nach dem nativen
Variablentyp, unabhängig vom bisher vermuteten Gerätetyp.
- Das Raummenü zeigt die gewählten Werte mit den Symcon-Einheiten und formatierten
Anzeigen. Der Alias der Integer-Variable **Raumstatus** ersetzt den berechneten
Komfortwert. Beschreibbare Heizungs- und Lüftungsvariablen werden über ihre native
Aktion bedient; reine Messwerte bleiben Anzeigen.
- Eine oder mehrere klassische **Symcon-Schaltuhren (Wochenplan-Ereignisse)** lassen
sich aus dem Objektbaum zuordnen. Das Raummenü zeigt Wochentage, Schaltpunkte und
Aktionsnamen sowie den nächsten Schaltpunkt. Aktivieren und Deaktivieren erhält
den vollständigen Wochenplan; Aktionsskripte bleiben auf dem Symcon-Server.
- Unter **Wettervariablen** werden Wetterzustand, Außentemperatur, Luftfeuchte,
Luftdruck, Wind, Böen, Windrichtung, Bewölkung, Niederschlag, Helligkeit, UV,
Sichtweite, Schnee, Nebel und Gewitter einzeln verknüpft. Der **Regensensor**
akzeptiert Boolean- und numerische Variablen auch bei abweichendem Gerätetyp.
Die Quellen steuern die Wetterdarstellung und Regenwarnung. Oben in der 3D-Ansicht
öffnet **Wetter** die aktuellen verknüpften Werte mit ihren nativen Einheiten.
- **Anwesenheit** verwendet beliebige Boolean-Variablen mit eigenem Personennamen:
true = anwesend, false = abwesend. Ein Raum für den 3D-Marker ist optional;
der Anwesenheitsstatus wird auch ohne Raum in der oberen Leiste angezeigt.
- Durchsagen, Lautsprecherauswahl, Ruhezeiten, Durchsagetexte und Bluetooth-Ortung
sind aus der Symcon-Oberfläche entfernt.
## Änderungen in 0.2.12
- Der konfigurierte **Name der Visualisierung** erscheint oben links statt „NextFloor“,
außerdem im Browser-Titel und als Titel des Kachel-Iframes.
- Der WebHook wird bereits in `Create`, bei `KR_READY`, nach dem Kernelstart und bei
Modulaktualisierungen registriert. Eine laufende Nachregistrierung alle 30 Sekunden
stellt ihn auch nach einem späteren Zurücksetzen wieder her; bei Fehlern wird alle
5 Sekunden erneut versucht. URL, Zugangs-Token und Projektdaten bleiben erhalten.
- Der erklärende Text im Symcon-Konfigurationsformular wurde entfernt.
## Änderungen in 0.2.11
- Die schwebenden Raumklimakarten werden in **Alle Etagen** ausgeblendet. Beim Öffnen
einer Etage oder eines Raums erscheinen die dort aktivierten Karten wieder.
## Änderungen in 0.2.10
- **Raumnamen** schaltet oben in der 3D-Ansicht und in der Werkzeugleiste des Editors
die Namen in 3D ein oder aus. Beide Ansichten verwenden dieselbe, im Browser gespeicherte
Einstellung. Die Namen im 2D-Plan bleiben davon unberührt.
- Die HTML-SDK-Kachel hat den Schalter ebenfalls oben in ihrer 3D-Ansicht. Notizen,
Geräte und Messwertkarten bleiben beim Ausblenden der Raumnamen sichtbar.
## Änderungen in 0.2.9
- **Behang in 3D umkehren** und **Lamellen in 3D umkehren** ändern ausschließlich die
Darstellung. Empfangene Werte, Prozentanzeigen, Regler und gesendete Steuerbefehle
bleiben unverändert: **0 bleibt 0**, auch bei aktiviertem Schalter.
- Dasselbe gilt beim zweiten Behang und für die Umkehrung des Positionssensors.
Bereits gespeicherte Umkehrungen gelten nach diesem Update nur für die Darstellung;
die Datenpunkte müssen nicht neu verknüpft werden. Ein Infosymbol erklärt die Optionen.
## Änderungen in 0.2.8
- Lange Namen und Objektpfade in der Datenpunktauswahl werden mit Auslassungspunkten
gekürzt. Der vollständige Pfad bleibt per Mauszeiger sichtbar.
- Ein separater **×**-Knopf entfernt die Verknüpfung direkt, ohne den Objektbaum zu öffnen.
Beim Raumklima mit mehreren Sensoren bleiben die anderen verknüpften Werte erhalten.
## Änderungen in 0.2.7
- Im Raumklima ist **Helligkeit** als weiterer Datenpunkt wählbar. Die Raumkarte zeigt ihn
@@ -165,7 +642,7 @@ Nach dem Update den Designer neu laden, damit die neue Übertragung auf beiden S
### Update bei „Hook not found“
Das vollständige Modul auf 0.2.1 aktualisieren und die NextFloor-Instanzkonfiguration
neu öffnen. Einmal **„WebHook reparieren“**, anschließend **„Designer in der Konsole öffnen“**
neu öffnen. Einmal **„WebHook reparieren“**, anschließend **„Designer im Browser öffnen“**
anklicken. Der Eintrag gehört unter **WebHook Control → Hooks (Intern)**; ein eigener
PHP-Skript-Hook unter „Benutzerdefiniert“ ist nicht erforderlich. Die bestehende Instanz
nicht neu anlegen, da ihr Plan in ihren Attributen gespeichert ist.
@@ -194,7 +671,7 @@ nicht neu anlegen, da ihr Plan in ihren Attributen gespeichert ist.
## Einrichtung
1. Eine **NextFloor**-Instanz anlegen.
2. In ihrer Konfiguration auf **„Designer in der Konsole öffnen“** klicken und den Grundriss
2. In ihrer Konfiguration auf **„Designer im Browser öffnen“** klicken und den Grundriss
anlegen.
3. Für die Anzeige in der Tile-Visualisierung die Instanz wie jede andere Visualisierungs-
Instanz als Kachel hinzufügen.
+3 -3
View File
@@ -6,7 +6,7 @@
"compatibility": {
"version": "9.0"
},
"version": "0.2.7",
"build": 10,
"date": 1794297600
"version": "0.4.3",
"build": 41,
"date": 1795046400
}
+126
View File
@@ -0,0 +1,126 @@
<?php
declare(strict_types=1);
require __DIR__ . '/support/access-runtime.php';
$module = new AccessFixtureModule(); initializeAccessFixture($module);
$method = static fn(string $name, mixed ...$args): mixed => (new ReflectionMethod($module, $name))->invoke($module, ...$args);
$accounts = $method('accounts');
$as = static function (string $name) use ($module, $accounts): void {
foreach ($accounts as $id => $a) if ($a['name'] === $name) {
(new ReflectionProperty(NextFloor::class, 'requestUser'))->setValue($module, [...$a, 'id' => $id, 'session_id' => 'fixture-' . $name, 'csrf' => 'fixture']);
(new ReflectionProperty(NextFloor::class, 'requestScope'))->setValue($module, null); return;
}
throw new RuntimeException('Unknown fixture account');
};
$denied = static function (callable $call, string $reason): void {
try { $call(); throw new LogicException('Unexpected permission grant: ' . $reason); }
catch (NextFloorDenied $e) { check($e->getMessage() === $reason, 'Expected ' . $reason . ', got ' . $e->getMessage()); }
};
foreach ($accounts as $a) check($a['password'] !== $a['name'] . '-test-password' && password_verify($a['name'] . '-test-password', $a['password']), 'Passwords are hashed');
$form = $module->GetConfigurationForm();
check(!str_contains($form, 'password_hash') && !str_contains($form, '$2y$') && !str_contains($form, '$argon2'), 'Configuration never exposes password hashes');
check(str_contains($form, 'SelectObject') && str_contains($form, 'Büro 2'), 'Rights use actual plan and native object choices');
$as('empty');
check($method('visibleTree', $method('objectTree'))['variables'] === [], 'An empty user sees no values');
$building = $method('visibleBuilding');
check(count($building['floors'][0]['rooms']) === 2 && count($building['floors'][0]['furniture']) === 1, 'All building geometry remains');
check($building['floors'][0]['rooms'][0]['climate_card'] === false && $building['floors'][0]['rooms'][1]['area_id'] === null, 'No live room binding leaks');
$denied(fn() => $method('authorizeApi', 'building/save', ['building' => fixtureBuilding()]), 'admin_required');
$denied(fn() => $method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.204']), 'read_forbidden');
$as('reader');
$tree = $method('visibleTree', $method('objectTree'));
check(count($tree['variables']) === 9, 'Global readers see every variable and the schedule');
check(!in_array(888, array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'), true), 'All means the visualization, never unrelated Symcon variables');
check(!in_array(888, array_column($tree['objects'], 'object_id'), true), 'Users never receive unrelated native object branches');
foreach ($tree['variables'] as $v) check($v['attributes']['symcon_can_control'] === false, 'Every reader value is marked readonly');
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.101']]), 'control_forbidden');
$as('office');
$tree = $method('visibleTree', $method('objectTree'));
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
check($ids === [101, 102, 103, 104, 105], 'Room control exposes its own native category and schedule only; links do not pull in private targets');
$method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'cover.101']]); // alias uses the same native capability
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => ['light.101', 'light.201']]]), 'control_forbidden');
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'sensor.103']]), 'variable_readonly');
$method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.104']);
$denied(fn() => $method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.204']), 'read_forbidden');
$building = $method('visibleBuilding');
check($building['floors'][0]['rooms'][1]['climate']['temperature'] === 'none', 'Foreign room climate is removed');
check($building['floors'][0]['placements'][1]['entity_id'] === 'none', 'Foreign placement link is removed even while its geometry stays');
$topology = $method('objectTree');
foreach ($topology['objects'] as &$node) if ($node['object_id'] === 103) $node['parent_id'] = 11;
unset($node);
$topology['objects'][] = ['object_id' => 11, 'parent_id' => 10, 'name' => 'Strom', 'path' => 'Gebäude / Büro 2 / Strom', 'object_type' => 0];
$as('office');
$withTopology = $method('visibleTree', $topology);
check(in_array(11, array_column($withTopology['objects'], 'object_id'), true), 'Utility discovery retains an authorized meter category');
check(!in_array(900, array_column($withTopology['objects'], 'object_id'), true), 'Unrelated instance branches remain private');
$as('device');
$tree = $method('visibleTree', $method('objectTree'));
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
check($ids === [102, 103], 'Single-device grant does not grant its whole room or native area');
$building = $method('visibleBuilding');
check($building['floors'][0]['rooms'][0]['climate_card'] === false, 'Device grant does not reveal room climate');
check(in_array('switch.102', $building['floors'][0]['rooms'][0]['panel'], true), 'Approved device is still reachable in its room under its actual native entity');
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.101']]), 'control_forbidden');
// Shared variables and legacy bindings on a different item must not reappear outside the granted room.
$extended = fixtureBuilding();
$extended['floors'][0]['furniture'][] = ['id' => 'private', 'type' => 'wallbox', 'x' => 7, 'z' => 2, 'temp_entity2' => 'sensor.104', 'legacy_binding' => 'sensor.104', 'picture' => 'https://camera.invalid/live'];
$fixture['attributes']['Building'] = json_encode($extended);
$as('office'); $projected = $method('visibleBuilding')['floors'][0]['furniture'][1];
check($projected['temp_entity2'] === 'none' && $projected['legacy_binding'] === 'none' && !isset($projected['picture']), 'Unauthorized items never reuse otherwise approved values or live pictures');
$extended['floors'][0]['furniture'][0]['temp_entity2'] = 'sensor.104';
$fixture['attributes']['Building'] = json_encode($extended);
$as('device');
check($method('allowedEntity', 'sensor.104', false), 'Additional temperature bindings belong to an explicitly granted device');
$extended['floors'][0]['furniture'][0]['hydronic'] = ['status' => 'cover.104', 'circuits' => [['id' => 'c1', 'status' => 'cover.105']], 'stations' => [['id' => 's1', 'status' => 'cover.204']]];
$fixture['attributes']['Building'] = json_encode($extended);
$as('device');
foreach ([104, 105, 204] as $id) check($method('allowedEntity', 'sensor.' . $id, false), 'A granted device includes its plant, circuit and station status');
$as('empty');
$hiddenHydronic = $method('visibleBuilding')['floors'][0]['furniture'][0]['hydronic'];
check($hiddenHydronic['status'] === 'none' && $hiddenHydronic['circuits'][0]['status'] === 'none' && $hiddenHydronic['stations'][0]['status'] === 'none', 'Unauthorized hydronic statuses remain private');
$fixture['attributes']['Building'] = json_encode(fixtureBuilding());
$as('operator');
$method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.201']]);
$denied(fn() => $method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.888']), 'read_forbidden');
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'sensor.888']]), 'control_forbidden');
$as('native');
$tree = $method('visibleTree', $method('objectTree'));
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
check($ids === [201, 203], 'An explicit native instance grant follows its descendants, not its whole area');
$as('admin');
$method('authorizeApi', 'building/save', ['building' => fixtureBuilding()]);
check(count($method('visibleTree', $method('objectTree'))['objects']) > 0, 'Admin retains the native editor tree');
check($method('visibleBuilding') === fixtureBuilding(), 'Admin project is unmodified');
ob_start(); $method('sendApiResult', ['payload' => str_repeat('x', 300000)], true); $manifest = json_decode((string) ob_get_clean(), true)['_nextfloor_transfer'];
$as('reader');
try { $method('readTransfer', $manifest['id'], 0); throw new LogicException('Cross-session transport read was accepted'); }
catch (RuntimeException $e) { check($e->getMessage() === 'transfer_not_found', 'Transfer ownership is enforced'); }
$method('releaseTransfer', $manifest['id']);
$as('admin');
check(strlen($method('readTransfer', $manifest['id'], 0)['data']) > 0, 'Another session cannot remove this snapshot');
$method('releaseTransfer', $manifest['id']);
$url = $module->OpenDesigner(); parse_str((string) parse_url(substr($url, 5), PHP_URL_QUERY), $query);
check(isset($query['ticket']) && !isset($query['token']), 'Console links use tickets, never a reusable admin token');
check($method('exchangeConsoleTicket', $query['ticket']), 'Console recovers admin access without an account');
check(!$method('exchangeConsoleTicket', $query['ticket']), 'Console tickets cannot be replayed');
check(!str_contains($module->GetVisualizationTile(), 'ticket=') && !str_contains($module->GetVisualizationTile(), 'token='), 'Tiles never embed admin capabilities');
// A saved rights/enable change and a native delete revoke a previously valid cookie.
$accountID = array_key_first(array_filter($accounts, static fn(array $a): bool => $a['name'] === 'officeview'));
$browserToken = str_repeat('b', 64);
$fixture['attributes']['Sessions'] = json_encode([hash('sha256', $browserToken) => ['account' => $accountID, 'epoch' => $accounts[$accountID]['epoch'], 'csrf' => 'test', 'seen' => time(), 'expires' => time() + 3600]]);
$_COOKIE['NFSC_Session_12345'] = $browserToken;
check($method('resolveSession') !== null, 'Cookie starts valid');
$module->SaveAccessUser($accountID, 'officeview', 'user', false, false, false, '[]', '[]', '[]', '');
check($method('resolveSession') === null, 'Disabling or editing rights revokes the old cookie');
$module->DeleteAccessUser($accountID);
check(!isset($method('accounts')[$accountID]) && $method('resolveSession') === null, 'Deletion removes the account and its access');
echo "OK: hashed accounts, console recovery, one-use tickets, admin/reader/room/device scopes, alias-resistant access, private state and geometry separation, bulk preauthorization, archive guards and native readonly variables\n";
+75
View File
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
// Read-only native Archive Control fixtures exercise the actual module methods.
class IPSModuleStrict {}
$types = [30 => 2, 31 => 0, 32 => 3, 33 => 1, 34 => 2, 35 => 1];
$calls = []; $dense = false; $metadataQueries = 0;
function check(bool $ok, string $message): void { if (!$ok) throw new RuntimeException($message); }
function IPS_GetInstanceListByModuleID(string $id): array { check($id === '{43192F0B-135B-4CE7-A0A7-1475603F3060}', 'Discover native Archive Control'); return [100]; }
function AC_GetAggregationVariables(int $archive, bool $database): array {
global $metadataQueries; ++$metadataQueries;
return array_map(fn($id) => ['VariableID' => $id, 'AggregationActive' => $id !== 35, 'AggregationVisible' => false, 'AggregationType' => $id === 34 ? 1 : 0, 'FirstTime' => 100, 'LastTime' => 1900], [30, 31, 32, 34, 35]);
}
function IPS_GetChildrenIDs(int $id): array { global $types; return $id === 0 ? [10] : ($id === 10 ? array_keys($types) : []); }
function IPS_ObjectExists(int $id): bool { return $id === 10 || IPS_VariableExists($id); }
function IPS_VariableExists(int $id): bool { global $types; return isset($types[$id]); }
function IPS_GetObject(int $id): array { return ['ParentID' => $id === 10 ? 0 : 10, 'ObjectType' => $id === 10 ? 0 : 2, 'ObjectName' => $id === 10 ? 'Raum' : 'Wert ' . $id, 'ObjectPosition' => 0, 'ObjectIsHidden' => false, 'ObjectIcon' => '']; }
function IPS_GetName(int $id): string { return IPS_GetObject($id)['ObjectName']; }
function IPS_GetVariable(int $id): array { global $types; return ['VariableType' => $types[$id], 'VariableCustomProfile' => '', 'VariableProfile' => '', 'VariableAction' => 0, 'VariableCustomAction' => 0]; }
function IPS_GetVariablePresentation(int $id): array { return []; }
function IPS_VariableProfileExists(string $profile): bool { return false; }
function GetValue(int $id): mixed { return [31 => false, 32 => 'Bereit'][$id] ?? 10; }
function GetValueFormatted(int $id): string { return (string) GetValue($id); }
function AC_GetLoggedValues(int $archive, int $id, int $start, int $end, int $limit): array {
global $calls, $dense; $calls[] = ['raw', $id, $start, $end, $limit];
$value = $id === 32 ? '=1+2' : ($id === 31 ? false : 21.5);
if ($limit === 1) return [['TimeStamp' => 900, 'Value' => $value, 'Duration' => 500]];
if ($dense) return array_fill(0, 10000, ['TimeStamp' => 1500, 'Value' => $value, 'Duration' => 0]);
return [['TimeStamp' => 1900, 'Value' => $id === 32 ? 'Fertig' : 0, 'Duration' => 100], ['TimeStamp' => 1300, 'Value' => $value, 'Duration' => 600]];
}
function AC_GetAggregatedValues(int $archive, int $id, int $level, int $start, int $end, int $limit): array {
global $calls; $calls[] = ['aggregated', $id, $level, $start, $end, $limit];
return [['TimeStamp' => $start + 60, 'Avg' => 2.5, 'Min' => 1, 'Max' => 4, 'Duration' => 60], ['TimeStamp' => $start, 'Avg' => 1.5, 'Min' => 0, 'Max' => 3, 'Duration' => 60]];
}
require __DIR__ . '/../NextFloor/module.php';
$module = new NextFloor();
$tree = (new ReflectionMethod($module, 'objectTree'))->invoke($module);
$states = array_column($tree['variables'], null, 'entity_id');
check($metadataQueries === 1, 'Query logging metadata in bulk, not per variable');
foreach ([30, 31, 32, 34] as $id) {
$state = array_values(array_filter($tree['variables'], fn($v) => $v['attributes']['symcon_id'] === $id))[0];
check($state['attributes']['symcon_archive']['id'] === 100, 'Logged values get trend metadata even with graph visibility off');
}
foreach ([33, 35] as $id) {
$state = array_values(array_filter($tree['variables'], fn($v) => $v['attributes']['symcon_id'] === $id))[0];
check(!isset($state['attributes']['symcon_archive']), 'Unlogged and disabled variables have no trend icon metadata');
}
$method = new ReflectionMethod($module, 'archiveTrend');
$request = ['entity_id' => 'sensor.30', 'start' => 1000, 'end' => 2000, 'aggregation' => 'raw'];
$result = $method->invoke($module, $request);
check(array_column($result['points'], 't') === [1000, 1300, 1900], 'Return chronological data and carry the state at the left boundary');
check($result['points'][2]['v'] === 0.0, 'Zero is a real archived value');
$epoch = $method->invoke($module, [...$request, 'start' => 1, 'end' => 10]);
check($epoch['points'] === [], 'Do not use native EndTime=0 (until now) as a previous value at the Unix epoch');
$boolean = $method->invoke($module, [...$request, 'entity_id' => 'light.31']);
check($boolean['points'][0]['v'] === 0.0 && $boolean['points'][1]['v'] === 0 && $boolean['type'] === 0, 'Boolean archives and actuator domains retain native zero');
$string = $method->invoke($module, [...$request, 'entity_id' => 'sensor.32', 'aggregation' => 'day']);
check($string['aggregation'] === 'raw' && $string['points'][0]['v'] === '=1+2', 'Strings use raw event records');
$counter = $method->invoke($module, [...$request, 'entity_id' => 'sensor.34', 'aggregation' => 'day']);
check($counter['counter'] && $counter['points'][1]['v'] === 2.5 && $counter['points'][1]['min'] === 1.0, 'Use native counter deltas and native min/max, without differentiating a counter twice');
check(end($calls)[2] === 1, 'Daily aggregation uses the native level 1');
$dense = true;
$auto = $method->invoke($module, [...$request, 'aggregation' => 'auto']);
check($auto['aggregation'] === 'minute' && !$auto['truncated'], 'Dense automatic raw data falls back to native minute aggregates');
$raw = $method->invoke($module, $request);
check($raw['truncated'] && count($raw['points']) === 10000, 'Explicit raw queries report the hard limit and avoid inventing a left boundary');
$dense = false;
foreach ([['start' => 2000], ['start' => 1.5], ['entity_id' => []], ['entity_id' => 'sensor.33'], ['entity_id' => 'sensor.35'], ['aggregation' => 'invalid'], ['start' => 1, 'end' => 1700000000, 'aggregation' => 'minute']] as $bad) {
$rejected = false;
try { $method->invoke($module, [...$request, ...$bad]); }
catch (InvalidArgumentException | RuntimeException) { $rejected = true; }
check($rejected, 'Reject invalid parameters');
}
echo "OK: bulk logging discovery, hidden graphs, raw/Boolean/string archives, carried values, counter aggregation, dense fallback, truncation and invalid request guards\n";
+18
View File
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
if (!getenv('NEXTFLOOR_TEST_STATE')) { echo "Local authentication browser-test fixture; NEXTFLOOR_TEST_STATE required.\n"; exit; }
require __DIR__ . '/support/access-runtime.php';
$module = new AccessFixtureModule(); initializeAccessFixture($module);
$path = parse_url((string) $_SERVER['REQUEST_URI'], PHP_URL_PATH);
if ($path === '/__test/console') { header('Content-Type: application/json'); echo json_encode(['url' => substr($module->OpenDesigner(), 5)]); return; }
if ($path === '/__test/state') {
header('Content-Type: application/json');
echo json_encode(['writes' => $fixture['writes'], 'accounts' => array_map(static fn(array $a): array => ['name' => $a['name'], 'enabled' => $a['enabled']], json_decode($fixture['attributes']['Accounts'], true))]); return;
}
if ($path === '/__test/reset' && $_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode((string) file_get_contents('php://input'), true);
$accounts = json_decode($fixture['attributes']['Accounts'], true);
foreach ($accounts as $id => $a) if ($a['name'] === ($data['name'] ?? '')) { echo $module->ResetUserPassword($id, (string) ($data['password'] ?? '')); return; }
}
$module->hook();
+57
View File
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
// Native variables and classic weekly schedule events; no live Symcon system is modified.
class IPSModuleStrict {}
$objects = [
10 => ['ParentID' => 0, 'ObjectName' => 'Gebäude', 'ObjectType' => 0],
11 => ['ParentID' => 10, 'ObjectName' => 'Heizung Wochenplan', 'ObjectType' => 4],
12 => ['ParentID' => 10, 'ObjectName' => 'Zyklischer Timer', 'ObjectType' => 4],
13 => ['ParentID' => 10, 'ObjectName' => 'Verknüpfte Schaltuhr', 'ObjectType' => 6],
14 => ['ParentID' => 10, 'ObjectName' => 'Heizung', 'ObjectType' => 2],
15 => ['ParentID' => 10, 'ObjectName' => 'Raumstatus', 'ObjectType' => 2],
];
$events = [11 => ['EventType' => 2, 'EventActive' => true, 'NextRun' => 1794387600, 'NextActionID' => 2,
'ScheduleActions' => [['ID' => 1, 'Name' => 'Nacht', 'Color' => 255, 'ScriptText' => 'SECRET_SCRIPT', 'ActionParameters' => ['secret' => true]], ['ID' => 2, 'Name' => 'Tag', 'Color' => 16711680]],
'ScheduleGroups' => [['ID' => 0, 'Days' => 31, 'Points' => [['ID' => 0, 'Start' => ['Hour' => 6, 'Minute' => 30, 'Second' => 0], 'ActionID' => 2]]]]], 12 => ['EventType' => 1]];
$writes = [];
function check(bool $value, string $message): void { if (!$value) throw new RuntimeException($message); }
function IPS_GetChildrenIDs(int $id): array { global $objects; return array_keys(array_filter($objects, fn($o) => $o['ParentID'] === $id)); }
function IPS_ObjectExists(int $id): bool { global $objects; return isset($objects[$id]); }
function IPS_GetObject(int $id): array { global $objects; return [...$objects[$id], 'ObjectPosition' => 0, 'ObjectIsHidden' => false, 'ObjectIcon' => '']; }
function IPS_GetName(int $id): string { global $objects; return $objects[$id]['ObjectName']; }
function IPS_GetLink(int $id): array { return ['TargetID' => 11]; }
function IPS_GetEvent(int $id): array { global $events; return $events[$id]; }
function IPS_EventExists(int $id): bool { global $events; return isset($events[$id]); }
function IPS_SetEventActive(int $id, bool $active): bool { global $events; $events[$id]['EventActive'] = $active; return true; }
function IPS_VariableExists(int $id): bool { return in_array($id, [14, 15]); }
function IPS_GetVariable(int $id): array { return ['VariableType' => $id === 14 ? 0 : 1, 'VariableProfile' => '', 'VariableCustomProfile' => '', 'VariableAction' => $id === 14 ? 123 : 0, 'VariableCustomAction' => 0]; }
function GetValue(int $id): mixed { return $id === 14 ? false : 2; }
function GetValueFormatted(int $id): string { return $id === 14 ? 'Aus' : 'Besprechung'; }
function IPS_GetVariablePresentation(int $id): array { return []; }
function IPS_VariableProfileExists(string $profile): bool { return false; }
function RequestAction(int $id, mixed $value): void { global $writes; $writes[] = [$id, $value]; }
function SetValue(int $id, mixed $value): void { throw new LogicException('Native controls must never silently write read-only variables'); }
require __DIR__ . '/../NextFloor/module.php';
$module = new NextFloor();
$tree = (new ReflectionMethod($module, 'objectTree'))->invoke($module);
$states = array_column($tree['variables'], null, 'entity_id');
$nodes = array_column($tree['objects'], null, 'object_id');
check($nodes[11]['entity_id'] === 'schedule.11' && $nodes[13]['entity_id'] === 'schedule.11', 'Schedule events and their links are selectable in the original object tree');
check(!isset($nodes[12]['entity_id']), 'Ordinary timers must not be offered as weekly schedules');
check($states['schedule.11']['attributes']['groups'][0]['days'] === 31 && $states['schedule.11']['attributes']['groups'][0]['points'][0]['minute'] === 30, 'Native day masks and switch times must survive export');
check(!str_contains(json_encode($tree), 'SECRET_SCRIPT') && !str_contains(json_encode($tree), 'ActionParameters'), 'Action scripts and parameters must not be exported');
check($states[$nodes[14]['entity_id']]['attributes']['symcon_value'] === false, 'Native Boolean false is preserved');
check($states[$nodes[15]['entity_id']]['attributes']['symcon_formatted'] === 'Besprechung', 'Integer status retains its Symcon alias');
$action = new ReflectionMethod($module, 'variableAction');
$before = $events[11]['ScheduleGroups'];
$action->invoke($module, 'schedule', 'set_active', ['entity_id' => 'schedule.11', 'active' => false]);
check($events[11]['EventActive'] === false && $events[11]['ScheduleGroups'] === $before, 'Disabling a linked clock must retain every switch point');
$action->invoke($module, 'symcon', 'set_value', ['entity_id' => 'switch.14', 'value' => true]);
check($writes === [[14, true]], 'Writable native Boolean uses RequestAction');
foreach ([['schedule', 'set_active', ['entity_id' => 'schedule.12', 'active' => true]], ['symcon', 'set_value', ['entity_id' => 'sensor.15', 'value' => 3]], ['symcon', 'set_value', ['entity_id' => 'switch.14', 'value' => 'false']]] as $call) {
try { $action->invoke($module, ...$call); throw new LogicException('Invalid native action accepted'); }
catch (InvalidArgumentException) {}
}
echo "OK: selectable native schedules, protected action data, aliases, raw Boolean controls and read-only guards\n";
+2 -1
View File
@@ -25,7 +25,7 @@ $objects = [
function IPS_GetChildrenIDs(int $id): array { global $objects; return array_keys(array_filter($objects, static fn(array $object): bool => $object['ParentID'] === $id)); }
function IPS_ObjectExists(int $id): bool { global $objects; return isset($objects[$id]); }
function IPS_GetObject(int $id): array { global $objects; return [...$objects[$id], 'ObjectIsHidden' => in_array($id, [10, 12], true), 'ObjectIcon' => 'Temperature']; }
function IPS_GetInstance(int $id): array { return ['ModuleInfo' => ['ModuleType' => [18 => 1, 20 => 0, 21 => 2, 22 => 4, 23 => 5, 24 => 6][$id] ?? 3]]; }
function IPS_GetInstance(int $id): array { return ['ModuleInfo' => ['ModuleType' => [18 => 1, 20 => 0, 21 => 2, 22 => 4, 23 => 5, 24 => 6][$id] ?? 3, 'ModuleID' => $id === 11 ? '{485D0419-BE97-4548-AA9C-C083EB82E61E}' : '{OTHER}']]; }
function IPS_GetName(int $id): string { global $objects; return $objects[$id]['ObjectName']; }
function IPS_GetLink(int $id): array { return ['TargetID' => 12]; }
function IPS_GetVariable(int $id): array { return ['VariableType' => 2, 'VariableProfile' => '', 'VariableCustomProfile' => '', 'VariableCustomAction' => 0, 'VariableAction' => 0]; }
@@ -48,4 +48,5 @@ check(!isset($nodes[16]['entity_id']), 'Scripts are visible but are not variable
check($nodes[10]['hidden'] === true && $nodes[11]['parent_id'] === 10, 'Hidden categories and all their children must be exported');
check(array_column(array_intersect_key($nodes, array_flip([18, 20, 21, 22, 23, 24])), 'module_type') === [1, 0, 2, 4, 5, 6], 'Export real module types for logical system grouping');
check($nodes[11]['module_type'] === 3 && $nodes[19]['parent_id'] === 18, 'Keep devices and system-variable parents unchanged in native export');
check($nodes[11]['module_id'] === '{485D0419-BE97-4548-AA9C-C083EB82E61E}', 'Export the real module ID so dummy utility containers can be recognized');
echo "OK: full native object hierarchy, positions, hidden nodes and variable links\n";
+40
View File
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
require __DIR__ . '/support/access-runtime.php';
$module = new AccessFixtureModule(); initializeAccessFixture($module);
$method = static fn(string $name, mixed ...$args): mixed => (new ReflectionMethod($module, $name))->invoke($module, ...$args);
$as = static function (string $name) use ($module, $method): void {
foreach ($method('accounts') as $id => $a) if ($a['name'] === $name) {
(new ReflectionProperty(NextFloor::class, 'requestUser'))->setValue($module, [...$a, 'id' => $id, 'session_id' => 'fixture-' . $name, 'csrf' => 'fixture']);
(new ReflectionProperty(NextFloor::class, 'requestScope'))->setValue($module, null); return;
}
};
$before = $method('building'); $after = $before;
$source = &$after['floors'][0];
$target = [...$source, 'id' => 'og', 'name' => 'Obergeschoss', 'elevation' => 3, 'rooms' => [], 'furniture' => [], 'placements' => []];
$target['rooms'][] = array_shift($source['rooms']);
$target['furniture'][] = array_shift($source['furniture']);
$target['placements'][] = array_shift($source['placements']);
unset($source); $after['floors'][] = $target;
$as('admin'); $method('saveBuilding', $after);
$accounts = array_column($method('accounts'), null, 'name');
check($accounts['office']['rooms'] === [['target' => 'room:og:office2', 'access' => 'control']], 'Room control rights follow the moved room');
check($accounts['officeview']['rooms'] === [['target' => 'room:og:office2', 'access' => 'view']], 'Readonly room rights stay readonly');
check($accounts['device']['devices'] === [['target' => 'furniture:og:wallbox', 'access' => 'control']], 'Explicit device rights follow its unique identity');
check($accounts['empty']['rooms'] === [] && $accounts['empty']['devices'] === [], 'Moving cannot create a new grant');
$as('office'); $tree = $method('visibleTree', $method('objectTree'));
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
check($ids === [101, 102, 103, 104, 105], 'The moved room still exposes exactly its original native variables');
$as('device'); $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.102']]);
$as('admin'); $method('saveBuilding', $before);
$accounts = array_column($method('accounts'), null, 'name');
check($accounts['office']['rooms'][0]['target'] === 'room:eg:office2', 'Undo restores the original grant key');
check($accounts['device']['devices'][0]['target'] === 'furniture:eg:wallbox', 'Undo also restores the explicit device key');
// An ambiguous ID may be a duplicate rather than a move; never guess and widen its grant.
$ambiguous = $after; $ambiguous['floors'][0]['furniture'][] = $target['furniture'][0];
$method('saveBuilding', $ambiguous);
$accounts = array_column($method('accounts'), null, 'name');
check($accounts['device']['devices'][0]['target'] === 'furniture:eg:wallbox', 'Duplicate identities never trigger automatic grant migration');
echo "OK: room/device grants follow unique floor moves and undo, preserve view/control levels and native visibility, reject ambiguous identities and create no grants\n";
+105
View File
@@ -0,0 +1,105 @@
<?php
declare(strict_types=1);
// Deliberately small local Symcon fixture. No connection to a user's actual kernel or variables.
const KR_READY = 10103;
const IPS_KERNELSTARTED = 10001;
const KL_ERROR = 10205;
$fixtureFile = getenv('NEXTFLOOR_TEST_STATE') ?: '';
$fixture = $fixtureFile !== '' && is_file($fixtureFile) ? json_decode((string) file_get_contents($fixtureFile), true) : [];
$fixture += ['attributes' => [], 'properties' => [], 'writes' => [], 'initialized' => false];
function persistFixture(): void { global $fixture, $fixtureFile; if ($fixtureFile !== '') file_put_contents($fixtureFile, json_encode($fixture, JSON_THROW_ON_ERROR), LOCK_EX); }
function check(bool $condition, string $message): void { if (!$condition) throw new RuntimeException($message); }
class IPSModuleStrict
{
protected int $InstanceID;
public array $fields = [];
public function __construct(int $id = 12345) { $this->InstanceID = $id; }
public function Create(): void {}
public function ApplyChanges(): void {}
public function MessageSink(int $t, int $s, int $m, array $d): void {}
protected function RegisterPropertyString(string $name, string $value): void { global $fixture; $fixture['properties'][$name] ??= $value; persistFixture(); }
protected function RegisterAttributeString(string $name, string $value): void { global $fixture; $fixture['attributes'][$name] ??= $value; persistFixture(); }
protected function RegisterAttributeInteger(string $name, int $value): void { global $fixture; $fixture['attributes'][$name] ??= $value; persistFixture(); }
protected function ReadAttributeString(string $name): string { global $fixture; return (string) ($fixture['attributes'][$name] ?? ''); }
protected function ReadAttributeInteger(string $name): int { global $fixture; return (int) ($fixture['attributes'][$name] ?? 0); }
protected function WriteAttributeString(string $name, string $value): void { global $fixture; $fixture['attributes'][$name] = $value; persistFixture(); }
protected function WriteAttributeInteger(string $name, int $value): void { global $fixture; $fixture['attributes'][$name] = $value; persistFixture(); }
protected function ReadPropertyString(string $name): string { global $fixture; return (string) ($fixture['properties'][$name] ?? ''); }
protected function RegisterMessage(int $sender, int $message): void {}
protected function RegisterTimer(string $name, int $interval, string $script): void {}
protected function SetTimerInterval(string $name, int $interval): void {}
protected function SetVisualizationType(int $type): void {}
protected function SetStatus(int $status): void {}
protected function LogMessage(string $message, int $type): void { throw new RuntimeException('Unexpected module log: ' . $message); }
protected function RegisterHook(string $path): bool { return true; }
protected function UpdateFormField(string $name, string $key, mixed $value): void { $this->fields[$name][$key] = $value; }
protected function UpdateVisualizationValue(string $value): void {}
}
function IPS_GetKernelRunlevel(): int { return KR_READY; }
function IPS_GetInstanceListByModuleID(string $module): array { return $module === '{43192F0B-135B-4CE7-A0A7-1475603F3060}' ? [700] : []; }
function fixtureObjects(): array
{
return [1 => [0, 0, 'Gebäude'], 10 => [1, 0, 'Büro 2'], 20 => [1, 0, 'Büro 3'], 900 => [20, 1, 'Privates Gerät'],
101 => [10, 2, 'Licht'], 102 => [10, 2, 'Wallbox schalten'], 103 => [10, 2, 'Wallbox Leistung'], 104 => [10, 2, 'Raumtemperatur'],
105 => [10, 4, 'Schaltuhr'], 201 => [900, 2, 'Licht privat'], 203 => [900, 2, 'Leistung privat'], 204 => [20, 2, 'Temperatur privat'],
999 => [1, 2, 'Gesamtleistung'], 888 => [1, 2, 'Nicht mit NextFloor verknüpftes Geheimnis'], 109 => [10, 6, 'Link auf privaten Datenpunkt']];
}
function IPS_ObjectExists(int $id): bool { return isset(fixtureObjects()[$id]); }
function IPS_VariableExists(int $id): bool { return (fixtureObjects()[$id][1] ?? -1) === 2; }
function IPS_EventExists(int $id): bool { return $id === 105; }
function IPS_GetName(int $id): string { return fixtureObjects()[$id][2]; }
function IPS_GetObject(int $id): array { $o = fixtureObjects()[$id]; return ['ParentID' => $o[0], 'ObjectType' => $o[1], 'ObjectPosition' => $id, 'ObjectIsHidden' => false, 'ObjectIcon' => '']; }
function IPS_GetChildrenIDs(int $id): array { return array_keys(array_filter(fixtureObjects(), static fn(array $o): bool => $o[0] === $id)); }
function IPS_GetLink(int $id): array { return ['TargetID' => 201]; }
function IPS_GetInstance(int $id): array { return ['ModuleInfo' => ['ModuleType' => 3, 'ModuleID' => '{00000000-0000-0000-0000-000000000001}']]; }
function IPS_GetVariable(int $id): array { return ['VariableType' => in_array($id, [101, 102, 201], true) ? 0 : 2, 'VariableCustomAction' => 0, 'VariableAction' => in_array($id, [101, 102, 201], true) ? 1 : 0, 'VariableCustomProfile' => '', 'VariableProfile' => '']; }
function IPS_GetVariablePresentation(int $id): array { return ['SUFFIX' => in_array($id, [104, 204], true) ? '°C' : (in_array($id, [103, 203, 999], true) ? 'W' : ''), 'MIN' => 0, 'MAX' => 100]; }
function IPS_VariableProfileExists(string $name): bool { return false; }
function GetValue(int $id): mixed { global $fixture; return $fixture['values'][$id] ?? match ($id) { 101, 102 => true, 201 => false, 104 => 22.3, 204 => 26.7, 103 => 7400.0, 203 => 531.0, default => 7931.0 }; }
function GetValueFormatted(int $id): string { $v = GetValue($id); return is_bool($v) ? ($v ? 'An' : 'Aus') : (string) $v; }
function RequestAction(int $id, mixed $value): void { global $fixture; $fixture['writes'][] = [$id, $value]; $fixture['values'][$id] = $value; persistFixture(); }
function SetValue(int $id, mixed $value): void { RequestAction($id, $value); }
function IPS_GetEvent(int $id): array { global $fixture; return ['EventType' => 2, 'EventActive' => $fixture['values'][105] ?? true, 'ScheduleActions' => [], 'ScheduleGroups' => []]; }
function IPS_SetEventActive(int $id, bool $active): bool { RequestAction($id, $active); return true; }
function AC_GetAggregationVariables(int $id, bool $all): array { return array_map(static fn(int $v): array => ['VariableID' => $v, 'AggregationActive' => true, 'AggregationType' => 0], [104, 204]); }
function AC_GetLoggedValues(int $a, int $id, int $start, int $end, int $limit): array { return $start === 0 ? [] : [['TimeStamp' => $start, 'Value' => GetValue($id), 'Duration' => 60], ['TimeStamp' => $end, 'Value' => GetValue($id), 'Duration' => 0]]; }
function AC_GetAggregatedValues(int $a, int $id, int $level, int $start, int $end, int $limit): array { return []; }
require_once __DIR__ . '/../../NextFloor/module.php';
class AccessFixtureModule extends NextFloor { public function hook(): void { $this->ProcessHookData(); } }
function fixtureBuilding(): array
{
$room = static fn(string $id, string $name, int $x, int $category, string $temperature): array => ['id' => $id, 'name' => $name, 'area_id' => 'symcon-category-' . $category, 'points' => [[$x, 0], [$x + 4, 0], [$x + 4, 3], [$x, 3]], 'floor_material' => 'wood', 'climate_card' => true, 'climate' => ['temperature' => $temperature]];
return ['version' => 1, 'settings' => ['grid' => 0.1, 'north' => 0, 'wall_exterior' => 0.24, 'wall_interior' => 0.12, 'roof' => ['type' => 'none'], 'plugins' => []],
'energy' => ['consumption' => 'sensor.999'], 'presence' => [], 'floors' => [['id' => 'eg', 'name' => 'Erdgeschoss', 'elevation' => 0, 'height' => 2.7, 'cut_height' => 1.2,
'rooms' => [$room('office2', 'Büro 2', 0, 10, 'sensor.104'), $room('office3', 'Büro 3', 5, 20, 'sensor.204')],
'openings' => [], 'walls' => [], 'outdoor' => [], 'background' => null,
'placements' => [['entity_id' => 'light.101', 'x' => 2, 'z' => 1, 'y' => null], ['entity_id' => 'light.201', 'x' => 7, 'z' => 1, 'y' => null]],
'furniture' => [['id' => 'wallbox', 'type' => 'wallbox', 'name' => 'Wallbox Büro 2', 'x' => 3, 'z' => 2, 'w' => 0.3, 'd' => 0.3, 'h' => 0.4, 'rotation' => 0, 'entity' => 'light.102', 'power' => 'sensor.103', 'power_card' => true]]]]];
}
function initializeAccessFixture(AccessFixtureModule $module): void
{
global $fixture;
$module->Create();
if ($fixture['initialized']) return;
$fixture['properties']['Title'] = 'Bürogebäude';
$fixture['attributes']['Building'] = json_encode(fixtureBuilding(), JSON_THROW_ON_ERROR);
$fixture['attributes']['BuildingRevision'] = 1;
$make = static function (string $name, string $role, bool $viewAll, bool $controlAll, array $rooms = [], array $devices = [], array $objects = []) use ($module): void {
$result = $module->SaveAccessUser('', $name, $role, true, $viewAll, $controlAll, json_encode($rooms), json_encode($devices), json_encode($objects), $name . '-test-password');
check(str_starts_with($result, 'Benutzer gespeichert'), $result);
};
$make('admin', 'admin', true, true);
$make('reader', 'user', true, false);
$make('office', 'user', false, false, [['target' => 'room:eg:office2', 'access' => 'control']]);
$make('officeview', 'user', false, false, [['target' => 'room:eg:office2', 'access' => 'view']]);
$make('device', 'user', false, false, [], [['target' => 'furniture:eg:wallbox', 'access' => 'control']]);
$make('empty', 'user', false, false);
$make('operator', 'user', true, true);
$make('native', 'user', false, false, [], [], [['target' => 900, 'access' => 'view']]);
$fixture['initialized'] = true; persistFixture();
}
+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
require __DIR__ . '/support/access-runtime.php';
$module = new AccessFixtureModule(); initializeAccessFixture($module);
$method = static fn(string $name, mixed ...$args): mixed => (new ReflectionMethod($module, $name))->invoke($module, ...$args);
$accounts = $method('accounts');
$as = static function (string $name) use ($module, $accounts): void {
foreach ($accounts as $id => $a) if ($a['name'] === $name) {
(new ReflectionProperty(NextFloor::class, 'requestUser'))->setValue($module, [...$a, 'id' => $id, 'session_id' => 'fixture-' . $name, 'csrf' => 'fixture']);
(new ReflectionProperty(NextFloor::class, 'requestScope'))->setValue($module, null); return;
}
};
$b = fixtureBuilding();
$b['topology'] = ['locations' => [['id' => 'urbach', 'name' => 'Urbach'], ['id' => 'ulm', 'name' => 'Ulm']],
'branches' => [['id' => 'hq', 'name' => 'Zentrale', 'location_id' => 'urbach'], ['id' => 'south', 'name' => 'Süd', 'location_id' => 'ulm']],
'buildings' => [['id' => 'ras19', 'name' => 'RAS19', 'branch_id' => 'hq'], ['id' => 'ulm1', 'name' => 'RAS19', 'branch_id' => 'south']]];
$b['floors'][0]['building_id'] = 'ras19';
$outside = ['id' => 'garden', 'name' => 'Außen', 'building_id' => null, 'outdoor_location_id' => 'urbach', 'elevation' => 0, 'height' => 2.5,
'rooms' => [], 'openings' => [], 'placements' => [], 'outdoor' => [], 'furniture' => [['id' => 'garden-meter', 'type' => 'wallbox', 'name' => 'Gartengerät', 'entity' => 'sensor.203', 'x' => 1, 'z' => 2]]];
$b['floors'][] = $outside;
$b['floors'][] = [...$outside, 'id' => 'branch-garden', 'outdoor_location_id' => null, 'outdoor_branch_id' => 'hq', 'furniture' => [[...$outside['furniture'][0], 'id' => 'branch-meter', 'name' => 'Hofgerät']]];
$b['floors'][] = [...$outside, 'id' => 'building-garden', 'outdoor_location_id' => null, 'outdoor_building_id' => 'ras19', 'furniture' => [[...$outside['furniture'][0], 'id' => 'building-meter', 'name' => 'Terrassengerät']]];
$as('admin'); $method('authorizeApi', 'building/save', ['building' => $b]); $method('saveBuilding', $b);
check($method('building')['topology'] === $b['topology'], 'The complete hierarchy persists without changing native links');
$form = $module->GetConfigurationForm();
check(str_contains($form, 'Urbach / Zentrale / RAS19 / Erdgeschoss / Büro 2'), 'Room choices include their complete topology path');
check(str_contains($form, 'Urbach / Außen / Gartengerät'), 'Outdoor device grants belong to the location path');
check(str_contains($form, 'Urbach / Zentrale / Außen / Hofgerät'), 'Branch outdoor device grants use their own full path');
check(str_contains($form, 'Urbach / Zentrale / RAS19 / Außen / Terrassengerät'), 'Building outdoor device grants use their own full path');
$as('office');
$tree = $method('visibleTree', $method('objectTree'));
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
check($ids === [101, 102, 103, 104, 105], 'Existing room rights keep their stable key and do not grant outdoor/other-location values');
$visible = $method('visibleBuilding');
check($visible['topology'] === $b['topology'], 'Users retain the complete logical topology, like the building geometry');
check($visible['floors'][1]['furniture'][0]['entity'] === 'none', 'Unapproved outdoor status is still filtered server-side');
$as('empty');
check($method('visibleTree', $method('objectTree'))['variables'] === [], 'Adding topology cannot grant access to an empty account');
echo "OK: persisted five-level topology with location/branch/building outdoors; complete grant choice paths; unchanged room keys; scoped state and native permissions\n";
+82
View File
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
require __DIR__ . '/support/access-runtime.php';
$module = new AccessFixtureModule(); initializeAccessFixture($module);
$method = static fn(string $name, mixed ...$args): mixed => (new ReflectionMethod($module, $name))->invoke($module, ...$args);
// Like a native List variable, this object is iterable/array-accessible but does not JSON-encode its rows.
final class NativeFormList implements IteratorAggregate, ArrayAccess
{
public function __construct(private array $rows) {}
public function getIterator(): Traversable { foreach ($this->rows as $row) yield new ArrayObject($row); }
public function offsetExists(mixed $offset): bool { return isset($this->rows[$offset]); }
public function offsetGet(mixed $offset): mixed { return $this->rows[$offset] ?? null; }
public function offsetSet(mixed $offset, mixed $value): void { throw new LogicException('Readonly fixture'); }
public function offsetUnset(mixed $offset): void { throw new LogicException('Readonly fixture'); }
}
function NFSC_SaveAccessUser(int $id, string $user, string $name, string $role, bool $enabled, bool $view, bool $control, string $rooms, string $devices, string $objects, string $password): string
{
global $module;
return $module->SaveAccessUser($user, $name, $role, $enabled, $view, $control, $rooms, $devices, $objects, $password);
}
function NFSC_SelectAccessUser(int $id, string $user): void { global $module; $module->SelectAccessUser($user); }
function formItems(): array
{
global $module;
$form = json_decode($module->GetConfigurationForm(), true, 512, JSON_THROW_ON_ERROR);
return array_values(array_filter($form['actions'], static fn(array $a): bool => ($a['type'] ?? '') === 'ExpansionPanel'))[0]['items'];
}
function clickSave(string $script, array $fields): string
{
extract($fields);
$id = 12345;
ob_start();
try { eval($script); return (string) ob_get_contents(); }
finally { ob_end_clean(); }
}
$items = formItems();
$names = array_column($items, 'name');
check(array_search('AccountPassword', $names, true) === array_search('AccountName', $names, true) + 1, 'Password belongs directly below the user name');
$save = array_values(array_filter($items, static fn(array $item): bool => ($item['caption'] ?? '') === 'Benutzer speichern'))[0]['onClick'];
$script = is_array($save) ? implode("\n", $save) : $save;
$fields = ['AccountSelect' => '', 'AccountName' => 'form-empty', 'AccountRole' => 'user', 'AccountEnabled' => true,
'AccountViewAll' => true, 'AccountControlAll' => false, 'AccountPassword' => 'form-test-password',
'AccountRooms' => new NativeFormList([]), 'AccountDevices' => new NativeFormList([]), 'AccountObjects' => new NativeFormList([])];
check(json_encode($fields['AccountRooms']) === '{}', 'Fixture reproduces the unsupported direct List serialization');
check(str_starts_with(clickSave($script, $fields), 'Benutzer gespeichert.'), 'The actual save button accepts empty native form lists');
$emptyID = $module->fields['AccountSelect']['value'];
$empty = $method('accounts')[$emptyID];
check($empty['rooms'] === [] && $empty['devices'] === [] && $empty['objects'] === [], 'Empty tables remain empty');
$rooms = [['target' => 'room:eg:office2', 'access' => 'view'], ['target' => 'room:old:removed', 'access' => 'control']];
$devices = [['target' => 'furniture:eg:wallbox', 'access' => 'control']];
$objects = [['target' => 900, 'access' => 'view'], ['target' => 104, 'access' => 'view']];
$fields = [...$fields, 'AccountName' => 'form-scoped', 'AccountViewAll' => false,
'AccountRooms' => new NativeFormList($rooms), 'AccountDevices' => new NativeFormList($devices), 'AccountObjects' => new NativeFormList($objects)];
check(str_starts_with(clickSave($script, $fields), 'Benutzer gespeichert.'), 'The actual save button serializes every row, including rows that are not selected');
$scopedID = $module->fields['AccountSelect']['value'];
$scoped = $method('accounts')[$scopedID];
check($scoped['rooms'] === $rooms && $scoped['devices'] === $devices && $scoped['objects'] === $objects, 'All three grant tables retain exact per-user rights');
$change = array_values(array_filter($items, static fn(array $item): bool => ($item['name'] ?? '') === 'AccountSelect'))[0]['onChange'];
$select = static function (string $selected) use ($change): void { $id = 12345; $AccountSelect = $selected; eval($change); };
$select($emptyID);
foreach (['AccountRooms', 'AccountDevices', 'AccountObjects'] as $name) check(json_decode($module->fields[$name]['values'], true) === [], 'Switching to an unrestricted reader clears the previous grants');
check($module->fields['AccountName']['value'] === 'form-empty' && $module->fields['AccountPassword']['value'] === '', 'User changes load the right name and clear the password field');
check(!in_array('room:old:removed', array_column(json_decode($module->fields['AccountRooms']['columns'], true)[0]['edit']['options'], 'value'), true), 'Stale target choices do not leak into another user');
$select($scopedID);
foreach (['AccountRooms' => $rooms, 'AccountDevices' => $devices, 'AccountObjects' => $objects] as $name => $expected) check(json_decode($module->fields[$name]['values'], true) === $expected, 'Each table restores the selected user');
check(in_array('room:old:removed', array_column(json_decode($module->fields['AccountRooms']['columns'], true)[0]['edit']['options'], 'value'), true), 'Previously linked missing plan targets remain visible when switching users');
$fields = [...$fields, 'AccountSelect' => $scopedID, 'AccountPassword' => ''];
check(str_starts_with(clickSave($script, $fields), 'Benutzer gespeichert.'), 'Saving an existing user permits an empty password');
check(password_verify('form-test-password', $method('accounts')[$scopedID]['password']), 'Empty password preserves the previous hash');
check(str_starts_with(clickSave($script, [...$fields, 'AccountSelect' => '', 'AccountName' => 'no-password']), 'Für neue Benutzer'), 'New accounts still require a password');
$select('');
foreach (['AccountRooms', 'AccountDevices', 'AccountObjects'] as $name) check(json_decode($module->fields[$name]['values'], true) === [], 'New user selection resets every grant table');
check(!$module->fields['AccountReset']['enabled'] && !$module->fields['AccountDelete']['enabled'], 'New user selection disables existing-account operations');
check($module->SaveAccessUser($emptyID, 'form-empty', 'user', true, true, false, '{"target":"room:eg:office2","access":"control"}', '[]', '[]', '') === 'Ungültige Freigabeliste.', 'A selected row cannot be mistaken for the complete grants list');
$form = json_decode($module->GetConfigurationForm(), true);
check($form['actions'][1]['caption'] === 'Designer im Browser öffnen' && $form['actions'][1]['link'] === true, 'The browser link does not promise a native Pro Console tab');
echo "OK: real form save with opaque iterable Lists; empty/multiple grants; user-switch reload/reset and missing-target choices; password position and preservation; honest browser action\n";
+4 -1
View File
@@ -56,10 +56,13 @@ export function validateSymconPackage(root = fileURLToPath(new URL("../", import
ids.add(module.id);
assert.equal(entry.name, module.name.replaceAll(" ", ""), "Module directory must match its PHP class name");
const php = readFileSync(join(directory, "module.php"), "utf8");
for (const helper of ["Access.php", "Users.php", "Permissions.php"]) {
assert.ok(readFileSync(join(directory, "libs", helper)).length > 0, `Missing server access helper: ${helper}`);
}
assert.match(php, new RegExp(`class\\s+${entry.name}\\s+extends\\s+IPSModuleStrict\\b`), "Module PHP class is missing or mismatched");
const form = readJson(join(directory, "form.json"));
assert.ok(Array.isArray(form.elements) && Array.isArray(form.actions), "Module form must contain elements and actions");
for (const asset of ["nextfloor-designer.js", "nextfloor-3d.js", "nextfloor-editor.js", "nextfloor-card-editor.js"]) {
for (const asset of ["nextfloor-designer.js", "nextfloor-3d.js", "nextfloor-editor.js", "nextfloor-card-editor.js", "nextfloor-trend.js", "nextfloor-hydronics.js"]) {
assert.ok(readFileSync(join(directory, "assets", asset)).length > 0, `Missing build asset: ${asset}`);
}
modules.push(module);
+47 -7
View File
@@ -25,6 +25,7 @@ class IPSModuleStrict
public int $status = 101;
public ?bool $registrationResult = true;
public bool $registrationThrows = false;
public array $registrationRunlevels = [];
public function __construct(int $id) { $this->InstanceID = $id; }
public function Create(): void {}
@@ -53,7 +54,7 @@ class IPSModuleStrict
protected function RegisterHook(string $path): ?bool
{
global $nativeHooks;
check(IPS_GetKernelRunlevel() === KR_READY, 'Do not depend on WebHook Control before the kernel is ready');
$this->registrationRunlevels[] = IPS_GetKernelRunlevel();
if ($this->registrationThrows) throw new RuntimeException('WebHook Control unavailable');
if ($this->registrationResult !== false) $nativeHooks['/hook/' . $path] = $this->InstanceID;
return $this->registrationResult;
@@ -62,26 +63,48 @@ class IPSModuleStrict
require __DIR__ . '/../NextFloor/module.php';
$module = new NextFloor(12345);
$hook = '/hook/nextfloor/12345';
$module->Create();
check($nativeHooks === [] && $module->status === 104, 'Startup must wait instead of reporting a nonexistent hook as ready');
check(($nativeHooks[$hook] ?? null) === 12345 && $module->status === 104, 'Create registers the native hook early without reporting the initializing kernel as ready');
check($module->registrationRunlevels === [KR_INIT], 'Create must register hooks during initialization, as required by the native lifecycle');
check(in_array([0, IPS_KERNELSTARTED], $module->messages, true), 'Module must listen for the completed kernel startup');
check(in_array([0, KR_READY], $module->messages, true), 'Module also restores its route as soon as the kernel becomes ready');
check($module->timers['WebHookRetry']['interval'] === 5000, 'Startup recovery must be scheduled');
$kernelRunlevel = KR_READY;
$nativeHooks = [];
$module->MessageSink(1, 0, KR_READY, []);
check(isset($nativeHooks[$hook]), 'KR_READY restores routes cleared after Create');
$nativeHooks = [];
$module->MessageSink(1, 0, IPS_KERNELSTARTED, []);
$hook = '/hook/nextfloor/12345';
check(($nativeHooks[$hook] ?? null) === 12345 && $module->status === 102, 'Kernel startup must restore the instance hook');
check($module->timers['WebHookRetry']['interval'] === 0, 'Successful registration stops the retry timer');
check($module->timers['WebHookRetry']['interval'] === 30000, 'Successful registration keeps maintenance active for delayed resets');
$token = $module->attributes['AccessToken'];
$module->attributes['Building'] = '{"preserved_project":true}';
$module->properties['Title'] = ' Haus & Büro <West> ';
$nativeHooks = [];
$link = $module->OpenDesigner();
check(isset($nativeHooks[$hook]) && str_starts_with($link, 'link:' . $hook . '/designer?'), 'Opening the designer repairs a lost route before returning its URL');
$nativeHooks = [];
check(str_contains($module->GetVisualizationTile(), '<iframe') && isset($nativeHooks[$hook]), 'Opening a tile also repairs its route');
check(str_contains($module->GetVisualizationTile(), 'title="Haus &amp; Büro &lt;West&gt;"'), 'Tile iframe uses the escaped configured view name');
$module->ApplyChanges();
check(isset($nativeHooks[$hook]), 'ApplyChanges restores hooks after module reload');
for ($reload = 0; $reload < 3; $reload++) {
unset($nativeHooks[$hook]); // WebHook Control resets after our successful ApplyChanges.
$module->RetryWebHook();
check(isset($nativeHooks[$hook]) && $module->status === 102, 'Maintenance restores delayed hook loss without opening a designer or tile');
check($module->timers['WebHookRetry']['interval'] === 30000, 'Maintenance must survive every successful recovery');
}
$kernelRunlevel = KR_INIT;
$nativeHooks = [];
$module->Create();
$module->ApplyChanges();
check($module->status === 104, 'Restart initialization must not report ready');
$kernelRunlevel = KR_READY;
$module->MessageSink(2, 0, IPS_KERNELSTARTED, []);
check(isset($nativeHooks[$hook]) && $module->attributes['AccessToken'] === $token, 'A full restart restores the same route and retains the original access token');
$module->registrationResult = false;
$module->ApplyChanges();
@@ -110,15 +133,30 @@ check($module->attributes['AccessToken'] === $token && $module->attributes['Buil
$other = new NextFloor(54321);
$other->Create();
check(isset($nativeHooks[$hook]) && isset($nativeHooks['/hook/nextfloor/54321']), 'Instances must keep independent routes');
$kernelRunlevel = KR_INIT;
$earlyFailure = new NextFloor(34567);
$earlyFailure->registrationThrows = true;
$earlyFailure->Create();
check($earlyFailure->status === 104 && $earlyFailure->timers['WebHookRetry']['interval'] === 5000 && $earlyFailure->logs === [], 'An early startup registration failure waits and retries without an error log');
$kernelRunlevel = KR_READY;
$earlyFailure->registrationThrows = false;
$earlyFailure->RetryWebHook();
check(isset($nativeHooks['/hook/nextfloor/34567']) && $earlyFailure->status === 102, 'Unavailable early WebHook Control must recover automatically');
// Verify that returned URLs reach the real dispatcher, including Symcon's SCRIPT_NAME fallback.
parse_str((string) parse_url(substr($link, 5), PHP_URL_QUERY), $_GET);
$_GET = [];
$browserToken = str_repeat('a', 64);
$_COOKIE = ['NFSC_Session_12345' => $browserToken];
$module->attributes['Sessions'] = json_encode([hash('sha256', $browserToken) => ['account' => '__console__', 'epoch' => $token, 'csrf' => 'fixture', 'expires' => time() + 3600, 'seen' => time()]]);
$_SERVER['REQUEST_URI'] = $hook . '/designer';
$process = new ReflectionMethod($module, 'ProcessHookData');
ob_start();
$process->invoke($module);
$html = ob_get_clean();
check(str_contains($html, 'window.__NEXTFLOOR_SYMCON__=') && str_contains($html, 'assets/nextfloor-designer.js'), 'Designer route must serve its host page');
check(str_contains($html, '<title>Haus &amp; Büro &lt;West&gt;</title>'), 'Browser title uses the escaped configured view name');
preg_match('/window\.__NEXTFLOOR_SYMCON__=(.*?);<\/script>/s', $html, $hostConfig);
check(json_decode($hostConfig[1], true)['title'] === 'Haus & Büro <West>', 'Frontend receives the configured title as plain text');
$version = json_decode((string) file_get_contents(__DIR__ . '/../library.json'), true)['version'];
check(str_contains($html, 'nextfloor-designer.js?v=' . $version), 'A module update must invalidate the cached designer entry bundle');
unset($_SERVER['REQUEST_URI']);
@@ -128,9 +166,11 @@ $process->invoke($module);
$fallback = ob_get_clean();
check(str_contains($fallback, 'window.__NEXTFLOOR_SYMCON__='), 'Dispatcher must accept SCRIPT_NAME when REQUEST_URI is absent');
$_GET['token'] = 'wrong-token';
$_COOKIE = [];
$_SERVER['SCRIPT_NAME'] = $hook . '/api';
ob_start();
$process->invoke($module);
$unauthorized = ob_get_clean();
check(http_response_code() === 403 && str_contains($unauthorized, 'forbidden'), 'Recovery must not bypass hook authentication');
check(http_response_code() === 401 && str_contains($unauthorized, 'authentication_required'), 'Recovery and legacy URL tokens must not bypass session authentication');
echo "OK: kernel startup, reload, designer/tile recovery, failed registration, retry, repair, data preservation, routing and authentication\n";
echo "OK: early registration, startup/update and delayed reset recovery, ongoing maintenance, titles, data preservation, routing and authentication\n";