Many of my sensor turn to “unknown” randomly throughout the day. I don’t know if this can be avoided, but mostly I’ve tried to make my automations resilient to it.
The code below is an automation that switches on the air purifier is the air was bad (binary sensor) for 5 minutes. I’ve set it up in a way that it only triggers if the new/current state of the binary sensor is on or off (not unknown).
Alas, today I got an error message because HA tried to execute the action turn_unknown which I think should never happen based on the code below.
Any advice?
I’ve considered adding a condition the the current state is actually on or off. But seems to be redundant to the trigger which also requests the same
As you are not basing your action on trigger.to_state.state but on querying the state manually, even if unlikely it is not impossible that the state could change in the split second between the trigger and the action.
In addition to Magnus’ comment above (which is the main issue)… You may want to consider using specific values for the from key so that the automation isn’t triggering if the sensor’s state is bouncing between “unknown”, “on”, and “off”. The use of the for duration should prevent most of those issues, but it’s something to keep in mind if you continue to get unwanted trigger events:
@jackjourneyman In this example, it’s a TP-Link Wifi Switch sitting in the same network as HA. But I’ve also noticed it for Shelly devices, for example, which are also sitting in the same network and are connected through WiFi directly.
@Mayhem_SWE Thank you so much, that’s the solution! I was actually wondering if there’s a way to not query the state twice. Where can I find more documentation on “local variables” like trigger.to_state.state?—it doesn’t seem like I can derive it from the YAML structure.
Which properties that are available on the trigger varies with the type of trigger. There is also the this variable.
Within loops there will be a repeat variable. After wait_template or wait_for_trigger there will be a wait variable. Those and whatever others I’ve forgotten are all documented in the sections covering their specific script/automation syntax.
You can also see in the script/automation traces for each action whether they changed any variables.