Skip to content

Instantly share code, notes, and snippets.

@ElectricImpSampleCode
Last active September 10, 2018 10:30
Show Gist options
  • Save ElectricImpSampleCode/5dd49e36768ba55ccda5 to your computer and use it in GitHub Desktop.
Save ElectricImpSampleCode/5dd49e36768ba55ccda5 to your computer and use it in GitHub Desktop.
This example shows a typical imp disconnection handler flow.
// Set the disconnection policy
server.setsendtimeoutpolicy(RETURN_ON_ERROR, WAIT_TIL_SENT, 10);
// Constants
const RECONNECT_TIME = 900;
const RECONNECT_TIMEOUT = 60;
// Globals
disData <- "";
disFlag <- false;
// Define the disconnection handler function
function disconnectionHandler(reason) {
if (reason != SERVER_CONNECTED) {
// Try to reconnect in 'RECONNECT_TIME' seconds
imp.wakeup(RECONNECT_TIME, reconnect);
// Record time and reason of disconnection
if (disData.len() == 0) {
disData = format("Disconnected at %s. Reason code: %i\n", setTimeString(), reason);
}
disFlag = true;
} else {
// Device is connected again, so update the message string
if (disData.len() != 0) {
disData = disData + "Reconnected at: " + setTimeString();
server.log(disData);
disData = "";
}
disFlag = false;
}
}
// Define the reconnection function
function reconnect() {
// server.connect calls disconnectHandler() on success or failure
// with an appropriate reason parameter
if (!server.isconnected()) {
server.connect(disconnectionHandler, RECONNECT_TIMEOUT);
} else {
disconnectionHandler(SERVER_CONNECTED);
}
}
// Format the disconnection time
function setTimeString() {
local now = date();
return (now.hour.tostring() + ":" + now.min.tostring() + ":" + now.sec.tostring);
}
// Register the unexpected disconnect handler
server.onunexpecteddisconnect(disconnectionHandler);
// Main Device Code Here...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment