Making a template sensor, trying to work smarter

Hi All,

I’m trying to make a few sensors for displaying stuff on my dashboard. I feel that I want to make a smarter version of a list of lights that are turned on and a sensor with the count of lights that are on.

I have a working template sensor for a list of lights that are on:

      lights_turned_on:
          value_template: >
            {{ states.light 
              | rejectattr('state', 'eq', 'off')
              | rejectattr('entity_id', 'equalto', 'light.keuken_kookeiland_3')
              | rejectattr('entity_id', 'equalto', 'light.keuken_kookeiland_4')
              | selectattr('state','eq','on') 
              | map(attribute ='name')
              | list
            }}

If I make the same template sensor with the ‘count’ filter I get a number returned of the numerb of lights that are on. I then have to remember to modify both if something changes in my filtering. So I want to use the sensor sensor.lights_turned_on to provide the count. If I paste the following in Developer Tools > Template a list is returned (contained in another object i presume)

{{ (states.sensor 
  | selectattr('entity_id','eq','sensor.lights_turned_on') 
  | map(attribute ='state')
  | list  )
}}

So when I run this through the Count filter it returns 1. How (if at all possible) can I split this back into an object that I can count the number of lights within the sensor.
Other smart solutions are also welcome obviously.

Kind regards, Marcel

Just saw that I can remove | rejectattr('state', 'eq', 'off')

You can reduce the first template to this:

      lights_turned_on:
          value_template: >
            {{ states.light 
              | selectattr('state','eq','on')
              | rejectattr('entity_id', 'in', ['light.keuken_kookeiland_3', 'light.keuken_kookeiland_4'])
              | map(attribute ='name')
              | list
            }}

However, the problem with this template is that if you have many lights on, the length of the list may exceed the 255-character limit of the state value. In addition, a state value is always interpreted as a string so even though your template creates a list, it will be handled as a string.

The two limitations I just described do not exist for an entity’s attributes. Therefore it’s preferable to use this template to create a list that will be stored in a Template Sensor’s attribute. The same Template Sensor’s can be used to store the quantity of lights that are on in its state. In other words, one Template Sensor can contain both.

1 Like