Last active
November 15, 2018 16:13
-
-
Save nrobinson2000/3f8ba6312e6dfe4c21f440744d28e160 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "Particle.h" | |
SYSTEM_MODE(SEMI_AUTOMATIC); | |
SYSTEM_THREAD(ENABLED); | |
SerialLogHandler usbLogHandler(LOG_LEVEL_TRACE); | |
#define CLOUD_TIMEOUT 60000 // how many ms are acceptable for lost cloud connection (needs to be > 45sec) | |
#define CLOUD_MAXRETRY 5 // how many unsuccessful connection attempts befor a System.reset | |
#define SECOND_MS 1000 | |
inline void softDelay(uint32_t msDelay) { | |
for (uint32_t ms = millis(); millis() - ms < msDelay; Particle.process()); | |
} | |
void setup() { | |
Serial.begin(115200); | |
Particle.connect(); | |
} | |
static uint32_t msSeenCloud = 0; // remember when we last saw the cloud | |
static int retries = 0; // how many retries to connect are left | |
void maintainWiFi(); | |
void loop() { | |
maintainWiFi(); | |
} | |
void maintainWiFi() { | |
// check cloud connection and if required reconnect | |
if (Particle.connected()) { | |
msSeenCloud = millis(); | |
retries = 0; | |
} | |
else if (millis() - msSeenCloud > CLOUD_TIMEOUT) { | |
Particle.disconnect(); | |
softDelay(500); | |
WiFi.disconnect(); | |
softDelay(1500); | |
WiFi.off(); | |
softDelay(4000); | |
if (retries++ < CLOUD_MAXRETRY) { | |
Log.info("Reconnect to Cloud (%d)", retries); | |
WiFi.off(); | |
WiFi.on(); | |
Particle.connect(); | |
if (waitFor(Particle.connected, CLOUD_TIMEOUT)) { // only works with SYSTEM_THREAD(ENABLED) | |
retries = 0; | |
} | |
else { | |
Log.info("\tfailed - retry in %d sec", CLOUD_TIMEOUT / SECOND_MS); | |
Particle.disconnect(); | |
} | |
msSeenCloud = millis(); // don't check too early | |
} | |
else { | |
System.reset(); // no success in reconnection - restart from scratch | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment