Skip to content

Instantly share code, notes, and snippets.

@ElectricImpSampleCode
Last active March 25, 2019 12:48
Show Gist options
  • Save ElectricImpSampleCode/e389f707e271f81780bd to your computer and use it in GitHub Desktop.
Save ElectricImpSampleCode/e389f707e271f81780bd to your computer and use it in GitHub Desktop.
A code snippet showing a way to manage attempts to reconnect to the imp’s agent.
// EARLY CALL CODE
server.setsendtimeoutpolicy(RETURN_ON_ERROR, WAIT_TIL_SENT, 30.0);
// GLOBALS
local disconnectedFlag = false;
local disconnectedCount = 0;
// FUNCTIONS
function mainProgramLoop() {
// Ensure the program loops safely every second
imp.wakeup(1.0, mainProgramLoop);
// Reconnection handler code
if (disconnectedFlag) {
// Device is disconnected
disconnectedCount++;
if (disconnectedCount > 900) {
// mainProgramLoop() loops every second, so when 'disconnectedCount' reaches
// 900, then 15 minutes have gone by since the disconnection. It's time to
// reconnect.
disconnectedFlag = false;
disconnectedCount = 0;
// Attempt to connect
// The result will be passed into 'disconnectionHandler()'
server.connect(disconnectionHandler, 30.0);
}
}
}
function disconnectionHandler(reason) {
// Function called automatically if the agent link is lost
if (reason != SERVER_CONNECTED) {
// The device is not connected, so record this fact
disconnectedFlag = true;
} else {
// The device is online again
server.log("Device re-connected");
disconnectedFlag = false;
disconnectedCount = 0;
}
}
// START OF RUNTIME
server.onunexpecteddisconnect(disconnectionHandler);
mainProgramLoop();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment