I’ve created a project to open and close a chickencoopdoor based on sunset time. Because I want to open and close even if Wifi is not available, I use a piece of code to calculate the sunset hours. Open time is fixed. Wifi is only used for opening and closing via app and timesync.
When wifi connection is losed, It does not come back automatically and my code is also not running anymore.
How can I write my code so that is also working without wifi and when wifi is back, sync time. Or is there something why he is switching from offline to online whole day?
You should really do a quick forum search regarding this, as this is the single most repeadetly asked question around here, and there are countless topics already discussing this.
Alas, to point you in the right direction, check the docs for 'system modes' and threaded operation.
I also added the timers for reconnecting when he is offline (found in the forum)
const uint32_t msRetryDelay = 5*60000; // retry every 5min
const uint32_t msRetryTime = 30000; // stop trying after 30sec
bool retryRunning = false;
Timer retryTimer(msRetryDelay, retryConnect); // timer to retry connecting
Timer stopTimer(msRetryTime, stopConnect); // timer to stop a long running try
void retryConnect()
{
if (!Particle.connected()) // if not connected to cloud
{
Serial.println("reconnect");
stopTimer.start(); // set of the timout time
WiFi.on();
Particle.connect(); // start a reconnectino attempt
}
else // if already connected
{
Serial.println("connected");
retryTimer.stop(); // no further attempts required
retryRunning = false;
}
}
void stopConnect()
{
Serial.println("stopped");
if (!Particle.connected()) // if after retryTime no connection
WiFi.off(); // stop trying and swith off WiFi
stopTimer.stop();
}
You may want to check the return values of your WiFi.setCredentials() calls and also power cycle the WiFi module (with apropriat delays) before calling WiFi.connect().
Also this doesn’t make too much sense
WiFi.connect();
if (!waitFor(Particle.connected, msRetryTime))
WiFi.off(); // no luck, no need for WiFi
With only calling WiFi.connect() you will never get to the Particle.connected state you are waiting for.
I guess you’ll rather want waitFor(WiFi.ready, msRetryTime)