Value of this.state After Restart

My new template sensor helper uses its previous state when the input is invalid. It parses the content of last_notification and if a regex matches, the state is updated. Otherwise, it uses the current state with this.state:

{% set grade = (states('sensor.oneplus_last_notification') | regex_findall(find='\d{1,3}\.?\d*(?=%\) in .+ Integrated Math)', ignorecase=False))[0] %}
{% if grade is defined %}
  {{ grade }}
{% else %}
  {{ this.state }}
{% endif %}

It works as expected until HA restarts. Then the state changes to unknown.

The same happens using states() instead of this.state.

I guess the explanation is that at some point during the restart the state of the sensor is in fact unavailable but doesn’t this.state reference the last valid (non-unavailable or unknown) state?

The state of trigger-based template sensors get restored, which leads me to think such sensors should have a value for this then (barring possible bugs). On mobile now, so I can’t test. What does your sensor definition look like? Is it a trigger-based sensor? If not, I’d say the behaviour is probably correct.

You are right. I was using a helper template sensor. But switching to a trigger-based template sensor did the trick.

I had totally forgotten about the sensor value restore functionality:

The state, including attributes, of trigger-based sensors and binary sensors is restored when Home Assistant is restarted. The state of other trigger-based template entities is not restored.

Thanks!

1 Like