Today, I learned how to create sensors that report the number of lights on in each room. Since the code is basically the same except for the room name/entity name, I wanted to minimize the duplication of code. I found a section in the docs on reusable templates so I followed that. Is there a more efficient way to implement this use case? Thanks!
I created a file called sensor.yaml and included in configuation.yaml:
sensor: !include sensor.yaml
I created a file called room_lights_on_count.jinja and put it in the config/custom_templates folder.
{% macro room_lights_on_count(search_area) %}
{%- set search_state = 'on' %}
{%- set ns = namespace(lights=[]) %}
{%- for light in states.light | selectattr('state','eq', search_state) if area_name(light.entity_id) == search_area %}
{%- set ns.lights = ns.lights + [ light.entity_id ] %}
{%- endfor %}
{{ ns.lights | count}}
{% endmacro %}
Here is what is inside the sensor.yaml file. I started with an implementation for two rooms just in case there is a better way.
Ah, with yaml anchors I only have to do the non-unique code once. I like it. I tried using unique_id in a custom component but it wouldn’t stick. Is this going to allow me to assign the sensor to an area? Where did you get the unique id from? Thanks! Lots of good stuff here.
YAML is new to me so I just want to be sure that I am understanding anchors. When I define an anchor with &settings, it sets that anchor to all yaml at the current level and below. Basically, everything up to the next entry that is higher in the hierarchy. I made this assertion because there is not an ending marker for the anchor.