Trigger template sensor is switching to unknown on reload

I have this template

  - trigger:
      - platform: state
        entity_id: sensor.weather_home_max_temp_today
      - platform: homeassistant
        event: start
      - platform: event
        event_type: event_template_reloaded
      - name: Weather Home Max Temp Today Zeit
        unique_id: unique_id_template_sensor_weather_home_max_temp_today_zeit
        state: |
          {% set max_zeit = namespace(foo=0) %}
          {% set for_break = namespace(foo=false) %}
          {% for my_item in state_attr('sensor.weather_home_hourly','forecast') if == false %}
            {% if as_datetime(my_item['datetime']).date() == now().date() %}
              {% if my_item['temperature']|float(0) == states('sensor.weather_home_max_temp_today')|float(0) %}
                {% set = my_item['datetime'] %}
                {% set = true %}
              {% else %}
                {% set = states('sensor.weather_home_max_temp_today_zeit') %}
              {% endif %}
            {% endif %}
          {% endfor %}
          {{ }}

But when the events start or reload are triggering this sensor, and values with

{% if my_item['temperature']|float(0) == states('sensor.weather_home_max_temp_today')|float(0) %}

are not there anymore, it sets to unknown.

But I expected that the state is restored during restart/reload (as it is a trigger sensor) and then the else-path would set to old/restored value. But it is not woking.

Where is my problem?

Your machine is slow (or too fast) and misses the event_template_reloaded trigger completely because the integration is reloading when the event is fired. I.e. your template isn’t loaded in the system to catch the event.

why are you even using trigger’s there? There’s no reason to with that template.

EDIT: Also, that template can be simplified.

      - name: Weather Home Max Temp Today Zeit
        unique_id: unique_id_template_sensor_weather_home_max_temp_today_zeit
        state: >
          {% set date = now().date() | string %}
          {% set max_today = states('sensor.weather_home_max_temp_today') | float %}
          {{ state_attr('sensor.weather_home_hourly','forecast') | selectattr('datetime', 'match', '^' ~ date) | selectattr('temperature','eq', max_today) | map(attribute='datetime') | first | default }}
        availability: >
          {{ state_attr('sensor.weather_home_hourly','forecast') is not none and states('sensor.weather_home_max_temp_today') | is_number }}

Thanks a lot for the ideas.

Don’t understand it. You say that the trigger event_template_reloaded is not working at all?

To have it restored after reboot. And so to have always a value, even if max today time is in the past.

Don’t get how this would work if max_today is in the past/not in forecast anymore.

No, it works. But you’re reloading templates and expecting a template to catch it… while it’s reloading.

Put the reload event in an automation and it’ll fire every time… because you aren’t reloading automations when the templates are reloading.

… but you’ll always have a value. the template will update when the source sensor updates. I’m assuming you created a template sensor that gets the forecast, correct?

the template I provided is literally no different than what you have. It’s just simplified code. What you’re doing before doesn’t really make sense at all. You’re iterating through hourly forecasts and matching it to a specific number if it’s today otherwise getting something in the future.

Is your goal to just get the max temperature? If yes, there are much simpler ways to do that.

Don’t understand. All my and your code is about to get the time of the max temperature. So no, I don’t want to get the max temperature (I have it already in the other sensor, you and I are using in the templates already), I only need the time of the max.

No. Because I have to (wanted) time of the max temperature of the whole today, even if it is in the past and not in the forecast anymore. And with yours I only have the time, if it is still in the forecast. This is the difference, where yours is currently not fitting my requirement.

I’m totally fine with other or better approaches and not to use the perhaps quick and dirty ones of me, but it should still deliver the wanted value: The time of the max temperature of the whole day (even it was in the past).

And what is between reboot and first update of the source sensor? E.g. let’s have the source sensor (whyever) only gets their first value/update 1 hour after reboot. For this I thought, that a normal sensor is not restored and so empty and will not get the value from before-reboot.

No. I look if the forecast value is from today (and not already from tomorrow). Wanted. And I look and take the time where the max temperature (the other sensor) is. And if does not find this max in the forecast (anymore), it takes the old value (of the past, but today) of the sensor.

Hm. It is working 99%. Only on template reload trigger it is not working. The way of iterating and taking the old value makes at least so much sense, that it is working and delivering the wanted values.

If you want the time the max for today is at, your forecast sensor should only update at midnight and the only template you need is…

  - sensor:
      - name: Weather Home Max Temp Today Zeit
        unique_id: unique_id_template_sensor_weather_home_max_temp_today_zeit
        state: >
          {{ state_attr('sensor.weather_home_hourly','forecast') | sort(attribute='temperature', reverse=True) | map(attribute='datetime') | first | default }}
        availability: >
          {{ state_attr('sensor.weather_home_hourly','forecast') is not none }}

that shouldn’t apply here if you made 'sensor.weather_home_hourly' correctly because it will be populated during a reboot because it should be a trigger based entity and forecast will have restored data on restart.

Edit: I have a feeling you’ll come back and say “but this only looks in the future” or something like that.

and if htat’s the case then your forecast should keep the historical data, not your current sensor.

  - name: ...
      forecast: >
        {% set upcoming = response['weather.home'].forecast | rejectattr('datetime', '>=', (today_at() + timedelta(days=1)).isoformat()) | list %}
        {% set current = this.attributes.forecast | rejectattr('datetime', '>=', upcoming[0].datetime) | list if this.attributes is defined and this.attributes.forecast is defined and this.attributes.forecast is not none else [] %}
        {{ (current + upcoming) | sort(attribute='datetime') }}

A forecast can change. Or not reach eod alread midnight. Or …

I didn’t mention this sensor here. It was a general question. In such cases and when the sensor is not a trigger sensor, the value would not be there.

Of course, because this was and is the requirement. :wink: Solutions, which ignore the requirement are not real alternatives. :sunglasses:

Yes, but then it is not a forecast anymore, the sensor would be “bigger” than needed (even if I only store today and yesterday) and with your current proposal it would grow “infinite”. Yes, one can limit this on top, etc. but …

… where is the problem as done by me with just store the time of max temp today if it (because perhaps changed) in the future and otherwise take the old value? With the approach of post 1 I don’t have all the other problems now introduced with the proposals, do I?

Anyway, I understood, that a template_reload_trigger is not triggering after the templates is already initialized (with restored value) but already before and it is no solution here. Thanks again for this hint. But to be honest, then I don’t understand, why it is implemented that way and not in a way, that the trigger would only trigger after initializing. But that is ofc not a topic to discuss here.

So if it isn’t, I would just remove this trigger out of my trigger sensor and everything should work as wanted and in “design” of post 1, e.g. ob reboot. I’ll see.

No… the current proposal is truncated to todays forecast, did you try the code or read it? If there’s a mistake (I didn’t try the code) in it where it does grow infinite, you simply add a filter so that it doesn’t. The goal of the sensor is to have todays forecast from midnight to midnight without duplicates.

Your current approach is memory heavy when it doesn’t need to be and it creates restart issues on all your sensors instead of just one. You’re welcome to do whatever you want.

No, you still aren’t understanding. The event is occurring WHILE the template integration is reloading so all template entities miss it and therefore do not trigger.

Because all other integrations and systems still catch the event. But when an integration is reloading (therefor not running), it will miss it. It just so happens that you’re reloading the integration that would be using the trigger. It’s a chicken-egg scenario. I have an automation that catches the event, delays it, and fires a new event. I use that in my template entities so that I don’t miss the event.

- alias: Events - Forward Reload Templates
  id: reload_templates
  - platform: event
    event_type: event_template_reloaded
  - delay: "00:00:01"
  - event: templates_reloaded
    event_data: {}