Skip to main content

Monitoring Device Disconnections From The Agent

When To Send A Warning That The Device Is No Longer Connected To Its Agent

It is generally not necessary to set up agent code to periodically ping its device to check whether the device is connected — the Electric Imp Platform does this for you. However, it will only notify the agent if you have registered suitable callback functions using the imp API methods device.onconnect() and/or device.ondisconnect().

Typically, a device which connects using WiFi or Ethernet will be marked offline when it has not been seen for approximately 4.5 minutes (up to 9 minutes). The cellular disconnection period is longer.

An edge case can occur when the connection is determined to have gone stale. This causes the device to reconnect which results in a disconnection notification to be sent to the agent, followed very closely by a connection notification.

The following agent code demonstrates how these imp API methods can be used, and shows how to manage the case mentioned above. It waits 30 seconds after receiving a disconnection event to check that it wasn’t triggered by a device reconnection. If we get the connection notification within 30 seconds of the disconnection notification, we clear the timer; this is clearly a reconnection and no action need be taken. Otherwise, the timer fires after 30 seconds and calls the function definitelyOffline(), in which you can implement your device-has-disconnected strategy.

API Methods Used

Sample Code

// Store any current disconnection-check timer
local disconnectTimer = null;

function definitelyOffline() {
    // Your 'device is definitely disconnected' function
    // You might use this to report the outage, eg. via
    // an SMS or push notification service's API
    reportOutage();
}

device.ondisconnect(function() {
    // Set a timer for 30s; if it isn't cancelled by a subsequent connect, 
    // then it'll call the function 'definitelyOffline()'
    if (disconnectTimer == null) disconnectTimer = imp.wakeup(30, definitelyOffline);
});

device.onconnect(function() {
    // Cancel the 'disconnectTimer' if there's one running
    if (disconnectTimer != null) {
        imp.cancelwakeup(disconnectTimer);
        disconnectTimer = null;
    }
});