简体   繁体   中英

Unable to connect in Ap_mode in esp32

I am making and auto connect code for esp32 in which i am trying to get wifi credential from the webpage when it is operated in ap-mode after getting credential it will connected to wifi whose credential are provided in webpage. But problem i am facing is that i am unable to connect my esp module when it is in ap mode here is my code.

#include "SPIFFS.h"
#include <FS.h>
#include <ArduinoJson.h>
#include "WiFi.h"
#include "ESPAsyncWebServer.h"

uint8_t pin_led = 2;
char* ssid = "YOUR_SSID"; //not used
char* password = "YOUR_AP_PASSWORD";
char* mySsid = "YOUR_AP_SSID";
AsyncWebServer server(80);

IPAddress local_ip(192,168,11,4);
IPAddress gateway(192,168,11,1);
IPAddress netmask(255,255,255,0);

char webpage[] PROGMEM = R"=====(
  <html>
   <head>
    </head>
       <body>
        <form>
       <fieldset>
           <div>
              <label for="ssid">SSID</label>      
              <input value="" id="ssid" placeholder="SSID">
             </div>
          <div>
              <label for="password">PASSWORD</label>
           <input type="password" value="" id="password" placeholder="PASSWORD">
          </div>
            <div>
             <button class="primary" id="savebtn" type="button" onclick="myFunction()">SAVE</button>
                </div>
         </fieldset>
         </form>
            </body>
              <script>
         function myFunction()
           { 
              console.log("button was clicked!");
              var ssid = document.getElementById("ssid").value;
              var password = document.getElementById("password").value;
                    var data = {ssid:ssid, password:password};
                 var xhr = new XMLHttpRequest();
                 var url = "/settings";
                xhr.onreadystatechange = function() {
               if (this.readyState == 4 && this.status == 200) {
               // Typical action to be performed when the document is ready:
              if(xhr.responseText != null){
               console.log(xhr.responseText);
                 }
               }
              };
               xhr.open("POST", url, true);
               xhr.send(JSON.stringify(data));
             };
        </script>
         </html>
           )=====";

     void setup()
     {
       pinMode(pin_led, OUTPUT);
       Serial.begin(115200);
       SPIFFS.begin();

       wifiConnect();
      server.on("/", HTTP_POST, [](AsyncWebServerRequest *request){
          request->send_P(200, "text/html", webpage);
          });
      server.on("/toggle", HTTP_POST, [](AsyncWebServerRequest *request){
         digitalWrite(pin_led,!digitalRead(pin_led));
          request->send(204,"");
         });
          server.on("/settings", HTTP_POST, [](AsyncWebServerRequest *request){
          if(request->hasArg("plain")){
         String data = request->arg("plain");//("plain");
         DynamicJsonDocument doc(1024);
         serializeJson(doc, data);
       // DynamicJsonBuffer jBuffer;
       //JsonObject jObject = doc.as<JsonObject>();

         File configFile = SPIFFS.open("/config.json", "w");
        serializeJsonPretty(doc, configFile);

        //jObject.printTo(configFile);  
        configFile.close();

        request->send(200, "application/json", "{\"status\" : \"ok\"}");
        delay(500);

        wifiConnect();
         }});

         server.begin();
        }

      void loop()
      {
      }

      void wifiConnect()
      {
       //reset networking
       WiFi.softAPdisconnect(true);
       WiFi.disconnect();          
       delay(1000);
        //check for stored credentials
       if(SPIFFS.exists("/config.json")){
        const char * _ssid = "", *_pass = "";
         File configFile = SPIFFS.open("/config.json", "r");
        if(configFile){
        size_t size = configFile.size();
        std::unique_ptr<char[]> buf(new char[size]);
        configFile.readBytes(buf.get(), size);
        configFile.close();

  DynamicJsonDocument doc(1024);
 // DynamicJsonBuffer jsonBuffer;
   DeserializationError error=deserializeJson(doc, buf.get());
 //JsonObject& jObject = doc.as<JsonObject>();
 if (error)
   {
   Serial.print("deserializeJson() failed: ");
   Serial.println(error.c_str());
   }
    else{
      _ssid = doc["ssid"];
      _pass = doc["password"];
    WiFi.mode(WIFI_STA);
    WiFi.begin(_ssid, _pass);
    unsigned long startTime = millis();
    while (WiFi.status() != WL_CONNECTED) 
    {
      delay(500);
      Serial.print(".");
      digitalWrite(pin_led,!digitalRead(pin_led));
      if ((unsigned long)(millis() - startTime) >= 5000) break;
    }
  }
 }
}

if (WiFi.status() == WL_CONNECTED)
{
  digitalWrite(pin_led,HIGH);
} else 
{
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(local_ip, gateway, netmask);
  WiFi.softAP(mySsid, password); 
  digitalWrite(pin_led,LOW);      
}
Serial.println("");
WiFi.printDiag(Serial);
}

Please help me to figure it out

Putting the wifiConnect() as the last command in setup worked for my environment.
This program works only under two important preconditions.
1. No json on SPIFFS - so make sure during testing you always have a fresh formatted SPIFFS
2. No open AP in range, because it will connect to it without pw and no AP_mode would be initiated.
There are a lot of more or less working examples for captive portals especially for ESP32 around, but they all have their specific detection problems (eg always read the issues on github)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM