Issue with catching sensor state "unknown"

I have a sensor which might have status “unknown” at HA start. To catch this I’ve created in template.yaml:

- sensor:

      - name: "Batterie entladen Monat"

        device_class: energy

        unit_of_measurement: "kWh"          

        state: >  

            {% if is_state('sensor.month_batt_discharge', 'unknown') %}                                  

              0                              

            {% elif states('sensor.month_batt_discharge') | float > 1000 %}

              {% set state = states('sensor.month_batt_discharge') %}{{ (state | float / 1000 | round (1, default=0) if is_number(state))}}

            {% else %}

              {% set state = states('sensor.month_batt_discharge') %}{{ (state | float / 1000 | round (3, default=0) if is_number(state))}}

            {% endif %}

which works fine in developer tools, means I see a “0” when setting entity state to unknown. But at HA config reload I get error in log like:

Error while processing template: Template("{% if is_state('sensor.month_batt_charge', 'unknown') %} 0 {% elif states('sensor.month_batt_charge') | float > 1000 %} {% set state = states('sensor.month_batt_charge') %}{{ (state | float / 1000 | round (1, default=0) if is_number(state))}} {% else %} {% set state = states('sensor.month_batt_charge') %}{{ (state | float / 1000 | round (3, default=0) if is_number(state))}} {% endif %}")
Error while processing template: Template("{% if is_state('sensor.month_batt_discharge', 'unknown') %} 0 {% elif states('sensor.month_batt_discharge') | float > 1000 %} {% set state = states('sensor.month_batt_discharge') %}{{ (state | float / 1000 | round (1, default=0) if is_number(state))}} {% else %} {% set state = states('sensor.month_batt_discharge') %}{{ (state | float / 1000 | round (3, default=0) if is_number(state))}} {% endif %}")
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 1771, in forgiving_float_filter
    return float(value)
ValueError: could not convert string to float: 'unknown'

Try this version:

  - sensor:
      - name: "Batterie entladen Monat"
        device_class: energy
        unit_of_measurement: "kWh"          
        state: >  
          {% set s = states('sensor.month_batt_discharge') %}           
          {% if s | is_number %}
            {% set s = s | float(0) %}
            {{ (s / 1000) | round(iif(s > 1000, 1, 3), default=0) }}
          {% else %}
            0
          {% endif %}

Indeed this works fine. Thanks very much, if was very helpful.

1 Like