Time since last state change?

Hi!

I’m trying to get the time (in minutes) since last state change for a sensor. Any easy way to do this? Thanks!

If you’re using the websocket version each entity will have a property timeSinceChangedMs. Which is the time in milliseconds since the state last changed.

1 Like

Sorry, but I’m not using that node. Any way, I took a look and couldn’t find out how to achieve what I need. Thanks

Sorry, I’m talking about Node-RED nodes.

So are we - the Node Red node is from ‘node-red-contrib-home-assistant-websocket’ which you can find at https://flows.nodered.org/node/node-red-contrib-home-assistant-websocket.

Using the events_state node to listen for a specific sensor changing state - we have msg.data.new_state.timeSinceChangedMs . msg.data.old_state tells us about the previous state and msg.data.new_state tells us about the new state. Since the value is in milliseconds, we can divide by 1000 to get seconds and then divide by 60 to get minutes.

var lastChange = Math.floor(msg.data.new_state.timeSinceChangedMs / 1000);
if (lastChange > 300 && msg.data.new_state.state === true) {
// do something because the state last changed 5 minutes ago and is now true/on
}

(node-red newbie)

Okay, great so we can calculate the lastChange time.
But where do I put the calculation

(var lastChange = Math.floor(msg.data.new_state.timeSinceChangedMs / 1000);

in a function node, template node? How do I use it?

Probably a very dump question but its not obvious if you are a beginner like me…

That’ll be in a function node, that’s the easiest way to to calculations on the data contained in the msg object.

This is my current (working) code that I use daily for calculating a delay to wait and check if the state is still the same:

var lastChange = new Date(msg.data.old_state.last_changed).getTime();
var now = new Date().getTime();
var secs = Math.floor((now / 1000)-(lastChange / 1000));
msg.sensor = {};
msg.sensor.lastChange = secs;
msg.delay = Math.floor(secs/3) * 1000;
if (msg.delay < 60000) { msg.delay = 60000; }
else if (msg.delay > 900000) { msg.delay = 900000; }
return msg;

This code is used to check how long ago a door contact changed, and calculate a delay for the delay node to check again to make sure the door is still closed. If the door is still closed after the delay, then the light is turned off. The delay changes based on how long the door was opened for.

7 Likes