Skip to content

WiFi.status() still returns WL_CONNECTED when after access point is turned off (Only AndroidAP) #4352

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
toomasz opened this issue Feb 11, 2018 · 8 comments
Labels
waiting for feedback Waiting on additional info. If it's not received, the issue may be closed.

Comments

@toomasz
Copy link

toomasz commented Feb 11, 2018

Basic Infos

Hardware

Hardware: ESP-12E
Core Version: 2.4

Description

Test scenario:
1.Start sketch, access point is disabled
2.Enable access point
3.Sketch can connect to access point
4.Disable access point
5. WiFi.Status() still returns WL_CONNECTED

Settings in IDE

Module: NodeMCU 1.0 (ESP12-E)
Flash Size: 4MB
CPU Frequency: 160Mhz
Upload Using: Serial
Reset Method: nodemcu

Sketch

#include <Arduino.h>
#include <ESP8266WiFi.h>

void setup()
{
	Serial.begin(115200);
	Serial.println("Setup");
}
bool wifiConnect(int timeout)
{
	Serial.println("Connecting to wifi...");
	uint64_t start = millis();

	WiFi.setAutoReconnect(false);
	WiFi.setAutoConnect(false);
	WiFi.mode(WiFiMode_t::WIFI_STA);
	auto connectResult = WiFi.begin("AndroidAP", "*******");
	
	while (WiFi.status() != WL_CONNECTED)
	{
		delay(100);
		Serial.print(".");

		if (millis() - start > timeout)
		{
			WiFi.disconnect();
			return false;
		}
	}
	
	Serial.println();
	return true;
}

wl_status_t prevStatus;
void loop()
{
	
	auto wifiState = WiFi.status();
	if (WiFi.status() != prevStatus)
	{
		Serial.printf("Wifi State changed to %s\n", WlStatusToStr(WiFi.status()));
		prevStatus = WiFi.status();
	}

	if (!WiFi.isConnected())
	{		
		if (wifiConnect(5000))
		{
			Serial.println("Successfully connected");
		}
		else
		{
			Serial.println("Timeout");
		}
		delay(1000);
	}
}

const char* WlStatusToStr(wl_status_t wlStatus)
{
	switch (wlStatus)
	{
	case WL_NO_SHIELD: return "WL_NO_SHIELD";
	case WL_IDLE_STATUS: return "WL_IDLE_STATUS";
	case WL_NO_SSID_AVAIL: return "WL_NO_SSID_AVAIL";
	case WL_SCAN_COMPLETED: return "WL_SCAN_COMPLETED";
	case WL_CONNECTED: return "WL_CONNECTED";
	case WL_CONNECT_FAILED: return "WL_CONNECT_FAILED";
	case WL_CONNECTION_LOST: return "WL_CONNECTION_LOST";
	case WL_DISCONNECTED: return "WL_DISCONNECTED";
	default: return "Unknown";
	}
}

Debug Messages from AndroidAP

Connecting to wifi...
.....................scandone
wifi evt: 1
STA disconnect: 201
..........................Timeout
Connecting to wifi...
.....................scandone
wifi evt: 1
STA disconnect: 201
..........................Timeout
Connecting to wifi...
.......wifi evt: 2
..............scandone
state: 0 -> 2 (b0)
.state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 1
cnt 

connected with AndroidAP, channel 6
dhcp client start...
wifi evt: 0
.ip:192.168.43.112,mask:255.255.255.0,gw:192.168.43.1
wifi evt: 3
.
Successfully connected
Wifi State changed to WL_CONNECTED
pm open,type:2 0
state: 5 -> 2 (3c0)
rm 0
pm close 7
wifi evt: 1
STA disconnect: 3

Debug messages from hardware router:

Wifi State changed to WL_CONNECTED
pm open,type:2 0
bcn_timout,ap_probe_send_start
ap_probe_send over, rest wifi status to disassoc
state: 5 -> 0 (1)
rm 0
pm close 7
wifi evt: 1
STA disconnect: 200
Wifi State changed to WL_IDLE_STATUS
Connecting to wifi...
.scandone
wifi evt: 1
STA disconnect: 201
@toomasz toomasz changed the title WiFi.status() still returns WL_CONNECTED when after access point is turned off WiFi.status() still returns WL_CONNECTED when after access point is turned off (Only AndroidAP) Feb 11, 2018
@devyte
Copy link
Collaborator

devyte commented Jul 13, 2018

Several fixes have been merged since this was opened, especially into the lwip glue code. Is this issue still valid with latest git?

@devyte devyte added the waiting for feedback Waiting on additional info. If it's not received, the issue may be closed. label Jul 13, 2018
@toomasz
Copy link
Author

toomasz commented Jul 22, 2018

@devyte

Unfortunately still reproducible:

Opening port
Port open
.................................................Timeout
Connecting to wifi...
............................scandone
wifi evt: 1
STA disconnect 1: 201
......................Timeout
Connecting to wifi...
...............wifi evt: 2
.............scandone
state: 0 -> 2 (b0)
.state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 1
cnt 

connected with gx2, channel 11
dhcp client start...
wifi evt: 0
.ip:192.168.43.16,mask:255.255.255.0,gw:192.168.43.1
wifi evt: 3
.
Successfully connected
Wifi State changed to WL_CONNECTED
state: 5 -> 2 (3c0)
rm 0
wifi evt: 1
STA disconnect: 3

@LucaEstiva
Copy link

LucaEstiva commented Jan 30, 2019

WiFi connection status tested ( On my scenario is WORKING ):
The simple scenario is one Lolin as STATION one as AP
Development board Lolin V3:

STATION CODE:

  //
  #include <ESP8266WiFi.h>

  #define WLAN_SSID "ESPap"
  #define WLAN_PASS "12345678"

    // 5 Sec interval
  #define INTERVAL_5 5000
  
  // 
  uint32_t time_1 = 0;
  //
  uint32_t StartTime = 0;
  //
  int32_t TimeLapsed = 0;

  // Expands to <HOST NAME>-<last 4 decimal chars of MAC address>
  #define WIFI_HOSTNAME "%s-%04d"
  
  // WiFi STATUS STRINGS
  const char* WiFiStat[]={"WL_IDLE_STATUS", "WL_NO_SSID_AVAIL", "WL_SCAN_COMPLETED",
  "WL_CONNECTED", "WL_CONNECT_FAILED", "WL_CONNECTION_LOST", "WL_DISCONNECTED"};
  
  // Composed Wifi hostname
  char this_hostname[33];

  // CURRENT WiFi CONNECTION STATUS
  uint8_t wifi_status;

  // WiFi FIRST TIME CONNECTION STATUS FLAG
  bool WiFi_Connected = false;
  // WiFi DISCONNECTED STATUS  FLAG
  bool WiFi_Disconnected = false;

  //
  int WiFi_Connection_Time_Out = 15;
  //
  int WiFi_Connection_Time = 0;

//------------------------------------------------------------------------------------------
// SETUP
//------------------------------------------------------------------------------------------
void setup()
{
  
  //
  Serial.begin(115200);
  //
  Serial.printf("%s%d\n", "Chip id: ", ESP.getChipId());

  // Compose the host name string
  snprintf_P( this_hostname, sizeof( this_hostname )-1, WIFI_HOSTNAME, "TEST", ESP.getChipId() & 0x1FFF );

  // At this point WiFi state is WL_DISCONNECTED
  Serial.printf("1: Connection status: %s\n", WiFiStat[WiFi.status()] );
  
  // Set up basic WiFi parameters
  WiFiStationSetup();
  // At this point WiFi state is WL_IDLE_STATUS
  Serial.printf("2: Connection status: %s\n", WiFiStat[WiFi.status()] );

}

