Alert if State 'on' too Frequently

I'm wanting to use Node-Red with Home Assistant to alert me if a certain device state is running too frequently (state 'on' twice in 15m or less). I've taken a few shots at this thinking I could use MQTT to flag the state having been on and hold that for 15m and if another event comes in within that time; send an alert - but didn't get that working as I had trouble comparing output from MQTT and the home assistant state event.

I have a sneaking suspicion I'm making this harder than it needs to be, but am really new to this and kind of floundering at this point. I'm not seeing anything else in the forums that clicks for this.

You can use a function node where you set the timestamp to a context variable and compare it to the current timestamp

curr = Date.now();
prev = context.get("prev") || 0
diff = curr-prev

if(diff<900000 && diff !== 0){
    msg.payload = "within 15 minutes: " + diff
}
else{
    msg.payload = "longer than 15 minutes: "+ diff
    
}

context.set("prev", Date.now())
return msg;

The 900000 = 15 minutes * 60 * 1000 (timestamp is in milliseconds)

Example flow:

[{"id":"f7117452.73323","type":"inject","z":"adf0695a.6e8388","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":288,"y":384,"wires":[["d31ac860.7f697"]]},{"id":"d31ac860.7f697","type":"function","z":"adf0695a.6e8388","name":"","func":"curr = Date.now();\nprev = context.get(\"prev\") || Date.now()\ndiff = curr-prev\n\nif(diff<900000){\n    msg.payload = \"within 15 minutes: \" + diff\n}\nelse{\n    msg.payload = \"longer than 15 minutes: \"+ diff\n    \n}\n\ncontext.set(\"prev\", Date.now())\nreturn msg;","outputs":1,"noerr":0,"x":434,"y":384,"wires":[["ea060a36.2de4c"]]},{"id":"ea060a36.2de4c","type":"debug","z":"adf0695a.6e8388","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":598,"y":384,"wires":[]}]
1 Like

Given you're using Home Assistant, the history_stats sensor can be configured to do the counting per interval for you. Then you can automate the action based on the count in NR.

I think it would be something like that below (I've not tried it though):

  - platform: history_stats
    name: a_new_name
    entity_id: your_existing_entity
    state: 'on'
    type: count
    duration: 00:15
    end: "{{ now() }}"

This suggestion seems perfect - exactly what I was looking for; I think my biggest issue was not knowing how to persist the previous event timestamp between one run of the flow and the next. This was just what I needed, thank you.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.