pyscript icon indicating copy to clipboard operation
pyscript copied to clipboard

State_trigger does not trigger on each attr change / rest sensor

Open Beiri22 opened this issue 4 years ago • 3 comments

Hi there,

following situation: @state_trigger("sensor.json.attr1"), but attr1 is a map, like produced from a json_sensor

When I change sensor.json.attr1={"sub": "other"} -- it triggers When I change sensor.json.attr1["sub"]="other" -- it does not trigger

Why do i bother: I am using a json sensor that results in such map attributes. When getting the json data only changes those sub-attributes, my trigger doesn't trigger. I don't think that I can change the behaviour of the json sensor to fully reassign the attribute; so maybe there is some chance to adapt pyscript.

Any idea?

Beiri22 avatar Dec 01 '21 18:12 Beiri22

Because it's a "map" (or "object" in JSON, "dict" in Python) it's a mutable object. This means the only way to compare it is to "walk the tree" and compare each node. And since Home Assistant doesn't provide any assistance in this regard, it means that pyscript would have to do all of the walking and possibly store previous versions of that attribute for comparison purposes.

It's a fairly uncommon use case, and involves quite a bit of overhead. So, it's much easier to just do this yourself when you need it.

Instead of a @state_trigger use an @event_trigger (as outlined here)[https://github.com/custom-components/pyscript/wiki/Event-based-triggers]. You'll want a "state_changed" event with "sensor.json" as the entity_id. This means your trigger will run any time anything in that entity changes.

Using a global variable in your script, you can store the last value of whatever bits and pieces you're interested in comparing. Then you can compare them to the new incoming value and decide if the rest of the trigger should run or not.

dlashua avatar Dec 01 '21 19:12 dlashua

Maybe we could integrate such behaviour into ´´´@state_trigger´´´ like ´´´@state_trigger("sensor.json.**")´´´ for triggering on every state change of sensor.json?

Beiri22 avatar Dec 01 '21 19:12 Beiri22

For me, I think it works just fine that @state_trigger has extra features to help only trigger when there's actually a change, while @event_trigger on "state_changed" means every state change regardless of if anything changed. I use both of these quite a bit in my automations.

I also don't have an issue with there being some specific syntax on @state_trigger to do the same thing.

dlashua avatar Dec 02 '21 03:12 dlashua