//------------------------------------------------------------------------------------------
// MAIN LOOP
//------------------------------------------------------------------------------------------
void loop()
{
  
  // Returns the number of milliseconds since the Arduino board began running the current program.
  // This number will overflow (go back to zero), after approximately 50 days.
  // https://arduino.stackexchange.com/questions/12587/how-can-i-handle-the-millis-rollover
  if( StartTime > millis() )
    StartTime = UINT32_MAX - ( UINT32_MAX - millis() );
  else
    StartTime = millis();

    // RUN THIS CODE EVER 5 Sec
    if( StartTime > ( time_1 + INTERVAL_5 ) )
    {
        // Save the current time
        time_1 = StartTime;
        //
        WiFiState();
    }
  
  // CALCULATE ELAPSED TIME
  TimeLapsed = ( int32_t )millis() - StartTime;
  
}

//------------------------------------------------------------------------------------------
// WiFi NEED SOME TIME TO CONNECT...
//------------------------------------------------------------------------------------------
void WiFiState()
{

// 0 : WL_IDLE_STATUS when Wi-Fi is in process of changing between statuses
// 1 : WL_NO_SSID_AVAIL in case configured SSID cannot be reached
// 3 : WL_CONNECTED after successful connection is established
// 4 : WL_CONNECT_FAILED if password is incorrect
// 6 : WL_DISCONNECTED if module is not configured in station mode

  // Get the actually WiFi connection status
  wifi_status = WiFi.status();
  //
  Serial.printf("Connection status: %s\n", WiFiStat[wifi_status] );

  // IMMEDIATELY AFTER WiFi IS CONFIGURED THE STATUS IS WL_IDLE_STATUS
  // WHEN THE WiFi ARE CONNECTED AND THEN DISCONNECTED THE STATUS IS WL_IDLE_STATUS !!!
  // IMMEDIATELY AFTER CONNECTION BEGIN IS CALLED THE STATUS BECOME WL_DISCONNECTED !!!

  // Check the connection status
  switch ( wifi_status )
  {
    
    case WL_CONNECTED:

      //
      Serial.printf("WiFi connected. IP address: %s\n", WiFi.localIP().toString().c_str() );

      // SET FIRST WiFi CONNECTION SUCCESS FLAG
      if( !WiFi_Connected ) WiFi_Connected = true;
      //
      WiFi_Connection_Time = 0;
        
      break;
    case WL_CONNECTION_LOST:
        //
        Serial.printf("WiFi connection LOST !\n");
      break;
    case WL_NO_SSID_AVAIL:  // THE ACCESS POINT IS NOT REACHABLE
        //
        Serial.printf("WiFi connection FAIL - WL_NO_SSID_AVAIL\n");
      break;
    case WL_CONNECT_FAILED:
        //
        Serial.printf("WiFi connection FAIL -WL_CONNECT_FAILED\n");
      break;
    case WL_DISCONNECTED:
    
      // TRY TO RECONNECT...
      if( WiFi_Connection_Time >= WiFi_Connection_Time_Out )
      {
        //
        WiFi_Connection_Time = 0;
        //
        WiFiStationStart();
      }
      else
        //
        WiFi_Connection_Time += 5;
      
      break;
    case WL_IDLE_STATUS:

      // WHEN THE WiFi ARE CONNECTED AND THEN DISCONNECTED THE STATUS IS WL_IDLE_STATUS !!!
      // THE WiFi NEED TO BE RECONFIGURED, THIS PROBABLY IS BECAUSE NO WiFi PARAMETERS ARE SAVED...
    
      //
      if( WiFi_Connected )
      {
        // SET THE WiFi DISCONNECTED FLAG TO THE RIGHT VALUE
        WiFi_Disconnected = true;
        //
        WiFiStationSetup();
        //
        delay(1000);
      }
      
      // MAKE VERY FIRST WiFi CONNECTION AFTER WiFi CONFIG WITHOUT RECONFIGURE THE WiFi.

      //
      WiFiStationStart();

      
      break;
    default:  //
    break;
  }

}

