Here’s a really quick snippet for you to work with:
Device Code:
`const INTERVAL = 60; // checkin every 60 seconds
// send a “stillhere” message every INTERVAL seconds
function watchdog() {
imp.wakeup(INTERVAL, watchdog);
agent.send(“stillhere”, null);
}
// start the watchdog
watchdog();`
Agent Code:
`const INTERVAL = 5; // needs to be same as device
const MISSED_MESSAGES_BEFORE_TRIGGERING = 2; // must be >= 2
watchdogTimer <- null;
missedMessages <- 0;
function watchdog() {
// increment missed message counter
missedMessages++;
// if we've missed too many messages
if (missedMessages > MISSED_MESSAGES_BEFORE_TRIGGERING) {
// execute your function here:
server.log("SENDING EMAIL");
} else {
// scheudle next watchdog
watchdogTimer = imp.wakeup(INTERVAL, watchdog);
}
}
device.on(“stillhere”, function(nulldata) {
// clear the watchdog timer if it exists
if (watchdogTimer != null) {
imp.cancelwakeup(watchdogTimer);
watchdogTimer = null;
}
// clear missedMessages
missedMessages = 0;
// reschedule the watchdog timer
watchdogTimer = imp.wakeup(INTERVAL, watchdog);
});`
The device code is pretty simple - it just checks in every seconds (or however often you want… probably much longer than that).
The agent code runs a watchdog function every 5 seconds that increments a counter. When the counter exceeds a certain number (in this case 2) it triggers the email function (you need to fill that part in, I’m just logging right now).
Whenever the agent gets one of the messages from the device, it resets the counter, clears the current timer, and creates a new one.
Since we’re checking in every 5 seconds, server.log(“SENDING EMAIL”); will execute after the device has failed to checkin for 10 seconds (2 missed checkins).
This is also setup so that the “SENDING EMAIL” will only happen the FIRST time the device goes offline (it needs to come back online before the watchdog restarts… although that is a fairly easy change if you don’t want that behaviour).
Let me know if you have any questions 