Goal: to create sensors which count the number of lights on in each area that has been set up.
My intent is to use this to set up custom area buttons with dynamic labels.
Using the developer tools > template you can generate the appropriate YAML to create “light on” sensors.
{% set ns = namespace(areas=[], lights= expand(
states.light|selectattr('name','ne','All'),
) | list) %}
{% for elm in ns.lights if not area_id(elm.entity_id) in ns.areas%}
{% set ns.areas = ns.areas + [area_id(elm.entity_id)] %}
{%- endfor %}
{% for elm in ns.areas %}
template:
- sensor:
- name: {{elm | replace ('_', ' ') | title}} Lights On
state: >
{% raw %}{%{% endraw %} set {{ elm }}_lights_on = expand(area_entities('{{ elm | capitalize }}')) | selectattr('domain','eq','light') | selectattr('state','eq','on') | list | count {% raw %}%}{% endraw %}
{% raw %}{{{% endraw %}{{ elm}}_lights_on{% raw %}}}{% endraw %}
{% endfor %}
Result:
template:
- sensor:
- name: Attic Lights On
state: >
{% set attic_lights_on = expand(area_entities('Attic')) | selectattr('domain','eq','light') | selectattr('state','eq','on') | list | count %}
{{attic_lights_on}}
template:
- sensor:
- name: Kitchen Lights On
state: >
{% set kitchen_lights_on = expand(area_entities('Kitchen')) | selectattr('domain','eq','light') | selectattr('state','eq','on') | list | count %}
{{kitchen_lights_on}}
template:
- sensor:
- name: Front Porch Lights On
state: >
{% set front_porch_lights_on = expand(area_entities('Front_porch')) | selectattr('domain','eq','light') | selectattr('state','eq','on') | list | count %}
{{front_porch_lights_on}}
...
template:
- sensor:
{%- for a in states.light | map(attribute='entity_id') | map('area_name') | unique | list %}
- name: {{ a | title }} Lights On
state: >
{% raw %}{{ expand(area_entities('{% endraw %}{{ a }}'{% raw %}) | select('match', 'light')) | selectattr('state','eq','on') | list | count }}{% endraw %}
{%- endfor -%}
Im struggling to get this to work.
If I past the code into Developer Tools > Template, It works
But whilst trying to create a sensor Ive tried so many different things but no joy.
Ive added the line template: !include templates.yaml in my configuration file and created the template folder and restarted HA - all was good there.
When I try to add the code I just cant get it to format correctly, any ideas please.
You have misunderstood the purpose of this template. The template cannot be used directly in your configuration. Instead, it is meant to be used only in the Template editor, then you copy the output and paste that into your configuration.
Are you sure…? Here is an example of the author of that post giving the same advice I am giving you for a very similar question last month:
What Taras provided in his post above is a cleaner and properly formatted version of the top post. In that top post OP specifically states the use case for this template: