Ref:
My existing template trigger is:
{{ states.binary_sensor | rejectattr('attributes.device_class', 'undefined') | selectattr('attributes.device_class', 'eq', 'moisture') | selectattr('state', 'eq', 'on') | map(attribute = 'name') | list | length > 0 }}
And this is not ideal because it will only trigger upon first moisture sensor state become “on”.
Ideally the template should trigger upon any result changes, compared by its value.
To maintain the backward compatibility I think the behavior should be opt-in only, meaning user can toggle on a checkbox indicating they want the trigger to compare the template outcome without converting them to Boolean values.
I was able to locate the corresponding code:
In: core/homeassistant/helpers/event.py at c3cd60e0cb66f2ddae5165d652b091cec2ed8b96 · home-assistant/core · GitHub the _template_changed_listener
calls result_as_boolean
in: core/homeassistant/helpers/template.py at c3cd60e0cb66f2ddae5165d652b091cec2ed8b96 · home-assistant/core · GitHub
It is not immediately clear to me why it is trying to convert the result to Boolean, my guesses are:
- Maybe it is to address unstable arrays that introduce confusion among users why a trigger may run although the array contains same set of elements.
- Maybe it is to address some objects that are not possible to be rendered into strings? However it should be obviously if the template failed to render.
My proposal is to add debugging info regarding old and new state and always render the outcome into string for comparison, which will be most obvious in most cases.
It will also be easier to implement as a simple string comparison can decide if a trigger needs to be fired.
I’m currently working on the change and would like some feedback from someone more knowledgeable, thank you.