Last active
January 31, 2019 12:20
-
-
Save ElectricImpSampleCode/4bebe1972210c7cf19508db069ca5ede to your computer and use it in GitHub Desktop.
imp API Cookbook ‘How To Disconnect And/or Deep-sleep Devices Correctly’ Sample Code
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
const RETRY_TIME = 120; | |
const CONNECT_TIMEOUT = 30; | |
// Set the reconnection/error trigger policy (RETURN_ON_ERROR) early | |
server.setsendtimeoutpolicy(RETURN_ON_ERROR, WAIT_TIL_SENT, 10); | |
function connectHandler(reason) { | |
if (reason != SERVER_CONNECTED) { | |
// Queue up a reconnection attempt | |
imp.wakeup(RETRY_TIME, reconnect); | |
} else { | |
server.log("Device connected"); | |
} | |
} | |
function reconnect() { | |
// Attempt to connect to the server | |
server.connect(connectHandler, CONNECT_TIMEOUT); | |
} | |
// Use 'imp.onidle()' to register a function that will be called | |
// when impOS and Squirrel tasks are complete. | |
// The registered function has no parameters | |
imp.onidle(function() { | |
// Disconnect from the server now it's OK to do so | |
server.log("Device disconnecting"); | |
server.flush(10); | |
server.disconnect(); | |
// Queue up a reconnection attempt in 60 seconds | |
imp.wakeup(60, reconnect); | |
}); |
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
const SLEEP_TIME = 3600; | |
// Use 'imp.onidle()' to register a function that will be called | |
// when impOS and Squirrel tasks are complete. | |
// The registered function has no parameters | |
imp.onidle(function() { | |
// Sleep for 'SLEEP_TIME' seconds now it's OK to do so | |
server.sleepfor(SLEEP_TIME); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment