Last active
March 25, 2019 12:48
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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