Templated sensors - state and attribute updates

Is it possible to be certain when attributes are updated for a templated sensor?

I have a template binary sensor which has many triggers, some turn it on, some turn it off, and I want to update the attributes dependant upon the state of the sensor at the moment of the trigger.

Are the attributes evaluated and updated after the sensor has had its state updated or before?

For example if I have a trigger which turns the binary sensor (hence its state) to on and the sensor has an attribute start_time which I only want updated if the sensor is not already on, do I test for the sensor being on or off?

I hope that makes sense and yes, start_time is just a placeholder for illustrative purposes.

Also, I admit I asked a very similar question back in 2022 but never got an answer to the specific question.

this.state contains the Trigger-based Template Sensor’s existing state value. In other words, before it is computed by the state template. The value of this.state is the same whether referenced in the sensor’s attribute’s template or its state template.

For a brand new Trigger-based Template Sensor triggered for the very first time, the value of this.state would be unknown.

Thanks!!
And of course.
I am slightly embarrassed to have missed that.

1 Like