Created
January 8, 2015 16:29
-
-
Save dmiddlecamp/65a5a94deaef6fdc4167 to your computer and use it in GitHub Desktop.
a workaround to detect and recover when event subscriptions are lost
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
unsigned int last_heartbeat = 0; | |
#define HEARTBEAT_PERIOD_SECONDS 60 | |
#define MAX_MISSED_HEARTBEATS 3 | |
void setup() { | |
Serial.begin(115200); | |
Spark.subscribe("heartbeat", heartbeat_handler); | |
//Spark.subscribe("heartbeat", heartbeat_handler, MY_DEVICES); | |
last_heartbeat = millis(); | |
} | |
void loop() { | |
//it might take a few seconds for the real time clock to get synced, lets assume we weren't turned on in the 1970s, and sync the clock... | |
//lets essentially keep this on pause until the clock syncs up | |
if (last_heartbeat < 60000) { | |
last_heartbeat = millis(); | |
} | |
double elapsedSeconds = (millis() - last_heartbeat) / 1000.0; | |
if (elapsedSeconds > (MAX_MISSED_HEARTBEATS * HEARTBEAT_PERIOD_SECONDS)) { | |
Serial.println("Subscribe is dead, long live subscribe!"); | |
delay(500); | |
System.reset(); | |
} | |
else { | |
Serial.println("things are okay... but it's been " + String(elapsedSeconds) + " since last heartbeat"); | |
delay(1000); | |
} | |
} | |
void heartbeat_handler(const char *topic, const char *data) { | |
last_heartbeat = millis(); | |
Serial.println("Heartbeat... at " + Time.timeStr()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment