Add template support

This commit is contained in:
thomas committed 2020-01-09 22:03:50 +01:00
1 parent f4d1b54579
commit 906869a37c
3 files changed
+79 -13

No files matched your search

+49 -4
View File
@@ -25,6 +25,7 @@ entities:
- <entity>
- <entity>
filter:
template: <template>
include:
- <filter>
- <filter>
@@ -42,14 +43,15 @@ sort: <sort_method>
- `card:` **Required.** The card to display. Specify this as you would specify any normal lovelace card, but ommit the `entities:` parameter.
- `entities:` Any entities added here will be added to the card before any filters are applied.
- `filter:`
- `include:` **Required.** A list of filters specifying which entities to add to the card
- `template:` A jinja2 template evaluating to a whitespace- or comma-separated list of entity ids to include
- `include:` A list of filters specifying which entities to add to the card
- `exclude:` A list of filters specifying which entities to remove from the card
- `show_empty:` Whether to display the card if it has no entities. Default: `true`.
- `unique:` Whether to remove duplicate values after filtering and sorting. Default: `false`.
- `sort:` How to sort the entities of the card. Default: `none`. See [Sorting entities for details](#sorting-entities)
### Filters
The two filter sections `include` and `exclude` each takes a list of filters.
The two main filter sections `include` and `exclude` each takes a list of filters.
Filters have the following options, and will match any entity fulfilling **ALL** options:
@@ -70,11 +72,17 @@ Special options:
- `not:` Specifies a filter that entities must *not* match.
- `sort:` Specifies a method to sort entities matched by *this filter only*.
### Template filter
The filter section `template` takes a jinja2 template which evaluates to a list of comma- or whitespace separated `entity_id`s which are included.
> Note: Due to how the templating engine of Home Assistant works, this may or may not be as useful as it sounds. See note at templating example below.
## How it works
`auto-entities` creates a list of entities by:
1. Including every entitiy given in `entities:` (this allow nesting of `auto-entities`if you'd want to do that for some reason...)
2. Include all entities that matches **ALL** options of **ANY** filter in the `filter.include` section. The same entity may be included several times by different filters.
3. Remove all entities that matches **ALL** options on **ANY** filter in the `filter.exclude` section.
2. Include every entity listed in a `filter.template` evaluation
3. Include all entities that matches **ALL** options of **ANY** filter in the `filter.include` section. The same entity may be included several times by different filters.
4. Remove all entities that matches **ALL** options on **ANY** filter in the `filter.exclude` section.
It then creates a card based on the configuration given in `card:`, and fills in `entities:` of that card with the entities from above.
@@ -296,5 +304,42 @@ filter:
entity_id: this.entity_id
```
Example using templates:
```yaml
type: custom:auto-entities
card:
type: entities
filter:
template: |
{% for light in states.light %}
{% if light.state == "on" %}
{{ light.entity_id}},
{% endif %}
{% endfor %}
```
> Note: templates won't update automatically on state changes unless they contain the literal entity id of the entity whose state changes.
> I.e. the example above will not update when a light is turned on or off, unless the view is reloaded.
>
> This is a limitation of the Home Assistant template engine, and nothing I can do anything about. There are, however two mitigations you could make.
>
> One is to redefine the template, e.g.:
> ```yaml
> template: |
> {%if is_state('light.bed_light','on')%}light.bed_light{%endif%}
> {%if is_state('light.kitchen_lights','on')%}light.kitchen_lights{%endif%}
> {%if is_state('light.ceiling_lights','on')%}light.ceiling_lights{%endif%}
> ```
>
> The other option is to add a list of entities to monitor:
> ```yaml
> filter:
> template: |
> ...etc...
> entity_ids:
> - light.bed_light
> - light.kitchen_lights
> - light.ceiling_lights
> ```
---
<a href="https://www.buymeacoffee.com/uqD6KHCdJ" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/white_img.png" alt="Buy Me A Coffee" style="height: auto !important;width: auto !important;" ></a>
+1 -1
View File
@@ -1,2 +1,2 @@
!function(t){var e={};function i(s){if(e[s])return e[s].exports;var r=e[s]={i:s,l:!1,exports:{}};return t[s].call(r.exports,r,r.exports,i),r.l=!0,r.exports}i.m=t,i.c=e,i.d=function(t,e,s){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:s})},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.t=function(t,e){if(1&e&&(t=i(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var s=Object.create(null);if(i.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)i.d(s,r,function(e){return t[e]}.bind(null,r));return s},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="",i(i.s=0)}([function(t,e,i){"use strict";i.r(e);const s=customElements.get("home-assistant-main")?Object.getPrototypeOf(customElements.get("home-assistant-main")):Object.getPrototypeOf(customElements.get("hui-view")),r=s.prototype.html;s.prototype.css;function n(){return document.querySelector("home-assistant").hass}const a=n().callWS({type:"config/area_registry/list"}),o=n().callWS({type:"config/device_registry/list"}),c=n().callWS({type:"config/entity_registry/list"});async function u(){return window.cardToolsData=window.cardToolsData||{areas:await a,devices:await o,entities:await c},window.cardToolsData}function l(t){const e=window.cardToolsData;let i=[];if(!t)return i;for(const s of e.devices)s.area_id===t.area_id&&i.push(s);return i}function f(t){const e=window.cardToolsData;let i=[];if(!t)return i;for(const s of e.entities)s.device_id===t.id&&i.push(s.entity_id);return i}function d(t,e){if("string"==typeof e&&"string"==typeof t&&(t.startsWith("/")&&t.endsWith("/")||-1!==t.indexOf("*"))){return t.startsWith("/")||(t=`/^${t=t.replace(/\./g,".").replace(/\*/g,".*")}$/`),new RegExp(t.slice(1,-1)).test(e)}if("string"==typeof t){if(t.startsWith("<="))return parseFloat(e)<=parseFloat(t.substr(2));if(t.startsWith(">="))return parseFloat(e)>=parseFloat(t.substr(2));if(t.startsWith("<"))return parseFloat(e)<parseFloat(t.substr(1));if(t.startsWith(">"))return parseFloat(e)>parseFloat(t.substr(1));if(t.startsWith("!"))return parseFloat(e)!=parseFloat(t.substr(1));if(t.startsWith("="))return parseFloat(e)==parseFloat(t.substr(1))}return t===e}function h(t,e){return function(i){const s="string"==typeof i?t.states[i]:t.states[i.entity];if(!i)return!1;for(const[r,n]of Object.entries(e))switch(r.split(" ")[0]){case"options":case"sort":break;case"domain":if(!d(n,s.entity_id.split(".")[0]))return!1;break;case"entity_id":if(!d(n,s.entity_id))return!1;break;case"state":if(!d(n,s.state))return!1;break;case"name":if(!s.attributes.friendly_name||!d(n,s.attributes.friendly_name))return!1;break;case"group":if(!(n.startsWith("group.")&&t.states[n]&&t.states[n].attributes.entity_id&&t.states[n].attributes.entity_id.includes(s.entity_id)))return!1;break;case"attributes":for(const[t,e]of Object.entries(n)){let i=t.trim(),r=s.attributes;for(;i&&r;){let t;[t,i]=i.split(":"),r=r[t]}if(void 0===r||void 0!==e&&!d(e,r))return!1}break;case"not":if(h(t,n)(i))return!1;break;case"device":if(!window.cardToolsData||!window.cardToolsData.devices)return!1;let e=!1;for(const t of window.cardToolsData.devices)d(n,t.name)&&f(t).includes(s.entity_id)&&(e=!0);if(!e)return!1;break;case"area":if(!window.cardToolsData||!window.cardToolsData.areas)return!1;let r=!1;for(const t of window.cardToolsData.areas)d(n,t.name)&&l(t).flatMap(f).includes(s.entity_id)&&(r=!0);if(!r)return!1;break;case"last_changed":if(!d(n,((new Date).getTime()-new Date(s.last_changed).getTime())/6e4))return!1;break;case"last_updated":if(!d(n,((new Date).getTime()-new Date(s.last_updated).getTime())/6e4))return!1;break;default:return!1}return!0}}function g(t,e){return"string"==typeof e&&(e={method:e}),function(i,s){const r="string"==typeof i?t.states[i]:t.states[i.entity],n="string"==typeof s?t.states[s]:t.states[s.entity];if(void 0===r||void 0===n)return 0;const[a,o]=e.reverse?[-1,1]:[1,-1];function c(t,i){return e.ignore_case&&t.toLowerCase&&(t=t.toLowerCase()),e.ignore_case&&i.toLowerCase&&(i=i.toLowerCase()),e.numeric&&(isNaN(parseFloat(t))&&isNaN(parseFloat(i))||(t=isNaN(parseFloat(t))?void 0:parseFloat(t),i=isNaN(parseFloat(i))?void 0:parseFloat(i))),void 0===t&&void 0===i?0:void 0===t?a:void 0===i?o:t<i?o:t>i?a:0}switch(e.method){case"domain":return c(r.entity_id.split(".")[0],n.entity_id.split(".")[0]);case"entity_id":return c(r.entity_id,n.entity_id);case"friendly_name":case"name":return c(r.attributes.friendly_name||r.entity_id.split(".")[1],n.attributes.friendly_name||n.entity_id.split(".")[1]);case"state":return c(r.state,n.state);case"attribute":let t=r.attributes,i=n.attributes,s=e.attribute;for(;s;){let e;if([e,s]=s.split(":"),t=t[e],i=i[e],void 0===t&&void 0===i)return 0;if(void 0==Line truncated
!function(t){var e={};function i(s){if(e[s])return e[s].exports;var r=e[s]={i:s,l:!1,exports:{}};return t[s].call(r.exports,r,r.exports,i),r.l=!0,r.exports}i.m=t,i.c=e,i.d=function(t,e,s){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:s})},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.t=function(t,e){if(1&e&&(t=i(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var s=Object.create(null);if(i.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)i.d(s,r,function(e){return t[e]}.bind(null,r));return s},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="",i(i.s=0)}([function(t,e,i){"use strict";i.r(e);const s=customElements.get("home-assistant-main")?Object.getPrototypeOf(customElements.get("home-assistant-main")):Object.getPrototypeOf(customElements.get("hui-view")),r=s.prototype.html;s.prototype.css;function n(){return document.querySelector("home-assistant").hass}const a=n().callWS({type:"config/area_registry/list"}),o=n().callWS({type:"config/device_registry/list"}),l=n().callWS({type:"config/entity_registry/list"});async function c(){return window.cardToolsData=window.cardToolsData||{areas:await a,devices:await o,entities:await l},window.cardToolsData}function u(t){const e=window.cardToolsData;let i=[];if(!t)return i;for(const s of e.devices)s.area_id===t.area_id&&i.push(s);return i}function f(t){const e=window.cardToolsData;let i=[];if(!t)return i;for(const s of e.entities)s.device_id===t.id&&i.push(s.entity_id);return i}function d(t,e){if("string"==typeof e&&"string"==typeof t&&(t.startsWith("/")&&t.endsWith("/")||-1!==t.indexOf("*"))){return t.startsWith("/")||(t=`/^${t=t.replace(/\./g,".").replace(/\*/g,".*")}$/`),new RegExp(t.slice(1,-1)).test(e)}if("string"==typeof t){if(t.startsWith("<="))return parseFloat(e)<=parseFloat(t.substr(2));if(t.startsWith(">="))return parseFloat(e)>=parseFloat(t.substr(2));if(t.startsWith("<"))return parseFloat(e)<parseFloat(t.substr(1));if(t.startsWith(">"))return parseFloat(e)>parseFloat(t.substr(1));if(t.startsWith("!"))return parseFloat(e)!=parseFloat(t.substr(1));if(t.startsWith("="))return parseFloat(e)==parseFloat(t.substr(1))}return t===e}function h(t,e){return function(i){const s="string"==typeof i?t.states[i]:t.states[i.entity];if(!i)return!1;for(const[r,n]of Object.entries(e))switch(r.split(" ")[0]){case"options":case"sort":break;case"domain":if(!d(n,s.entity_id.split(".")[0]))return!1;break;case"entity_id":if(!d(n,s.entity_id))return!1;break;case"state":if(!d(n,s.state))return!1;break;case"name":if(!s.attributes.friendly_name||!d(n,s.attributes.friendly_name))return!1;break;case"group":if(!(n.startsWith("group.")&&t.states[n]&&t.states[n].attributes.entity_id&&t.states[n].attributes.entity_id.includes(s.entity_id)))return!1;break;case"attributes":for(const[t,e]of Object.entries(n)){let i=t.trim(),r=s.attributes;for(;i&&r;){let t;[t,i]=i.split(":"),r=r[t]}if(void 0===r||void 0!==e&&!d(e,r))return!1}break;case"not":if(h(t,n)(i))return!1;break;case"device":if(!window.cardToolsData||!window.cardToolsData.devices)return!1;let e=!1;for(const t of window.cardToolsData.devices)d(n,t.name)&&f(t).includes(s.entity_id)&&(e=!0);if(!e)return!1;break;case"area":if(!window.cardToolsData||!window.cardToolsData.areas)return!1;let r=!1;for(const t of window.cardToolsData.areas)d(n,t.name)&&u(t).flatMap(f).includes(s.entity_id)&&(r=!0);if(!r)return!1;break;case"last_changed":if(!d(n,((new Date).getTime()-new Date(s.last_changed).getTime())/6e4))return!1;break;case"last_updated":if(!d(n,((new Date).getTime()-new Date(s.last_updated).getTime())/6e4))return!1;break;default:return!1}return!0}}function g(t,e){return"string"==typeof e&&(e={method:e}),function(i,s){const r="string"==typeof i?t.states[i]:t.states[i.entity],n="string"==typeof s?t.states[s]:t.states[s.entity];if(void 0===r||void 0===n)return 0;const[a,o]=e.reverse?[-1,1]:[1,-1];function l(t,i){return e.ignore_case&&t.toLowerCase&&(t=t.toLowerCase()),e.ignore_case&&i.toLowerCase&&(i=i.toLowerCase()),e.numeric&&(isNaN(parseFloat(t))&&isNaN(parseFloat(i))||(t=isNaN(parseFloat(t))?void 0:parseFloat(t),i=isNaN(parseFloat(i))?void 0:parseFloat(i))),void 0===t&&void 0===i?0:void 0===t?a:void 0===i?o:t<i?o:t>i?a:0}switch(e.method){case"domain":return l(r.entity_id.split(".")[0],n.entity_id.split(".")[0]);case"entity_id":return l(r.entity_id,n.entity_id);case"friendly_name":case"name":return l(r.attributes.friendly_name||r.entity_id.split(".")[1],n.attributes.friendly_name||n.entity_id.split(".")[1]);case"state":return l(r.state,n.state);case"attribute":let t=r.attributes,i=n.attributes,s=e.attribute;for(;s;){let e;if([e,s]=s.split(":"),t=t[e],i=i[e],void 0===t&&void 0===i)return 0;if(void 0==Line truncated
${this.card}`}getCardSize(){let t=0;return this.card&&this.card.getCardSize&&(t=this.card.getCardSize()),1===t&&this.entities.length&&(t=this.entities.length),0===t&&this._config.filter&&this._config.filter.include&&(t=Object.keys(this._config.filter.include).length),t||1}}),p("ll-rebuild",{})}]);
+29 -8
View File
@@ -5,6 +5,7 @@ import { getData } from "card-tools/src/devices";
import { fireEvent } from "card-tools/src/event";
import { createCard } from "card-tools/src/lovelace-element";
import { hass } from "card-tools/src/hass";
import {subscribeRenderTemplate} from "card-tools/src/templates";
class AutoEntities extends LitElement {
@@ -28,6 +29,19 @@ class AutoEntities extends LitElement {
this._config = config;
this.hass = this.hass;
}
if(config.filter && config.filter.template) {
this.template = "";
if(String(config.filter.template).includes("{%") || String(config.filter.template).includes("{{")) {
subscribeRenderTemplate(null, (res) => {
this.template = res;
this._getEntities();
}, {
template: config.filter.template,
variables: {config},
entity_ids: config.filter.entity_ids,
});
}
}
// Reevaluate all filters once areas have been loaded
getData().then(() => this._getEntities());
@@ -35,21 +49,28 @@ class AutoEntities extends LitElement {
_getEntities()
{
const format_entities = (e) => {
if(!e) return null;
if(typeof(e) === "string")
return {entity: e.trim()}
return e;
}
let entities = [];
// Start with any entities added by the `entities` parameter
if(this._config.entities)
entities = entities.concat(this._config.entities)
.map((e) => {
if(typeof(e) === "string")
return {entity: e};
return e;
});
entities = entities.concat(this._config.entities.map(format_entities));
if(!this.hass || !this._config.filter) return entities;
if(this.template) {
entities = entities.concat(this.template.split(/[\s,]+/).map(format_entities));
}
entities = entities.filter(Boolean);
if(this._config.filter.include) {
const all_entities = Object.keys(this.hass.states)
.map((e) => new Object({entity: e}));
const all_entities = Object.keys(this.hass.states).map(format_entities);
for(const f of this._config.filter.include) {
if(f.type !== undefined) {