Perthboy
Perthboy

Reputation: 327

ESP32 async scan networks returning fail even though successful scan. How do I detect a real fail

Environment ESP32-WROOM-32UE. I need to run WiFi.scanNetworks() asynchronously for my project. My sample code returns a list of discovered networks however the output during WiFi.scanComplete() does not make sense. Snippet from test code:

void _scan_check() {
   int asyncscan = WiFi.scanNetworks(true);
   delay(1000);
   int status = WiFi.scanComplete();
   while(status < 0) {
    Serial.printf("Status = %d", status);
    delay(1000);
    status = WiFi.scanComplete();
   }
   Serial.printf("Status = %d", status);
}

When run I get the following output (commented):

Status = -1  //equal to WIFI_SCAN_RUNNING
Status = -1  //equal to WIFI_SCAN_RUNNING
Status = -1  //equal to WIFI_SCAN_RUNNING
Status = -1  //equal to WIFI_SCAN_RUNNING
Status = -2  //equal to WIFI_SCAN_FAILED
Status = -2  //equal to WIFI_SCAN_FAILED
Status = 7   // discovered 7 networks

This happens regardless of how many networks discovered. So my question is, why do I always get one or more WIFI_SCAN_FAILED prior to getting the actual count of discovered networks and how do I detect a real scan fail? Is this an undocumented way it works or is there some bug with the ESP32 backend code?

Upvotes: 1

Views: 269

Answers (1)

Tyler Camp
Tyler Camp

Reputation: 197

(This is apparently dependent on the Arduino SDK version used. I'm using v2.0.16 locally. )

I've just faced the same problem and it seems to be a race condition between timeout detection in scanComplete() and the underlying event system which reports completion to the Arduino WiFi library. (Ref - Handling of ESP32 events and internal callback for its own tracking.)

I viewed the underlying event logs by adding this to my build flags: -DCORE_DEBUG_LEVEL=5, and some println debugging shows that the timeout condition returns a failure before the ARDUINO_EVENT_WIFI_SCAN_DONE is received, which would've normally been caught by the rest of that function.

It appears to have been fixed with this PR for v3.0.0. Locally I can confirm that the issue is fixed when I manually apply the change.

... and how do I detect a real scan fail?

The update from that PR fixes the timeout issue, but I don't see anything checking the wifi_scan_done field of that event which would tell you whether the scan was a success or failure.

As a workaround, you could use WiFi.onEvent manually to detect completion + failures.

Upvotes: 0

Related Questions