Creating Template Sensor

Ok, I don’t typicaly use template sensors as I just haven’t had the need.

Does it create an entity when you create one?

I cannot get this to work.

I created the file sensors.yaml

Added to my config
sensor: !include sensors.yaml

Within sensors.yaml

- platform: template
  sensors:
    count_of_speakers_on:
      friendly_name: Count of Speakers On
      unit_of_measurement: 'on'
      value_template: "{{ states|selectattr('entity_id','in',state_attr('group.all_avr_speakers','entity_id'))|selectattr('state','eq','on')|list|count }}"
1 Like

Yes

As always though:

  1. Run a config check command after editing YAML
  2. Test any templates in Developer tools → Templates
  3. Reload the integration (where supported) or restart HA
  4. If things don’t work, check the log file

Got it, there was an old sensor in my config file that I didn’t know was there. Removed and all is good.

Your template monitors more entities than is necessary. The template begins with states which means Home Assistant will listen for state-changes of all entities in your system. Your template is actually only interested in the state-changes of the entities contained within the group.

The following template performs the same function but focuses exclusively on the group’s members:

- platform: template
  sensors:
    count_of_speakers_on:
      friendly_name: Count of Speakers On
      unit_of_measurement: 'on'
      value_template: "{{ expand('group.all_avr_speakers')|selectattr('state','eq','on')|list|count }}"

FWIW, I use this method to create several Template Sensors that report open doors, unlocked locks, illuminated lights, active appliances, etc. In my case, the entity’s state reports the names of the active entities (comma-separated) and an attribute reports the quantity.

Example:

    appliances_on:
      friendly_name: 'Active Appliances'
      value_template: >
        {{ expand('group.appliances_all')
          | selectattr('state', 'eq', 'on')
          | map(attribute='name')
          | list | join(', ') }}
      attribute_templates:
        qty: >
          {{ expand('group.appliances_all')
          | selectattr('state', 'eq', 'on') 
          | list | count }}

Thx…I will keep that in mind for the future.

… and if there’s any doubt in your mind, simple paste your template into the Template Editor and observe the last line in the results pane. It will report:

This template listens for all state changed events.

Screenshot:

Screenshot from 2021-01-27 17-35-04

1 Like