Skip to content

Instantly share code, notes, and snippets.

@ElectricImpSampleCode
Last active March 25, 2019 12:52
Show Gist options
  • Save ElectricImpSampleCode/88e63c51c04c51d3f78e to your computer and use it in GitHub Desktop.
Save ElectricImpSampleCode/88e63c51c04c51d3f78e to your computer and use it in GitHub Desktop.
This example shows how device code can deliberately disconnect from the server yet remain operational.
// EARLY CALL CODE
server.setsendtimeoutpolicy(RETURN_ON_ERROR, WAIT_TIL_SENT, 30.0);
// GLOBALS
local downTime = time();
local reconnectAttemptFlag = false;
local sensorData = {};
// FUNCTIONS
function mainLoop() {
// Schedule the next sample in 2 seconds
imp.wakeup(2.0, mainLoop);
// Sample data from sensor(s), process it and store it in 'sensorData'
// NOTE Body of function omitted for clarity
// Check whether it's time to attempt to reconnect
if (time() - downTime > 3600 && !reconnectAttemptFlag) {
// Every hour, attempt to connect to WiFi
reconnectAttemptFlag = true;
// Attempt to connect to server. Use default timeout, 30s
server.connect(disconnectHandler);
}
}
function disconnectHandler(reason) {
reconnectAttemptFlag = false;
downTime = time();
if (reason == SERVER_CONNECTED) {
// Device has successfully connected
server.log("Device temporarily online to save data");
// Relay data to agent
agent.send("save.data", sensorData);
sensorData = {};
// Warn about going offline, then disconnect
server.log("Device is now going offline");
imp.onidle(function() {
server.flush(10);
server.disconnect();
});
}
}
// START OF RUNTIME
server.log("Device is running, but going offline");
// Queue up the disconnection to take place once Squirrel
// is done (ie. after line 59 has been executed) and
// impOS is ready
imp.onidle(function() {
server.flush(10);
server.disconnect();
downTime = time();
});
// Start the loop in two seconds' time
imp.wakeup(2.0, mainLoop);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment