Icon template not behaving

I get, “Could not render template Harmony Family Activity, the state is unknown” in the logs when HA first comes up and the icons take a varied amount to show up due to the entity not being ready.

- platform: template
  sensors:
    family_activity:
      friendly_name: 'Harmony Family'
      entity_id: remote.family_room
      value_template: '{{ states.remote.family_room.attributes.current_activity }}'
      icon_template: >
        {% if is_state_attr('remote.family_room', 'current_activity', 'Dish') %} mdi:satellite-uplink
          {% elif is_state_attr('remote.family_room', 'current_activity', 'Xbox') %} mdi:xbox
          {% elif is_state_attr('remote.family_room', 'current_activity', 'Roku') %} mdi:alpha-r-box-outline
          {% elif is_state_attr('remote.family_room', 'current_activity', 'Blu-ray') %} mdi:disc-player
          {% elif is_state_attr('remote.family_room', 'current_activity', 'TV') %} mdi:television-classic
          {% elif is_state_attr('remote.family_room','current_activity', 'PowerOff') %} mdi:power-plug-off
        {% endif %}

EDIT: I’m sure there is a more elegant solution, but this works;

  value_template: >
    {% if '' in states.remote.family_room.state %}
      '{{ states.remote.family_room.attributes.current_activity }}'
    {% endif %}

As you surmised, the entity’s state is probably unknown upon startup when the template sensor is first evaluated. However, the error message is produced because of this:

value_template: '{{ states.remote.family_room.attributes.current_activity }}'

When you explicitly request an entity’s state or attribute, whose value is unknown, the evaluation halts and throws an error.

In contrast, if you use a function to request the entity’s state or attribute, whose value is unknown, the function returns None and evaluation continues.

value_template: "{{ state_attr('remote.family_room', 'current_activity') }}"

To make you code more fault-tolerant, it’s preferable to use the states and state-attr functions.

Regarding the icon_template, here’s another way to do it:

icon_template: >-
  {% set activities =
     { 'Dish':'mdi:satellite-uplink',
       'Xbox':'mdi:xbox',
       'Roku':'mdi:alpha-r-box-outline',
       'Blu-ray':'mdi:disc-player',
       'TV':'mdi:television-classic',
       'PowerOff':'mdi:power-plug-off',
       'None':'mdi:help-circle' } %}
  {% set current = state_attr('remote.family_room', 'current_activity') %}
  {% set icon = activities[current] if current in activities %}
  {{icon}}
1 Like

and that’s the difference between a programmer and a glommer

Thanks