Template Sensor shows "Unknown" - but it works in Dev Tools

I think something got messed up with entity names / IDs (in HA’s DB?) as I was doing some testing with my template sensors and some names/IDs were changed along the way.

I’ve got this template in my config:

  - name: "Owlet Battery"
    unique_id: "owlet_battery_ac000w123123123"
    state: >-
        {% if states.sensor.owlet_smart_sock_ac000w123123123 is not none %}
          '{{states.sensor.owlet_smart_sock_ac000w123123123.attributes.battery}}'
        {% else %}
          'unavailable'
        {% endif %}
    unit_of_measurement: '%'

If I copy and paste the “state” block into Dev Tools, it works and shows me a result which updates every 10 seconds (when the sensor’s attributes update). For example:

But, the Entity for the template sensor always says “Unknown”:

What I’ve tried so far:
Restarting HA - about 30 times.
Removing the integration (it is in HACS), deleting all config of it including all template sensors I had created for it, deleting the entities from the Entities page in Settings.
Restarted after this.
Reinstalled the integration. Restarted. Enabled it. Restarted. Confirmed the integration was working, the base sensor was working and it had the attributes.
Added the template sensors back. Restarted.
Still the same result.

I also tried adding a new template sensor, this one does the same thing, which is very confusing to me:

  - name: "Owlet Battery New"
    unique_id: "owlet_battery_ac000w123123123_new"
    state: >-
        {% if states.sensor.owlet_smart_sock_ac000w123123123 is not none %}
          '{{states.sensor.owlet_smart_sock_ac000w123123123.attributes.battery}}'
        {% else %}
          'unavailable'
        {% endif %}
    unit_of_measurement: '%'

'88' is not a number.
88 is a number.

See the quotes?

Remove the quotes around your template return variables.

secondly, don’t return unavailable, return None. It will automatically make the value unavailable. Make sure you don’t use quotes there either.

Or you could just use a different approach

  - name: "Owlet Battery New"
    unique_id: "owlet_battery_ac000w123123123_new"
    state: >
      {{ state_attr('sensor.owlet_smart_sock_ac000w123123123', 'battery') }}
    availability: >
      {{ state_attr('sensor.owlet_smart_sock_ac000w123123123', 'battery') | is_number }}
    unit_of_measurement: '%'
1 Like

Ouch.

Love the new approach too, I didn’t know about this before. I’ll be updating some other template sensors now too, thank you @petro.

1 Like