Skip to content

Connect to Wifi network take almost 3 seconds. I am using static IP and BSSID and channel. On ESP8266, the same code connected within 100ms. What I am doing wrong #1675

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
robertgregor opened this issue Jul 25, 2018 · 51 comments · Fixed by #5975
Labels
Area: ESP-IDF related ESP-IDF related issues Status: Solved Type: Feature request Feature request for Arduino ESP32

Comments

@robertgregor
Copy link

Hi, I am migrating the code of ESP8266 for battery powerred device. But seems, I have a problem to have reasonable time to connect to wifi. It takes at least 3 secods always. Here is the code:

#include <FS.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <SPIFFS.h>

// SKETCH BEGIN
AsyncWebServer server(80);

const char* ssid = "Bob";
const char* pwd = "xxx";
byte ip[] = {192,168,1,115};
byte gw[] = {192,168,1,1};
byte mask[] = {255,255,255,0};
byte dns[] = {194,41,3,193};
byte bssid[] = {0xF8, 0xD1, 0x11, 0x24, 0xB3, 0x84};
byte chnl = 4;

IPAddress getIpAddrFromArr(byte ipAddr[]) {
return IPAddress(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3]);
}

void connectToWifi(String ssid, String pwd, byte ip[], byte gw[], byte mask[], byte dns[], byte bssid[], byte chnl ) {
if (WiFi.status() == WL_CONNECTED) return;
Serial.println(F("Connecting wifi..."));
long st = millis();
WiFi.enableSTA(true);
WiFi.mode(WIFI_STA);
if (ip[0] != 0) WiFi.config(getIpAddrFromArr(ip), getIpAddrFromArr(gw), getIpAddrFromArr(mask),getIpAddrFromArr(dns));
if ((ssid.length() != 0) && (pwd.length() == 0)) {
WiFi.begin(ssid.c_str());
} else if ((ssid.length() != 0) && (pwd.length() != 0)) {
if (bssid[0] == 0) {
WiFi.begin(ssid.c_str(), pwd.c_str());
} else {
WiFi.begin(ssid.c_str(), pwd.c_str(), chnl, bssid);
}
WiFi.setAutoConnect(true);
}
int attempts = 0;
while (WiFi.status() != WL_CONNECTED) {
if (++attempts < 300) {
Serial.print(".");
delay(50);
} else break;
}
if (WiFi.status() == WL_CONNECTED) {
long tm = millis() - st;
Serial.print(F("\nConnected to AP in "));
Serial.print(tm, DEC);
Serial.print(F("ms. IP: "));
for (byte thisByte = 0; thisByte < 4; thisByte++) {
Serial.print(String(WiFi.localIP()[thisByte], DEC));
if (thisByte != 3) Serial.print(".");
}
Serial.println();
}
}

void setup(){
Serial.begin(115200);
Serial.setDebugOutput(true);
Serial.println(F("Connecting wifi..."));
long st = millis();
connectToWifi(ssid, pwd, ip, gw, mask, dns, bssid, chnl);
SPIFFS.begin();
server.on("/heap", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(200, "text/plain", String(ESP.getFreeHeap()));
});
server.serveStatic("/", SPIFFS, "/").setDefaultFile("index.html");
server.onNotFound([](AsyncWebServerRequest *request){
request->send(404);
});
server.onFileUpload([](AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data, size_t len, bool final) {
request->send(403);
});
server.begin();
}

void loop(){
}

So as is seen, I will do:
WiFi.enableSTA(true);
WiFi.mode(WIFI_STA);
WiFi.config(getIpAddrFromArr(ip), getIpAddrFromArr(gw), getIpAddrFromArr(mask),getIpAddrFromArr(dns));
WiFi.begin(ssid.c_str(), pwd.c_str(), chnl, bssid);

But this tahes around 3.2 seconds always:

Connecting wifi...
...............................................................
Connected to AP in 3201ms. IP: 192.168.1.115

On my ESP8266, this worked much much faster, I was connected in less than 100 ms always...

Anyone has an idea, why it take so long?????

Robert

@robertgregor
Copy link
Author

With DEBUG, I have this:

Connecting wifi...
[D][WiFiGeneric.cpp:293] _eventCallback(): Event: 2 - STA_START
...............................................................[D][WiFiGeneric.cpp:293] _eventCallback(): Event: 7 - STA_GOT_IP
[D][WiFiGeneric.cpp:293] _eventCallback(): Event: 7 - STA_GOT_IP

Connected to AP in 3205ms. IP: 192.168.1.115

@me-no-dev
Copy link
Member

we are going to investigate this. Will keep you posted :)

@me-no-dev me-no-dev reopened this Jul 26, 2018
@me-no-dev me-no-dev added Type: Feature request Feature request for Arduino ESP32 Status: To be implemented Selected for Development Area: ESP-IDF related ESP-IDF related issues labels Jul 26, 2018
@cendev
Copy link

cendev commented Jul 26, 2018

Had the same problem and checked everything over and over.. Created a post on the forum too.

Just after an hour, created an AP from my ubuntu pc and tried to connect.. Voila.. In just 900 ms and connected to my tcp server + sent data + went back to sleep..

Strangely i had 4 esp8266 modules on the same wifi router with no speed problem at that same moment.. only my 2 of my wroom32s havin difficulty..

Btw if i change security to Open or WEP connection time is only 300ms+ but WPA types were about 3~4 secs.

@me-no-dev
Copy link
Member

are you sure it's slow only on WPA?

@cendev
Copy link

cendev commented Jul 27, 2018

  • For ESP32 It takes around 1000ms to connect and get ip to my routers with WPA security.
  • For ESP8266 it is only ~210ms to same WPA network
  • Wİth open security its around ~230ms for ESP32 to connect to the same network.

So it's about 0.7 secs difference between WPA & Open networks For ESP32, which cannot be observed on ESP8266. I'm using Wroom32 Modules. Tried with 3 different APs. A Huawei wireless router/modem, A ubiquiti, and an Asus. Huawei had the worst results. Ubi was the best..

  • RSSI levels are around -40 to -60 for both esp32's and 8266 modules
  • 2 routers are on Channel 6, Only ubi was on 11
  • Also I've noticed no difference between "with channel parameter" and "without one"..
  • Never able to connect with BSSID parameter so couldn't try that. (Don't know whats wrong x) probably my mistake)

Edit : This connection time problems also observed on IDF too, not only arduino.

@robertgregor
Copy link
Author

Hi, interresting. It really seems, that the cause of this issue is the WPA2 security. I have disabled the security on my router, so my network is open. And in that case, my code will join the network within 160 ms:

ets Jun 8 2016 00:22:57

rst:0x5 (DEEPSLEEP_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:956
load:0x40078000,len:0
load:0x40078000,len:13076
entry 0x40078a58
Wakeup caused by timer
Connecting wifi...
..........
Connecting wifi...
[D][WiFiGeneric.cpp:293] _eventCallback(): Event: 2 - STA_START
a
...[D][WiFiGeneric.cpp:293] _eventCallback(): Event: 7 - STA_GOT_IP
[D][WiFiGeneric.cpp:293] _eventCallback(): Event: 7 - STA_GOT_IP

Connected to AP in 167ms. IP: 192.168.1.115

@robertgregor
Copy link
Author

I have updated now the latest IDF and latest development release and with that, the connection time is even slower - almost 4 seconds.

@robertgregor
Copy link
Author

Here is the trace debug with WPA2:

Wakeup was not caused by deep sleep
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 0 - WIFI_READY
....[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:357] _eventCallback(): Reason: 204 - HANDSHAKE_TIMEOUT
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 7 - STA_GOT_IP
[D][WiFiGeneric.cpp:386] _eventCallback(): STA IP: 192.168.1.50, MASK: 255.255.255.0, GW: 192.168.1.1
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 7 - STA_GOT_IP
[D][WiFiGeneric.cpp:386] _eventCallback(): STA IP: 192.168.1.50, MASK: 255.255.255.0, GW: 192.168.1.1
.

Connected to AP in 4159ms. IP: 192.168.1.50

It run the code bellow:

long st = millis();
WiFi.mode(WIFI_STA);
WiFi.config(getIpAddr("192.168.1.50"), getIpAddr("192.168.1.1"), getIpAddr("255.255.255.0"), getIpAddr("192.168.1.1"));
WiFi.begin();
for (int i=0; i<200; i++) {
delay(50);
if (i%20 == 0) Serial.print(".");
if (WiFi.status() == WL_CONNECTED) break;
}
Serial.println();
if (WiFi.status() == WL_CONNECTED) {
long tm = millis() - st;
Serial.print(F("\nConnected to AP in "));
Serial.print(tm, DEC);
Serial.print(F("ms. IP: "));
for (byte thisByte = 0; thisByte < 4; thisByte++) {
Serial.print(String(WiFi.localIP()[thisByte], DEC));
if (thisByte != 3) Serial.print(".");
}
Serial.println();
} else {
long tm = millis() - st;
Serial.print(F("\nNot connected to AP within "));
Serial.print(tm, DEC);
Serial.println(F("ms."));
createAP();
}

@mvadu
Copy link

mvadu commented Nov 12, 2018

I am facing same issue with my Esp32 (Doit dev board) which was working fine with older IDF few month ago. I don't use this board very often as its mostly my breadboarding kit. My code is waiting for 5 seconds before deciding it could not connect. Every time I started getting WL_DISCONNECTED at the end of that period. I even tried with 30 second but it did not connect. Then I followed various issues (#234, #653) and added an even listener. What I found is ESP32 actually gets the IP almost 40-140 seconds after bootup!! My network is a 2.4GHz WPA2 with AES authentication, Asus Rt-n87u with DDWRT.

Looking at the output it looks like it loops from WIFI_READY -> STA_START -> STA_START -> STA_DISCONNECTED with reason of HANDSHAKE_TIMEOUT every 100 milli seconds. FInally in nth loop it goes to STA_CONNECTED and STA_GOT_IP.

bool connectToWifi()
{
    unsigned long max = 5 * 1000; //30 sec timeout
    unsigned long t = millis();
    if ( WiFi.status() == WL_CONNECTED )
        return true;
            
    WiFi.onEvent(WiFiEvent);

    Serial.printf("Trying to connect - %s, %s\n", config.ssid.c_str(), config.password.c_str());
    WiFi.setHostname(hostName);
    wifiStatus = WifiStatus::Connecting;
    WiFi.disconnect(true); // delete old config
    WiFi.persistent(false); //Avoid to store Wifi configuration in Flash    
   
    uint8_t ledlvl = 0;
    ledcWrite(1, 8000);
    WiFi.begin(config.ssid.c_str(), config.password.c_str());
    t = millis();
    while (max > millis() - t)
    {
        ledcWrite(1, ++ledlvl * 10);
        if (WiFi.status() == WL_CONNECTED) break;
        delay(100);
    }
    Serial.printf("WiFi.status: %d, duration: %d \n", WiFi.status(), (millis() - t));

    if (WiFi.status() == WL_CONNECTED)
    {
        ledcWrite(1, 16000);
        Serial.printf("Connected: %s\n", WiFi.localIP().toString().c_str());
        wifiStatus = WifiStatus::Connected;
        config.valid = true;
    }
    else
    {
        Serial.println("Failed to connect");
        wifiStatus = WifiStatus::ConnectFailed;
        ledcWrite(1, 0);
    }
    return wifiStatus == WifiStatus::Connected;
}
void WiFiEvent(WiFiEvent_t event, WiFiEventInfo_t info)
{
    Serial.printf("[WiFi-event] event: %d timestamp:%d\n", event,millis());
    switch (event)
    {
    case SYSTEM_EVENT_STA_GOT_IP:
        Serial.printf("WiFi connected IP address: %s duration %d\n", WiFi.localIP().toString().c_str(),millis());
        break;
    }
}

Code debug output.. along with time stamps printed in event handler

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1324
load:0x40078000,len:7788
ho 0 tail 12 room 4
load:0x40080400,len:6448
entry 0x400806e8
Starting Esp32 with IDF 
v3.2-dev-1055-g3276a1316
Found config espressif, esp32, 1 
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 0 - WIFI_READY
Trying to connect - espressif, esp32
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 3 - STA_STOP
[WiFi-event] event: 3 timestamp:144
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:158
[WiFi-event] event: 0 timestamp:162
WiFi.status: 6, duration: 5000 
Failed to connect
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:357] _eventCallback(): Reason: 204 - HANDSHAKE_TIMEOUT
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 0 - WIFI_READY
[WiFi-event] event: 0 timestamp:11076
[WiFi-event] event: 2 timestamp:11077
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:11084
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:11093
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:357] _eventCallback(): Reason: 204 - HANDSHAKE_TIMEOUT
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 0 - WIFI_READY
[WiFi-event] event: 0 timestamp:21217
[WiFi-event] event: 2 timestamp:21217
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:21225
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:21233
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:357] _eventCallback(): Reason: 204 - HANDSHAKE_TIMEOUT
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 0 - WIFI_READY
[WiFi-event] event: 0 timestamp:31357
[WiFi-event] event: 2 timestamp:31358
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:31365
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:31374
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:357] _eventCallback(): Reason: 204 - HANDSHAKE_TIMEOUT
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 0 - WIFI_READY
[WiFi-event] event: 0 timestamp:41497
[WiFi-event] event: 2 timestamp:41498
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:41505
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:41514
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:357] _eventCallback(): Reason: 204 - HANDSHAKE_TIMEOUT
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 0 - WIFI_READY
[WiFi-event] event: 0 timestamp:51637
[WiFi-event] event: 2 timestamp:51638
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:51645
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:51654
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:357] _eventCallback(): Reason: 204 - HANDSHAKE_TIMEOUT
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 0 - WIFI_READY
[WiFi-event] event: 0 timestamp:61778
[WiFi-event] event: 2 timestamp:61778
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:61785
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:61794
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:357] _eventCallback(): Reason: 204 - HANDSHAKE_TIMEOUT
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 0 - WIFI_READY
[WiFi-event] event: 0 timestamp:71919
[WiFi-event] event: 2 timestamp:71920
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:71927
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:71936
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:357] _eventCallback(): Reason: 204 - HANDSHAKE_TIMEOUT
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 0 - WIFI_READY
[WiFi-event] event: 0 timestamp:82059
[WiFi-event] event: 2 timestamp:82060
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:82067
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:82076
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:357] _eventCallback(): Reason: 204 - HANDSHAKE_TIMEOUT
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 0 - WIFI_READY
[WiFi-event] event: 0 timestamp:92199
[WiFi-event] event: 2 timestamp:92200
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:92207
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:92216
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:357] _eventCallback(): Reason: 204 - HANDSHAKE_TIMEOUT
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 0 - WIFI_READY
[WiFi-event] event: 0 timestamp:102349
[WiFi-event] event: 2 timestamp:102350
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:102355
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:102364
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 5 - STA_DISCONNECTED
[W][WiFiGeneric.cpp:357] _eventCallback(): Reason: 204 - HANDSHAKE_TIMEOUT
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 0 - WIFI_READY
[WiFi-event] event: 0 timestamp:112489
[WiFi-event] event: 2 timestamp:112490
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:112497
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 2 - STA_START
[WiFi-event] event: 2 timestamp:112506
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 4 - STA_CONNECTED
[WiFi-event] event: 4 timestamp:112647
[D][WiFiGeneric.cpp:342] _eventCallback(): Event: 7 - STA_GOT_IP
[D][WiFiGeneric.cpp:386] _eventCallback(): STA IP: 192.168.2.108, MASK: 255.255.255.0, GW: 192.168.2.1
[WiFi-event] event: 7 timestamp:113567
WiFi connected IP address: 192.168.2.108 duration 113571

@mvadu
Copy link

mvadu commented Nov 12, 2018

@robertgregor I think this issue title is too long. You might want to edit the issue and re-title it to say something smaller with same meaning.. Connecting to a network with WPA2 authentication takes long time something like that..

@mvadu
Copy link

mvadu commented Nov 16, 2018

@me-no-dev I can confirm that the previous version of Arduino-esp32 (one released under board manager json) is working fine..

#include <WiFi.h>

const char* ssid     = "espressif";
const char* password = "Huzzah32";

WiFiServer server(80);

void WiFiEvent(WiFiEvent_t event, WiFiEventInfo_t info)
{
    Serial.printf("[WiFi-event] event: %d timestamp:%d\n", event, millis());
    switch (event)
    {
    case SYSTEM_EVENT_STA_GOT_IP:
        Serial.printf("WiFi connected IP address: %s duration %d\n", WiFi.localIP().toString().c_str(), millis());
        break;
    }
}

void setup()
{
    Serial.begin(115200);
    pinMode(5, OUTPUT);      // set the LED pin mode
    Serial.println("Starting Esp32 with IDF ");
    Serial.println(ESP.getSdkVersion());

    WiFi.disconnect(true);  // delete old config
    WiFi.persistent(false); //Avoid to store Wifi configuration in Flash
    WiFi.mode(WIFI_STA);
    WiFi.onEvent(WiFiEvent);
    WiFi.begin(ssid, password);
}

void loop(){
 
}

with v3.2-dev-39-gaaf12390

ets Jun  8 2016 00:22:57

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371 
ets Jun  8 2016 00:22:57

rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:808
load:0x40078000,len:6084
load:0x40080000,len:6696
entry 0x400802e4
Starting Esp32 with IDF 
v3.2-dev-39-gaaf12390
[WiFi-event] event: 4 timestamp:975
[WiFi-event] event: 7 timestamp:2045
WiFi connected IP address: 192.168.23.108 duration 2045

But with latest pull and executing get.exe (mkspiffs-0.2.3-arduino-esp32-win32.zip) v3.2-dev-1055-g3276a1316 I am getting the issue of never ending loop of WIFI_READY -> STA_START -> STA_START -> STA_DISCONNECTED with reason of HANDSHAKE_TIMEOUT and getting an IP after 100+ seconds. Any ETA that we can expect to see a fix?

@mvadu
Copy link

mvadu commented Nov 17, 2018

I did a hard reset of the esp32-arduino to last known good version git reset --hard a59eafbc9dfa3ce818c110f996eebf68d755be24 followed by tools\get.exe which reverted the idf version as well.

System: Windows, Info: Windows-10-10.0.17134
Platform: i686-mingw32
Tool xtensa-esp32-elf-win32-1.22.0-80-g6c4433a-5.2.0.zip already downloaded
Extracting xtensa-esp32-elf-win32-1.22.0-80-g6c4433a-5.2.0.zip
Downloading esptool-da31d9d-windows.zip
Done
Extracting esptool-da31d9d-windows.zip
Tool mkspiffs-0.2.3-arduino-esp32-win32.zip already downloaded
Extracting mkspiffs-0.2.3-arduino-esp32-win32.zip
Renaming mkspiffs-0.2.3-arduino-esp32-win32/ to mkspiffs
Done

@Adesin-fr
Copy link

Adesin-fr commented Dec 12, 2018

Same problem for me: Connecting with an ESP8266 to my AP in WPA security is taking about 450ms.
When trying with an ESP32, It takes about 1200ms.
Most important I think : Connecting to WEP access point takes about 250ms, on either ESP8266 and ESP32 !

@robertgregor
Copy link
Author

Yes only with WPA there is an issue. Wep or open network is ok.

@mvadu
Copy link

mvadu commented Jan 8, 2019

Today I pulled latest beta release and I can confirm that it is now connecting to WPA network in reasonable time..

sdkVersion : v3.3-beta1-136-g97eecfa1b-dirty

Trying to connect - 
[WiFi-event] event: 0 timestamp:135
[WiFi-event] event: 2 timestamp:136
[WiFi-event] event: 4 timestamp:2070
[WiFi-event] event: 7 timestamp:2082
WiFi connected IP address: *.*.*.160 duration 2082

@Adesin-fr
Copy link

That's worse than my tests; I was already at 1200ms for a WPA on ESP32.
That's still more than the 450ms of the ESP8266 !

@kenken64
Copy link

kenken64 commented Apr 2, 2019

02:30:37.966 -> ets Jun 8 2016 00:22:57
02:30:37.966 ->
02:30:37.966 -> rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
02:30:37.966 -> configsip: 0, SPIWP:0xee
02:30:37.966 -> clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
02:30:37.966 -> mode:DIO, clock div:1
02:30:37.966 -> load:0x3fff0018,len:4
02:30:37.966 -> load:0x3fff001c,len:928
02:30:37.966 -> ho 0 tail 12 room 4
02:30:37.966 -> load:0x40078000,len:9280
02:30:37.966 -> load:0x40080400,len:5848
02:30:37.966 -> entry 0x40080698
02:30:38.273 -> I (35) wifi: wifi driver task: 3ffb4e6c, prio:23, stack:3584, core=0
02:30:38.273 -> I (129) wifi: wifi firmware version: 6b44342
02:30:38.273 -> I (129) wifi: config NVS flash: enabled
02:30:38.273 -> I (131) wifi: config nano formating: disabled
02:30:38.273 -> I (152) wifi: Init dynamic tx buffer num: 32
02:30:38.308 -> I (152) wifi: Init data frame dynamic rx buffer num: 10
02:30:38.308 -> I (152) wifi: Init management frame dynamic rx buffer num: 10
02:30:38.308 -> I (155) wifi: Init static rx buffer size: 1600
02:30:38.308 -> I (160) wifi: Init static rx buffer num: 4
02:30:38.308 -> I (163) wifi: Init dynamic rx buffer num: 10
02:30:38.377 -> I (234) wifi: mode : sta (3c:71:bf:4d:6e:4c)
02:30:38.511 -> I (369) wifi: new:<9,0>, old:<1,0>, ap:<255,255>, sta:<9,0>, prof:1
02:30:39.258 -> I (1109) wifi: state: init -> auth (b0)
02:30:39.258 -> I (1112) wifi: state: auth -> assoc (0)
02:30:39.258 -> I (1116) wifi: state: assoc -> run (10)
02:30:39.258 -> I (1136) wifi: connected with xxxxxx, channel 9, bssid = 16:0c:c3:e4:26:00
02:30:39.293 -> I (1172) wifi: pm start, type: 1
02:30:39.328 ->

02:32:36.696 -> Guru Meditation Error: Core 1 panic'ed (Interrupt wdt timeout on CPU1)
02:32:36.696 -> Core 1 register dump:
02:32:36.696 -> PC : 0x4009765e PS : 0x00060734 A0 : 0x800967e2 A1 : 0x3ffbe2a0
02:32:36.730 -> A2 : 0x3ffba928 A3 : 0x3ffc0c80 A4 : 0x00000001 A5 : 0x00000001
02:32:36.730 -> A6 : 0x00060723 A7 : 0x00000000 A8 : 0x3ffc0c80 A9 : 0x3ffc0c80
02:32:36.730 -> A10 : 0x00000018 A11 : 0x00000018 A12 : 0x00000001 A13 : 0x00000001
02:32:36.730 -> A14 : 0x00060721 A15 : 0x00000000 SAR : 0x0000000a EXCCAUSE: 0x00000006
02:32:36.730 -> EXCVADDR: 0x00000000 LBEG : 0x4000c2e0 LEND : 0x4000c2f6 LCOUNT : 0xffffffff
02:32:36.765 -> Core 1 was running in ISR context:
02:32:36.765 -> EPC1 : 0x40101bf0 EPC2 : 0x00000000 EPC3 : 0x00000000 EPC4 : 0x4009765e
02:32:36.765 ->
02:32:36.765 -> Backtrace: 0x4009765e:0x3ffbe2a0 0x400967df:0x3ffbe2c0 0x40095297:0x3ffbe2e0 0x40101b6d:0x3ffbe320 0x400f09ab:0x3ffbe340 0x401020a5:0x3ffbe370 0x401025be:0x3ffbe390 0x400efa08:0x3ffbe3d0 0x400f01ed:0x3ffbe400 0x400d2aad:0x3ffbe420 0x400d243a:0x3ffbe460 0x400d24dd:0x3ffbe4a0 0x400810c0:0x3ffbe8e0 0x40081445:0x3ffbe900 0x40081bc1:0x3ffbe920 0x40101aae:0x00000000
02:32:36.800 ->
02:32:36.800 -> Core 0 register dump:
02:32:36.800 -> PC : 0x40095c6c PS : 0x00060034 A0 : 0x80096e09 A1 : 0x3ffb33d0
02:32:36.800 -> A2 : 0x3ffbdd08 A3 : 0x0000cdcd A4 : 0xb33fffff A5 : 0x00000001
02:32:36.800 -> A6 : 0x00060023 A7 : 0x0000abab A8 : 0x0000cdcd A9 : 0x3ffb33e0
02:32:36.835 -> A10 : 0x3ffbac3c A11 : 0x3ffbac3c A12 : 0x00060820 A13 : 0x00002d32
02:32:36.835 -> A14 : 0x00000000 A15 : 0x00777606 SAR : 0x00000019 EXCCAUSE: 0x00000006
02:32:36.835 -> EXCVADDR: 0x00000000 LBEG : 0x4000c2e0 LEND : 0x4000c2f6 LCOUNT : 0xffffffff
02:32:36.835 ->
02:32:36.835 -> Backtrace: 0x40095c6c:0x3ffb33d0 0x40096e06:0x3ffb3400 0x400951f7:0x3ffb3420 0x40101a96:0x3ffb3460 0x40101d72:0x3ffb3480 0x400f1e10:0x3ffb34a0 0x400f1e79:0x3ffb34c0 0x400f710d:0x3ffb34e0 0x400f7790:0x3ffb3510 0x40102d62:0x3ffb3580 0x40103a76:0x3ffb35a0 0x400f0805:0x3ffb35c0 0x4009457d:0x3ffb35f0
02:32:36.870 ->
02:32:36.870 -> Rebooting...
02:32:36.870 -> ets Jun 8 2016 00:22:57
02:32:36.870 ->
02:32:36.870 -> rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
02:32:36.870 -> configsip: 0, SPIWP:0xee
02:32:36.870 -> clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
02:32:36.905 -> mode:DIO, clock div:1
02:32:36.905 -> load:0x3fff0018,len:4
02:32:36.905 -> load:0x3fff001c,len:928
02:32:36.905 -> ho 0 tail 12 room 4
02:32:36.905 -> load:0x40078000,len:9280
02:32:36.905 -> load:0x40080400,len:5848
02:32:36.905 -> entry 0x40080698
02:32:37.178 -> I (33) wifi: wifi driver task: 3ffb4e6c, prio:23, stack:3584, core=0
02:32:37.212 -> I (126) wifi: wifi firmware version: 6b44342
02:32:37.212 -> I (126) wifi: config NVS flash: enabled
02:32:37.212 -> I (128) wifi: config nano formating: disabled
02:32:37.212 -> I (149) wifi: Init dynamic tx buffer num: 32
02:32:37.212 -> I (149) wifi: Init data frame dynamic rx buffer num: 10
02:32:37.212 -> I (149) wifi: Init management frame dynamic rx buffer num: 10
02:32:37.212 -> I (152) wifi: Init static rx buffer size: 1600
02:32:37.246 -> I (156) wifi: Init static rx buffer num: 4
02:32:37.246 -> I (160) wifi: Init dynamic rx buffer num: 10
02:32:37.280 -> I (228) wifi: mode : sta (3c:71:bf:4d:6e:4c)
02:32:37.417 -> I (363) wifi: new:<9,0>, old:<1,0>, ap:<255,255>, sta:<9,0>, prof:1
02:32:38.167 -> I (1104) wifi: state: init -> auth (b0)
02:32:38.167 -> I (1106) wifi: state: auth -> assoc (0)
02:32:38.167 -> I (1109) wifi: state: assoc -> init (6c0)
02:32:38.167 -> I (1110) wifi: new:<9,0>, old:<9,0>, ap:<255,255>, sta:<9,0>, prof:1
02:32:38.201 -> I (1111) wifi: flush txq
02:32:38.201 -> I (1112) wifi: stop sw txq
02:32:38.201 -> I (1115) wifi: lmac stop hw txq
02:32:38.201 -> I (1125) wifi: mode : sta (3c:71:bf:4d:6e:4c)
02:32:38.304 -> I (1248) wifi: new:<9,0>, old:<1,0>, ap:<255,255>, sta:<9,0>, prof:1
02:32:38.304 -> I (1249) wifi: state: init -> auth (b0)
02:32:38.339 -> I (1251) wifi: state: auth -> assoc (0)
02:32:38.339 -> I (1254) wifi: state: assoc -> run (10)
02:32:38.339 -> I (1266) wifi: connected with xxxxx, channel 9, bssid = 16:0c:c3:e4:26:00
02:32:38.339 -> I (1270) wifi: pm start, type: 1
02:32:38.339 ->

@ChuckJonas
Copy link

it's taking several minutes to connect to a wifi network for me... is this normal?

void setup()
{
    Serial.begin(115200);
    delay(10);

    // We start by connecting to a WiFi network

    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

@kifantidis
Copy link

Hello @ChuckJonas.
Which device are you using esp32 or esp8266? Have you checked your wifi range ? If you are far away from router it may be a problem. Also check with a second device the same code because the first may be not working properly.

You can find more about this problem in here: esp8266 forum and in here esp32 forum

@ChuckJonas
Copy link

ChuckJonas commented Jun 10, 2020

@kifantidis esp32. Took me FOREVER to figure out but it appears it was an issue with my router configuration.

Using a netgear RT-N56U.

Basically I had to reboot my router to get it to connect and the any subsequent connections attempts would fail with a status code of WL_NO_SSID_AVAIL. If I waited an extremely long time, sometimes it would connect again.

Tried a million different code tweaks to WiFi, with no real change.

Also, even when it did connect, any HTTP requests outside of local host would come back Connection Refused.

I turned off Spanning Tree Protocol and disabled the SPI Firewall in the router, and both issues seemed to be fixed now. Need to do more testing to narrow it down, but I feel like turning off the firewall is what really fixed it (although that kinda sucks and isn't a long term solution).

🤷

@tobiasisenberg
Copy link

I noticed recently that my connection times with the ESP32 grew to more than 2s for the pure Wifi connection after recompiling a sketch for a new device that I use in production for existing devices. I used to have much lower connection times before (completing voltage and input pin measurement, Wifi connection, and MQTT reporting all within approx. 1.3s). I tested a lot and ultimately found that the problem starts with Release 1.0.5 of arduino-esp32. With 1.0.4 I am able to connect typically within 0.96s using channel and bssid and without persistence:

WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, channel, bssid, true);

and I can connect typically within 0.21s using persistence (using WiFi.begin(WIFI_SSID, WIFI_PASSWORD); only if the regular connection fails):

WiFi.persistent(true);
WiFi.mode(WIFI_STA);
WiFi.begin();

Release 1.0.6 also is as slow as 1.0.5. I tested both with a regular router and with esp32_nat_router, the results are the same for both connection types. It would be great if the problem that was apparently introduced between 1.0.4 and 1.0.5 could be fixed in a new release. As a work-around to get fast connection times, revert to release 1.0.4 and use persistent connection (which overwrites the information in the flash only if things change, so this should generally not be a problem).

@CrappyTan
Copy link

I am really struggling with this issue.
I have a weather station which uses a 8266, wakes up every 10 minutes spends <75ms taking measurements and then a further 2-3 seconds to connect to wifi. It used to be around 300-400ms but seems some library somewhere has really slowed it down.

Static IP and also happens if I connect to a test, dummy AP with nothing else.

Around 3300% of my time is now spent connecting to wifi :)

Is there something else we can do with this?

@UncleGrumpy
Copy link

This is still a problem. Using static IP and supplying the network bssid and channel still takes over 2 seconds to connect, and over 2.5 seconds on wroom-32d chips. Changing the persistence makes absolutely no difference in connection time. Verbose debugging does not show any network scans (which is the expected behavior when supplying bssid and chan) so I have no what could be causing the delay. The same method on ESP8266 modules consistently connects in 1 second.

@CrappyTan
Copy link

I will try this this evening. That would be brilliant if we're down to those times.!

@sheffieldnikki
Copy link

sheffieldnikki commented Oct 19, 2021

I've only just started with the ESP32 and using the latest 2.0.0 release I'm also getting very slow WiFi connect times of 2.1 seconds with a static IP, or 2.6 seconds with DHCP. I've tried setting channels 11 and 13 on my router (that has a strong signal and is in the same room), supplying the channel+BSSID or not in WiFi.begin(), no authentication or WPA2. This is from a power reset, not coming out of deep sleep, and WiFi.persistent is false.

Reverting to the old 1.0.4 release suggested by @tobiasisenberg, I'm getting MUCH faster connect times of 0.21 seconds average (0.18 to 0.26s). That is with static IP and WPA2.

This is obviously a serious problem for some battery-based projects, and for my own project 2.0.0 is unusable.

2.0.0 verbose logging:

[    39][D][WiFiGeneric.cpp:808] _eventCallback(): Arduino Event: 0 - WIFI_READY
[   134][V][WiFiGeneric.cpp:96] set_esp_interface_ip(): Configuring Station static IP: 192.168.1.105, MASK: 255.255.255.0, GW: 192.168.1.1
[   134][V][WiFiGeneric.cpp:272] _arduino_event_cb(): STA Started
[   145][D][WiFiGeneric.cpp:808] _eventCallback(): Arduino Event: 2 - STA_START
[  2235][V][WiFiGeneric.cpp:284] _arduino_event_cb(): STA Connected: SSID: CENSORED, BSSID: CENSORED, Channel: 11, Auth: WPA2_PSK
[  2238][D][WiFiGeneric.cpp:808] _eventCallback(): Arduino Event: 4 - STA_CONNECTED
[  2241][V][WiFiGeneric.cpp:294] _arduino_event_cb(): STA Got New IP:192.168.1.105
[  2253][D][WiFiGeneric.cpp:808] _eventCallback(): Arduino Event: 7 - STA_GOT_IP
[  2260][D][WiFiGeneric.cpp:857] _eventCallback(): STA IP: 192.168.1.105, MASK: 255.255.255.0, GW: 192.168.1.1

1.0.4 verbose logging:

10:05:56.177 -> [D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
10:05:56.177 -> [D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
10:05:56.212 -> [D][WiFiGeneric.cpp:337] _eventCallback(): Event: 7 - STA_GOT_IP
10:05:56.352 -> [D][WiFiGeneric.cpp:381] _eventCallback(): STA IP: 192.168.1.105, MASK: 255.255.255.0, GW: 192.168.1.1
10:05:56.352 -> [D][WiFiGeneric.cpp:337] _eventCallback(): Event: 7 - STA_GOT_IP
10:05:56.352 -> [D][WiFiGeneric.cpp:381] _eventCallback(): STA IP: 192.168.1.105, MASK: 255.255.255.0, GW: 192.168.1.1

@tobiasisenberg
Copy link

@sheffieldnick So you do not get fast connection with 2.0.0 and with persistence enabled? Btw, my connection times of 0.21s for 1.0.4 and 0.09s for 2.0.0 did not use static IPs (on the side of the ESP32), just regular DHCP (where the MAC address, in my case, is always assigned a specific IP address on the router side) and WPA2. Static IPs (on the side of the ESP32) do not seem to be necessary.

@sheffieldnikki
Copy link

@sheffieldnick So you do not get fast connection with 2.0.0 and with persistence enabled?

I haven't experimented with persistence yet, so all my tests had WiFi.persistent set to false. I've now updated my comment to note that.

Static IPs (on the side of the ESP32) do not seem to be necessary.

Hmm. I imagine that is down to the specific DHCP server and settings for IP address lease time, etc? Apparently some servers can take several seconds as they check that nothing else is using the IP address they are about to assign.

@tobiasisenberg
Copy link

@sheffieldnick No, you do not need specific DHCP settings. I do not think that the DHCP settings matter at all (or much) on most routers. I simply wanted to point out that a static IP (on the side of the ESP sketch) should not be needed. And please test persistence with 2.0.0, I measured my low timing values only for a sketch that uses persistence (for both 1.0.4 and 2.0.0). This means that you should try with a simple WiFi.begin(); first, and only if this does not lead to a connection after, say, 3 or so seconds should you start another connection attempt with WiFi.begin(WIFI_SSID, WIFI_PASSWORD);. This way the ESP should, by default, connect with the credentials stored in flash (without overwriting them), and only store new credentials in flash when absolutely necessary. This should limit flash writes to a minimum, so should not cause any problems.

@RichFalk
Copy link

RichFalk commented Oct 24, 2021

I did some extensive testing with the latest build for the ESP32 and found the following regarding timing for esp_wifi_connect (this includes DHCP getting an IP address and an AP in close proximity):

  • With CONFIG_ESP32_WIFI_NVS_ENABLED not set, using a scan method of WIFI_ALL_CHANNEL_SCAN (with sort method of WIFI_CONNECT_AP_BY_SIGNAL) is very slow taking 3.6 seconds. This is also the time when CONFIG_ESP32_WIFI_NVS_ENABLED is set but the saved channel is not available so a channel scan is needed.
  • With CONFIG_ESP32_WIFI_NVS_ENABLED not set, using the default scan method (WIFI_FAST_SCAN), it is somewhat faster but still pretty slow taking 2.1 seconds if one chooses the best channel or if waking up from a deep sleep restart and takes 2.6 seconds if one chooses the worst channel and is waking up from a SW restart (not deep sleep). Some data must be stored in RTC memory for Wi-Fi to have this restart reason dependent difference in time but I didn't see it in the linker map file.
  • With CONFIG_ESP32_WIFI_NVS_ENABLED set, using a scan method of WIFI_ALL_CHANNEL_SCAN (with sort method of WIFI_CONNECT_AP_BY_SIGNAL) takes 2.1 seconds.
  • With CONFIG_ESP32_WIFI_NVS_ENABLED set, using the default scan method (WIFI_FAST_SCAN) takes 0.6 to 1.0 seconds depending on the reset/restart type and whether a regular scan is done prior to the connect. With no prior regular scan, it's 0.7 seconds on power on reset, 0.8 seconds on SW CPU reset, and 0.9 seconds on deep sleep reset.
  • The channel setting appears to be ignored when CONFIG_ESP32_WIFI_NVS_ENABLED is set.
  • Note that esp_wifi_set_storage(WIFI_STORAGE_RAM) with CONFIG_ESP32_WIFI_NVS_ENABLED set behaves between resets/restarts similarly to having CONFIG_ESP32_WIFI_NVS_ENABLED not set, as would be expected.
  • esp_wifi_scan_start only takes 1.3 seconds so the 2.1 and especially the 3.6 second time when doing an all channel scan are excessive.

As for NVS with CONFIG_ESP32_WIFI_NVS_ENABLED set, esp_wifi_init sets nvs.net80211 ap.sndChan which doesn't seem to change so will not be written to Flash (except the very first time).
esp_wifi_connect sets nvs.net80211 sta.chan and sta.apinfo so are written to flash only if they are changing. This can occur if one is intentionally changing APs between calls (such as changing SSIDs) or if one is moving between two APs of the same name (such as being equidistant between them if they have similar RSSI) AND one is using WIFI_ALL_CHANNEL_SCAN with WIFI_CONNECT_AP_BY_SIGNAL.

So it would appear that one should always be using CONFIG_ESP32_WIFI_NVS_ENABLED unless one knows they will frequently be switching between different APs. One should probably use WIFI_ALL_CHANNEL_SCAN with WIFI_CONNECT_AP_BY_SIGNAL on a new installation such as when setting the SSID from a user or from a power on reset (as a way for a user to force a best RSSI scan) or perhaps periodically such as once a day (but not frequently); otherwise one should use the default scan method (WIFI_FAST_SCAN). If you don't use an all channel scan initially, then the first matching AP found will be used and it may have poor signal strength (low RSSI).

Unfortunately, it looks like the libnet80211.a sources are not available so I can't investigate further what is going on with the esp_wifi_connect function.

@eyaleb
Copy link

eyaleb commented Oct 30, 2021

Glad to have found this thread. I was using plain IDF and everything worked just fine. My app reads some sensors and sends a UDP packet to a server. The whole activity takes about 500-600ms. The wifi connection takes 70-150ms.
The Arduino version takes 2.3-3.5 seconds. This was discussed above at length,

My initial issue is that I see on the AP there are DHCP requests from the esp32 client for each packet, and I expected none. The DHCP exchange is rather quick so it does not explain the excessively long connection time, but it still should not happen (updated: the IDF version does not show DHCP requests).

I then copied the full wifi part from the IDF project into the Arduino IDE sketch and it ran as slowly as the native Arduino sketch. Basically the same code.

I suspect there is something fundamental in the Arduino environment that acts differently to the IDF.

later

I checked-in a simple Arduino sketch I use to test the timing (wifi_test) and a similar IDF project (wifi-v4.3), here.
I will accept any specific suggestions to get the Arduino connect faster and test them.
These examples were excised from full projects so please ignore unused parts and bad style.

important note

Tested the Arduino using board version 2.0.0 - slow. Using version 1.0.6 - slow. Using version 1.0.5 - fast as expected. So there is a regression there. HTH

@luckwaski
Copy link

luckwaski commented Nov 23, 2021

Anyone looking into that?
Same here. IDF 4.3, static ip, hardcoded ssid, pass, bssid, fast_scan enabled == 3.5 seconds...
Tried various APs.

@obaterspok
Copy link
Contributor

@eyaleb

Tested the Arduino using board version 2.0.0 - slow. Using version 1.0.6 - slow. Using version 1.0.5 - fast as expected. So there is a regression there. HTH

1.0.6 changed scanning method to WIFI_ALL_CHANNEL_SCAN. Try to comment line 179 in WiFiSTA.cpp to check if that makes it as fast as 1.0.5

@eyaleb
Copy link

eyaleb commented Nov 29, 2021

Two things @obaterspok

  1. in 1.0.6 it is line 137 that needs to be commented out, and it fixes the speed problem.

  2. in 2.0.1 it is, as you say, line 179 but it makes no difference.
    I needed to fix line 85 and change the default scan_method in wifi_sta_config to
    ... scan_method=WIFI_FAST_SCAN, ...
    which did fix the speed.

HTH

@obaterspok
Copy link
Contributor

With the above patch you can do an initial slow connect in order to find the best possible channel. When we get the IP we save the channel in RTC_DATA and use it for fast connect after wakeup.

RTC_DATA_ATTR int32_t my_wifi_channel = 0;
void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info)
{
my_wifi_channel = WiFi.channel();
}

void setup()
{
// Begin serial communication
Serial.begin(115200);
Serial.printf("\nInitializing...\n");

WiFi.onEvent(WiFiGotIP, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP);

Serial.printf("Starting wifi using channel %d!\n", my_wifi_channel);
WiFi.begin("my_ap", "my_ap_pwd", my_wifi_channel);
}

@eyaleb
Copy link

eyaleb commented Dec 4, 2021

The above suggestion should work, but it means that all sketches that worked fast before, now need to be modified to work fast.
In other words, the recent change (in 1.0.6 and 2.0.*) is user visible. Do we have a policy to minimize such changes, that require modifying sketches?

@RichFalk
Copy link

RichFalk commented Dec 5, 2021

Newer ESP-IDF code (v4.4-dev-3703) is now taking only 1.5 seconds for a full scan (with CONFIG_ESP32_WIFI_NVS_ENABLED set) so this has improved from the 2.1 seconds I previously reported. This is using direct ESP-IDF code, not Arduino.

@eyaleb
Copy link

eyaleb commented Dec 14, 2021

@RichFalk . 1.5s is much slower than the 200-300ms it takes to go with WIFI_FAST_SCAN, and for my app that takes less than 500ms wakeup-to-sleep, running on battery, it is a major issue.

@RichFalk
Copy link

@eyaleb If you are waking up to do Wi-Fi frequently in a battery-powered device then yes, using the fast scan will save power. However, it doesn't come free because many environments have multiple APs sharing the same SSID in order to have automatic roaming so you want to get the strongest signal from the closest AP. So at a minimum you have to do a full scan at some point, such as from a power up (not a deep sleep restart) but even then if you lock in to the strongest signal that might still be relatively weak, then you'll have to tell users that if they add another AP or an extender to improve the signal that they would need to power cycle your device. Otherwise you will get "stuck" always connecting to the original AP with its (now) weaker signal compared to the new AP. So while you are saving power, you may be sacrificing the user experience if they try to improve RSSI by adding a new closer AP.

@eyaleb
Copy link

eyaleb commented Dec 19, 2021

Appreciated @RichFalk . For me, and anyone with a simple setup (only one AP, with hard-coded config), the old fast scan was good.
Now, I know how to work with this change, but being a change that affects users did lead to others complaining so one should be careful with user visible changes. Maybe I am more pedantic than most but when I was in charge of a product with many users, backward compatibility was critical to them. Even fixing clear bugs had to be considered carefully, documented and announced ahead of time.

@langrock
Copy link

langrock commented Dec 24, 2021

Fascinating discussion. Does anyone have a complete code sample for the 8266? I still get a connection time of around 4 seconds, using a static IP, regardless of the persistence setting. I am trying to implement a MQTT WiFi button. The MQTT part is super fast, but the network connection seems slow. Authentication is WPA2-PSK. I do recall having gotten this to work faster in the distant past, but I think that was before 'upgrading' my WiFi network.

// the following doesn't seem to make any difference
WiFi.mode(WIFI_OFF) ;
WiFi.forceSleepBegin();
delay( 1 );
WiFi.persistent(false);

WiFi.mode(WIFI_STA);
WiFi.config(ip,dns,gateway,subnet);
WiFi.begin(ssid, pass);

for (int i=0; i<200; i++) {
delay(50);
if (WiFi.status() == WL_CONNECTED) break;
}

If someone could share a known-good snippet for an 8266-01, that'd be terrific.

Thanks

p.s.: The above statement is true for both an ESP-01 and a Wemos D1 mini module. I am using the Arduino IDE 1.8.13 with the ESP8266 Community version 3.0.2

@danielchiaradia
Copy link

@langrock That worked for me (~200ms for full connection) on ESP01:

if (WiFi.SSID() != WIFI_SSID)
  {
    IPAddress local_IP(192, 168, 178, 2);
    IPAddress gateway(192, 168, 178, 1);
    IPAddress subnet(255, 255, 255, 0);
    WiFi.config(local_IP, gateway, subnet);
    WiFi.mode(WIFI_STA);
    WiFi.hostname(HOSTNAME);
    WiFi.setAutoConnect(true);
    WiFi.setAutoReconnect(true);
    int channel = getWifiChannel(WIFI_SSID);
    WiFi.begin(WIFI_SSID, PASSWORD, channel, bssid);
    WiFi.persistent(true);
  }

  if (WiFi.waitForConnectResult(6000) == WL_CONNECTED)
  {
  ...

The getWifiChannel performs a full scan via WiFi.scanNetworks() and graps the channel from the SSID. Static IP is most probably not required as mentioned above. First connection is slow but further connections from deep sleep are fast. If you change details in the wifi setup you are doomed and you have to change the hardcoded WiFi string back and forth. There is probably a better way ...

For ESP32 the solution provided by #5975 works perfect. Around 150ms for a full connection.

@langrock
Copy link

langrock commented Jan 5, 2022

@danielchiaradia Thanks. This is essentially the same that I've been using except for specifying the BSSID, which I think is the MAC address of the router, correct? I also don't recall if I ever added the channel information ... Anyhow, what confuses me a bit is the statement that you see different connection speeds depending on whether power was initially applied or the chip wakes from deep sleep. I was under the impression that waking from deep sleep (i.e. going through a full reset), is identical to completely removing and re-establishing power to the device. Is that not correct? If not, and deep sleep is indeed much faster, I will rethink the approach for some of the applications I am considering. Thanks again.

@danielchiaradia
Copy link

@langrock Yes, the BSSID is the router MAC. The slow WiFi connection is as per my understanding caused by the channel scan. If you provide the channel in WiFi.begin(... then the channel scan will be skipped.
By first connection I mean the first time your program ever runs on the ESP8266. The first boot up will determine the correct channel and then the ESP8266 stores the channel information in flash memory. If you turn the ESP8266 off and on again then the ESP8266 will establish the WiFi connection with the stored credentials and channel information.

However, your router might change the channel automatically depending on your router settings. So, be sure your program on the ESP8266 can deal with it (e.g. scan the channel again when the connection cannot be established within the timeout).

@eyaleb
Copy link

eyaleb commented Jan 5, 2022

@langrock, a reset is not the same as deep-sleep wake-up. Read on power modes to see the details, but basically deep-sleep keeps an RTC running and keeps RTC memory content while a reset clears everything. Separately, some wifi info supplied on first reset can be saved and used after reset and after wake-up.

@sp4rkie
Copy link

sp4rkie commented Apr 16, 2023

I do not use a static IP, BSSID or channel.

even with that it takes an average of about 220ms(!) overall elapsed time between keypress (wakeup) to status (received from remote machine)
started to document my setup here: sp4rkie/ultra-remote-idf: fast ESP32 WiFi remote control (ESP-IDF variant)

espressif must have done lots of improvements since then. cheers

@denielsenp
Copy link

Hi, I've read this thread and tried various fixes that was posted, but still I only manage to make it go on average of 2.2s to connect to wifi. Does anybody have any update regarding this?

int capacitivePin=26;
RTC_DATA_ATTR int32_t my_wifi_channel = 0;
void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info)
{
my_wifi_channel = WiFi.channel();
}
void setup(){
    Serial.begin(115200);
    pinMode(GPIO_NUM_26, INPUT);
    Serial.print("Wifi Channel on Wake: ");
    Serial.println(my_wifi_channel);
    unsigned long StartTime = millis();
    WiFi.onEvent(WiFiGotIP, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP);
    WiFi.begin(ssid, password,my_wifi_channel);
    Serial.println("\nConnecting");
    while(WiFi.status() != WL_CONNECTED){
        Serial.print(".");
    }
    unsigned long CurrentTime = millis();
    unsigned long ElapsedTime = CurrentTime - StartTime;
    Serial.println("");
    Serial.print("Elapsed Time to Connect: ");
    Serial.println(ElapsedTime);
    Serial.print("Wifi Channel: ");
    Serial.println(my_wifi_channel);
    WiFi.disconnect();
    esp_sleep_enable_ext0_wakeup(GPIO_NUM_26,1);
    esp_deep_sleep_start();
}

@marcelstoer
Copy link
Contributor

@denielsenp Setting the BSSID (AP MAC address) in addition to channel in WiFi.begin() I managed to reduce the handshake time from ~2.2s to <50ms.

Obvious caveats:

  • Initially the BSSID is likely unknown unless you do this for a WiFi network you control -> use the same approach you chose for dealing with the channel number
  • What if you (or the user) replaces the AP but keeps the SSID/password (-> new BSSID)? -> implement graceful error handling, e.g. "forget" BSSID and channel after five failed connection attempts
  • OR use a WiFi manager library that takes care of this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Area: ESP-IDF related ESP-IDF related issues Status: Solved Type: Feature request Feature request for Arduino ESP32
Projects
None yet
Development

Successfully merging a pull request may close this issue.