Does entity state change while an automation is running?

I’m trying to create an automation that remembers the brightness level of a light whenever it changes. The brightness of the light returns None when the light is off.

I’m remembering the last brightness value in an input_number variable. If I try to set this when the light is off (i.e. to None) then I get an error evaluating the data template, which I expected.

In an attempt to avoid this, I’ve added a condition of {{ state_attribute('light.my_light', 'brightness') != None }} to the automation. I have verified that this condition evaluates to True when the light is on and False when it is off.

However, when I turn off the light – changing the brightness to None an thus triggering my automation – the condition seems to fail to evaluate properly and the action to set the value runs and fails, resulting in errors in the logs.

I’ve confirmed that the condition clause is being executed because if I set it to return False then the action does not run when I turn off the light, as expected.

I see the same behavior if I move the condition into the actions list.

What is going on here? It seems like the state is changing between the condition testing it and the action executing. I would have expected some level of atomicity here, otherwise I don’t see how it’s possible to implement a guard condition like I’m trying to do.

Does anybody know how this actually works?

Yes. But not me.

To answer your original question, it can. Entity states and automations are pretty much autonomous, so an entity state could change while an automation is running.

I have learned that for any question in Home Assistant there would be five or more correct answers. I am just guessing, but what if you use a separate automation that remembers the brightness whenever it changes and simply ignores “none”. In your on/off automation, use the last recorded brightness.

That’s the automation I’m trying to write. :slight_smile:

I’m trying to ignore None and can’t figure out how to do it, because (apparently) the brightness changes from not-Noneto None after I look at it but before I get a chance to write out the new brightness level.

Show what you have tried. (I speak YAML, but not like a native).

I was just able to figure this out.

It turns out I was wrong about the source of the error. Somehow I ended up dropping the value property of the data argument to the input_number.set_value action. :roll_eyes:

The condition in the automation seems to be working as expected after fixing that issue.

I guess the positive here is that I did learn about trigger variables – those will let you capture state in the automation before the condition and action run, so if this is actually a problem in the future I think I have a way to address it.