Last active
January 29, 2019 11:14
-
-
Save ElectricImpSampleCode/b8f282c19bc75fe7f94d to your computer and use it in GitHub Desktop.
An example of how to deal with multiple proximate calls to server.connect(), which maintains only a single callback reference.
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
// Establish threshold trigger flags for all your sensors | |
local sensorOneTriggerFlag = false; | |
local sensorTwoTriggerFlag = false; | |
// Define the function that will be called when the device has connected | |
// to the server (or the connection attempt times out) | |
function connectResponseCallback(reason) { | |
if (reason == SERVER_CONNECTED) { | |
// Server is online. Because we can't say which sensor | |
// triggered the server.connect() we check both trigger | |
// flags so both cases are handled. If only one sensor | |
// triggers the callback, that works too. | |
if (sensorOneTriggerFlag) { | |
// Do Sensor One-specific operations... | |
// ...then clear the flag | |
sensorOneTriggerFlag = false; | |
} | |
if (sensorTwoTriggerFlag) { | |
// Do Sensor Two-specific operations... | |
// ...then clear the flag | |
sensorTwoTriggerFlag = false; | |
} | |
// Go offline again | |
imp.onidle(function() { | |
server.disconnect(); | |
}); | |
} | |
} | |
function readSensors() { | |
local sensorOneReading, sensorTwoReading; | |
// Take readings... | |
// Compare readings with threshold values set earlier | |
// in your code. If either or both sensors' readings | |
// exceed these thresholds, set the flag(s) and make | |
// an attempt to contact the server | |
if (sensorOneReading > SENSOR_ONE_THRESHOLD_VALUE) { | |
sensorOneTriggerFlag = true; | |
server.connect(connectResponseCallback, 60); | |
} | |
if (sensorTwoReading > SENSOR_TWO_THRESHOLD_VALUE) { | |
sensorTwoTriggerFlag = true; | |
server.connect(connectResponseCallback, 60); | |
} | |
// Perform any other tasks, eg. update display... | |
// Read sensors again in 30 seconds' time | |
imp.wakeup(30, readSensors); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment