Counting time of turned on device

Hey Guys,

Basically i have a TP link switch that when it turns off i want it to send me a notification (through pushover) telling me how long it was switched on for. I've tried a few different ways with counter nodes with no success. Any one have any recommendations?

Not possible of course which is hopefully why you are using Node-RED.

I do this with lots of switches many of which don't give any feedback so I have to maintain state within Node-RED (or in MQTT).

I did have a TP-Link switch but I think that the relay has gone. I'll take it apart one day to find out (took nearly 6 months for someone on Amazon to actually send me the appropriate bits to unscrew its security bolts).

For that switch, I used the tp-link node and whenever I received a notification about switch change, I would add some extra data and send out to MQTT. The extra data was to add onTime or offTime timestamp values. The data was also stored in a retained Node-RED variable so that when the switch goes on, I can work out the time difference between when it was switched off and now. And the other way around for when it switches off (now - onTime). For convenience, I also add those elapsed times to the output as well.

You don't need to use MQTT to do all of this but if you don't, you will need to drive any downstream flow from the input node since updating Node-RED variables sadly doesn't trigger an event right now. One day I'm going to write something that does trigger an event on update if someone doesn't beat me to it.

Simple trick I've used is to wrap global.set() to a function inside a function node which I then also store in global context. When the function is called it uses node.send() to output the new data. In my case it was slightly more complex but this was the core idea.

Of course this required always setting the context with a function node. Maybe the function could also be called in a JSONata expression(?). Otherwise polling would be required.

That's a work around I suppose but still leaves you needing to interconnect flows that might not really warrant it. You don't need to do that when using MQTT.

What would really be good would be able to make use of Node-RED's event system.