Create time out for Spark.connect()?

Almost there, I think.

After the amout of effort you already put into this, I’d like to suggest these adaptions
At this point I haven’t tested them myself, but just from experience this should work - and I’ll test it soon and correct if required :wink:
Edit: This is now working code, but in my tests I’ve got the impression, all that interrupt/timer effort is not needed anyhow, since Spark.connect() doesn’t seem to block anymore (despite still being stated to be and as I remember it to have been)
@mdma, has anything been changed “recently” that hasn’t found its way into the docs? Or am I imagining things?

// This #include statement was automatically added by the Spark IDE.
#include "SparkIntervalTimer/SparkIntervalTimer.h"

SYSTEM_MODE(SEMI_AUTOMATIC);

// Create IntervalTimer object
IntervalTimer myTimer;

// Pre-define ISR callback functions
void checkWifi(void);

volatile uint8_t isrTriggered = 0;

const unsigned long CONNECT_TIMEOUT = 30000;
unsigned long lastMillis;    // it's always good to have this for non-blocking delays

void setup(void) {
    pinMode(D7, OUTPUT);  

    digitalWrite(D7,HIGH);   // blink D7 fast once before timer activated
    delay(40);
    digitalWrite(D7,LOW);

    // this would only wait 20ms since uSec is micro seconds
    // myTimer.begin(checkWifi, 20000, uSec);   // check for wifi and shutdown if no connection after 20 seconds
    // the other time scale is half-milliseconds (hence 2*)
    myTimer.begin(checkWifi, 2 * CONNECT_TIMEOUT, hmSec);
    
    lastMillis = millis();  // store soft-delay reference time
    
    // try to connect
    isrTriggered = 0;
    Spark.connect();
    if (!isrTriggered)
    {   // only wait if connection attempt succeeded
        myTimer.end();  // don't disconnect prematurely
    
        while ((millis() - lastMillis) < CONNECT_TIMEOUT)
        {
            digitalWrite(D7, HIGH); 
            delay(50);             // flash LED about 10Hz
            Spark.process();
            digitalWrite(D7, LOW);  
            delay(50);             // flash LED about 10Hz
        } 
        Spark.disconnect();  // missed your chance for OTA flashing
    }
    WiFi.off();  // deactivate WiFi in any case  
}

// no need to re-check inside loop() now
void loop()
{
    digitalWrite(D7, HIGH); 
    delay(500);            // flash LED about 10Hz
    digitalWrite(D7, LOW);  
    delay(500);            // flash LED about 10Hz
}

void checkWifi(void) 
{
    isrTriggered = 1;
    Spark.disconnect();  // no more required inside ISR
}

Edit: Fixed some build error - Spark.connect() does not return any success/fail indicatior :frowning:

1 Like