//------------------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------------------
void WiFiStationSetup(void)
{
  
  // Solve possible wifi init errors (re-add at 6.2.1.16 #4044, #4083)
  // Don't save WiFi configuration in flash - optional
  WiFi.persistent( false );
  // Delete SDK WiFi config
  WiFi.disconnect( true );
  //
  delay(500);
  //
  WiFi.config( IPAddress( 192,168,4,70 ), IPAddress( 192,168,4,1 ), IPAddress( 255,255,255,0 ) );

  /* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
     would try to act as both a client and an access-point and could cause
     network-issues with your other WiFi-devices on your WiFi-network. */
  WiFi.mode( WIFI_STA );
  //
  WiFi.setAutoReconnect(false);
  
  // AutoConnect control screen will be displayed automatically for establishing new connections.
  // It aids by the captive portal when vested the connection cannot be detected.
  // By using the AutoConnect menu, to manage the connections convenient
  // https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/station-class.html?highlight=disconnect#disconnect
  if( WiFi.getAutoConnect() ) WiFi.setAutoConnect( false );
  
  //
  WiFi.hostname( this_hostname );

  //
  Serial.printf("WiFi STATION SETUP OK\n");
  
}

//------------------------------------------------------------------------------
// BEGIN CONNECTING TO THE WIFI ACCESS POINT
//------------------------------------------------------------------------------
void WiFiStationStart(void)
{
  //
  WiFi.begin( WLAN_SSID, WLAN_PASS );
  //
  Serial.printf("WiFi is try to connect to: %s\n", WLAN_SSID);
}

ACCESS POINT CODE ( NOT CLEANED sry… BUT WORKING ):

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

  // Max number of characters in (serial and http) command buffer
  #define INPUT_BUFFER_SIZE 520

/* Set these to your desired credentials. */
const char *ssid = "ESPap";
const char *password = "12345678";

ESP8266WebServer server(80);

//------------------------------------------------------------------------------
// HANDLE HTTP HOME PAGE REQUEST
//------------------------------------------------------------------------------
void HandleRoot()
{

  String message = "<!DOCTYPE html><html>";
  message += "<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">";
  message += "<link rel=\"icon\" href=\"data:,\">";
  
  // CSS to style the on/off buttons 
  message += "<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;";
  message += ".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;";
  message += "text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;";
  message += ".button2 {background-color: #555555;}</style></head>";
            
  // Web Page Heading
  message += "<body><h1>ESP8266 ACCESS POINT</h1>";
  message += "AP IP: " + String( WiFi.softAPIP() )+ "</p>";

  //
  message += "<p>RSSI: " + String(WiFi.RSSI(), DEC) + " dBm </p>";
  //
  message += "</br>";
  //
  message += "<p>Connected devices: " + String(WiFi.softAPgetStationNum(), DEC) + "</p>";
  
//  //
//  if( WiFi.softAPgetStationNum() )
//  {
//    //
//    message += "<table style='width:100%'>";
//    //
//    for( int i = 0; i < WiFi.softAPgetStationNum(); i++ )
//    {
//      //
//      message += "<tr>";
//      //
//      message += "<th>" + + "</th>";
//      //
//      message += "</tr>";
//    }
//
//    //
//    message += "</table>";
//  }

  //
  message += "<p><a href=\"/cm?cmnd=Disconnect cliens\"><button class=\"button button2\">DisC</button></a></p>";
  
  //
  message += "</body></html>";

  // SEND RESPONSE TO THE HTTP CLIENT
  // 200 OK
  server.send(200, "text/html", message);
  
}

//------------------------------------------------------------------------------
// WEB DATA HANDLER
//------------------------------------------------------------------------------
void HandleHttpCommand(void)
{
  
  // if (header.indexOf("GET /26/on") >= 0)
  // Serial.printf("Access point ready with ip: %s\n", WiFi.softAPIP() );
  // http://192.168.0.1/cm?cmnd=POWER1 ON
  // http://192.168.0.1/cm?cmnd=Restart
  // http://192.168.0.1/cm?cmnd=Update


  // Large to serve Backlog
  char svalue[INPUT_BUFFER_SIZE];
  //
  WebGetArg("cmnd", svalue, sizeof(svalue));
  
  // THE COMMAND IS CONTAINED IN TO THE WEB ARGS STRING ?
  if( strlen( svalue ) )
  {
    //
    if( strcmp(svalue, "DisC") == 0 )
    {
      //
      DisconnectClients();
      Serial.print("Disconnect all connected clients !\n");
    }

  }

    //
    String message = "Number of args received:";
    // Get number of parameters
    message += server.args();
    // Add a new line caracter
    message += "\n";

    //
    for( int i = 0; i < server.args(); i++ )
    {
      // Include the current iteration value
      message += "Arg no: " + ( String )i + " -> ";
      // Get the name of the parameter
      message += server.argName(i) + " : ";
      // Get the value of the parameter
      message += server.arg(i) + "\n";
    }
    
  // SEND RESPONSE TO THE HTTP CLIENT
  // 200 OK
  server.send(200, "text/plain", message);
  
}

//------------------------------------------------------------------------------------------
// WEB SERVER HANDLE NOT FOUND PAGE - 404 NOT FOUND
//------------------------------------------------------------------------------------------
void HandleNotFound()
{

  String message = "Page Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  
  //
  for( uint8_t i = 0; i < server.args(); i++ )
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";

  //
  server.send(404, "text/plain", message);

}

//------------------------------------------------------------------------------
// 
//------------------------------------------------------------------------------
static void WebGetArg(const char* arg, char* out, size_t max)
{
  //
  String s = server.arg(arg);
  //
  strlcpy(out, s.c_str(), max);
}

//------------------------------------------------------------------------------------------
// WEB SERVER HANDLE NOT FOUND PAGE - 404 NOT FOUND
//------------------------------------------------------------------------------------------
void DisconnectClients()
{
  // IF ONE OR MORE CLIENT CONNECTED - Disconnect stations from the network established by the soft-AP.
  if( WiFi.softAPgetStationNum() ) WiFi.softAPdisconnect( false );
  //
  delay(500);
}

//------------------------------------------------------------------------------------------
// WEB SERVER HANDLE NOT FOUND PAGE - 404 NOT FOUND
//------------------------------------------------------------------------------------------
void setup()
{
  delay(1000);
  Serial.begin(115200);

  static WiFiEventHandler e1;
  
  Serial.println();
  Serial.print("Configuring access point...");

  // WIFI_AP_STA
  WiFi.mode(WIFI_AP);
  /* You can remove the password parameter if you want the AP to be open. */
  WiFi.softAP(ssid, password);
  // Event subscription
  e1 = WiFi.onSoftAPModeStationConnected(onNewStation);
  //
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  //
  server.on("/", HandleRoot);
  server.on("/cm", HandleHttpCommand);
  server.onNotFound(HandleNotFound);
  
  //
  server.begin();

  //
  Serial.println("HTTP server started");
}

//------------------------------------------------------------------------------------------
// WEB SERVER HANDLE NOT FOUND PAGE - 404 NOT FOUND
//------------------------------------------------------------------------------------------
void loop()
{
  //
  server.handleClient();
}

void onNewStation(WiFiEventSoftAPModeStationConnected sta_info)
{

  char last_mac[18];
  Serial.println("New Station :");
  sprintf(last_mac,"%02X:%02X:%02X:%02X:%02X:%02X", MAC2STR(sta_info.mac));
  Serial.printf("MAC address : %s\n",last_mac);
  Serial.printf("Id : %d\n", sta_info.aid);

}

@d-a-v
Copy link
Collaborator

d-a-v commented Jan 30, 2019

@toomasz Please confirm for the fix in latest releases

@d-a-v d-a-v added waiting for feedback Waiting on additional info. If it's not received, the issue may be closed. and removed waiting for feedback Waiting on additional info. If it's not received, the issue may be closed. labels Jan 30, 2019
@abqmichael
Copy link

I am actually having a similar issue on an ESP32 but have not built a simplified test case to narrow this down.

@devyte
Copy link
Collaborator

devyte commented Feb 2, 2020

Closing in view of @LucaEstiva 's comment and due to lack of feedback by OP.

@devyte devyte closed this as completed Feb 2, 2020
@HaunsTM
Copy link

HaunsTM commented Mar 8, 2021

Are there any news here? I'm facing the same issue on Mar 8, 2021?

@JorgeVelez
Copy link

same issue april 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
waiting for feedback Waiting on additional info. If it's not received, the issue may be closed.
Projects
None yet
Development

No branches or pull requests

7 participants