My example is quite specific and it would be difficult to understand without seeing the entire concept. But this is the main part of the code:
var devicename = "sdm120"; // Device name used for context variable
var temp = context.get(devicename+"_update"); // This is where the last update value is stored (when I got message from the device last time
var current = new Date();
msg.payload = "No data";
if (msg.topic!=="timecheck") {
// Do not update the context if it is triggered by the timecheck inject node
// Implement a code here to store your parameters in the context. In the below line I store the current timestamp
context.set(devicename+"_update",current);
}
if (temp===undefined) {
// this will be the case when node-red is booting up or redeployed and this function running for the first time
context.set(devicename+"_update",current);
}
if (temp!==undefined) {
// in the code below, I calculate the time passed since the last update received from the device
current = current - temp;
current = Math.floor(current/1000);
var minute = Math.floor(current/60);
var hour = Math.floor(minute/60);
var day = Math.floor(hour/24);
if (current>24*60*60) {
msg.payload = "Last update " + day + " days, " + hour%24 + " hours, " + minute%60 + " minutes, " + current%60 + " seconds ago";
} else if (current>60*60) {
msg.payload = "Last update " + hour%24 + " hours, " + minute%60 + " minutes, " + current%60 + " seconds ago";
} else if (current>60) {
msg.payload = "Last update " + minute%60 + " minutes, " + current%60 + " seconds ago";
} else {
msg.payload = "Last update " + current%60 + " seconds ago";
}
}
node.status({fill:"blue",shape:"ring",text:msg.payload});
// you need to put this line inside in one of the if statements, not to send out result every time.
return msg;
Cheers,
Csongor