Skip to content

Instantly share code, notes, and snippets.

@electricimp
Last active June 8, 2018 22:12
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 electricimp/6040696 to your computer and use it in GitHub Desktop.
Save electricimp/6040696 to your computer and use it in GitHub Desktop.
This example shows how one imp can have multiple wifi configurations hard coded into it, and cycle through them whenever it unexpectedly disconnects from the server.
// Set the timeout policy to RETURN_ON_ERROR, ie. to continue running at disconnect
server.setsendtimeoutpolicy(RETURN_ON_ERROR, WAIT_TIL_SENT, 30)
// Configure Pin 1 to drive the connection status LED
hardware.pin1.configure(DIGITAL_OUT);
hardware.pin1.write(0);
// Create an array of WiFi networks, each defined by a table
connections <- [
{ ssid = "SSID1", pw = "SSID1PW" },
{ ssid = "SSID2", pw = "SSID2PW" }
]
currentConnection <- 0
// disconnects from current network (if required)
// tries connecting with the supplied ssid / pw
// executes the callback
function changeWifi(ssid, pw, callback)
{
if (server.isconnected())
{
// Server is connected, so make sure all the pending data has been sent to the server...
server.flush(30)
// ... and disconnect from it
server.disconnect()
}
// Re-configure the imp's WiFi and attempt to connect
imp.setwificonfiguration(ssid, pw);
server.connect(callback, 30);
}
// This function doesn't use the result parameter but it's required because it's also
// the callback from a server.connect()
function connectOrFailToNextConnection(result = null)
{
if (!server.isconnected())
{
// Server is not connected
if (currentConnection >= connections.len())
{
// We've tried all the available networks without success, so put the imp to sleep for 10 minutes
currentConnection = 0
imp.deepsleepfor(600)
}
else
{
// If there are still connections to try, grab current ssid and pw, and increment currentConnection
// for the next attempt (if connection fails)
local ssid = connections[currentConnection].ssid
local pw = connections[currentConnection].pw
currentConnection++
// Attempt to connect
changeWifi(ssid, pw, connectOrFailToNextConnection)
}
}
else
{
// The imp is connected, so turn the LED on
hardware.pin1.write(1);
}
}
// Define a function to handle disconnections
function disconnectHandler(reason)
{
if (reason != SERVER_CONNECTED)
{
// Turn LED off
hardware.pin1.write(0)
// Loop through connections until we connect
currentConnection = 0
connectOrFailToNextConnection()
}
}
// Register the disconnection handler
server.onunexpecteddisconnect(disconnectHandler)
// On boot, make sure we're connected or try connecting
connectOrFailToNextConnection()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment