Code: Select all
#include <AdafruitIO_WiFi.h>
#include "config.h" // holds %defs for ssid, password, IO_USER and IO_KEY
AdafruitIO_WiFi myio(IO_USER, IO_KEY, ssid, password);
bool WiFiIsConnecting = false;
bool AIOIsOK = false;
bool AIOIsConnecting = false;
void setup() {
Serial.begin(9600);
delay(10);
Serial.println("\n\nBegin non-blocking WiFi demo");
}
void loop() {
/*******************Time-critical state machine logic goes here**********/
if (AIOIsOK) myio.run(); // true if AIO is connected
/*****The following code connects, or reconnects, to WiFi & AIO, non-blocking********/
if (!AIOIsConnecting) { // true if AIO is not connecting.
if (WiFi.status() != WL_CONNECTED) { // true if WiFi is not connected
if (!WiFiIsConnecting) { // true if WiFi.begin needs calling (1st pass through)
WiFiIsConnecting = true;
Serial.println("WiFi connection initiated");
WiFi.begin(ssid, password);
}
} else { // true if WiFi is connected
if (WiFiIsConnecting) { // true if WiFi just connected. call myio.connect
Serial.print("WiFi connected to ");
Serial.println(WiFi.localIP());
Serial.println("Connecting to AdafruitIO");
myio.connect();
AIOIsConnecting = true;
WiFiIsConnecting = false;
}
}
}
if (AIOIsConnecting) { // true if AIO not yet responded to connect request
if (myio.status() == AIO_CONNECTED) { // true if AIO is now connected
AIOIsOK = true;
AIOIsConnecting = false;
Serial.println(myio.statusText());
}
}
}
One caveat: the logic hasn't been tested against the scenario where AIO goes down while WiFi remains connected. I had no way of testing this, so I didn't put any logic to detect and respond to such an event. Easy enough to test myio.status() against AIO_CONNECTED and issue a WiFi.disconnect(), but I didn't put that in the code.
I know the logic is somewhat kludgy, but it works. If anyone has any improvements to offer I would love to consider them.