Skip to content

Commit eb12b49

Browse files
committed
ESP8266WiFiMulti: change the connection loop to be async
1 parent a1b9491 commit eb12b49

File tree

2 files changed

+16
-9
lines changed

2 files changed

+16
-9
lines changed

libraries/ESP8266WiFi/src/ESP8266WiFiMulti.cpp

+15-9
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
#include <limits.h>
2828
#include <string.h>
2929

30-
ESP8266WiFiMulti::ESP8266WiFiMulti() {
30+
ESP8266WiFiMulti::ESP8266WiFiMulti() : connect_timeout_ms(0) {
3131
}
3232

3333
ESP8266WiFiMulti::~ESP8266WiFiMulti() {
@@ -116,22 +116,26 @@ void ESP8266WiFiMulti::selectBest(BestNetwork& best, int8_t scanResult) {
116116
}
117117

118118
wl_status_t ESP8266WiFiMulti::connectLoop() {
119-
static const uint32_t connectTimeout = 5000; //5s timeout
120-
121-
auto startTime = millis();
122119
wl_status_t status = WiFi.status();
123120
// wait for connection, fail, or timeout
124-
while(status != WL_CONNECTED && status != WL_NO_SSID_AVAIL && status != WL_CONNECT_FAILED && (millis() - startTime) <= connectTimeout) {
125-
delay(10);
126-
status = WiFi.status();
121+
if (status == WL_CONNECTED ||
122+
status == WL_NO_SSID_AVAIL ||
123+
status == WL_CONNECT_FAILED ||
124+
(millis() > connect_timeout_ms))
125+
{
126+
handleConnectComplete(status);
127+
connect_timeout_ms = 0;
127128
}
128129

129-
handleConnectComplete(status);
130130
return status;
131131
}
132132

133133
wl_status_t ESP8266WiFiMulti::run(void) {
134134

135+
if (connect_timeout_ms != 0) {
136+
return connectLoop();
137+
}
138+
135139
wl_status_t status = WiFi.status();
136140
if(status == WL_DISCONNECTED || status == WL_NO_SSID_AVAIL || status == WL_IDLE_STATUS || status == WL_CONNECT_FAILED) {
137141

@@ -158,6 +162,8 @@ wl_status_t ESP8266WiFiMulti::run(void) {
158162
}
159163

160164
if(scanResult > 0) {
165+
static const uint32_t connectTimeout = 5000; // 5s timeout
166+
161167
// scan done, analyze
162168
BestNetwork best;
163169

@@ -177,8 +183,8 @@ wl_status_t ESP8266WiFiMulti::run(void) {
177183
DEBUG_WIFI_MULTI("[WIFI] Connecting BSSID: %02X:%02X:%02X:%02X:%02X:%02X SSID: %s Channel: %d (%d)\n", best.BSSID[0], best.BSSID[1], best.BSSID[2], best.BSSID[3], best.BSSID[4], best.BSSID[5], best.Network.ssid, best.Channel, best.NetworkDb);
178184

179185
WiFi.begin(best.Network.ssid, best.Network.passphrase, best.Channel, best.BSSID);
186+
connect_timeout_ms = millis() + connectTimeout;
180187

181-
status = connectLoop();
182188
} else {
183189
DEBUG_WIFI_MULTI("[WIFI] no matching wifi found!\n");
184190
}

libraries/ESP8266WiFi/src/ESP8266WiFiMulti.h

+1
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ class ESP8266WiFiMulti {
6060

6161
private:
6262
WifiAPlist APlist;
63+
unsigned long connect_timeout_ms;
6364

6465
void selectBest(BestNetwork& best, int8_t scanResult);
6566
void handleConnectComplete(wl_status_t status);

0 commit comments

Comments
 (0)