Flush messages before going to sleep

One way to be completely sure your events have been sent and received is to send a specific “ready to sleep” event last, which you subscribe to, and wait for the subscription to come back. Like this:

#include "application.h"

bool canSleep = false; // set to true when the core can sleep
void subscribeHandler(const char* event, const char* data) {
    // data set to the device ID that wants to sleep.
    String id = Spark.deviceID();
    // see if this was a notification from this core that we can sleep
    if (!strcmp(data, id.c_str()))  
        canSleep = true;
}

void setup()
{
    Spark.publish("boot");      // startup events etc..
    Spark.subscribe("sleep", subscribeHandler, MY_DEVICES);  // listen for sleep events
}

void loop()
{
    // do other stuff, including publishing events
    
    // publish the sleep event last
    String deviceID = Spark.deviceID();
    Spark.publish("sleep", deviceID.c_str(), 60, PRIVATE);
    
    while (!canSleep) {
        delay(100);   // waiting for the event - delay runs the system idle code
    }
    Spark.sleep(SLEEP_MODE_DEEP, 10);
}

When I run this, I see the core connect to the cloud, publish boot and sleep events (which I see in the event stream), and wait a few seconds for the response before sleeping.

I hope that’s what you were looking for! :smile:

Cheers,
mat.

6 Likes