Skip to content

Instantly share code, notes, and snippets.

@electricimp
Created January 29, 2015 09:36
Show Gist options
  • Save electricimp/d2b936a91c42d212ad5a to your computer and use it in GitHub Desktop.
Save electricimp/d2b936a91c42d212ad5a to your computer and use it in GitHub Desktop.
Handle multiple server.connect() calls code snippet
// Establish threshold trigger flags for all your sensors
sensorOneTriggerFlag <- false
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
. . .
// Clear the flag
sensorOneTriggerFlag = false
}
if (sensorTwoTriggerFlag)
{
// Do Sensor Two-specific operations
. . .
// Clear the flag
sensorTwoTriggerFlag = false
}
// Go offline again
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 10 seconds' time
imp.wakeup(10, readSensors)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment