How to stop WiFi.listen() if no credentials are stored?


Hey all,
I know this is a very specfic case but im trying to stop Wifi listening when no credentials are stored.

I first tried to use WiFi.listen(false). But if there are no credentials stored the Wifi.listen is automaticalled called. I want stop this from happening as I do not want the WiFi SSID to keep broadcasting. I have also tried to put a timeout but have the same result.

I tried another approach where i checked if there are any credentials stored. If there isn’t then I would turn off WiFi (which worked HOWEVER, when you turn the wifi back on and put the device into listening mode it would return the WiFi.listening() as true but that doesnt seem to be the case as no WIFI SSID is visible or the blinking blue is not on. This approach would also sometimes block code if you call after listening. Listed bellow is the code to reproduce this error.

I am using Firmware 1.0.1.
Device: P1

#include "Particle.h"
#include "application.h"
void setup() {

void loop() {
  Serial.println("WiFi off");
  Serial.println("WiFi on");

  Serial.println("WiFi listening");


The approach I use is to check for WiFi credentials before calling WiFi.connect(). There are several conditions you can face; credentials/no credentials, if credentials exist, they may be wrong/bad or the WAP may be off or out of range.

I use a couple of global bool variables to avoid retesting since WiFi.hasCredentials() is blocking once connected! Also, certain conditions are best detected at startup. Another simplifier is to only store 1 credential (I know it can store as many as 5).

There also then needs to be timed/regular recheck processes to check for WiFi.ready() and to call Particle.connect().
With SYSTEM_THREAD(ENABLED); and SYSTEM_MODE(SEMI_AUTOMATIC); once you have called WiFi.connect() it will keep trying in the background and should not block the application thread.

        hasStoredCredentials = WiFi.hasCredentials();
        int sap = WiFi.getCredentials(ap, 5);
        unsigned long timeout = 8000 * (unsigned long) sap;
        if (hasStoredCredentials && !hasBadCredentials)         //credentials exist but they may not be in range or may be wrong
            waitFor(WiFi.ready, timeout);                               //timeout variable to reduce wait period otherwise 5 x 6-7 seconds!
            if (!WiFi.ready() && hasStoredCredentials)          //stop trying to find WAP and block application if there are credentials but a wifi connection to one of them cannot be made
                if (isStartup) hasBadCredentials = true;
                else if (wasWiFiConnected) isWiFiOutofRange = true;
                else hasBadCredentials = true;