I need help with an automation condition that always returns ‘false’.
I want to have a condition that checks if a value in the triggered event is not set.
A wall switch, how is doing what?
Scenario: I press the wall switch and the state is changed. Run the automation action
Scenario: Home assistant adjust the light and the state is changed. Do not run the automation action
Solution: condition will check if the to_state has a user_id. This will be null if the phyical device is pressed.
My Automation
alias: "Button: Kitchen"
description: ""
### CHECK FOR STATE CHANGE ON THE WALL SWITCH THAT CONTROLS LIGHT
trigger:
- platform: state
entity_id:
- switch.double_switch_2_2
- switch.double_switch_2
condition:
## SHOULD CHECK THAT user_id IS NULL
- condition: template
value_template: |-
{% if trigger.to_state.context.user_id is not defined %}
true
{% else %}
false
{% endif %}
action:
#### DO THINGS
mode: restart
Issue:
The condition always returns ‘false’ Guess the value is always null because the ‘path’ is wrong?
Trying to debug:
Trace the automation. Look at the ‘changed variables’. Convert the data to json ( I stripped information not needed). Try dev tools template to check if it works, here it works.
{% set tevent = {
"this": { },
"trigger": {
"from_state": { },
"to_state": {
"context": {
"id": "01HC0CR54978KVE2W0B44DW60E",
"parent_id": null,
"user_id": null
}
}
}
} %}
{% if tevent.trigger.to_state.context.user_id is not defined %}
true, it works
{% else %}
false
{% endif %}
If you mean a script or automation instead of the dashboard interface changes the switch then you need to look at the parent_id instead. The user_id will be none for both your physical and automated change. Though the parent_id being none could be due to a change by the dashboard interface or the physical device.
If you want to distinguish between physical device, or automation or dashboard you need to check all three contexts.
condition: template
value_template: >-
{% if trigger.to_state.context.user_id is not defined and
trigger.to_state.context.parent_id is not defined and
trigger.to_state.context.id is defined %}
true
{% else %}
false
{% endif %}
Here’s another way to do it using a template sensor. It’s only useful if you use the context a lot and don’t want to keep writing out all the conditions: