diff --git a/.gitignore b/.gitignore index f9ea024..352f21e 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ yarn-009.lock package-009.json package-000.json package-lock-001.json +REF/test.ts diff --git a/clean b/clean new file mode 100755 index 0000000..217314f --- /dev/null +++ b/clean @@ -0,0 +1,3 @@ +#!/bin/bash +(set -x; rm -rf package-lock.json yarn.lock dist node_modules) +(set -x; mkdir dist node_modules) diff --git a/dist/rpi-monitor-card.js b/dist/rpi-monitor-card.js index 74cd4b2..d04b182 100644 --- a/dist/rpi-monitor-card.js +++ b/dist/rpi-monitor-card.js @@ -28,13 +28,13 @@ function t(t,e,i,o){var s,n=arguments.length,r=n<3?e:null===o?o=Object.getOwnPro * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ -var g;f.finalized=!0,f.elementProperties=new Map,f.elementStyles=[],f.shadowRootOptions={mode:"open"},null==u||u({ReactiveElement:f}),(null!==(l=c.reactiveElementVersions)&&void 0!==l?l:c.reactiveElementVersions=[]).push("1.6.1");const v=window,y=v.trustedTypes,b=y?y.createPolicy("lit-html",{createHTML:t=>t}):void 0,$=`lit$${(Math.random()+"").slice(9)}$`,w="?"+$,C=`<${w}>`,A=document,S=(t="")=>A.createComment(t),I=t=>null===t||"object"!=typeof t&&"function"!=typeof t,x=Array.isArray,E=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,k=/-->/g,T=/>/g,U=RegExp(">|[ \t\n\f\r](?:([^\\s\"'>=/]+)([ \t\n\f\r]*=[ \t\n\f\r]*(?:[^ \t\n\f\r\"'`<>=]|(\"|')|))|$)","g"),D=/'/g,F=/"/g,P=/^(?:script|style|textarea|title)$/i,M=(t=>(e,...i)=>({_$litType$:t,strings:e,values:i}))(1),N=Symbol.for("lit-noChange"),O=Symbol.for("lit-nothing"),R=new WeakMap,V=A.createTreeWalker(A,129,null,!1);class H{constructor({strings:t,_$litType$:e},i){let o;this.parts=[];let s=0,n=0;const r=t.length-1,a=this.parts,[l,c]=((t,e)=>{const i=t.length-1,o=[];let s,n=2===e?"":"",r=E;for(let e=0;e"===l[0]?(r=null!=s?s:E,c=-1):void 0===l[1]?c=-2:(c=r.lastIndex-l[2].length,a=l[1],r=void 0===l[3]?U:'"'===l[3]?F:D):r===F||r===D?r=U:r===k||r===T?r=E:(r=U,s=void 0);const d=r===U&&t[e+1].startsWith("/>")?" ":"";n+=r===E?i+C:c>=0?(o.push(a),i.slice(0,c)+"$lit$"+i.slice(c)+$+d):i+$+(-2===c?(o.push(void 0),e):d)}const a=n+(t[i]||"")+(2===e?"":"");if(!Array.isArray(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return[void 0!==b?b.createHTML(a):a,o]})(t,e);if(this.el=H.createElement(l,i),V.currentNode=this.el.content,2===e){const t=this.el.content,e=t.firstChild;e.remove(),t.append(...e.childNodes)}for(;null!==(o=V.nextNode())&&a.length0){o.textContent=y?y.emptyScript:"";for(let i=0;ix(t)||"function"==typeof(null==t?void 0:t[Symbol.iterator]))(t)?this.k(t):this.g(t)}O(t,e=this._$AB){return this._$AA.parentNode.insertBefore(t,e)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}g(t){this._$AH!==O&&I(this._$AH)?this._$AA.nextSibling.data=t:this.T(A.createTextNode(t)),this._$AH=t}$(t){var e;const{values:i,_$litType$:o}=t,s="number"==typeof o?this._$AC(t):(void 0===o.el&&(o.el=H.createElement(o.h,this.options)),o);if((null===(e=this._$AH)||void 0===e?void 0:e._$AD)===s)this._$AH.p(i);else{const t=new j(s,this),e=t.v(this.options);t.p(i),this.T(e),this._$AH=t}}_$AC(t){let e=R.get(t.strings);return void 0===e&&R.set(t.strings,e=new H(t)),e}k(t){x(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let i,o=0;for(const s of t)o===e.length?e.push(i=new z(this.O(S()),this.O(S()),this,this.options)):i=e[o],i._$AI(s),o++;o2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=O}get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}_$AI(t,e=this,i,o){const s=this.strings;let n=!1;if(void 0===s)t=L(this,t,e,0),n=!I(t)||t!==this._$AH&&t!==N,n&&(this._$AH=t);else{const o=t;let r,a;for(t=s[0],r=0;rt}):void 0,$=`lit$${(Math.random()+"").slice(9)}$`,w="?"+$,C=`<${w}>`,A=document,S=(t="")=>A.createComment(t),x=t=>null===t||"object"!=typeof t&&"function"!=typeof t,I=Array.isArray,E=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,T=/-->/g,k=/>/g,D=RegExp(">|[ \t\n\f\r](?:([^\\s\"'>=/]+)([ \t\n\f\r]*=[ \t\n\f\r]*(?:[^ \t\n\f\r\"'`<>=]|(\"|')|))|$)","g"),U=/'/g,R=/"/g,M=/^(?:script|style|textarea|title)$/i,P=(t=>(e,...i)=>({_$litType$:t,strings:e,values:i}))(1),F=Symbol.for("lit-noChange"),O=Symbol.for("lit-nothing"),N=new WeakMap,V=A.createTreeWalker(A,129,null,!1);class H{constructor({strings:t,_$litType$:e},i){let o;this.parts=[];let s=0,n=0;const r=t.length-1,a=this.parts,[l,c]=((t,e)=>{const i=t.length-1,o=[];let s,n=2===e?"":"",r=E;for(let e=0;e"===l[0]?(r=null!=s?s:E,c=-1):void 0===l[1]?c=-2:(c=r.lastIndex-l[2].length,a=l[1],r=void 0===l[3]?D:'"'===l[3]?R:U):r===R||r===U?r=D:r===T||r===k?r=E:(r=D,s=void 0);const d=r===D&&t[e+1].startsWith("/>")?" ":"";n+=r===E?i+C:c>=0?(o.push(a),i.slice(0,c)+"$lit$"+i.slice(c)+$+d):i+$+(-2===c?(o.push(void 0),e):d)}const a=n+(t[i]||"")+(2===e?"":"");if(!Array.isArray(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return[void 0!==b?b.createHTML(a):a,o]})(t,e);if(this.el=H.createElement(l,i),V.currentNode=this.el.content,2===e){const t=this.el.content,e=t.firstChild;e.remove(),t.append(...e.childNodes)}for(;null!==(o=V.nextNode())&&a.length0){o.textContent=y?y.emptyScript:"";for(let i=0;iI(t)||"function"==typeof(null==t?void 0:t[Symbol.iterator]))(t)?this.k(t):this.g(t)}O(t,e=this._$AB){return this._$AA.parentNode.insertBefore(t,e)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}g(t){this._$AH!==O&&x(this._$AH)?this._$AA.nextSibling.data=t:this.T(A.createTextNode(t)),this._$AH=t}$(t){var e;const{values:i,_$litType$:o}=t,s="number"==typeof o?this._$AC(t):(void 0===o.el&&(o.el=H.createElement(o.h,this.options)),o);if((null===(e=this._$AH)||void 0===e?void 0:e._$AD)===s)this._$AH.p(i);else{const t=new z(s,this),e=t.v(this.options);t.p(i),this.T(e),this._$AH=t}}_$AC(t){let e=N.get(t.strings);return void 0===e&&N.set(t.strings,e=new H(t)),e}k(t){I(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let i,o=0;for(const s of t)o===e.length?e.push(i=new j(this.O(S()),this.O(S()),this,this.options)):i=e[o],i._$AI(s),o++;o2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=O}get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}_$AI(t,e=this,i,o){const s=this.strings;let n=!1;if(void 0===s)t=L(this,t,e,0),n=!x(t)||t!==this._$AH&&t!==F,n&&(this._$AH=t);else{const o=t;let r,a;for(t=s[0],r=0;r{var o,s;const n=null!==(o=null==i?void 0:i.renderBefore)&&void 0!==o?o:e;let r=n._$litPart$;if(void 0===r){const t=null!==(s=null==i?void 0:i.renderBefore)&&void 0!==s?s:null;n._$litPart$=r=new z(e.insertBefore(S(),t),t,void 0,null!=i?i:{})}return r._$AI(t),r})(e,this.renderRoot,this.renderOptions)}connectedCallback(){var t;super.connectedCallback(),null===(t=this._$Do)||void 0===t||t.setConnected(!0)}disconnectedCallback(){var t;super.disconnectedCallback(),null===(t=this._$Do)||void 0===t||t.setConnected(!1)}render(){return N}}Q.finalized=!0,Q._$litElement$=!0,null===(J=globalThis.litElementHydrateSupport)||void 0===J||J.call(globalThis,{LitElement:Q});const tt=globalThis.litElementPolyfillSupport;null==tt||tt({LitElement:Q}),(null!==(X=globalThis.litElementVersions)&&void 0!==X?X:globalThis.litElementVersions=[]).push("3.2.2"); +var Z,J;class X extends f{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var t,e;const i=super.createRenderRoot();return null!==(t=(e=this.renderOptions).renderBefore)&&void 0!==t||(e.renderBefore=i.firstChild),i}update(t){const e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=((t,e,i)=>{var o,s;const n=null!==(o=null==i?void 0:i.renderBefore)&&void 0!==o?o:e;let r=n._$litPart$;if(void 0===r){const t=null!==(s=null==i?void 0:i.renderBefore)&&void 0!==s?s:null;n._$litPart$=r=new j(e.insertBefore(S(),t),t,void 0,null!=i?i:{})}return r._$AI(t),r})(e,this.renderRoot,this.renderOptions)}connectedCallback(){var t;super.connectedCallback(),null===(t=this._$Do)||void 0===t||t.setConnected(!0)}disconnectedCallback(){var t;super.disconnectedCallback(),null===(t=this._$Do)||void 0===t||t.setConnected(!1)}render(){return F}}X.finalized=!0,X._$litElement$=!0,null===(Z=globalThis.litElementHydrateSupport)||void 0===Z||Z.call(globalThis,{LitElement:X});const tt=globalThis.litElementPolyfillSupport;null==tt||tt({LitElement:X}),(null!==(J=globalThis.litElementVersions)&&void 0!==J?J:globalThis.litElementVersions=[]).push("3.2.2"); /** * @license * Copyright 2017 Google LLC @@ -55,16 +55,16 @@ const et=t=>e=>"function"==typeof e?((t,e)=>(customElements.define(t,e),e))(t,e) * @license * Copyright 2021 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */var nt;null===(nt=window.HTMLSlotElement)||void 0===nt||nt.prototype.assignedElements;var rt,at,lt=function(t,e){return ct(e).format(t)},ct=function(t){return new Intl.DateTimeFormat(t.language,{year:"numeric",month:"long",day:"numeric"})};!function(t){t.language="language",t.system="system",t.comma_decimal="comma_decimal",t.decimal_comma="decimal_comma",t.space_comma="space_comma",t.none="none"}(rt||(rt={})),function(t){t.language="language",t.system="system",t.am_pm="12",t.twenty_four="24"}(at||(at={}));var ht=function(t){if(t.time_format===at.language||t.time_format===at.system){var e=t.time_format===at.language?t.language:void 0,i=(new Date).toLocaleString(e);return i.includes("AM")||i.includes("PM")}return t.time_format===at.am_pm},dt=function(t,e){return ut(e).format(t)},ut=function(t){return new Intl.DateTimeFormat(t.language,{year:"numeric",month:"long",day:"numeric",hour:ht(t)?"numeric":"2-digit",minute:"2-digit",hour12:ht(t)})},pt=function(t,e){return mt(e).format(t)},mt=function(t){return new Intl.DateTimeFormat(t.language,{hour:"numeric",minute:"2-digit",hour12:ht(t)})};function _t(){return(_t=Object.assign||function(t){for(var e=1;e-1?t.split(".")[1].length:0;i.minimumFractionDigits=o,i.maximumFractionDigits=o}return i},yt=function(t,e,i,o){var s=void 0!==o?o:e.state;if("unknown"===s||"unavailable"===s)return t("state.default."+s);if(function(t){return!!t.attributes.unit_of_measurement||!!t.attributes.state_class}(e)){if("monetary"===e.attributes.device_class)try{return gt(s,i,{style:"currency",currency:e.attributes.unit_of_measurement})}catch(t){}return gt(s,i)+(e.attributes.unit_of_measurement?" "+e.attributes.unit_of_measurement:"")}var n=function(t){return ft(t.entity_id)}(e);if("input_datetime"===n){var r;if(void 0===o)return e.attributes.has_date&&e.attributes.has_time?(r=new Date(e.attributes.year,e.attributes.month-1,e.attributes.day,e.attributes.hour,e.attributes.minute),dt(r,i)):e.attributes.has_date?(r=new Date(e.attributes.year,e.attributes.month-1,e.attributes.day),lt(r,i)):e.attributes.has_time?((r=new Date).setHours(e.attributes.hour,e.attributes.minute),pt(r,i)):e.state;try{var a=o.split(" ");if(2===a.length)return dt(new Date(a.join("T")),i);if(1===a.length){if(o.includes("-"))return lt(new Date(o+"T00:00"),i);if(o.includes(":")){var l=new Date;return pt(new Date(l.toISOString().split("T")[0]+"T"+o),i)}}return o}catch(t){return o}}return"humidifier"===n&&"on"===s&&e.attributes.humidity?e.attributes.humidity+" %":"counter"===n||"number"===n||"input_number"===n?gt(s,i):e.attributes.device_class&&t("component."+n+".state."+e.attributes.device_class+"."+s)||t("component."+n+".state._."+s)||s},bt=["closed","locked","off"],$t=function(t,e,i,o){o=o||{},i=null==i?{}:i;var s=new Event(e,{bubbles:void 0===o.bubbles||o.bubbles,cancelable:Boolean(o.cancelable),composed:void 0===o.composed||o.composed});return s.detail=i,t.dispatchEvent(s),s},wt=function(t){$t(window,"haptic",t)},Ct=function(t,e){return function(t,e,i){void 0===i&&(i=!0);var o,s=ft(e),n="group"===s?"homeassistant":s;switch(s){case"lock":o=i?"unlock":"lock";break;case"cover":o=i?"open_cover":"close_cover";break;default:o=i?"turn_on":"turn_off"}return t.callService(n,o,{entity_id:e})}(t,e,bt.includes(t.states[e].state))},At=function(t,e,i,o){if(o||(o={action:"more-info"}),!o.confirmation||o.confirmation.exemptions&&o.confirmation.exemptions.some((function(t){return t.user===e.user.id}))||(wt("warning"),confirm(o.confirmation.text||"Are you sure you want to "+o.action+"?")))switch(o.action){case"more-info":(i.entity||i.camera_image)&&$t(t,"hass-more-info",{entityId:i.entity?i.entity:i.camera_image});break;case"navigate":o.navigation_path&&function(t,e,i){void 0===i&&(i=!1),i?history.replaceState(null,"",e):history.pushState(null,"",e),$t(window,"location-changed",{replace:i})}(0,o.navigation_path);break;case"url":o.url_path&&window.open(o.url_path);break;case"toggle":i.entity&&(Ct(e,i.entity),wt("success"));break;case"call-service":if(!o.service)return void wt("failure");var s=o.service.split(".",2);e.callService(s[0],s[1],o.service_data,o.target),wt("success");break;case"fire-dom-event":$t(t,"ll-custom",o)}};function St(t){return void 0!==t&&"none"!==t.action}const It={required:{icon:"tune",name:"Required",secondary:"Required options for this card to function",show:!0},actions:{icon:"gesture-tap-hold",name:"Actions",secondary:"Perform actions based on tapping/clicking",show:!1,options:{tap:{icon:"gesture-tap",name:"Tap",secondary:"Set the action to perform on tap",show:!1},hold:{icon:"gesture-tap-hold",name:"Hold",secondary:"Set the action to perform on hold",show:!1},double_tap:{icon:"gesture-double-tap",name:"Double Tap",secondary:"Set the action to perform on double tap",show:!1}}},appearance:{icon:"palette",name:"Appearance",secondary:"Customize the name, icon, etc",show:!1}};let xt=class extends Q{constructor(){super(...arguments),this._initialized=!1}setConfig(t){this._config=t,this.loadCardHelpers()}shouldUpdate(){return this._initialized||this._initialize(),!0}get _name(){var t;return(null===(t=this._config)||void 0===t?void 0:t.name)||""}get _entity(){var t;return(null===(t=this._config)||void 0===t?void 0:t.entity)||""}get _show_warning(){var t;return(null===(t=this._config)||void 0===t?void 0:t.show_warning)||!1}get _show_error(){var t;return(null===(t=this._config)||void 0===t?void 0:t.show_error)||!1}get _tap_action(){var t;return(null===(t=this._config)||void 0===t?void 0:t.tap_action)||{action:"more-info"}}get _hold_action(){var t;return(null===(t=this._config)||void 0===t?void 0:t.hold_action)||{action:"none"}}get _double_tap_action(){var t;return(null===(t=this._config)||void 0===t?void 0:t.double_tap_action)||{action:"none"}}render(){if(!this.hass||!this._helpers)return M``;this._helpers.importMoreInfoControl("climate");const t=Object.keys(this.hass.states).filter((t=>"sun"===t.substr(0,t.indexOf("."))));return M` + */var nt;null===(nt=window.HTMLSlotElement)||void 0===nt||nt.prototype.assignedElements;var rt,at,lt=function(t,e){return ct(e).format(t)},ct=function(t){return new Intl.DateTimeFormat(t.language,{year:"numeric",month:"long",day:"numeric"})};!function(t){t.language="language",t.system="system",t.comma_decimal="comma_decimal",t.decimal_comma="decimal_comma",t.space_comma="space_comma",t.none="none"}(rt||(rt={})),function(t){t.language="language",t.system="system",t.am_pm="12",t.twenty_four="24"}(at||(at={}));var ht=function(t){if(t.time_format===at.language||t.time_format===at.system){var e=t.time_format===at.language?t.language:void 0,i=(new Date).toLocaleString(e);return i.includes("AM")||i.includes("PM")}return t.time_format===at.am_pm},dt=function(t,e){return ut(e).format(t)},ut=function(t){return new Intl.DateTimeFormat(t.language,{year:"numeric",month:"long",day:"numeric",hour:ht(t)?"numeric":"2-digit",minute:"2-digit",hour12:ht(t)})},pt=function(t,e){return mt(e).format(t)},mt=function(t){return new Intl.DateTimeFormat(t.language,{hour:"numeric",minute:"2-digit",hour12:ht(t)})};function _t(){return(_t=Object.assign||function(t){for(var e=1;e-1?t.split(".")[1].length:0;i.minimumFractionDigits=o,i.maximumFractionDigits=o}return i},yt=function(t,e,i,o){var s=void 0!==o?o:e.state;if("unknown"===s||"unavailable"===s)return t("state.default."+s);if(function(t){return!!t.attributes.unit_of_measurement||!!t.attributes.state_class}(e)){if("monetary"===e.attributes.device_class)try{return gt(s,i,{style:"currency",currency:e.attributes.unit_of_measurement})}catch(t){}return gt(s,i)+(e.attributes.unit_of_measurement?" "+e.attributes.unit_of_measurement:"")}var n=function(t){return ft(t.entity_id)}(e);if("input_datetime"===n){var r;if(void 0===o)return e.attributes.has_date&&e.attributes.has_time?(r=new Date(e.attributes.year,e.attributes.month-1,e.attributes.day,e.attributes.hour,e.attributes.minute),dt(r,i)):e.attributes.has_date?(r=new Date(e.attributes.year,e.attributes.month-1,e.attributes.day),lt(r,i)):e.attributes.has_time?((r=new Date).setHours(e.attributes.hour,e.attributes.minute),pt(r,i)):e.state;try{var a=o.split(" ");if(2===a.length)return dt(new Date(a.join("T")),i);if(1===a.length){if(o.includes("-"))return lt(new Date(o+"T00:00"),i);if(o.includes(":")){var l=new Date;return pt(new Date(l.toISOString().split("T")[0]+"T"+o),i)}}return o}catch(t){return o}}return"humidifier"===n&&"on"===s&&e.attributes.humidity?e.attributes.humidity+" %":"counter"===n||"number"===n||"input_number"===n?gt(s,i):e.attributes.device_class&&t("component."+n+".state."+e.attributes.device_class+"."+s)||t("component."+n+".state._."+s)||s},bt=["closed","locked","off"],$t=function(t,e,i,o){o=o||{},i=null==i?{}:i;var s=new Event(e,{bubbles:void 0===o.bubbles||o.bubbles,cancelable:Boolean(o.cancelable),composed:void 0===o.composed||o.composed});return s.detail=i,t.dispatchEvent(s),s},wt=function(t){$t(window,"haptic",t)},Ct=function(t,e){return function(t,e,i){void 0===i&&(i=!0);var o,s=ft(e),n="group"===s?"homeassistant":s;switch(s){case"lock":o=i?"unlock":"lock";break;case"cover":o=i?"open_cover":"close_cover";break;default:o=i?"turn_on":"turn_off"}return t.callService(n,o,{entity_id:e})}(t,e,bt.includes(t.states[e].state))},At=function(t,e,i,o){if(o||(o={action:"more-info"}),!o.confirmation||o.confirmation.exemptions&&o.confirmation.exemptions.some((function(t){return t.user===e.user.id}))||(wt("warning"),confirm(o.confirmation.text||"Are you sure you want to "+o.action+"?")))switch(o.action){case"more-info":(i.entity||i.camera_image)&&$t(t,"hass-more-info",{entityId:i.entity?i.entity:i.camera_image});break;case"navigate":o.navigation_path&&function(t,e,i){void 0===i&&(i=!1),i?history.replaceState(null,"",e):history.pushState(null,"",e),$t(window,"location-changed",{replace:i})}(0,o.navigation_path);break;case"url":o.url_path&&window.open(o.url_path);break;case"toggle":i.entity&&(Ct(e,i.entity),wt("success"));break;case"call-service":if(!o.service)return void wt("failure");var s=o.service.split(".",2);e.callService(s[0],s[1],o.service_data,o.target),wt("success");break;case"fire-dom-event":$t(t,"ll-custom",o)}};function St(t){return void 0!==t&&"none"!==t.action}const xt={required:{icon:"tune",name:"Required",secondary:"Required options for this card to function",show:!0},actions:{icon:"gesture-tap-hold",name:"Actions",secondary:"Perform actions based on tapping/clicking",show:!1,options:{tap:{icon:"gesture-tap",name:"Tap",secondary:"Set the action to perform on tap",show:!1},hold:{icon:"gesture-tap-hold",name:"Hold",secondary:"Set the action to perform on hold",show:!1},double_tap:{icon:"gesture-double-tap",name:"Double Tap",secondary:"Set the action to perform on double tap",show:!1}}},appearance:{icon:"palette",name:"Appearance",secondary:"Customize the name, icon, etc",show:!1}};let It=class extends X{constructor(){super(...arguments),this._initialized=!1}setConfig(t){this._config=t,this.loadCardHelpers()}shouldUpdate(){return this._initialized||this._initialize(),!0}get _name(){var t;return(null===(t=this._config)||void 0===t?void 0:t.name)||""}get _entity(){var t;return(null===(t=this._config)||void 0===t?void 0:t.entity)||""}get _show_warning(){var t;return(null===(t=this._config)||void 0===t?void 0:t.show_warning)||!1}get _show_error(){var t;return(null===(t=this._config)||void 0===t?void 0:t.show_error)||!1}get _tap_action(){var t;return(null===(t=this._config)||void 0===t?void 0:t.tap_action)||{action:"more-info"}}get _hold_action(){var t;return(null===(t=this._config)||void 0===t?void 0:t.hold_action)||{action:"none"}}get _double_tap_action(){var t;return(null===(t=this._config)||void 0===t?void 0:t.double_tap_action)||{action:"none"}}render(){if(!this.hass||!this._helpers)return P``;this._helpers.importMoreInfoControl("climate");const t=Object.keys(this.hass.states).filter((t=>"sun"===t.substr(0,t.indexOf("."))));return P`
- -
${It.required.name}
+ +
${xt.required.name}
-
${It.required.secondary}
+
${xt.required.secondary}
- ${It.required.show?M` + ${xt.required.show?P`
e=>"function"==typeof e?((t,e)=>(customElements.define(t,e),e))(t,e) .configValue=${"entity"} > - ${t.map((t=>M` ${t} `))} + ${t.map((t=>P` ${t} `))}
`:""}
- -
${It.actions.name}
+ +
${xt.actions.name}
-
${It.actions.secondary}
+
${xt.actions.secondary}
- ${It.actions.show?M` + ${xt.actions.show?P`
- -
${It.actions.options.tap.name}
+ +
${xt.actions.options.tap.name}
-
${It.actions.options.tap.secondary}
+
${xt.actions.options.tap.secondary}
- ${It.actions.options.tap.show?M` + ${xt.actions.options.tap.show?P`
Action Editors Coming Soon
`:""}
- -
${It.actions.options.hold.name}
+ +
${xt.actions.options.hold.name}
-
${It.actions.options.hold.secondary}
+
${xt.actions.options.hold.secondary}
- ${It.actions.options.hold.show?M` + ${xt.actions.options.hold.show?P`
Action Editors Coming Soon
`:""}
- -
${It.actions.options.double_tap.name}
+ +
${xt.actions.options.double_tap.name}
-
${It.actions.options.double_tap.secondary}
+
${xt.actions.options.double_tap.secondary}
- ${It.actions.options.double_tap.show?M` + ${xt.actions.options.double_tap.show?P`
Action Editors Coming Soon
@@ -126,12 +126,12 @@ const et=t=>e=>"function"==typeof e?((t,e)=>(customElements.define(t,e),e))(t,e) `:""}
- -
${It.appearance.name}
+ +
${xt.appearance.name}
-
${It.appearance.secondary}
+
${xt.appearance.secondary}
- ${It.appearance.show?M` + ${xt.appearance.show?P`
e=>"function"==typeof e?((t,e)=>(customElements.define(t,e),e))(t,e)
`:""}
- `}_initialize(){void 0!==this.hass&&void 0!==this._config&&void 0!==this._helpers&&(this._initialized=!0)}async loadCardHelpers(){this._helpers=await window.loadCardHelpers()}_toggleAction(t){this._toggleThing(t,It.actions.options)}_toggleOption(t){this._toggleThing(t,It)}_toggleThing(t,e){const i=!e[t.target.option].show;for(const[t]of Object.entries(e))e[t].show=!1;e[t.target.option].show=i,this._toggle=!this._toggle}_valueChanged(t){if(!this._config||!this.hass)return;const e=t.target;if(this[`_${e.configValue}`]!==e.value){if(e.configValue)if(""===e.value){const t=Object.assign({},this._config);delete t[e.configValue],this._config=t}else this._config=Object.assign(Object.assign({},this._config),{[e.configValue]:void 0!==e.checked?e.checked:e.value});$t(this,"config-changed",{config:this._config})}}static get styles(){return r` + `}_initialize(){void 0!==this.hass&&void 0!==this._config&&void 0!==this._helpers&&(this._initialized=!0)}async loadCardHelpers(){this._helpers=await window.loadCardHelpers()}_toggleAction(t){this._toggleThing(t,xt.actions.options)}_toggleOption(t){this._toggleThing(t,xt)}_toggleThing(t,e){const i=!e[t.target.option].show;for(const[t]of Object.entries(e))e[t].show=!1;e[t.target.option].show=i,this._toggle=!this._toggle}_valueChanged(t){if(!this._config||!this.hass)return;const e=t.target;if(this[`_${e.configValue}`]!==e.value){if(e.configValue)if(""===e.value){const t=Object.assign({},this._config);delete t[e.configValue],this._config=t}else this._config=Object.assign(Object.assign({},this._config),{[e.configValue]:void 0!==e.checked?e.checked:e.value});$t(this,"config-changed",{config:this._config})}}static get styles(){return r` .option { padding: 4px 0px; cursor: pointer; @@ -185,35 +185,37 @@ const et=t=>e=>"function"==typeof e?((t,e)=>(customElements.define(t,e),e))(t,e) ha-formfield { padding-bottom: 8px; } - `}};t([ot({attribute:!1})],xt.prototype,"hass",void 0),t([st()],xt.prototype,"_config",void 0),t([st()],xt.prototype,"_toggle",void 0),t([st()],xt.prototype,"_helpers",void 0),xt=t([et("rpi-monitor-card-editor")],xt);class Et{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}}const kt="ontouchstart"in window||navigator.maxTouchPoints>0||navigator.maxTouchPoints>0;class Tt extends HTMLElement{constructor(){super(),this.holdTime=500,this.held=!1,this.ripple=document.createElement("mwc-ripple")}connectedCallback(){Object.assign(this.style,{position:"absolute",width:kt?"100px":"50px",height:kt?"100px":"50px",transform:"translate(-50%, -50%)",pointerEvents:"none",zIndex:"999"}),this.appendChild(this.ripple),this.ripple.primary=!0,["touchcancel","mouseout","mouseup","touchmove","mousewheel","wheel","scroll"].forEach((t=>{document.addEventListener(t,(()=>{clearTimeout(this.timer),this.stopAnimation(),this.timer=void 0}),{passive:!0})}))}bind(t,e){if(t.actionHandler)return;t.actionHandler=!0,t.addEventListener("contextmenu",(t=>{const e=t||window.event;return e.preventDefault&&e.preventDefault(),e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0,e.returnValue=!1,!1}));const i=t=>{let e,i;this.held=!1,t.touches?(e=t.touches[0].pageX,i=t.touches[0].pageY):(e=t.pageX,i=t.pageY),this.timer=window.setTimeout((()=>{this.startAnimation(e,i),this.held=!0}),this.holdTime)},o=i=>{i.preventDefault(),["touchend","touchcancel"].includes(i.type)&&void 0===this.timer||(clearTimeout(this.timer),this.stopAnimation(),this.timer=void 0,this.held?$t(t,"action",{action:"hold"}):e.hasDoubleClick?"click"===i.type&&i.detail<2||!this.dblClickTimeout?this.dblClickTimeout=window.setTimeout((()=>{this.dblClickTimeout=void 0,$t(t,"action",{action:"tap"})}),250):(clearTimeout(this.dblClickTimeout),this.dblClickTimeout=void 0,$t(t,"action",{action:"double_tap"})):$t(t,"action",{action:"tap"}))};t.addEventListener("touchstart",i,{passive:!0}),t.addEventListener("touchend",o),t.addEventListener("touchcancel",o),t.addEventListener("mousedown",i,{passive:!0}),t.addEventListener("click",o),t.addEventListener("keyup",(t=>{13===t.keyCode&&o(t)}))}startAnimation(t,e){Object.assign(this.style,{left:`${t}px`,top:`${e}px`,display:null}),this.ripple.disabled=!1,this.ripple.active=!0,this.ripple.unbounded=!0}stopAnimation(){this.ripple.active=!1,this.ripple.disabled=!0,this.style.display="none"}}customElements.define("action-handler-rpi-monitor",Tt);const Ut=(t,e)=>{const i=(()=>{const t=document.body;if(t.querySelector("action-handler-rpi-monitor"))return t.querySelector("action-handler-rpi-monitor");const e=document.createElement("action-handler-rpi-monitor");return t.appendChild(e),e})();i&&i.bind(t,e)},Dt=(t=>(...e)=>({_$litDirective$:t,values:e}))(class extends Et{update(t,[e]){return Ut(t.element,e),N}render(t){}}),Ft="ifaces",Pt="ux_release",Mt="last_update",Nt="up_time",Ot="fs_total_gb",Rt="fs_free_prcnt",Vt="temperature_c",Ht="show-os-parts",Lt="memory_percent";var jt={version:"Version",invalid_configuration:"Invalid configuration",show_warning:"Show Warning",show_error:"Show Error"},zt={common:jt},Bt=Object.freeze({__proto__:null,common:jt,default:zt}),Gt={version:"Versjon",invalid_configuration:"Ikke gyldig konfiguration",show_warning:"Vis advarsel",show_error:"Vis feil"},Kt={common:Gt},qt=Object.freeze({__proto__:null,common:Gt,default:Kt}),Wt={version:"Version",invalid_configuration:"configuración no válida",show_warning:"Mostrar advertencia",show_error:"Mostrar error"},Yt={common:Wt};const Zt={en:Bt,es:Object.freeze({__proto__:null,common:Wt,default:Yt}),nb:qt};function Jt(t,e="",i=""){const o=(localStorage.getItem("selectedLanguage")||"en").replace(/['"]+/g,"").replace("-","_");let s;try{s=t.split(".").reduce(((t,e)=>t[e]),Zt[o])}catch(e){s=t.split(".").reduce(((t,e)=>t[e]),Zt.en)}return void 0===s&&(s=t.split(".").reduce(((t,e)=>t[e]),Zt.en)),""!==e&&""!==i&&(s=s.replace(e,i)),s}console.info(`%c RPI-MONITOR-CARD \n%c ${Jt("common.version")} 1.2.8 `,"color: orange; font-weight: bold; background: black","color: white; font-weight: bold; background: dimgray"),window.customCards=window.customCards||[],window.customCards.push({type:"rpi-monitor-card",name:"RPi Monitor Card",description:"A template custom card for you to create something awesome"});let Xt=class extends Q{constructor(){super(...arguments),this._firstTime=!0,this._sensorAvailable=!1,this._hostname="",this.kREPLACE_WITH_TEMP_UNITS="replace-with-temp-units",this._show_debug=!1,this._cardFullElements={"Storage Use":Rt,Storage:Ot,"Memory Use":Lt,Temperature:Vt,"Up-time":Nt,Updated:Mt,OS:Ht,Model:"rpi_model",Interfaces:Ft},this._cardFullIconNames={Storage:"sd","Storage Use":"file-percent","Memory Use":"memory",Temperature:"thermometer","Up-time":"clock-check-outline",Updated:"update",OS:"linux",Model:"raspberry-pi",Interfaces:""},this.kClassIdIconFSAvail="ico-fs-percent",this.kClassIdIconFSTotal="ico-fs-total",this.kClassIdIconSysTemp="ico-sys-temp",this.kClassIdIconUptime="ico-up-time",this.kClassIdIconUpdated="ico-last-update",this.kClassIdIconOS="ico-*nix",this.kClassIdIconRPiModel="ico-rpi-model",this.kClassIdIconInterfaces="ico-rpi-ifaces",this.kClassIdIconMemoryUsage="ico-memory-percent",this.kClassIdFSAvail="fs-percent",this.kClassIdFSTotal="fs-total",this.kClassIdSysTemp="sys-temp",this.kClassIdUptime="up-time",this.kClassIdUpdated="last-update",this.kClassIdOS="*nix",this.kClassIdRPiModel="rpi-model",this.kClassIdInterfaces="rpi-ifaces",this.kClassIdMemoryUsage="memory-percent",this.kClassIdTempScale="sys-temp-scale",this._cardFullCssIDs={"Storage Use":this.kClassIdFSAvail,Storage:this.kClassIdFSTotal,"Memory Use":this.kClassIdMemoryUsage,Temperature:this.kClassIdSysTemp,"Up-time":this.kClassIdUptime,Updated:this.kClassIdUpdated,OS:this.kClassIdOS,Model:this.kClassIdRPiModel,Interfaces:this.kClassIdInterfaces},this._cardFullIconCssIDs={"Storage Use":this.kClassIdIconFSAvail,Storage:this.kClassIdIconFSTotal,"Memory Use":this.kClassIdIconMemoryUsage,"Up-time":this.kClassIdIconUptime,Updated:this.kClassIdIconUpdated,Temperature:this.kClassIdIconSysTemp,OS:this.kClassIdIconOS,Model:this.kClassIdIconRPiModel,Interfaces:this.kClassIdIconInterfaces},this._cardGlanceElements={"%":Rt,GB:Ot,Mem:Lt,"replace-with-temp-units":Vt,UpTime:Nt,Upd:Mt},this._cardGlanceIconNames={"%":"file-percent",GB:"sd",Mem:"memory","replace-with-temp-units":"thermometer",UpTime:"clock-check-outline",Upd:"update"},this._cardGlanceCssIDs={"%":this.kClassIdFSAvail,GB:this.kClassIdFSTotal,Mem:this.kClassIdMemoryUsage,"replace-with-temp-units":this.kClassIdSysTemp,UpTime:this.kClassIdUptime,Upd:this.kClassIdUpdated},this._cardGlanceIconCssIDs={"%":this.kClassIdIconFSAvail,GB:this.kClassIdIconFSTotal,Mem:this.kClassIdIconMemoryUsage,"replace-with-temp-units":this.kClassIdIconSysTemp,UpTime:this.kClassIdIconUptime,Upd:this.kClassIdIconUpdated},this._circleIconsValueByName={"circle-outline":0,"circle-slice-1":13,"circle-slice-2":25,"circle-slice-3":38,"circle-slice-4":50,"circle-slice-5":63,"circle-slice-6":75,"circle-slice-7":88,"circle-slice-8":100},this._colorUsedSpaceDefault=[{color:"undefined",from:0,to:59},{color:"yellow",from:60,to:84},{color:"red",from:85,to:100}],this._colorTemperatureDefault=[{color:"undefined",from:0,to:59},{color:"yellow",from:60,to:79},{color:"red",from:85,to:100}],this._colorReportPeriodsAgoDefault=[{color:"white",from:0,to:3},{color:"yellow",from:4,to:4},{color:"red",from:5,to:100}],this._colorUsedMemoryDefault=[{color:"red",from:75,to:100},{color:"yellow",from:61,to:74},{color:"",from:0,to:60}],this._colorReleaseDefault=[{color:"red",os:"stretch"},{color:"red",os:"jessie"},{color:"red",os:"wheezy"}]}static async getConfigElement(){return document.createElement("rpi-monitor-card-editor")}static getStubConfig(){return{}}setConfig(t){if(this._showDebug()&&console.log("- setConfig()"),!t||t.show_error)throw new Error(Jt("common.invalid_configuration"));if(null!=t.card_style){const e=t.card_style.toLocaleLowerCase();if("full"!=e&&"glance"!=e)throw console.log("Invalid configuration. INVALID card_style = ["+t.card_style+"]"),new Error("Illegal card_style: value (card_style: "+t.card_style+") must be [full or glance]")}if(null!=t.temp_scale){const e=t.temp_scale.toLocaleLowerCase();if("c"!=e&&"f"!=e)throw console.log("Invalid configuration. INVALID temp_scale = ["+t.temp_scale+"]"),new Error("Illegal temp_scale: value (temp_scale: "+t.temp_scale+") must be [F or C]")}if(!t.entity)throw console.log("Invalid configuration. If no entity provided, you'll need to provide a remote entity"),new Error("You need to associate an entity");t.test_gui&&function(){var t=document.querySelector("home-assistant");if(t=(t=(t=(t=(t=(t=(t=(t=t&&t.shadowRoot)&&t.querySelector("home-assistant-main"))&&t.shadowRoot)&&t.querySelector("app-drawer-layout partial-panel-resolver"))&&t.shadowRoot||t)&&t.querySelector("ha-panel-lovelace"))&&t.shadowRoot)&&t.querySelector("hui-root")){var e=t.lovelace;return e.current_view=t.___curView,e}return null}().setEditMode(!0),this._config=Object.assign({},t),this._updateSensorAvailability()}shouldUpdate(t){if(this._updateSensorAvailability(),t.has("_config"))return!0;if(this.hass&&this._config){const e=t.get("hass");if(e)return e.states[this._config.entity]!==this.hass.states[this._config.entity]}return!0}render(){if(this._showDebug()&&console.log("- render()"),this._config.show_warning)return this.showWarning(Jt("common.show_warning"));if(this._config.show_error)return this.showError(Jt("common.show_error"));const t=this._config.entity?this._config.entity:void 0;if(t&&!this._sensorAvailable){const e="Entity Unavailable: "+t;return this.showWarning(e)}const e=this._config.entity?this.hass.states[this._config.entity]:void 0;if(!t&&!e)return this.showWarning("Entity Unavailable");this._firstTime&&(this._showDebug()&&(console.log("- stateObj:"),console.log(e)),this._startCardRefreshTimer(),this._showDebug()&&(console.log("- 1st-time _config:"),console.log(this._config)),this._firstTime=!1);const i=null==this._config.show_os_age||this._config.show_os_age,o=null==this._config.show_update_age||this._config.show_update_age,s=this._getAttributeValueForKey("fqdn");let n="RPi monitor "+s;const r=1==i?this._getAttributeValueForKey(Pt):"";n=null!=this._config.name_prefix?this._config.name_prefix+" "+s:n,n=null!=this._config.name?this._config.name:n;const a=null==this._config.show_title||this._config.show_title;0==a&&(n="");const l=0==a?"last-heard-full-notitle":"last-heard-full",c=0==a?"last-heard-notitle":"last-heard",h=0==a?"os-name-full-notitle":"os-name-full",d=0==a?"os-name-notitle":"os-name",[u,p]=this._getRelativeTimeSinceUpdate(),m=1==o?u:"";if(this._useFullCard()){const t=this._generateFullsizeCardRows();return M` + `}};t([ot({attribute:!1})],It.prototype,"hass",void 0),t([st()],It.prototype,"_config",void 0),t([st()],It.prototype,"_toggle",void 0),t([st()],It.prototype,"_helpers",void 0),It=t([et("rpi-monitor-card-editor")],It);class Et{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}}const Tt="ontouchstart"in window||navigator.maxTouchPoints>0||navigator.maxTouchPoints>0;class kt extends HTMLElement{constructor(){super(),this.holdTime=500,this.held=!1,this.ripple=document.createElement("mwc-ripple")}connectedCallback(){Object.assign(this.style,{position:"absolute",width:Tt?"100px":"50px",height:Tt?"100px":"50px",transform:"translate(-50%, -50%)",pointerEvents:"none",zIndex:"999"}),this.appendChild(this.ripple),this.ripple.primary=!0,["touchcancel","mouseout","mouseup","touchmove","mousewheel","wheel","scroll"].forEach((t=>{document.addEventListener(t,(()=>{clearTimeout(this.timer),this.stopAnimation(),this.timer=void 0}),{passive:!0})}))}bind(t,e){if(t.actionHandler)return;t.actionHandler=!0,t.addEventListener("contextmenu",(t=>{const e=t||window.event;return e.preventDefault&&e.preventDefault(),e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0,e.returnValue=!1,!1}));const i=t=>{let e,i;this.held=!1,t.touches?(e=t.touches[0].pageX,i=t.touches[0].pageY):(e=t.pageX,i=t.pageY),this.timer=window.setTimeout((()=>{this.startAnimation(e,i),this.held=!0}),this.holdTime)},o=i=>{i.preventDefault(),["touchend","touchcancel"].includes(i.type)&&void 0===this.timer||(clearTimeout(this.timer),this.stopAnimation(),this.timer=void 0,this.held?$t(t,"action",{action:"hold"}):e.hasDoubleClick?"click"===i.type&&i.detail<2||!this.dblClickTimeout?this.dblClickTimeout=window.setTimeout((()=>{this.dblClickTimeout=void 0,$t(t,"action",{action:"tap"})}),250):(clearTimeout(this.dblClickTimeout),this.dblClickTimeout=void 0,$t(t,"action",{action:"double_tap"})):$t(t,"action",{action:"tap"}))};t.addEventListener("touchstart",i,{passive:!0}),t.addEventListener("touchend",o),t.addEventListener("touchcancel",o),t.addEventListener("mousedown",i,{passive:!0}),t.addEventListener("click",o),t.addEventListener("keyup",(t=>{13===t.keyCode&&o(t)}))}startAnimation(t,e){Object.assign(this.style,{left:`${t}px`,top:`${e}px`,display:null}),this.ripple.disabled=!1,this.ripple.active=!0,this.ripple.unbounded=!0}stopAnimation(){this.ripple.active=!1,this.ripple.disabled=!0,this.style.display="none"}}customElements.define("action-handler-rpi-monitor",kt);const Dt=(t,e)=>{const i=(()=>{const t=document.body;if(t.querySelector("action-handler-rpi-monitor"))return t.querySelector("action-handler-rpi-monitor");const e=document.createElement("action-handler-rpi-monitor");return t.appendChild(e),e})();i&&i.bind(t,e)},Ut=(t=>(...e)=>({_$litDirective$:t,values:e}))(class extends Et{update(t,[e]){return Dt(t.element,e),F}render(t){}}),Rt="ifaces",Mt="ux_release",Pt="last_update",Ft="up_time",Ot="fs_total_gb",Nt="fs_free_prcnt",Vt="temperature_c",Ht="show-os-parts",Lt="memory_percent";var zt={version:"Version",invalid_configuration:"Invalid configuration",show_warning:"Show Warning",show_error:"Show Error"},jt={common:zt},Bt=Object.freeze({__proto__:null,common:zt,default:jt}),Gt={version:"Versjon",invalid_configuration:"Ikke gyldig konfiguration",show_warning:"Vis advarsel",show_error:"Vis feil"},Kt={common:Gt},qt=Object.freeze({__proto__:null,common:Gt,default:Kt}),Wt={version:"Version",invalid_configuration:"configuración no válida",show_warning:"Mostrar advertencia",show_error:"Mostrar error"},Yt={common:Wt};const Qt={en:Bt,es:Object.freeze({__proto__:null,common:Wt,default:Yt}),nb:qt};function Zt(t,e="",i=""){const o=(localStorage.getItem("selectedLanguage")||"en").replace(/['"]+/g,"").replace("-","_");let s;try{s=t.split(".").reduce(((t,e)=>t[e]),Qt[o])}catch(e){s=t.split(".").reduce(((t,e)=>t[e]),Qt.en)}return void 0===s&&(s=t.split(".").reduce(((t,e)=>t[e]),Qt.en)),""!==e&&""!==i&&(s=s.replace(e,i)),s}console.info(`%c RPI-MONITOR-CARD \n%c ${Zt("common.version")} 1.2.9 `,"color: orange; font-weight: bold; background: black","color: white; font-weight: bold; background: dimgray"),window.customCards=window.customCards||[],window.customCards.push({type:"rpi-monitor-card",name:"RPi Monitor Card",description:"A template custom card for you to create something awesome"});let Jt=class extends X{constructor(){super(...arguments),this._cardSecondsSinceUpdate=0,this._cardUpdateString="",this._firstTime=!0,this._sensorAvailable=!1,this._hostname="",this.kREPLACE_WITH_TEMP_UNITS="replace-with-temp-units",this.kMQTT_DAEMON_RELEASE_URL="https://raw.githubusercontent.com/ironsheep/RPi-Reporter-MQTT2HA-Daemon/master/Release",this.latestDaemonVersions=["v1.6.2","v1.6.1"],this.currentDaemonVersion="",this._show_debug=!1,this._cardFullElements={"Storage Use":Nt,Storage:Ot,"Memory Use":Lt,Temperature:Vt,"Up-time":Ft,Updated:Pt,OS:Ht,Model:"rpi_model",Interfaces:Rt},this._cardFullIconNames={Storage:"sd","Storage Use":"file-percent","Memory Use":"memory",Temperature:"thermometer","Up-time":"clock-check-outline",Updated:"update",OS:"linux",Model:"raspberry-pi",Interfaces:""},this.kClassIdIconFSAvail="ico-fs-percent",this.kClassIdIconFSTotal="ico-fs-total",this.kClassIdIconSysTemp="ico-sys-temp",this.kClassIdIconUptime="ico-up-time",this.kClassIdIconUpdated="ico-last-update",this.kClassIdIconOS="ico-*nix",this.kClassIdIconRPiModel="ico-rpi-model",this.kClassIdIconInterfaces="ico-rpi-ifaces",this.kClassIdIconMemoryUsage="ico-memory-percent",this.kClassIdFSAvail="fs-percent",this.kClassIdFSTotal="fs-total",this.kClassIdSysTemp="sys-temp",this.kClassIdUptime="up-time",this.kClassIdUpdated="last-update",this.kClassIdOS="*nix",this.kClassIdRPiModel="rpi-model",this.kClassIdInterfaces="rpi-ifaces",this.kClassIdMemoryUsage="memory-percent",this.kClassIdTempScale="sys-temp-scale",this._cardFullCssIDs={"Storage Use":this.kClassIdFSAvail,Storage:this.kClassIdFSTotal,"Memory Use":this.kClassIdMemoryUsage,Temperature:this.kClassIdSysTemp,"Up-time":this.kClassIdUptime,Updated:this.kClassIdUpdated,OS:this.kClassIdOS,Model:this.kClassIdRPiModel,Interfaces:this.kClassIdInterfaces},this._cardFullIconCssIDs={"Storage Use":this.kClassIdIconFSAvail,Storage:this.kClassIdIconFSTotal,"Memory Use":this.kClassIdIconMemoryUsage,"Up-time":this.kClassIdIconUptime,Updated:this.kClassIdIconUpdated,Temperature:this.kClassIdIconSysTemp,OS:this.kClassIdIconOS,Model:this.kClassIdIconRPiModel,Interfaces:this.kClassIdIconInterfaces},this._cardGlanceElements={"%":Nt,GB:Ot,Mem:Lt,"replace-with-temp-units":Vt,UpTime:Ft,Upd:Pt},this._cardGlanceIconNames={"%":"file-percent",GB:"sd",Mem:"memory","replace-with-temp-units":"thermometer",UpTime:"clock-check-outline",Upd:"update"},this._cardGlanceCssIDs={"%":this.kClassIdFSAvail,GB:this.kClassIdFSTotal,Mem:this.kClassIdMemoryUsage,"replace-with-temp-units":this.kClassIdSysTemp,UpTime:this.kClassIdUptime,Upd:this.kClassIdUpdated},this._cardGlanceIconCssIDs={"%":this.kClassIdIconFSAvail,GB:this.kClassIdIconFSTotal,Mem:this.kClassIdIconMemoryUsage,"replace-with-temp-units":this.kClassIdIconSysTemp,UpTime:this.kClassIdIconUptime,Upd:this.kClassIdIconUpdated},this._circleIconsValueByName={"circle-outline":0,"circle-slice-1":13,"circle-slice-2":25,"circle-slice-3":38,"circle-slice-4":50,"circle-slice-5":63,"circle-slice-6":75,"circle-slice-7":88,"circle-slice-8":100},this._colorUsedSpaceDefault=[{color:"default",from:0,to:59},{color:"yellow",from:60,to:84},{color:"red",from:85,to:100}],this._colorTemperatureDefault=[{color:"default",from:0,to:59},{color:"yellow",from:60,to:79},{color:"red",from:85,to:100}],this._colorReportPeriodsAgoDefault=[{color:"default",from:0,to:3},{color:"yellow",from:4,to:4},{color:"red",from:5,to:100}],this._colorUsedMemoryDefault=[{color:"red",from:75,to:100},{color:"yellow",from:61,to:74},{color:"default",from:0,to:60}],this._colorReleaseDefault=[{color:"red",os:"stretch"},{color:"red",os:"jessie"},{color:"red",os:"wheezy"}]}static async getConfigElement(){return document.createElement("rpi-monitor-card-editor")}static getStubConfig(){return{}}setConfig(t){if(this._showDebug()&&console.log("- setConfig()"),!t||t.show_error)throw new Error(Zt("common.invalid_configuration"));if(null!=t.card_style){const e=t.card_style.toLocaleLowerCase();if("full"!=e&&"glance"!=e)throw console.log("Invalid configuration. INVALID card_style = ["+t.card_style+"]"),new Error("Illegal card_style: value (card_style: "+t.card_style+") must be [full or glance]")}if(null!=t.temp_scale){const e=t.temp_scale.toLocaleLowerCase();if("c"!=e&&"f"!=e)throw console.log("Invalid configuration. INVALID temp_scale = ["+t.temp_scale+"]"),new Error("Illegal temp_scale: value (temp_scale: "+t.temp_scale+") must be [F or C]")}if(!t.entity)throw console.log("Invalid configuration. If no entity provided, you'll need to provide a remote entity"),new Error("You need to associate an entity");t.test_gui&&function(){var t=document.querySelector("home-assistant");if(t=(t=(t=(t=(t=(t=(t=(t=t&&t.shadowRoot)&&t.querySelector("home-assistant-main"))&&t.shadowRoot)&&t.querySelector("app-drawer-layout partial-panel-resolver"))&&t.shadowRoot||t)&&t.querySelector("ha-panel-lovelace"))&&t.shadowRoot)&&t.querySelector("hui-root")){var e=t.lovelace;return e.current_view=t.___curView,e}return null}().setEditMode(!0),this._config=Object.assign({},t),console.log("- config=["+this._config+"]"),this._updateSensorAvailability()}async loadDaemonReleases(){this.latestDaemonVersions=await fetch(this.kMQTT_DAEMON_RELEASE_URL).then((t=>t.text().then(this._loadDaemonReleaseInfo))),console.log("LDR ("+this._hostname+") latestDaemonVersions=["+this.latestDaemonVersions+"]("+this.latestDaemonVersions.length+")")}shouldUpdate(t){if(this._updateSensorAvailability(),t.has("_config"))return!0;if(this.hass&&this._config){const e=t.get("hass");if(e){return e.states[this._config.entity]!==this.hass.states[this._config.entity]}}return!0}render(){if(this._showDebug()&&console.log("- render("+this._hostname+")"),this._config.show_warning)return this.showWarning(Zt("common.show_warning"));if(this._config.show_error)return this.showError(Zt("common.show_error"));const t=this._config.entity?this._config.entity:void 0;if(t&&!this._sensorAvailable){const e="Entity Unavailable: "+t;return this.showWarning(e)}const e=this._config.entity?this.hass.states[this._config.entity]:void 0;if(!t&&!e)return this.showWarning("Entity Unavailable");if(0==this._sensorAvailable)return void console.log("?? Render w/o sensor!! ("+this._hostname+")");if(this._firstTime){this._showDebug()&&console.log("- stateObj: ["+e+"]");const t=this._getAttributeValueForKey("reporter").split(" ");this.currentDaemonVersion=t.length>1?t[1]:"",this._startCardRefreshTimer(),this._showDebug()&&console.log("- 1st-time _config: ["+this._config+"]"),this._firstTime=!1}const i=null==this._config.show_os_age||this._config.show_os_age,o=null==this._config.show_update_age||this._config.show_update_age,s=this._getAttributeValueForKey("fqdn");let n="RPi monitor "+s;const r=1==i?this._getAttributeValueForKey(Mt):"";let a="";n=null!=this._config.name_prefix?this._config.name_prefix+" "+s:n,n=null!=this._config.name?this._config.name:n;const l=null==this._config.show_title||this._config.show_title;0==l&&(n=""),this._showDebug()&&(console.log("- RNDR currentDaemonVersion=["+this.currentDaemonVersion+"]"),console.log("- RNDR latestDaemonVersions=["+this.latestDaemonVersions+"]")),this.latestDaemonVersions.length>0&&""!=this.currentDaemonVersion?this.currentDaemonVersion!=this.latestDaemonVersions[0]&&(a=this.currentDaemonVersion+" -- ("+this.latestDaemonVersions[0]+" avail.)"):a=""!=this.currentDaemonVersion?this.currentDaemonVersion+" {no info avail.}":"v?.?.? {no info avail.}";const c=0==l?"last-heard-full-notitle":"last-heard-full",h=0==l?"last-heard-notitle":"last-heard",d=0==l?"os-name-full-notitle":"os-name-full",u=0==l?"os-name-notitle":"os-name",p=0==l?"daemon-update-full-notitle":"daemon-update-full",m=0==l?"daemon-update-notitle":"daemon-update",_=1==o?this._cardUpdateString:"";if(this._useFullCard()){const t=this._generateFullsizeCardRows();return 0!=t.length&&t?P`
${t} -
${m}
-
${r}
+
${_}
+
${r}
+
${a}
- `}{const t=this._generateGlanceCardRows();return M` + `:void console.log("ERROR: failed to generate full rows!")}{const t=this._generateGlanceCardRows();return 0!=t.length&&t?P`
${t} -
${m}
-
${r}
+
${_}
+
${r}
+
${a}
- `}}_getRelativeTimeSinceUpdate(){var t;const e=this._config.entity?this.hass.states[this._config.entity]:void 0;let i="",o=0;if(null!=this.hass.locale&&null!=e){const s=yt(null===(t=this.hass)||void 0===t?void 0:t.localize,e,this.hass.locale),n=void 0===s?"{unknown}":this.prettyDate(s);i=this._sensorAvailable?n:"{unknown}";const r=n.split(" ")[0];o=r.includes("just")||r.includes("unknown")?0:Number(r)}return[i,o]}prettyDate(t){const e=new Date((t||"").replace(/-/g,"/").replace(/[TZ]/g," ")),i=((new Date).getTime()-e.getTime())/1e3,o=Math.floor(i/86400),s=e.getFullYear(),n=e.getMonth()+1,r=e.getDate();if(isNaN(o)||o<0||o>=31)return s.toString()+"-"+(n<10?"0"+n.toString():n.toString())+"-"+(r<10?"0"+r.toString():r.toString());let a="{unknown}";return 0==o?i<60?a="just now":i<120?a="1 minute ago":i<3600?a=Math.floor(i/60)+" minutes ago":i<7200?a="1 hour ago":i<86400&&(a=Math.floor(i/3600)+" hours ago"):1==o?a="Yesterday":o<7?a=o+" days ago":o<31&&(a=Math.ceil(o/7)+" weeks ago"),a}updated(t){if(this._showDebug()&&console.log("- updated()"),!this._config)return;if(this.hass){const e=t.get("hass");(!e||e&&e.themes!==this.hass.themes)&&function(t,e,i,o){void 0===o&&(o=!1),t._themes||(t._themes={});var s=e.default_theme;("default"===i||i&&e.themes[i])&&(s=i);var n=_t({},t._themes);if("default"!==s){var r=e.themes[s];Object.keys(r).forEach((function(e){var i="--"+e;t._themes[i]="",n[i]=r[e]}))}if(t.updateStyles?t.updateStyles(n):window.ShadyCSS&&window.ShadyCSS.styleSubtree(t,n),o){var a=document.querySelector("meta[name=theme-color]");if(a){a.hasAttribute("default-content")||a.setAttribute("default-content",a.getAttribute("content"));var l=n["--primary-color"]||a.getAttribute("default-content");a.setAttribute("content",l)}}}(this,this.hass.themes,this._config.theme)}this.hass.states[this._config.entity]||this._stopCardRefreshTimer();const e=this.shadowRoot;if(this._sensorAvailable){const t=this._getAttributeValueForKey(Pt),i=this._computeOsReleaseColor(t);if(""!=i){e.getElementById("os-name").style.setProperty("color",i)}if(this._useFullCard())for(const t in this._cardFullCssIDs){const i=this._cardFullCssIDs[t],o=this._cardFullElements[t],s=this._getAttributeValueForKey(o),n=this._getFullCardValueForAttributeKey(o);o==Lt&&console.log("- FULL memory latestValue=["+n+"]");const r=e.getElementById(i);r.textContent=n;const a=this._cardFullIconCssIDs[t],l=e.getElementById(a);if(o==Rt){const t=this._computeFileSystemUsageColor(s);""!=t&&(r.style.setProperty("color",t),l.style.setProperty("color",t))}if(o==Lt){const t=this._computeMemoryUsageColor(n.replace(" %",""));""!=t&&(r.style.setProperty("color",t),l.style.setProperty("color",t))}if(o==Vt){const t=this._computeTemperatureColor(s);""!=t&&(r.style.setProperty("color",t),l.style.setProperty("color",t))}}else for(const t in this._cardGlanceCssIDs){const i=this._cardGlanceCssIDs[t],o=this._cardGlanceElements[t],s=this._getAttributeValueForKey(o),n=this._getGlanceCardValueForAttributeKey(o);o==Lt&&console.log("- GLNC memory latestValue=["+n+"]");const r=e.getElementById(i);r.textContent=n;const a=this._cardGlanceIconCssIDs[t],l=e.getElementById(a);if(o==Rt){const t=this._computeFileSystemUsageColor(s);""!=t&&(r.style.setProperty("color",t),l.style.setProperty("color",t))}if(o==Lt){const t=this._computeMemoryUsageColor(n);""!=t&&(r.style.setProperty("color",t),l.style.setProperty("color",t))}if(o==Vt&&"n/a"!=n){const t=this._computeTemperatureColor(s);""!=t&&(r.style.setProperty("color",t),l.style.setProperty("color",t));e.getElementById(this.kClassIdTempScale).textContent=this._getTemperatureScale()}}}}_handleAction(t){this.hass&&this._config&&t.detail.action&&function(t,e,i,o){var s;"double_tap"===o&&i.double_tap_action?s=i.double_tap_action:"hold"===o&&i.hold_action?s=i.hold_action:"tap"===o&&i.tap_action&&(s=i.tap_action),At(t,e,i,s)}(this,this.hass,this._config,t.detail.action)}showWarning(t){return M` ${t} `}showError(t){const e=document.createElement("hui-error-card");return e.setConfig({type:"error",error:t,origConfig:this._config}),M` ${e} `}_startCardRefreshTimer(){this._updateTimerID=setInterval((()=>this._handleCardUpdateTimerExpiration()),1e3)}_stopCardRefreshTimer(){null!=this._updateTimerID&&(clearInterval(this._updateTimerID),this._updateTimerID=void 0)}_handleCardUpdateTimerExpiration(){const t=this.shadowRoot;let e=!1;if(null!=(this._config.entity?this.hass.states[this._config.entity]:void 0)){const i=t.getElementById("card-timestamp");if(i){const t=null==this._config.show_update_age||this._config.show_update_age,[o,s]=this._getRelativeTimeSinceUpdate();if(o){let n=o;o.includes("NaN")&&(n="waiting for report...",e=!0),i.textContent=1==t?n:"";const r=this._computeReporterAgeColor(s);""!=r&&null!=r&&i.style.setProperty("color",r)}e&&this._emptyCardValuesWhileWaitingForSensor()}}}_useFullCard(){let t=!0;return this._config&&null!=this._config.card_style&&(t="full"==this._config.card_style.toLocaleLowerCase()),t}_useTempsInC(){let t=!0;return this._config&&null!=this._config.temp_scale&&(t="c"==this._config.temp_scale.toLocaleLowerCase()),t}_logChangeMessage(t){""==this._hostname&&(this._hostname=this._getAttributeValueForKey("host_name"));const e="("+this._hostname+"): "+t;this._showDebug()&&console.log(e)}_updateSensorAvailability(){let t=!1;if(this.hass&&this._config){const e=this._config.entity?this._config.entity:void 0,i=this._config.entity?this.hass.states[this._config.entity]:void 0;if(e||i)try{const e="unavailable"!=this.hass.states[this._config.entity].state;t=this._sensorAvailable!=e,this._sensorAvailable=e}catch(e){this._sensorAvailable=!1,t=!0}else this._sensorAvailable=!1,t=!0}else this._sensorAvailable=!1,t=!0;t&&this._logChangeMessage("* SENSOR available: "+this._sensorAvailable)}_getIconNameForPercent(t){let e="";for(const i in this._circleIconsValueByName){if(t<=this._circleIconsValueByName[i]){e=i;break}}return e}_computeReporterAgeColor(t){let e;return this._colorReportPeriodsAgoDefault.forEach((i=>{t>=i.from&&t<=i.to&&(e=i.color)})),void 0===e&&(e=""),e}_computeTemperatureColor(t){const e=this._config,i=Number(t),o=e.temp_severity?e.temp_severity:this._colorTemperatureDefault;let s;isNaN(i)||o.forEach((e=>{if(i>=e.from&&i<=e.to){s=e.color;const i="_computeTemperatureColor() - value=["+t+"] matched(from="+e.from+", to="+e.to+", color="+s+")";this._showDebug()&&console.log(i)}}));const n="_computeTemperatureColor() - value=["+t+"] returns(color="+s+")";return this._showDebug()&&console.log(n),null==s&&(s=""),s}_computeFileSystemUsageColor(t){const e=this._config,i=Number(t),o=e.fs_severity?e.fs_severity:this._colorUsedSpaceDefault;let s;isNaN(i)||o.forEach((e=>{if(i>=e.from&&i<=e.to){s=e.color;const i="_computeFileSystemUsageColor() - value=["+t+"] matched(from="+e.from+", to="+e.to+", color="+s+")";this._showDebug()&&console.log(i)}}));const n="_computeFileSystemUsageColor() - value=["+t+"] returns(color="+s+")";return this._showDebug()&&console.log(n),null==s&&(s=""),s}_computeMemoryUsageColor(t){const e=this._config,i=Number(t),o=e.memory_severity?e.memory_severity:this._colorUsedMemoryDefault;let s;isNaN(i)||o.forEach((e=>{if(i>=e.from&&i<=e.to){s=e.color;const i="_computeMemoryUsageColor() - value=["+t+"] matched(from="+e.from+", to="+e.to+", color="+s+")";this._showDebug()&&console.log(i)}}));const n="_computeMemoryUsageColor() - value=["+t+"] returns(color="+s+")";return this._showDebug()&&console.log(n),null==s&&(s=""),s}_computeOsReleaseColor(t){const e=this._config;let i;(e.os_age?e.os_age:this._colorReleaseDefault).forEach((e=>{if(t===e.os){i=e.color;const o="_computeOsReleaseColor() - value=["+t+"] matched(os="+e.os+", color="+i+")";this._showDebug()&&console.log(o)}}));const o="_computeTemperatureColor() - value=["+t+"] returns(color="+i+")";return this._showDebug()&&console.log(o),null==i&&(i=""),i}_filterUptime(t){const e=t.split(" ");let i=t;if(i.includes(":")){for(let t=0;t=31)return s.toString()+"-"+(n<10?"0"+n.toString():n.toString())+"-"+(r<10?"0"+r.toString():r.toString());let a="{unknown}";return 0==o?i<60?a="just now":i<120?a="1 minute ago":i<3600?a=Math.floor(i/60)+" minutes ago":i<7200?a="1 hour ago":i<86400&&(a=Math.floor(i/3600)+" hours ago"):1==o?a="Yesterday":o<7?a=o+" days ago":o<31&&(a=Math.ceil(o/7)+" weeks ago"),a}updated(t){if(this._showDebug()&&console.log("- updated("+this._hostname+")"),!this._config)return;if(this.hass){const e=t.get("hass");(!e||e&&e.themes!==this.hass.themes)&&function(t,e,i,o){void 0===o&&(o=!1),t._themes||(t._themes={});var s=e.default_theme;("default"===i||i&&e.themes[i])&&(s=i);var n=_t({},t._themes);if("default"!==s){var r=e.themes[s];Object.keys(r).forEach((function(e){var i="--"+e;t._themes[i]="",n[i]=r[e]}))}if(t.updateStyles?t.updateStyles(n):window.ShadyCSS&&window.ShadyCSS.styleSubtree(t,n),o){var a=document.querySelector("meta[name=theme-color]");if(a){a.hasAttribute("default-content")||a.setAttribute("default-content",a.getAttribute("content"));var l=n["--primary-color"]||a.getAttribute("default-content");a.setAttribute("content",l)}}}(this,this.hass.themes,this._config.theme)}this.hass.states[this._config.entity]||this._stopCardRefreshTimer();const e=this.shadowRoot;if(this._sensorAvailable){const t=this._getAttributeValueForKey(Mt),i=this._computeOsReleaseColor(t);if(""!=i){e.getElementById("os-name").style.setProperty("color",i)}const o=this._computeDaemonUpdateVersionColor(this.currentDaemonVersion);if(""!=o){e.getElementById("daemon-update").style.setProperty("color",o)}const s=this._computeReporterAgeColor(this._cardSecondsSinceUpdate);if(""!=s&&null!=s){e.getElementById("card-timestamp").style.setProperty("color",s)}if(this._useFullCard())for(const t in this._cardFullCssIDs){const i=this._cardFullCssIDs[t],o=this._cardFullElements[t],s=this._getAttributeValueForKey(o),n=this._getFullCardValueForAttributeKey(o),r=e.getElementById(i);r.textContent=n;const a=this._cardFullIconCssIDs[t],l=e.getElementById(a);if(o==Nt){const t=this._computeFileSystemUsageColor(s);""!=t&&(r.style.setProperty("color",t),l.style.setProperty("color",t))}if(o==Lt){const t=this._computeMemoryUsageColor(n.replace(" %",""));""!=t&&(r.style.setProperty("color",t),l.style.setProperty("color",t))}if(o==Vt){const t=this._computeTemperatureColor(s);""!=t&&(r.style.setProperty("color",t),l.style.setProperty("color",t))}}else for(const t in this._cardGlanceCssIDs){const i=this._cardGlanceCssIDs[t],o=this._cardGlanceElements[t],s=this._getAttributeValueForKey(o),n=this._getGlanceCardValueForAttributeKey(o),r=e.getElementById(i);r.textContent=n;const a=this._cardGlanceIconCssIDs[t],l=e.getElementById(a);if(o==Nt){const t=this._computeFileSystemUsageColor(s);""!=t&&(r.style.setProperty("color",t),l.style.setProperty("color",t))}if(o==Lt){const t=this._computeMemoryUsageColor(n);""!=t&&(r.style.setProperty("color",t),l.style.setProperty("color",t))}if(o==Vt&&"n/a"!=n){const t=this._computeTemperatureColor(s);""!=t&&(r.style.setProperty("color",t),l.style.setProperty("color",t));e.getElementById(this.kClassIdTempScale).textContent=this._getTemperatureScale()}}}}_handleAction(t){this.hass&&this._config&&t.detail.action&&function(t,e,i,o){var s;"double_tap"===o&&i.double_tap_action?s=i.double_tap_action:"hold"===o&&i.hold_action?s=i.hold_action:"tap"===o&&i.tap_action&&(s=i.tap_action),At(t,e,i,s)}(this,this.hass,this._config,t.detail.action)}showWarning(t){return P` ${t} `}showError(t){const e=document.createElement("hui-error-card");return e.setConfig({type:"error",error:t,origConfig:this._config}),P` ${e} `}_startCardRefreshTimer(){this._updateTimerID=setInterval((()=>this._handleCardUpdateTimerExpiration()),1e3),console.log("TIMER: ("+this._hostname+") started")}_stopCardRefreshTimer(){null!=this._updateTimerID&&(clearInterval(this._updateTimerID),this._updateTimerID=void 0,console.log("TIMER: ("+this._hostname+") STOPPED"))}_handleCardUpdateTimerExpiration(){const[t,e]=this._getRelativeTimeSinceUpdate();if(this._cardSecondsSinceUpdate!=e&&(this._cardSecondsSinceUpdate=e),t){let e=t;t.includes("NaN")&&(console.log(" HCUTE (DBG) ("+this._hostname+") card_timestamp_value=["+t+"]"),e="{unexpected value}..."),this._cardUpdateString!=e&&(this._cardUpdateString=e)}}_useFullCard(){let t=!0;return this._config&&null!=this._config.card_style&&(t="full"==this._config.card_style.toLocaleLowerCase()),t}_useTempsInC(){let t=!0;return this._config&&null!=this._config.temp_scale&&(t="c"==this._config.temp_scale.toLocaleLowerCase()),t}_logChangeMessage(t){""==this._hostname&&(this._hostname=this._getAttributeValueForKey("host_name"));const e="("+this._hostname+"): "+t;this._showDebug()&&console.log(e)}_updateSensorAvailability(){let t=!1;if(this.hass&&this._config){const e=this._config.entity?this._config.entity:void 0,i=this._config.entity?this.hass.states[this._config.entity]:void 0;if(e||i)try{const e="unavailable"!=this.hass.states[this._config.entity].state;t=this._sensorAvailable!=e,this._sensorAvailable=e}catch(e){this._sensorAvailable=!1,t=!0}else this._sensorAvailable=!1,t=!0}else this._sensorAvailable=!1,t=!0;t&&this._logChangeMessage("* SENSOR available: "+this._sensorAvailable)}_loadDaemonReleaseInfo(t){let e=[];if(t){const i=t.split("\n");for(let t=0;t0){const t=o.split(" ");t.length>0&&(e.includes(t[0])||e.push(t[0]))}}}return e}_getRelativeTimeSinceUpdate(){var t;const e=this._config.entity?this.hass.states[this._config.entity]:void 0;let i="",o=0,s="";if(null!=this.hass.locale&&null!=e){try{const o=yt(null===(t=this.hass)||void 0===t?void 0:t.localize,e,this.hass.locale),n=void 0===o?"{unknown}":this.prettyDate(o);i=this._sensorAvailable?n:"{unknown}";s=n.split(" ")[0]}catch(t){console.log("GRTSU - exception:"),console.error(t)}o=s.includes("just")||s.includes("unknown")?0:Number(s)}return[i,o]}_getIconNameForPercent(t){let e="";for(const i in this._circleIconsValueByName){if(t<=this._circleIconsValueByName[i]){e=i;break}}return e}_computeReporterAgeColor(t){let e;return this._colorReportPeriodsAgoDefault.forEach((i=>{t>=i.from&&t<=i.to&&(e=i.color)})),null!=e&&"default"!=e||(e=""),e}_computeTemperatureColor(t){const e=this._config,i=Number(t),o=e.temp_severity?e.temp_severity:this._colorTemperatureDefault;let s;if(isNaN(i)||o.forEach((e=>{if(i>=e.from&&i<=e.to&&(s=e.color,this._showDebug())){const i="_computeTemperatureColor() - value=["+t+"] matched(from="+e.from+", to="+e.to+", color="+s+")";console.log(i)}})),this._showDebug()){const e="_computeTemperatureColor() - value=["+t+"] returns(color="+s+")";console.log(e)}return null!=s&&"default"!=s||(s=""),s}_computeFileSystemUsageColor(t){const e=this._config,i=Number(t),o=e.fs_severity?e.fs_severity:this._colorUsedSpaceDefault;let s;if(isNaN(i)||o.forEach((e=>{if(i>=e.from&&i<=e.to&&(s=e.color,this._showDebug())){const i="_computeFileSystemUsageColor() - value=["+t+"] matched(from="+e.from+", to="+e.to+", color="+s+")";console.log(i)}})),this._showDebug()){const e="_computeFileSystemUsageColor() - value=["+t+"] returns(color="+s+")";console.log(e)}return null!=s&&"default"!=s||(s=""),s}_computeMemoryUsageColor(t){const e=this._config,i=Number(t),o=e.memory_severity?e.memory_severity:this._colorUsedMemoryDefault;let s;if(isNaN(i)||o.forEach((e=>{if(i>=e.from&&i<=e.to&&(s=e.color,this._showDebug())){const i="_computeMemoryUsageColor() - value=["+t+"] matched(from="+e.from+", to="+e.to+", color="+s+")";console.log(i)}})),this._showDebug()){const e="_computeMemoryUsageColor() - value=["+t+"] returns(color="+s+")";console.log(e)}return null!=s&&"default"!=s||(s=""),s}_computeOsReleaseColor(t){const e=this._config,i=e.os_age?e.os_age:this._colorReleaseDefault;let o="default";if(i.forEach((e=>{if(t===e.os&&(o=e.color,this._showDebug())){const i="_computeOsReleaseColor() - value=["+t+"] matched(os="+e.os+", color="+o+")";console.log(i)}})),this._showDebug()){const e="_computeOsReleaseColor() - value=["+t+"] returns(color="+o+")";console.log(e)}return null!=o&&"default"!=o||(o=""),o}_computeDaemonUpdateVersionColor(t){let e;if(e=this.latestDaemonVersions.length>0&&""!=t?this.latestDaemonVersions[0]==t?"default":this.latestDaemonVersions.includes(t)?"yellow":"red":"orange",this._showDebug()){const i="_computeDaemonUpdateVersionColor() - value=["+t+"] returns(color="+e+")";console.log(i)}return null!=e&&"default"!=e||(e=""),e}_filterUptime(t){const e=t.split(" ");let i=t;if(i.includes(":")){for(let t=0;t
@@ -223,7 +225,7 @@ const et=t=>e=>"function"==typeof e?((t,e)=>(customElements.define(t,e),e))(t,e)
${o}
- `)}return t}_generateGlanceCardRows(){const t=[];for(const e in this._cardGlanceElements){const i=this._cardGlanceElements[e],o=this._getGlanceCardValueForAttributeKey(i);let s=e;s==this.kREPLACE_WITH_TEMP_UNITS&&(s="n/a"!=o?this._getTemperatureScale():""),i==Lt&&(s="% Mem");let n=this._cardGlanceIconNames[e];i==Rt&&(n=this._getIconNameForPercent(o));const r=this._cardGlanceCssIDs[e],a=this._cardGlanceIconCssIDs[e];let l="units";i==Vt&&(l=this.kClassIdTempScale),t.push(M` + `)}return t}_generateGlanceCardRows(){const t=[];for(const e in this._cardGlanceElements){const i=this._cardGlanceElements[e],o=this._getGlanceCardValueForAttributeKey(i);let s=e;s==this.kREPLACE_WITH_TEMP_UNITS&&(s="n/a"!=o?this._getTemperatureScale():""),i==Lt&&(s="% Mem");let n=this._cardGlanceIconNames[e];i==Nt&&(n=this._getIconNameForPercent(o));const r=this._cardGlanceCssIDs[e],a=this._cardGlanceIconCssIDs[e];let l="units";i==Vt&&(l=this.kClassIdTempScale),t.push(P`
@@ -231,7 +233,7 @@ const et=t=>e=>"function"==typeof e?((t,e)=>(customElements.define(t,e),e))(t,e)
${o}
${s}
- `)}return t}_getTemperatureScale(){const t=1==this._useTempsInC()?"ºC":"ºF",e="_getTemperatureScale() scaleInterp=("+t+")";return this._showDebug()&&console.log(e),t}_getScaledTemperatureValue(t){let e=t;"n/a"!=e&&0==this._useTempsInC()&&(e=(9*parseFloat(t)/5+32).toFixed(1));const i="_getScaledTemperatureValue("+t+") scaleInterp=("+e+")";return this._showDebug()&&console.log(i),e}_getFullCardValueForAttributeKey(t){const e=this._getAttributeValueForKey(t);let i=e;if(t==Lt)i=this._getPercentMemoryUsed()+" %";else if(t==Mt)i=this._getUIDateForTimestamp(e);else if(t==Vt){if(i=this._getScaledTemperatureValue(e),"n/a"!=i){i=i+" "+this._getTemperatureScale()}}else if(t==Ot)i=e+" GB";else if(t==Rt)i=e+" %";else if(t==Nt)i=this._filterUptime(i);else if(t==Ht){i=this._getAttributeValueForKey(Pt)+" v"+this._getAttributeValueForKey("ux_version")}else if(t==Ft){const t=[];e.includes("e")&&t.push("Ether"),e.includes("w")&&t.push("WiFi"),e.includes("b")&&t.push("Bluetooth"),i=t.join(", ")}return i}_getGlanceCardValueForAttributeKey(t){const e=this._getAttributeValueForKey(t);let i=e;return t==Lt?i=this._getPercentMemoryUsed():t==Mt?i=this._getUIDateForTimestamp(e):t==Vt?i=this._getScaledTemperatureValue(e):t==Nt&&(i=this._filterUptime(i)),i}_getUIDateForTimestamp(t){return new Date(t).toLocaleDateString("en-us")}_getPercentMemoryUsed(){const t=this._getAttributeValueForKey("memory"),e=t.size_mb,i=t.free_mb,o=Number(e);return((e-Number(i))/o*100).toFixed(0).toString()}_showDebug(){let t=this._show_debug;return this._config&&null!=this._config.show_debug&&(t=1==t||1==this._config.show_debug),t}static get styles(){return r` + `)}return t}_getTemperatureScale(){return 1==this._useTempsInC()?"ºC":"ºF"}_getScaledTemperatureValue(t){let e=t;return"n/a"!=e&&0==this._useTempsInC()&&(e=(9*parseFloat(t)/5+32).toFixed(1)),e}_getFullCardValueForAttributeKey(t){const e=this._getAttributeValueForKey(t);let i=e;if(t==Lt)i=this._getPercentMemoryUsed()+" %";else if(t==Pt)i=this._getUIDateForTimestamp(e);else if(t==Vt){if(i=this._getScaledTemperatureValue(e),"n/a"!=i){i=i+" "+this._getTemperatureScale()}}else if(t==Ot)i=e+" GB";else if(t==Nt)i=e+" %";else if(t==Ft)i=this._filterUptime(i);else if(t==Ht){i=this._getAttributeValueForKey(Mt)+" v"+this._getAttributeValueForKey("ux_version")}else if(t==Rt){const t=[];e.includes("e")&&t.push("Ether"),e.includes("w")&&t.push("WiFi"),e.includes("b")&&t.push("Bluetooth"),i=t.join(", ")}return i}_getGlanceCardValueForAttributeKey(t){const e=this._getAttributeValueForKey(t);let i=e;return t==Lt?i=this._getPercentMemoryUsed():t==Pt?i=this._getUIDateForTimestamp(e):t==Vt?i=this._getScaledTemperatureValue(e):t==Ft&&(i=this._filterUptime(i)),i}_getUIDateForTimestamp(t){return new Date(t).toLocaleDateString("en-us")}_getPercentMemoryUsed(){const t=this._getAttributeValueForKey("memory"),e=t.size_mb,i=t.free_mb,o=Number(e);return((e-Number(i))/o*100).toFixed(0).toString()}_showDebug(){let t=this._show_debug;return this._config&&null!=this._config.show_debug&&(t=1==t||1==this._config.show_debug),t}static get styles(){return r` ha-card { height: 100%; display: flex; @@ -371,4 +373,32 @@ const et=t=>e=>"function"==typeof e?((t,e)=>(customElements.define(t,e),e))(t,e) font-size: 12px; color: var(--primary-text-color); } - `}};t([ot({attribute:!1})],Xt.prototype,"hass",void 0),t([st()],Xt.prototype,"_config",void 0),Xt=t([et("rpi-monitor-card")],Xt);export{Xt as RPiMonitorCard}; + .daemon-update-full { + position: absolute; + top: 45px; + right: 150px; + font-size: 12px; + color: var(--primary-text-color); + } + .daemon-update { + position: absolute; + top: 55px; + right: 150px; + font-size: 12px; + color: var(--primary-text-color); + } + .daemon-update-full-notitle { + position: absolute; + top: 3px; + right: 150px; + font-size: 12px; + color: var(--primary-text-color); + } + .daemon-update-notitle { + position: absolute; + bottom: 5px; + right: 210px; + font-size: 12px; + color: var(--primary-text-color); + } + `}};t([ot({attribute:!1})],Jt.prototype,"hass",void 0),t([st()],Jt.prototype,"_config",void 0),t([st()],Jt.prototype,"_cardSecondsSinceUpdate",void 0),t([st()],Jt.prototype,"_cardUpdateString",void 0),Jt=t([et("rpi-monitor-card")],Jt);export{Jt as RPiMonitorCard}; diff --git a/package.json b/package.json index 8094593..0c7936b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rpi-monitor-card", - "version": "1.2.8", + "version": "1.2.9", "description": "Lovelace RPi Monitor Card", "keywords": [ "home-assistant", @@ -24,7 +24,7 @@ "@material/mwc-select": "^0.25.3", "@material/mwc-switch": "^0.25.3", "@material/mwc-textfield": "^0.25.3", - "custom-card-helpers": "^1.7.2", + "custom-card-helpers": "^1.9.0", "home-assistant-js-websocket": "^5.11.1", "lit": "^2.6.1", "tslib": "2.3.1" diff --git a/src/const.ts b/src/const.ts index 1ebedc7..a6f428a 100644 --- a/src/const.ts +++ b/src/const.ts @@ -1,4 +1,4 @@ -export const CARD_VERSION = '1.2.8'; +export const CARD_VERSION = '1.2.9'; /* * EXAMPLE attributes ISP-RPi-mqtt-daemon.py v1.5.4 diff --git a/src/rpi-monitor-card.ts b/src/rpi-monitor-card.ts index 339534d..36b2cff 100644 --- a/src/rpi-monitor-card.ts +++ b/src/rpi-monitor-card.ts @@ -54,6 +54,8 @@ export class RPiMonitorCard extends LitElement { @property({ attribute: false }) public hass!: HomeAssistant; @state() private _config!: RPiMonitorCardConfig; + @state() private _cardSecondsSinceUpdate: number = 0; + @state() private _cardUpdateString: string = ''; // and those that don't cause a re-render private _firstTime: boolean = true; @@ -61,10 +63,13 @@ export class RPiMonitorCard extends LitElement { private _updateTimerID: NodeJS.Timeout | undefined; private _hostname: string = ''; private kREPLACE_WITH_TEMP_UNITS: string = 'replace-with-temp-units'; + private kMQTT_DAEMON_RELEASE_URL: string = + 'https://raw.githubusercontent.com/ironsheep/RPi-Reporter-MQTT2HA-Daemon/master/Release'; + private latestDaemonVersions: string[] = ['v1.6.2', 'v1.6.1']; // REMOVE BEFORE FLIGHT (TEST DATA) + private currentDaemonVersion: string = ''; // WARNING set following to false before commit! - private _show_debug: boolean = false; - //private _show_debug: boolean = true; + private _show_debug: boolean = false; // REMOVE BEFORE FLIGHT (set to false!) // // FULL-SIZE CARD tables @@ -81,6 +86,7 @@ export class RPiMonitorCard extends LitElement { Model: Constants.RPI_MODEL_KEY, Interfaces: Constants.RPI_INTERFACES_KEY, }; + private _cardFullIconNames = { // top to bottom Storage: 'sd', @@ -208,7 +214,7 @@ export class RPiMonitorCard extends LitElement { // user sets 'fs_severity' to override private _colorUsedSpaceDefault = [ { - color: 'undefined', + color: 'default', from: 0, to: 59, }, @@ -228,7 +234,7 @@ export class RPiMonitorCard extends LitElement { // user sets 'temp_severity' to override private _colorTemperatureDefault = [ { - color: 'undefined', + color: 'default', from: 0, to: 59, }, @@ -248,7 +254,7 @@ export class RPiMonitorCard extends LitElement { // no user override for now private _colorReportPeriodsAgoDefault = [ { - color: 'white', + color: 'default', from: 0, to: 3, }, @@ -278,7 +284,7 @@ export class RPiMonitorCard extends LitElement { to: 74, }, { - color: '', + color: 'default', from: 0, to: 60, }, @@ -350,10 +356,27 @@ export class RPiMonitorCard extends LitElement { ...config, }; - //console.log('- config:'); - //console.log(this._config); + console.log('- config=[' + this._config + ']'); this._updateSensorAvailability(); + + // request the release info from the DAEMON repository + //this.loadDaemonReleases(); + } + + private async loadDaemonReleases(): Promise { + this.latestDaemonVersions = await fetch(this.kMQTT_DAEMON_RELEASE_URL).then((response) => + response.text().then(this._loadDaemonReleaseInfo), + ); + console.log( + 'LDR (' + + this._hostname + + ') latestDaemonVersions=[' + + this.latestDaemonVersions + + '](' + + this.latestDaemonVersions.length + + ')', + ); } /* @@ -366,10 +389,12 @@ export class RPiMonitorCard extends LitElement { // https://lit.dev/docs/components/lifecycle/#reactive-update-cycle-performing protected shouldUpdate(changedProps: PropertyValues): boolean { //return hasConfigOrEntityChanged(this, changedProps, false); + //console.log('shouldUpdate(' + this._hostname + ') changedProps= [' + changedProps.keys() + ']'); this._updateSensorAvailability(); if (changedProps.has('_config')) { + //console.log('shouldUpdate(' + this._hostname + ') = [' + true + '] - CONFIG'); return true; } @@ -378,10 +403,13 @@ export class RPiMonitorCard extends LitElement { if (oldHass) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - return oldHass.states[this._config.entity!] !== this.hass.states[this._config.entity!]; + const bShouldStatus: boolean = oldHass.states[this._config.entity!] !== this.hass.states[this._config.entity!]; + //console.log('shouldUpdate(' + this._hostname + ') = [' + bShouldStatus + '] HASS'); + return bShouldStatus; } } + //console.log('shouldUpdate(' + this._hostname + ') = [' + true + '] other'); return true; } @@ -389,7 +417,7 @@ export class RPiMonitorCard extends LitElement { protected render(): TemplateResult | void { // Check for stateObj or other necessary things and render a warning if missing if (this._showDebug()) { - console.log('- render()'); + console.log('- render(' + this._hostname + ')'); } if (this._config.show_warning) { return this.showWarning(localize('common.show_warning')); @@ -412,19 +440,28 @@ export class RPiMonitorCard extends LitElement { return this.showWarning('Entity Unavailable'); } + // don't let render happen on no-sensor! + if (this._sensorAvailable == false) { + console.log('?? Render w/o sensor!! (' + this._hostname + ')'); + return; + } + if (this._firstTime) { if (this._showDebug()) { - console.log('- stateObj:'); - console.log(stateObj); + console.log('- stateObj: [' + stateObj + ']'); } + const reporter_version: string = this._getAttributeValueForKey(Constants.RPI_SCRIPT_VER_KEY); + const reportParts: string[] = reporter_version.split(' '); + this.currentDaemonVersion = reportParts.length > 1 ? reportParts[1] : ''; + //console.log('- 1st-time currentDaemonVersion=[' + this.currentDaemonVersion + ']'); + // set timer so our card updates timestamp every 5 seconds : 5000 (1 second: 1000) // FIXME: UNDONE remember to clear this interval when entity NOT avail. and restore when comes avail again... this._startCardRefreshTimer(); if (this._showDebug()) { - console.log('- 1st-time _config:'); - console.log(this._config); + console.log('- 1st-time _config: [' + this._config + ']'); } this._firstTime = false; } @@ -437,6 +474,7 @@ export class RPiMonitorCard extends LitElement { const rpi_fqdn: string = this._getAttributeValueForKey(Constants.RPI_FQDN_KEY); let cardName: string = 'RPi monitor ' + rpi_fqdn; const ux_release: string = showOsAge == true ? this._getAttributeValueForKey(Constants.RPI_NIX_RELEASE_KEY) : ''; + let daemon_update_status: string = ''; cardName = this._config.name_prefix != undefined ? this._config.name_prefix + ' ' + rpi_fqdn : cardName; cardName = this._config.name != undefined ? this._config.name : cardName; @@ -446,22 +484,41 @@ export class RPiMonitorCard extends LitElement { cardName = ''; } - const last_heard_full_class = showCardName == false ? 'last-heard-full-notitle' : 'last-heard-full'; + if (this._showDebug()) { + console.log('- RNDR currentDaemonVersion=[' + this.currentDaemonVersion + ']'); + console.log('- RNDR latestDaemonVersions=[' + this.latestDaemonVersions + ']'); + } + if (this.latestDaemonVersions.length > 0 && this.currentDaemonVersion != '') { + if (this.currentDaemonVersion != this.latestDaemonVersions[0]) { + // reporter version is not latest + daemon_update_status = this.currentDaemonVersion + ' -- (' + this.latestDaemonVersions[0] + ' avail.)'; + } + } else { + if (this.currentDaemonVersion != '') { + daemon_update_status = this.currentDaemonVersion + ' {no info avail.}'; + } else { + daemon_update_status = 'v?.?.? {no info avail.}'; + } + } + const last_heard_full_class = showCardName == false ? 'last-heard-full-notitle' : 'last-heard-full'; const last_heard_class = showCardName == false ? 'last-heard-notitle' : 'last-heard'; const os_name_full_class = showCardName == false ? 'os-name-full-notitle' : 'os-name-full'; - const os_name_class = showCardName == false ? 'os-name-notitle' : 'os-name'; - const [card_timestamp_value, minsSinceUpdate] = this._getRelativeTimeSinceUpdate(); - if (minsSinceUpdate) { - } // kill compiler warning - const card_timestamp = showCardAge == true ? card_timestamp_value : ''; + const daemon_update_full_class = showCardName == false ? 'daemon-update-full-notitle' : 'daemon-update-full'; + const daemon_update_class = showCardName == false ? 'daemon-update-notitle' : 'daemon-update'; + + const card_timestamp = showCardAge == true ? this._cardUpdateString : ''; if (this._useFullCard()) { // our FULL card const fullRows = this._generateFullsizeCardRows(); + if (fullRows.length == 0 || !fullRows) { + console.log('ERROR: failed to generate full rows!'); + return; + } return html` ${card_timestamp}
${ux_release}
+
${daemon_update_status}
`; } else { // our GLANCE card const glanceRows = this._generateGlanceCardRows(); + if (glanceRows.length == 0 || !glanceRows) { + console.log('ERROR: failed to generate glance rows!'); + return; + } return html` ${card_timestamp}
${ux_release}
+
${daemon_update_status}
`; } } - private _getRelativeTimeSinceUpdate(): [string, number] { - const stateObj = this._config.entity ? this.hass.states[this._config.entity] : undefined; - let desiredValue: string = ''; - let desiredMinutes: number = 0; - if (this.hass.locale != undefined && stateObj != undefined) { - const stateStrInterp = computeStateDisplay(this.hass?.localize, stateObj, this.hass.locale); - // console.log('- grtsu card stateStrInterp=[' + stateStrInterp + ']'); - const relativeInterp = stateStrInterp === undefined ? '{unknown}' : this.prettyDate(stateStrInterp); - // console.log(' relativeInterp=[' + relativeInterp + ']'); - desiredValue = this._sensorAvailable ? relativeInterp : '{unknown}'; - // console.log(' desiredValue=[' + desiredValue + ']'); - const lineParts: string[] = relativeInterp.split(' '); - const minutesValue: string = lineParts[0]; - - if (minutesValue.includes('just') || minutesValue.includes('unknown')) { - desiredMinutes = 0; - } else { - desiredMinutes = Number(minutesValue); - } - } - return [desiredValue, desiredMinutes]; - } - private prettyDate(time: string): string { const date: Date = new Date((time || '').replace(/-/g, '/').replace(/[TZ]/g, ' ')); const diff: number = (new Date().getTime() - date.getTime()) / 1000; @@ -572,7 +612,7 @@ export class RPiMonitorCard extends LitElement { // Here we need to refresh the rings and titles after it has been initially rendered protected updated(changedProps: PropertyValues): void { if (this._showDebug()) { - console.log('- updated()'); + console.log('- updated(' + this._hostname + ')'); } if (!this._config) { return; @@ -600,10 +640,24 @@ export class RPiMonitorCard extends LitElement { if (this._sensorAvailable) { // update common label(s) const ux_release: string = this._getAttributeValueForKey(Constants.RPI_NIX_RELEASE_KEY); - const color = this._computeOsReleaseColor(ux_release); - if (color != '') { + const rlsNameColor = this._computeOsReleaseColor(ux_release); + if (rlsNameColor != '') { const labelElement = root.getElementById('os-name'); - labelElement.style.setProperty('color', color); + labelElement.style.setProperty('color', rlsNameColor); + } + + // apply color if RPi daemon should be updated + const daemonUpdColor = this._computeDaemonUpdateVersionColor(this.currentDaemonVersion); + if (daemonUpdColor != '') { + const labelElement = root.getElementById('daemon-update'); + labelElement.style.setProperty('color', daemonUpdColor); + } + + // now apply color if our entry is OLD + const intervalColor = this._computeReporterAgeColor(this._cardSecondsSinceUpdate); + if (intervalColor != '' && intervalColor != undefined) { + const labelElement = root.getElementById('card-timestamp'); + labelElement.style.setProperty('color', intervalColor); } if (this._useFullCard()) { @@ -613,9 +667,9 @@ export class RPiMonitorCard extends LitElement { const currAttrKey = this._cardFullElements[currName]; const rawValue = this._getAttributeValueForKey(currAttrKey); const latestValue = this._getFullCardValueForAttributeKey(currAttrKey); - if (currAttrKey == Constants.RPI_MEMORY_USED_PERCENT_KEY) { - console.log('- FULL memory latestValue=[' + latestValue + ']'); - } + // if (currAttrKey == Constants.RPI_MEMORY_USED_PERCENT_KEY) { + // console.log('- FULL memory latestValue=[' + latestValue + ']'); + // } const labelElement = root.getElementById(currLabelID); labelElement.textContent = latestValue; const currIconCssID = this._cardFullIconCssIDs[currName]; @@ -649,9 +703,9 @@ export class RPiMonitorCard extends LitElement { const currAttrKey = this._cardGlanceElements[currName]; const rawValue = this._getAttributeValueForKey(currAttrKey); const latestValue = this._getGlanceCardValueForAttributeKey(currAttrKey); - if (currAttrKey == Constants.RPI_MEMORY_USED_PERCENT_KEY) { - console.log('- GLNC memory latestValue=[' + latestValue + ']'); - } + // if (currAttrKey == Constants.RPI_MEMORY_USED_PERCENT_KEY) { + // console.log('- GLNC memory latestValue=[' + latestValue + ']'); + // } const labelElement = root.getElementById(currLabelID); labelElement.textContent = latestValue; const currIconCssID = this._cardGlanceIconCssIDs[currName]; @@ -716,12 +770,14 @@ export class RPiMonitorCard extends LitElement { private _startCardRefreshTimer(): void { this._updateTimerID = setInterval(() => this._handleCardUpdateTimerExpiration(), 1000); + console.log('TIMER: (' + this._hostname + ') started'); } private _stopCardRefreshTimer(): void { if (this._updateTimerID != undefined) { clearInterval(this._updateTimerID); this._updateTimerID = undefined; + console.log('TIMER: (' + this._hostname + ') STOPPED'); } } @@ -729,39 +785,25 @@ export class RPiMonitorCard extends LitElement { // // timestamp portion of card // + //console.log('TIMER: (' + this._hostname + ') timeout'); // eslint-disable-next-line @typescript-eslint/no-explicit-any - const root: any = this.shadowRoot; - let needCardFlush = false; - const stateObj = this._config.entity ? this.hass.states[this._config.entity] : undefined; - if (stateObj != undefined) { - const labelElement = root.getElementById('card-timestamp'); - if (labelElement) { - const showCardAge = this._config.show_update_age != undefined ? this._config.show_update_age : true; - const [card_timestamp_value, sinceInMinutes] = this._getRelativeTimeSinceUpdate(); - //console.log('-- card_timestamp_value=[' + card_timestamp_value + '] sinceInMinutes=[' + sinceInMinutes + ']'); - if (card_timestamp_value) { - let card_timestamp = card_timestamp_value; - // BUGFIX let's NOT show 'in NaN weeks' message on reload... - if (card_timestamp_value.includes('NaN')) { - card_timestamp = 'waiting for report...'; - needCardFlush = true; - } - labelElement.textContent = showCardAge == true ? card_timestamp : ''; - - // now apply color if our entry is OLD - //const periodMinutes: string = this._getAttributeValueForKey(Constants.RPI_SCRIPT_INTERVAL_KEY); - //console.log(' periodMinutes=[' + periodMinutes + ']'); - //const mumber_periods: number = (sinceInMinutes / parseInt(periodMinutes)) * 10; - //console.log(' mumber_periods=[' + mumber_periods + ']'); - const intervalColor = this._computeReporterAgeColor(sinceInMinutes); - if (intervalColor != '' && intervalColor != undefined) { - //console.log(' intervalColor=[' + intervalColor + ']'); - labelElement.style.setProperty('color', intervalColor); - } - } - if (needCardFlush) { - this._emptyCardValuesWhileWaitingForSensor(); - } + const [card_timestamp_value, sinceInMinutes] = this._getRelativeTimeSinceUpdate(); + if (this._cardSecondsSinceUpdate != sinceInMinutes) { + this._cardSecondsSinceUpdate = sinceInMinutes; + } + //console.log('-- card_timestamp_value=[' + card_timestamp_value + '] sinceInMinutes=[' + sinceInMinutes + ']'); + if (card_timestamp_value) { + let card_timestamp = card_timestamp_value; + //console.log(' HCUTE (' + this._hostname + ') card_timestamp_value=[' + card_timestamp_value + ']'); + // BUGFIX let's NOT show 'in NaN weeks' message on reload... + if (card_timestamp_value.includes('NaN')) { + console.log(' HCUTE (DBG) (' + this._hostname + ') card_timestamp_value=[' + card_timestamp_value + ']'); + //card_timestamp = 'waiting for report...'; + //needCardFlush = true; // we have a system bug causing a mis-fire... don't clear the card... + card_timestamp = '{unexpected value}...'; + } + if (this._cardUpdateString != card_timestamp) { + this._cardUpdateString = card_timestamp; } } } @@ -827,6 +869,60 @@ export class RPiMonitorCard extends LitElement { } } + private _loadDaemonReleaseInfo(retrievedText: string): string[] { + //console.log('LDRI retrievedText=[' + retrievedText + ']'); + let foundVersions: string[] = []; + if (retrievedText) { + const lines: string[] = retrievedText.split('\n'); + //console.log('FAR lines=[' + lines + '](' + lines.length + ')'); + for (let index: number = 0; index < lines.length; index++) { + const currLine: string = lines[index]; + //console.log('FAR currLine=[' + currLine + '](' + currLine.length + ')'); + if (currLine.length > 0) { + const lineParts: string[] = currLine.split(' '); + if (lineParts.length > 0) { + //console.log('FAR lineParts(' + index + ')=[' + lineParts + '](' + lineParts.length + ')'); + if (!foundVersions.includes(lineParts[0])) { + // add only non-duplicates + foundVersions.push(lineParts[0]); + } + } + } + } + } + //console.log('* foundVersions=[' + foundVersions + ']'); + return foundVersions; + } + + private _getRelativeTimeSinceUpdate(): [string, number] { + const stateObj = this._config.entity ? this.hass.states[this._config.entity] : undefined; + let desiredValue: string = ''; + let desiredMinutes: number = 0; + let minutesValue: string = ''; + if (this.hass.locale != undefined && stateObj != undefined) { + try { + const stateStrInterp = computeStateDisplay(this.hass?.localize, stateObj, this.hass.locale); + // console.log('- grtsu card stateStrInterp=[' + stateStrInterp + ']'); + const relativeInterp = stateStrInterp === undefined ? '{unknown}' : this.prettyDate(stateStrInterp); + // console.log(' relativeInterp=[' + relativeInterp + ']'); + desiredValue = this._sensorAvailable ? relativeInterp : '{unknown}'; + // console.log(' desiredValue=[' + desiredValue + ']'); + const lineParts: string[] = relativeInterp.split(' '); + minutesValue = lineParts[0]; + } catch (error) { + console.log('GRTSU - exception:'); + console.error(error); + } + + if (minutesValue.includes('just') || minutesValue.includes('unknown')) { + desiredMinutes = 0; + } else { + desiredMinutes = Number(minutesValue); + } + } + return [desiredValue, desiredMinutes]; + } + private _getIconNameForPercent(percent: string): string { // return name of icon we should show for given % let desiredIconName = ''; @@ -840,11 +936,10 @@ export class RPiMonitorCard extends LitElement { return desiredIconName; } - private _computeReporterAgeColor(numberValue: number): unknown { + private _computeReporterAgeColor(numberValue: number): string { const sections = this._colorReportPeriodsAgoDefault; - //console.log('color-table: sections='); - //console.log(sections); + //console.log('color-table: sections=[' + sections + ']'); //return ''; let color: undefined | string = undefined; @@ -855,17 +950,16 @@ export class RPiMonitorCard extends LitElement { } }); - if (color === undefined) color = ''; + if (color == undefined || color == 'default') color = ''; return color; } - private _computeTemperatureColor(value: string): unknown { + private _computeTemperatureColor(value: string): string { const config = this._config; const numberValue = Number(value); const sections = config.temp_severity ? config.temp_severity : this._colorTemperatureDefault; - //console.log('color-table: sections='); - //console.log(sections); + //console.log('color-table: sections=[' + sections + ']'); //return ''; let color: undefined | string; @@ -874,27 +968,27 @@ export class RPiMonitorCard extends LitElement { sections.forEach((section) => { if (numberValue >= section.from && numberValue <= section.to) { color = section.color; - const logMessage = - '_computeTemperatureColor() - value=[' + - value + - '] matched(from=' + - section.from + - ', to=' + - section.to + - ', color=' + - color + - ')'; if (this._showDebug()) { + const logMessage = + '_computeTemperatureColor() - value=[' + + value + + '] matched(from=' + + section.from + + ', to=' + + section.to + + ', color=' + + color + + ')'; console.log(logMessage); } } }); } - const logMessage = '_computeTemperatureColor() - value=[' + value + '] returns(color=' + color + ')'; if (this._showDebug()) { + const logMessage = '_computeTemperatureColor() - value=[' + value + '] returns(color=' + color + ')'; console.log(logMessage); } - if (color == undefined) color = ''; + if (color == undefined || color == 'default') color = ''; return color; } @@ -912,28 +1006,28 @@ export class RPiMonitorCard extends LitElement { sections.forEach((section) => { if (numberValue >= section.from && numberValue <= section.to) { color = section.color; - const logMessage = - '_computeFileSystemUsageColor() - value=[' + - value + - '] matched(from=' + - section.from + - ', to=' + - section.to + - ', color=' + - color + - ')'; if (this._showDebug()) { + const logMessage = + '_computeFileSystemUsageColor() - value=[' + + value + + '] matched(from=' + + section.from + + ', to=' + + section.to + + ', color=' + + color + + ')'; console.log(logMessage); } } }); } - const logMessage = '_computeFileSystemUsageColor() - value=[' + value + '] returns(color=' + color + ')'; if (this._showDebug()) { + const logMessage = '_computeFileSystemUsageColor() - value=[' + value + '] returns(color=' + color + ')'; console.log(logMessage); } - if (color == undefined) color = ''; + if (color == undefined || color == 'default') color = ''; return color; } @@ -948,56 +1042,86 @@ export class RPiMonitorCard extends LitElement { sections.forEach((section) => { if (numberValue >= section.from && numberValue <= section.to) { color = section.color; - const logMessage = - '_computeMemoryUsageColor() - value=[' + - value + - '] matched(from=' + - section.from + - ', to=' + - section.to + - ', color=' + - color + - ')'; if (this._showDebug()) { + const logMessage = + '_computeMemoryUsageColor() - value=[' + + value + + '] matched(from=' + + section.from + + ', to=' + + section.to + + ', color=' + + color + + ')'; console.log(logMessage); } } }); } - const logMessage = '_computeMemoryUsageColor() - value=[' + value + '] returns(color=' + color + ')'; if (this._showDebug()) { + const logMessage = '_computeMemoryUsageColor() - value=[' + value + '] returns(color=' + color + ')'; console.log(logMessage); } - if (color == undefined) color = ''; + if (color == undefined || color == 'default') color = ''; return color; } - private _computeOsReleaseColor(osName: string): unknown { + private _computeOsReleaseColor(osName: string): string { const config = this._config; const sections = config.os_age ? config.os_age : this._colorReleaseDefault; - //console.log('color-table: sections='); - //console.log(sections); + //console.log('color-table: sections=[' + sections + ']'); //return ''; - let color: undefined | string = undefined; + let color: undefined | string = 'default'; sections.forEach((section) => { if (osName === section.os) { color = section.color; - const logMessage = - '_computeOsReleaseColor() - value=[' + osName + '] matched(os=' + section.os + ', color=' + color + ')'; if (this._showDebug()) { + const logMessage = + '_computeOsReleaseColor() - value=[' + osName + '] matched(os=' + section.os + ', color=' + color + ')'; console.log(logMessage); } } }); - const logMessage = '_computeTemperatureColor() - value=[' + osName + '] returns(color=' + color + ')'; if (this._showDebug()) { + const logMessage = '_computeOsReleaseColor() - value=[' + osName + '] returns(color=' + color + ')'; + console.log(logMessage); + } + if (color == undefined || color == 'default') color = ''; + return color; + } + + private _computeDaemonUpdateVersionColor(currentReporterVersion: string): string { + //console.log('color-table: sections=[' + sections + ']'); + //return ''; + + let color: undefined | string = undefined; + + if (this.latestDaemonVersions.length > 0 && currentReporterVersion != '') { + if (this.latestDaemonVersions[0] == currentReporterVersion) { + // daemon is at latest + color = 'default'; + } else if (this.latestDaemonVersions.includes(currentReporterVersion)) { + // daemon is recent + color = 'yellow'; + } else { + // daemon is old (not even in latest or stable) + color = 'red'; + } + } else { + // daemon values are missing??? + color = 'orange'; + } + if (this._showDebug()) { + const logMessage = + '_computeDaemonUpdateVersionColor() - value=[' + currentReporterVersion + '] returns(color=' + color + ')'; console.log(logMessage); } - if (color == undefined) color = ''; + + if (color == undefined || color == 'default') color = ''; return color; } @@ -1157,10 +1281,10 @@ export class RPiMonitorCard extends LitElement { private _getTemperatureScale(): string { const scaleInterp = this._useTempsInC() == true ? 'ºC' : 'ºF'; - const logMessage = '_getTemperatureScale() scaleInterp=(' + scaleInterp + ')'; - if (this._showDebug()) { - console.log(logMessage); - } + // if (this._showDebug()) { + // const logMessage = '_getTemperatureScale() scaleInterp=(' + scaleInterp + ')'; + // console.log(logMessage); + // } return scaleInterp; } @@ -1172,10 +1296,10 @@ export class RPiMonitorCard extends LitElement { interpValue = ((parseFloat(temperature_raw) * 9) / 5 + 32.0).toFixed(1); } } - const logMessage = '_getScaledTemperatureValue(' + temperature_raw + ') scaleInterp=(' + interpValue + ')'; - if (this._showDebug()) { - console.log(logMessage); - } + // if (this._showDebug()) { + // const logMessage = '_getScaledTemperatureValue(' + temperature_raw + ') scaleInterp=(' + interpValue + ')'; + // console.log(logMessage); + // } return interpValue; } @@ -1420,6 +1544,34 @@ export class RPiMonitorCard extends LitElement { font-size: 12px; color: var(--primary-text-color); } + .daemon-update-full { + position: absolute; + top: 45px; + right: 150px; + font-size: 12px; + color: var(--primary-text-color); + } + .daemon-update { + position: absolute; + top: 55px; + right: 150px; + font-size: 12px; + color: var(--primary-text-color); + } + .daemon-update-full-notitle { + position: absolute; + top: 3px; + right: 150px; + font-size: 12px; + color: var(--primary-text-color); + } + .daemon-update-notitle { + position: absolute; + bottom: 5px; + right: 210px; + font-size: 12px; + color: var(--primary-text-color); + } `; } } diff --git a/yarn.lock b/yarn.lock index 4d43212..ff0e281 100644 --- a/yarn.lock +++ b/yarn.lock @@ -982,9 +982,9 @@ integrity sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ== "@types/node@*": - version "18.11.19" - resolved "https://registry.yarnpkg.com/@types/node/-/node-18.11.19.tgz#35e26df9ec441ab99d73e99e9aca82935eea216d" - integrity sha512-YUgMWAQBWLObABqrvx8qKO1enAvBUdjZOAWQ5grBAkp5LQv45jBvYKZ3oFS9iKRCQyFjqw6iuEa1vmFqtxYLZw== + version "18.13.0" + resolved "https://registry.yarnpkg.com/@types/node/-/node-18.13.0.tgz#0400d1e6ce87e9d3032c19eb6c58205b0d3f7850" + integrity sha512-gC3TazRzGoOnoKAhUx+Q0t8S9Tzs74z7m0ipwGpSqQrleP14hKxP4/JUeEQcD3W1/aIpnWl8pHowI7WokuZpXg== "@types/resolve@1.17.1": version "1.17.1" @@ -1234,9 +1234,9 @@ callsites@^3.0.0: integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ== caniuse-lite@^1.0.30001449: - version "1.0.30001450" - resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001450.tgz#022225b91200589196b814b51b1bbe45144cf74f" - integrity sha512-qMBmvmQmFXaSxexkjjfMvD5rnDL0+m+dUMZKoDYsGG8iZN29RuYh9eRoMvKsT6uMAWlyUUGDEQGJJYjzCIO9ew== + version "1.0.30001451" + resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001451.tgz#2e197c698fc1373d63e1406d6607ea4617c613f1" + integrity sha512-XY7UbUpGRatZzoRft//5xOa69/1iGJRBlrieH6QYrkKLIFn3m7OVEJ81dSrKoy2BnKsdbX5cLrOispZNYo9v2w== chalk@^2.0.0: version "2.4.2" @@ -1318,7 +1318,7 @@ cross-spawn@^7.0.2: shebang-command "^2.0.0" which "^2.0.1" -custom-card-helpers@^1.7.2: +custom-card-helpers@^1.9.0: version "1.9.0" resolved "https://registry.yarnpkg.com/custom-card-helpers/-/custom-card-helpers-1.9.0.tgz#dac7bb7a531101f4c83096b26a8be8ccad70d8c0" integrity sha512-5IW4OXq3MiiCqDvqeu+MYsM1NmntKW1WfJhyJFsdP2tbzqEI4BOnqRz2qzdp08lE4QLVhYfRLwe0WAqgQVNeFg== @@ -1385,9 +1385,9 @@ doctrine@^3.0.0: esutils "^2.0.2" electron-to-chromium@^1.4.284: - version "1.4.286" - resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.286.tgz#0e039de59135f44ab9a8ec9025e53a9135eba11f" - integrity sha512-Vp3CVhmYpgf4iXNKAucoQUDcCrBQX3XLBtwgFqP9BUXuucgvAV9zWp1kYU7LL9j4++s9O+12cb3wMtN4SJy6UQ== + version "1.4.289" + resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.289.tgz#02b59b1096486fc0bd4871a0484d8317802c6658" + integrity sha512-relLdMfPBxqGCxy7Gyfm1HcbRPcFUJdlgnCPVgQ23sr1TvUrRJz0/QPoGP0+x41wOVSTN/Wi3w6YDgHiHJGOzg== emoji-regex@^8.0.0: version "8.0.0" @@ -2339,9 +2339,9 @@ natural-compare@^1.4.0: integrity sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw== node-releases@^2.0.8: - version "2.0.9" - resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.9.tgz#fe66405285382b0c4ac6bcfbfbe7e8a510650b4d" - integrity sha512-2xfmOrRkGogbTK9R6Leda0DGiXeY3p2NJpy4+gNCffdUvV6mdEJnaDEic1i3Ec2djAo8jWYoJMR5PB0MSMpxUA== + version "2.0.10" + resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.10.tgz#c311ebae3b6a148c89b1813fd7c4d3c024ef537f" + integrity sha512-5GFldHPXVG/YZmFzJvKK2zDSzPKhEp0+ZR5SVaoSag9fsL5YgHbUHDfnG5494ISANDcK4KwPXAx2xqVEydmd7w== object-inspect@^1.12.2, object-inspect@^1.9.0: version "1.12.3" @@ -2486,9 +2486,9 @@ prettier-linter-helpers@^1.0.0: fast-diff "^1.1.2" prettier@^2.4.1: - version "2.8.3" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.8.3.tgz#ab697b1d3dd46fb4626fbe2f543afe0cc98d8632" - integrity sha512-tJ/oJ4amDihPoufT5sM0Z1SKEuKay8LfVAMlbbhnnkvt6BUserZylqo2PN+p9KeljLr0OHa2rXHU1T8reeoTrw== + version "2.8.4" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.8.4.tgz#34dd2595629bfbb79d344ac4a91ff948694463c3" + integrity sha512-vIS4Rlc2FNh0BySk3Wkd6xmwxB0FpOndW5fisM5H8hsZSxU2VWVB5CWIkIjWvrHjIhxk2g3bfMKM87zNTrZddw== progress@^2.0.0: version "2.0.3"