Skip to content

Instantly share code, notes, and snippets.

@ElectricImpSampleCode
Last active January 29, 2019 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ElectricImpSampleCode/b8f282c19bc75fe7f94d to your computer and use it in GitHub Desktop.
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.
// 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