Template binary_sensor using weather

Hi,

I have the following template for binary_sensor:

template:
  - binary_sensor:
      - name: "Previsão de chuva nas próximas horas"
        icon: mdi:weather-pouring
        state: >-
           {% set c = namespace(chuva = false) %}
           {% for hora in state_attr("weather.damha_vi_hourly", "forecast")[:4] %}
             {% if hora.condition == "lightning_rainy" or hora.condition == "pouring" or hora.condition == "rainy" %}
               {% set c.chuva = true %}
             {% endif %}
           {% endfor %}
           {{ c.chuva }}

When I restart HA, I see no error on log, but it never finishes starting… It keeps saying that not all entities are already available. If I remove this template from configuration, HA starts with no problem or delay.

Is there anything wrong with this template?

Thanks

Probably because on startup Home Assistant loads the Template Binary Sensor first but weather.damha_vi_hourly isn’t ready yet, so it waits (and waits and waits).


Try adding an availability template to ensure weather.damha_vi_hourly is available before the state template is evaluated.

template:
  - binary_sensor:
      - name: "Previsão de chuva nas próximas horas"
        icon: mdi:weather-pouring
        availability: "{{ states('weather.damha_vi_hourly') not in ['unavailable', 'unknown'] }}"
        state: >-
           {% set c = namespace(chuva = false) %}
           {% for hora in state_attr("weather.damha_vi_hourly", "forecast")[:4] %}
             {% if hora.condition == "lightning_rainy" or hora.condition == "pouring" or hora.condition == "rainy" %}
               {% set c.chuva = true %}
             {% endif %}
           {% endfor %}
           {{ c.chuva }}

You nailed it! :slight_smile:

It is working like a charm now. Thanks

1 Like