Losing Spark.subscribe() connection/subscription

Yes this would be harmful, since each call to Spark.subscribe() fills a new subscription slot in the firmware, and there are only 4 of these. So for now, it's best to add the code to register the event only on disconnect.

This is made more complex because Spark.connect() doesn't work instantly. So it's best to detect a reconnection to the cloud like this:

void loop() {
   static bool prev_connected = true;
   bool connected = Spark.connected();
   if (connected && !prev_connected) {
       Spark.subscribe(...);
   }
   prev_connected = connected;
   if (!connected)
      Spark.connect();
}

This will still fail after 4 disconnects. To avoid filling up the subscription slots, we have to go lower level:

Declare

extern SparkProtocol spark_protocol;

At the top of the file, and in loop() instead of using Spark.subscribe() use

spark_protocol.send_subscription("eventName", SubscriptionScope::MY_DEVICES);

This should then work for any number of disconnects. Please note that this is a hack and it will be fixed in a future version of the firmware, at which point you should remove this code.

Hope that helps!

1 Like