Calculating Offset Between Two States

I’ve been searching for an answer to this and keep running into walls. I’m just getting started with Node-Red, so please bear with me. What I’m trying to do is trigger a volume change on one set of speakers that is equal to the volume change on another.

I’ve got the volume change set up as a trigger and the event data returns both the old_state and the new_state which would allow me to compare the numbers and identify if it’s a “volume up” or “volume down” event and enact the same action on the other set of speakers.

Where I’m stuck is how to calculate this from the object (or array?). I’ve tried using a split node, but it’s essentially returning the same object.

How do I run a calculation on these two numbers efficiently? Or maybe there’s a way to compare them that I’m not thinking of.

image

import

[{"id":"19681afad5613993","type":"inject","z":"120358abd7c22d30","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"{\"entity_id\":\"sensor.living_room_sonos_volume\",\"old_state\":{\"entity_id\":\"sensor.living_room_sonos_volume\",\"state\":\"19\",\"attributes\":{\"last_changed\":\"2024-08-07T21:01:30.03585+00:00\"},\"context\":{}},\"new_state\":{\"entity_id\":\"sensor.living_room_sonos_volume\",\"state\":\"18\",\"attributes\":{\"last_changed\":\"2024-08-07T21:01:33.066761+00:00\"},\"context\":{},\"timeSinceChangedMs\":5}}","payloadType":"json","x":256,"y":7200,"wires":[["32be948b5f744969"]]},{"id":"588da0daf31922b4","type":"debug","z":"120358abd7c22d30","name":"debug 198","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":614,"y":7200,"wires":[]},{"id":"32be948b5f744969","type":"change","z":"120358abd7c22d30","name":"calculate difference","rules":[{"t":"set","p":"payload","pt":"msg","to":"$number(msg.payload.old_state.state) - $number(msg.payload.new_state.state) ","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":424,"y":7200,"wires":[["588da0daf31922b4"]]}]
1 Like

This worked perfectly. Thank you!