Brauche Hilfe bei meinem Project ESP zeigt nicht verbunden obwohl router verbunden zeigt

Hallo,

ich habe ein code geschrieben der ein Hotspot oeffnet und diesen automatisch beendet sobald die wifi daten eingegebn und gespeichert wurden. Allerdings oeffnet er nun jedesmal ein Hotspot auch wenn die Daten eingegeben sind und er sich mit dem Router verbindet.

Wo ist mein Fehler??

Hier mein Code

https://codeshare.io/QnVxLm

#define LOGLEVEL_ERROR 0
#define LOGLEVEL_WARN 1
#define LOGLEVEL_INFO 2
#define LOGLEVEL_DEBUG 3



#define SSID_MAX_LEN 32
//From v1.0.10, WPA2 passwords can be up to 63 characters long.
#define PASS_MAX_LEN 64


#include <ESPAsyncWebServer.h>
#include <EEPROM.h>
#include <FS.h>
#include <LittleFS.h>
#include "ArduinoJson.h"

#if defined(ESP8266)
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
//#define ASYNC_TCP_SSL_ENABLED       false

#define FILE_READ "r"
#define FILE_WRITE "w"
#define FILE_APPEND "a"
FSInfo fs_info;
#elif defined(ESP32)
#include <WiFi.h>
#include <ESPmDNS.h>
//#define ASYNC_TCP_SSL_ENABLED       false


//#define LED_BUILTIN D27

struct FSInfo {
  size_t totalBytes;
  size_t usedBytes;
};
FSInfo fs_info;

#else
#error "This ain't a ESP8266 or ESP32!"
#endif

bool flagConfigurationFileExist = false;
bool flagLittleFSExist = false;
bool flagConfigurationLoaded = false;
bool flagWebServerActive = false;

bool flagFileUploadStart = true;
bool flagFileUploadActive = false;
bool flagMQTTConfigured = false;
bool flagMQTTConnected = false;
bool flagLockWriteFileFunction = false;
int globalLogLevel = LOGLEVEL_INFO;



char voltagechar[50];
unsigned int voltageraw = 0;
float voltage = 0;

struct FileInformation {
  String name;
  size_t filesize;
};

std::vector<FileInformation> FileInformations;
std::vector<String> readedLines;


struct WiFiInformation {
  String name;
  int rssi;
  bool encryption;
};

std::vector<WiFiInformation> WiFiInformations;

typedef struct
{
  char wifi_ssid[SSID_MAX_LEN];
  char wifi_pw[PASS_MAX_LEN];

} WiFi_Credentials;


typedef struct
{
  WiFi_Credentials WiFi_Creds;
  uint16_t checksum;
} WM_Config;

WM_Config WM_config;




AsyncWebServer webServer(80);

int statusCode;

bool flagStatusMessageSend = false;
char configFileName[] = "/config.json";
#define DEVICENAME_LEN 20
char devicename[DEVICENAME_LEN] = "";







//Function Decalration
bool testWifi(void);
void launchWeb(void);
void setupAP(void);
void startWebServer();
void logging(int logLevel, String message, bool newLine);
void updateFromFS();
void createWebServer();

#if defined(ESP8266)
void infoFilesystem(fs::FS &fs, FSInfo *fs_info) {
  if (flagLittleFSExist) {
    fs.info(*fs_info);
  } else {
    logging(LOGLEVEL_ERROR, "Filesystem not mounted", true);
  }
}
#elif defined(ESP32)
void infoFilesystem(FSInfo *fs_info) {
  if (flagLittleFSExist) {
    fs_info->usedBytes = LittleFS.usedBytes();
    fs_info->totalBytes = LittleFS.totalBytes();
  }
}
#endif


int FindChar(char *ZeichenKette, char *c) {
  for (size_t i = 0; i < strlen(ZeichenKette); i++)
    if (ZeichenKette[i] == int(c))
      return (i);
  // ansonsten -1 zurückgeben
  return (-1);
}
/* ------------------------------------------------------------
 *  Daten in eine Datei schreiben
 *  - existiert die Datei, wird sie überschrieben (Modus FILE_WRITE)
 *    oder die Daten werden angehängt (Modus FILE_APPEND)
 *  
 *  Parameter:
 *  - Dateisystem (sollte LITTLEFS sein)
 *  - Dateiname (vollständige Pfadangabe)
 *  - zu schreibende Daten (als Zeichenkette)
 *  - Modus zum Öffnen (FILE_WRITE oder FILE_APPEND)
 * ------------------------------------------------------------ */
void writeFile(fs::FS &fs,
               const char *path,
               const char *message,
               const char *mode) {
  //logging(LOGLEVEL_INFO, "Schreibe Datei: " + String(path), true);

  char pathlocal[200];
  char pattern[] = { '/' };

  sprintf(pathlocal, path);

  if (flagLittleFSExist) {
#if defined(ESP8266)
    if (String(mode) != FILE_WRITE && String(mode) != FILE_APPEND) {
#elif defined(ESP32)
    if (mode != FILE_WRITE && mode != FILE_APPEND) {
#endif
      if (!flagLockWriteFileFunction) {
        logging(LOGLEVEL_ERROR, "- ungültiger Zugriffsmodus (WRITE/APPEND)", true);
        flagLockWriteFileFunction = true;
      } else {
      }
    }


    if (!FindChar(pathlocal, pattern) == 0) {



      sprintf(pathlocal, "%s%s", "/", path);
    }
    File file = fs.open(pathlocal, mode);



    if (!file) {
      if (!flagLockWriteFileFunction) {
        logging(LOGLEVEL_ERROR, "- kann Datei nicht zum Schreiben öffnen", true);
        flagLockWriteFileFunction = true;



      } else {
      }
      file.close();
      return;
    }

    if (file.print(message)) {

#if defined(ESP8266)
      if (String(mode) == FILE_WRITE) {
#elif defined(ESP32)
      if (mode == FILE_WRITE) {
#endif
        //logging(LOGLEVEL_INFO, "- Datei neu geschrieben", true);
      } else {
        //logging(LOGLEVEL_INFO, "- Daten an Datei angehängt", true);
      }
    } else {
      if (!flagLockWriteFileFunction) {
        logging(LOGLEVEL_ERROR, "- Schreiben fehlgeschlagen", true);
        flagLockWriteFileFunction = true;
      } else {
      }
    }
    file.close();
  }
  //free(finalpath);
}
/* ------------------------------------------------------------
 *  Inhalt einer (Text-)Datei ausgeben
 *  
 *  Parameter:
 *  - Dateisystem (sollte LITTLEFS sein)
 *  - Dateiname (vollständige Pfadangabe)
 * ------------------------------------------------------------ */
void readFile(fs::FS &fs, const char *path, std::vector<String> *readedLines) {
  logging(LOGLEVEL_INFO, "Lese Datei: " + String(path), true);
  char Zeichen;
  String ZKette;
  char pathlocal[200];
  char pattern[] = { '/' };

  sprintf(pathlocal, path);

  readedLines->clear();
  if (!FindChar(pathlocal, pattern) == 0) {



    sprintf(pathlocal, "%s%s", "/", path);
  }

  File file = fs.open(pathlocal, "r");

  if (!file || file.isDirectory()) {
    logging(LOGLEVEL_ERROR, "- kann Datei nicht zum Lesen öffnen", true);

    return;
  }
  logging(LOGLEVEL_INFO, "- lese Datei:", true);

  while (file.available()) {
    // Dateiinhalt Zeichen für Zeichen lesen und ausgeben
    Zeichen = file.read();
    if ((byte)Zeichen != 13 && (byte)Zeichen != 10) {
      ZKette += Zeichen;
      //logging(LOGLEVEL_INFO, ZKette, true);
    } else {
      logging(LOGLEVEL_INFO, "else", true);
      readedLines->push_back(ZKette);
      ZKette = "";
    }

    //Serial.write(file.read());
  }
  // if (strcmp(ZKette, "") ==0){
  readedLines->push_back(ZKette);
  //       }
  file.close();
}

/* ------------------------------------------------------------
 *  Datei löschen
 *  
 *  Parameter:
 *  - Dateisystem (sollte LITTLEFS sein)
 *  - Dateiname (vollständige Pfadangabe)
 * ------------------------------------------------------------ */
void deleteFile(fs::FS &fs, const char *path) {
  //logging(LOGLEVEL_INFO, "Lösche Datei: " + String(path), true);
  String finalpath = path;
  char pathlocal[200];
  char pattern[] = { '/' };

  sprintf(pathlocal, path);


  if (!FindChar(pathlocal, pattern) == 0) {



    sprintf(pathlocal, "%s%s", "/", path);
  }


  if (fs.remove(pathlocal)) {
    //logging(LOGLEVEL_INFO, "- Datei gelöscht", true);
  } else {
    //logging(LOGLEVEL_ERROR, String(path) + "- Datei konnte nicht gelöscht werden", true);
  }
}



void logging(int logLevel, String message, bool newLine) {
  String completeMessage = "";
  if (logLevel <= globalLogLevel) {


    String logPrefix = "";
    switch (logLevel) {
      case LOGLEVEL_ERROR:
        logPrefix = "[ERROR]: ";
        break;
      case LOGLEVEL_WARN:
        logPrefix = "[WARN]: ";
        break;
      case LOGLEVEL_INFO:
        logPrefix = "[INFO]: ";
        break;
      case LOGLEVEL_DEBUG:
        logPrefix = "[DEBUG]: ";
        break;
    }
    if (newLine) {
      Serial.print("\n" + String(millis()) + " " + logPrefix + message);
      //File file = LittleFS.open("/log.log", "a");
      completeMessage = "\n" + String(millis()) + " " + logPrefix + message;
      //file.print("\n" + String(millis()) + " " + logPrefix + message);
      //file.close();
      writeFile(LittleFS, "/log.log", completeMessage.c_str(), "a");
    } else {
      writeFile(LittleFS, "/log.log", message.c_str(), "a");
      Serial.print(message);
    }
  }
}

void startWebServer() {

  logging(LOGLEVEL_INFO, "Starting webServer", true);
  webServer.begin();
  flagWebServerActive = true;
}

void stopWebServer() {

  logging(LOGLEVEL_INFO, "Stopping webServer", true);
  webServer.end();
  flagWebServerActive = false;
}

void loadCredentials(WM_Config *data_dest) {
  EEPROM.begin(512);
  EEPROM.get(0, *data_dest);
  char ok[2 + 1];
  EEPROM.get(0 + sizeof(*data_dest), ok);
  EEPROM.end();
  if (String(ok) != String(F("OK"))) {
    *data_dest->WiFi_Creds.wifi_ssid = '\0';
    *data_dest->WiFi_Creds.wifi_pw = '\0';
  }
  EEPROM.end();
}
void saveCredentials(WM_Config *data_source) {
  EEPROM.begin(512);
  EEPROM.put(0, *data_source);
  char ok[2 + 1] = "OK";
  EEPROM.put(0 + sizeof(*data_source), ok);
  EEPROM.commit();
  EEPROM.end();
}
void notFound(AsyncWebServerRequest *request) {
  request->send(404, "text/plain", "Not found");
}


void readConfigurationFromFile(String configurationFileName) {
  if (flagLittleFSExist) {
    logging(LOGLEVEL_INFO, "reading config file", true);

    //File configFile;
    readedLines.clear();

    readFile(LittleFS, configurationFileName.c_str(), &readedLines);




    if (readedLines.size() == 1) {
      flagConfigurationFileExist = true;
      //logging(LOGLEVEL_INFO, "opened config file", true);
      //size_t size = configFile.size();
      // Allocate a buffer to store contents of the file.
      //std::unique_ptr<char[]> buf(new char[size]);

      //configFile.readBytes(buf.get(), size);


      StaticJsonDocument<1024> json;


      //      DeserializationError error = deserializeJson(json, buf.get());
      DeserializationError error = deserializeJson(json, readedLines[0]);
      //      logging(LOGLEVEL_INFO, buf.get(), true);
      // Test if parsing succeeds.
      if (error) {
        logging(LOGLEVEL_WARN, "deserializeJson() failed: ", true);
        logging(LOGLEVEL_WARN, error.f_str(), true);
        flagConfigurationLoaded = false;
        //      configFile.close();
      } else {
        logging(LOGLEVEL_INFO, "parsed json", true);

        strcpy(devicename, json["devicename"]);

        flagConfigurationLoaded = true;
        //configFile.close();
      }
    }
  }
}



void setup() {
  Serial.begin(115200);  //Initialising if(DEBUG)Serial Monitor
  //delay(10000);



  if (LittleFS.begin()) {
    flagLittleFSExist = true;
    if ((fs_info.totalBytes - fs_info.usedBytes) <= 230000) {
      deleteFile(LittleFS, "/log.log");
    }
    logging(LOGLEVEL_INFO, "mounted file system", true);
  } else {
    flagLittleFSExist = false;
    logging(LOGLEVEL_WARN, "mounting file system failed", true);
  }

#if defined(ESP8266)
  infoFilesystem(LittleFS, &fs_info);
#elif defined(ESP32)
  infoFilesystem(&fs_info);
#endif
  if ((fs_info.totalBytes - fs_info.usedBytes) <= 230000) {
    deleteFile(LittleFS, "/log.log");
    logging(LOGLEVEL_ERROR, "Free Filesystem avaiable less than 230000 Bytes", true);
    logging(LOGLEVEL_ERROR, "Total Filesystem (Bytes): " + String(fs_info.totalBytes), true);
    logging(LOGLEVEL_ERROR, "Used Filesystem (Bytes): " + String(fs_info.usedBytes), true);
    logging(LOGLEVEL_ERROR, "Filesystem available (Bytes): " + String((fs_info.totalBytes - fs_info.usedBytes)), true);


  } else {
    logging(LOGLEVEL_INFO, "Total Filesystem (Bytes): " + String(fs_info.totalBytes), true);
    logging(LOGLEVEL_INFO, "Used Filesystem (Bytes): " + String(fs_info.usedBytes), true);
    logging(LOGLEVEL_INFO, "Filesystem available (Bytes): " + String((fs_info.totalBytes - fs_info.usedBytes)), true);
  }


  //writeFile(LittleFS, "/teasta.txt", "aaq", "w");
  //readFile(LittleFS, "/consfig.json", &readedLines);
  //logging(LOGLEVEL_INFO, "readlines" + readedLines[0], true);



  if (flagLittleFSExist) {
    updateFromFS();
  }
  logging(LOGLEVEL_INFO, "Disconnecting previously connected WiFi", true);
  WiFi.disconnect();
  delay(10);
  //pinMode(LED_BUILTIN, OUTPUT);
  logging(LOGLEVEL_INFO, "Startup", true);
  if (strcmp(devicename, "") != 0) {
#if defined(ESP8266)
    WiFi.hostname(devicename);
#elif defined(ESP32)
    WiFi.setHostname(devicename);
#endif
  }
  if (flagLittleFSExist) {
    //listAllFilesInDir("/");
  }

  // String json = "{\"files\":[";
  // for (unsignedint i = 0; i < FileInformations.size(); i++) {
  //   if (i == 0) {
  //     json = json + "{\"name\":\"" + FileInformations[i].name + "\", \"filesize\":" + String(FileInformations[i].filesize) + "}";
  //   } else {
  //     json = json + ",{\"name\":\"" + FileInformations[i].name + "\", \"filesize\":" + String(FileInformations[i].filesize) + "}";
  //   }
  // }
  // json = json + "]}";
  // Serial.println(json);
  readConfigurationFromFile("/config.json");




  //---------------------------------------- Read EEPROM for SSID and pass
  logging(LOGLEVEL_INFO, "Reading EEPROM ssid", true);
  loadCredentials(&WM_config);
  logging(LOGLEVEL_INFO, "Recovered credentials:", true);
  logging(LOGLEVEL_INFO, WM_config.WiFi_Creds.wifi_ssid, true);
  logging(LOGLEVEL_INFO, strlen(String(WM_config.WiFi_Creds.wifi_pw).c_str()) > 0 ? "********" : "<no password>", true);



  WiFi.begin(WM_config.WiFi_Creds.wifi_ssid, WM_config.WiFi_Creds.wifi_pw);
  if (testWifi()) {
    logging(LOGLEVEL_INFO, "Succesfully Connected!!!", true);
    logging(LOGLEVEL_INFO, "local ip", true);
    logging(LOGLEVEL_INFO, WiFi.localIP().toString(), false);
  } else {
    logging(LOGLEVEL_INFO, "Turning the HotSpot On", true);
    launchWeb();
    setupAP();  // Setup HotSpot
  }

  logging(LOGLEVEL_INFO, "Waiting.", true);

  while ((WiFi.status() != WL_CONNECTED)) {
    logging(LOGLEVEL_INFO, ".", false);
    delay(100);
    //server.handleClient();
  }
  if (flagMQTTConfigured) {
  }



  if (strcmp(devicename, "") != 0) {
    if (MDNS.begin(devicename)) {
      logging(LOGLEVEL_INFO, "DNS gestartet, erreichbar unter: ", true);
      logging(LOGLEVEL_INFO, "http://" + String(devicename) + ".local/", false);

      MDNS.addService("http", "tcp", 80);

    } else {
      logging(LOGLEVEL_ERROR, "Error setting up MDNS responder!", true);
    }
  }




  webServer.on("/style.css", HTTP_GET, [](AsyncWebServerRequest *request) {
    //request->send(200, "text/plain", "Hello, world");
    request->send(LittleFS, "/style.css");
  });

  webServer.on("/filebrowser", HTTP_GET, [](AsyncWebServerRequest *request) {
    //request->send(200, "text/plain", "Hello, world");
    request->send(LittleFS, "filebrowser.html");
  });

  webServer.on("/filebrowsercommand", HTTP_GET, [](AsyncWebServerRequest *request) {
    if (request->hasParam("path") && request->hasParam("value")) {
      int params = request->params();
      logging(LOGLEVEL_INFO, "Parameteranzahl" + String(params), true);
      if (strcmp(request->getParam("value")->value().c_str(), "delete") == 0) {
        logging(LOGLEVEL_INFO, String(request->getParam("path")->value()), true);
        deleteFile(LittleFS, request->getParam("path")->value().c_str());
        request->send(200, "text/plain", "Path deleted");
      } else {
        request->send(400, "text/plain", "Error during path deleting");
      }

    } else {
      request->send(400, "text/plain", "Error during path deleting");
    }
  });




  webServer.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send(200, "text/plain", "Hello, world");
  });



  webServer.on("/configload", HTTP_GET, [](AsyncWebServerRequest *request) {
    if (LittleFS.exists("/config.json")) {

      request->send(LittleFS, "/config.json");
    }
  });


  webServer.on("/configuration", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send(LittleFS, "/configuration.html");
  });


  webServer.on("/configuration", HTTP_POST, [](AsyncWebServerRequest *request) {
    if (request->hasParam("devicename", true)) {
      int params = request->params();
      logging(LOGLEVEL_INFO, "Parameteranzahl" + String(params), true);
      AsyncWebParameter *p = request->getParam("devicename", true);
      logging(LOGLEVEL_INFO, p->name().c_str(), false);
      logging(LOGLEVEL_INFO, p->value().c_str(), false);

      String devicename = request->getParam("devicename", true)->value().c_str();

      StaticJsonDocument<400> json;
      json["devicename"] = devicename;


      /*File configFile = LittleFS.open("/config.json", "w");
      if (!configFile) {
        logging(LOGLEVEL_WARN, "failed to open config file for writing", true);
        request->send(400, "text/plain", "Error. Can't open file.");
      } else {*/
      String jsontemp = "";
      serializeJson(json, Serial);
      serializeJson(json, jsontemp);
      writeFile(LittleFS, "/config.json", jsontemp.c_str(), "w");
      //configFile.close();
      request->send(200, "text/plain", "Success, saving config.");
      //}
    } else {
      logging(LOGLEVEL_WARN, "Wrong parameters", true);
      request->send(400, "text/plain", "Error. Wrong parameters.");
    }
  });



  webServer.on("/devicename", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send(200, "text/plain", devicename);
  });


  webServer.serveStatic("/", LittleFS, "/");
  webServer.onNotFound(notFound);
}
String processor(const String &var) {
  if (var == "HELLO_FROM_TEMPLATE") {

    /*st = "<ol>";
    st += "<li>d</li>";

    st += "</ol>";*/
    return "dd";
  } else {
    return String();
  }
}
void loop() {

#if defined(ESP8266)
  infoFilesystem(LittleFS, &fs_info);
#elif defined(ESP32)
  infoFilesystem(&fs_info);
#endif

  if ((fs_info.totalBytes - fs_info.usedBytes) <= 230000) {
    deleteFile(LittleFS, "/log.log");
    logging(LOGLEVEL_ERROR, "Free Filesystem avaiable less than 230000 Bytes", true);
    logging(LOGLEVEL_ERROR, "Total Filesystem (Bytes): " + String(fs_info.totalBytes), true);
    logging(LOGLEVEL_ERROR, "Used Filesystem (Bytes): " + String(fs_info.usedBytes), true);
    logging(LOGLEVEL_ERROR, "Filesystem available (Bytes): " + String((fs_info.totalBytes - fs_info.usedBytes)), true);

  } else {
    logging(LOGLEVEL_INFO, "Total Filesystem (Bytes): " + String(fs_info.totalBytes), true);
    logging(LOGLEVEL_INFO, "Used Filesystem (Bytes): " + String(fs_info.usedBytes), true);
    logging(LOGLEVEL_INFO, "Filesystem available (Bytes): " + String((fs_info.totalBytes - fs_info.usedBytes)), true);
  }





  if (!flagMQTTConnected) {
    //startWebServer();
  }

  if (flagStatusMessageSend && !flagWebServerActive && !flagFileUploadActive) {
    //startDeepSleep();
  }




  delay(10000);
}



//-------- Fuctions used for WiFi credentials saving and connecting to it which you do not need to change
bool testWifi(void) {
  int c = 0;
  logging(LOGLEVEL_INFO, "Waiting for Wifi to connect", true);
  while (c < 20) {
    if (WiFi.status() == WL_CONNECTED) {
      return true;
    }
    delay(500);
    logging(LOGLEVEL_INFO, "*", false);
    c++;
  }
  logging(LOGLEVEL_INFO, "", true);
  logging(LOGLEVEL_INFO, "Connect timed out, opening AP", true);
  return false;
}

void launchWeb() {
  logging(LOGLEVEL_INFO, "", true);
  if (WiFi.status() == WL_CONNECTED)
    logging(LOGLEVEL_INFO, "WiFi connected", true);
  logging(LOGLEVEL_INFO, "Local IP: ", true);
  logging(LOGLEVEL_INFO, WiFi.localIP().toString(), false);
  logging(LOGLEVEL_INFO, "SoftAP IP: ", false);
  logging(LOGLEVEL_INFO, WiFi.softAPIP().toString(), false);
  createWebServer();
  // Start the server
  webServer.begin();
  logging(LOGLEVEL_INFO, "Server started", true);
}

void setupAP(void) {
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);
  int n = WiFi.scanNetworks();
  logging(LOGLEVEL_INFO, "scan done", true);
  if (n == 0)
    logging(LOGLEVEL_INFO, "no networks found", true);
  else {
    logging(LOGLEVEL_INFO, String(n), true);
    logging(LOGLEVEL_INFO, " networks found", false);
    for (int i = 0; i < n; ++i) {
      // Print SSID and RSSI for each network found
      logging(LOGLEVEL_INFO, String(i + 1), true);
      logging(LOGLEVEL_INFO, ": ", false);
      logging(LOGLEVEL_INFO, String(WiFi.SSID(i)), false);
      logging(LOGLEVEL_INFO, " ", false);
      logging(LOGLEVEL_INFO, String(WiFi.RSSI(i)), false);
      logging(LOGLEVEL_INFO, "))", false);
#if defined(ESP8266)
      logging(LOGLEVEL_INFO, (WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*", true);
#elif defined(ESP32)
      logging(LOGLEVEL_INFO, (WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*", true);
#endif

      delay(10);
    }
  }
  logging(LOGLEVEL_INFO, "", false);
  WiFiInformations.clear();
  for (int i = 0; i < n; ++i) {
    // Print SSID and RSSI for each network found
    WiFiInformation wifi;
    wifi.name = WiFi.SSID(i);
    wifi.rssi = WiFi.RSSI(i);
#if defined(ESP8266)
    wifi.encryption = (WiFi.encryptionType(i) == ENC_TYPE_NONE) ? false : true;
#elif defined(ESP32)
    wifi.encryption = (WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? false : true;
#endif

    WiFiInformations.push_back(wifi);
  }

  delay(100);
  WiFi.softAP("AcessPoint", "", true);
  logging(LOGLEVEL_INFO, "softap", false);
  launchWeb();
  logging(LOGLEVEL_INFO, "over", false);
}

void createWebServer() {
  /*webServer.on("/scan", HTTP_POST, [](AsyncWebServerRequest *request) {
    logging(LOGLEVEL_INFO, "Scan", true);
    //setupAP();
    IPAddress ip = WiFi.softAPIP();
    String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);

    content = "<!DOCTYPE HTML>\r\n<html>go back";
    request->send(200, "text/html", content);
  });*/

  webServer.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
    //IPAddress ip = WiFi.softAPIP();
    //String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
    String content = "<!DOCTYPE HTML><html><title>WLAN Configuration for ESP</title><head>";
    content += "<style>.container {height: 200px;display: flex;align-items: center;justify-content: center;}";
    content += ".item {background-color: whitesmoke;width: 20em;} body {font-family: sans-serif;}";
    content += "form {border: 0px solid black;width: 90%;background-color: whitesmoke;margin: 0 auto;padding: 0 1em;}";
    content += "form label {display: block;font-size: 0.8em;color: darkslategrey;padding-left: 3px;}";
    content += "input{width: 100%;font-size: 1.1em; padding: 4px;font-family: inherit;font-weight: lighter;border-radius: 0.3em;}";
    content += "input:focus{border:1px solid orange;}input[type=submit], input[type=reset] {background-color:#1fa3ec; color:#fff;width:100%;padding: .3em 0;border-radius: 0.7em;}";
    content += "input[type=submit]:hover, input[type=reset]:hover {background-color: blue;box-shadow: 2px 2px 2px grey;}</style></head>";
    content += "<body> <div class=\"container\"><div class=\"item\"><h3>Known WLANs</h3><ol>";
    for (unsigned i = 0; i < WiFiInformations.size(); i++) {
      content += "<li>" + WiFiInformations[i].name + "(" + WiFiInformations[i].rssi + ")";
      if (WiFiInformations[i].encryption) {
        content += " * ";
      } else {
        content += "  ";
      }
      content += "</li>";
    }
    content += "</ol><p>&nbsp</p></div> </div> <div class=\"container\"><div class=\"item\"> <h3>WLAN Configuration</h3> <form id=\"main\" method=\"get\" action=\"setting\">";
    content += "<label for=\"SSID\">SSID: </label><input type=\"text\" id=\"ssid\" name=\"ssid\" length=32 autofocus></p>";
    content += "<p><label for=\"passphrase\">Passphrase:</label><input type=\"text\" name=\"passphrase\" id=\"passphrase\" length=64></p>";
    content += "<p><input type=\"submit\" value=\"save\"></form><form action=\"scan\" method=\"POST\"><input type=\"submit\" value=\"scan\"></form></p></div></div>";
    content += "</body></html>";

    request->send(200, "text/html", content);


    //request->send(200, "text/plain", "Hello, world");
  });

  webServer.on("/setting", HTTP_GET, [](AsyncWebServerRequest *request) {
    String qsid;   // = server.arg(F("ssid"));
    String qpass;  // = server.arg(F("pass"));
    if (request->hasParam(F("ssid"))) {
      strcpy(WM_config.WiFi_Creds.wifi_ssid, (request->getParam(F("ssid"))->value()).c_str());
      //WM_config = ;
    } else {
      logging(LOGLEVEL_INFO, "No ssid sent", true);
    }
    if (request->hasParam(F("passphrase"))) {
      strcpy(WM_config.WiFi_Creds.wifi_pw, (request->getParam(F("passphrase"))->value()).c_str());
    } else {
      logging(LOGLEVEL_INFO, "No pass sent", true);
    }
    WM_config.checksum = 8;
    saveCredentials(&WM_config);


    String content = "{\"Success\":\"saved to eeprom... reset to boot into new wifi\"}";
    statusCode = 200;
#if defined(ESP8266)
    ESP.reset();
#elif defined(ESP32)
      ESP.restart();
#endif
    /*} else {
        content = "{\"Error\":\"404 not found\"}";
        statusCode = 404;
        logging(LOGLEVEL_INFO, "Sending 404", true);
      }*/
    //server.sendHeader(F("Access-Control-Allow-Origin", "*"));
    request->send(statusCode, "application/json", content);
  });
}


void performUpdate(Stream &updateSource, size_t updateSize) {
  if (Update.begin(updateSize)) {
    size_t written = Update.writeStream(updateSource);
    if (written == updateSize) {
      logging(LOGLEVEL_INFO, "Written : " + String(written) + " successfully", true);
    } else {
      logging(LOGLEVEL_WARN, "Written only : " + String(written) + "/" + String(updateSize) + ". Retry?", true);
    }
    if (Update.end()) {
      logging(LOGLEVEL_INFO, "OTA done!", true);
      if (Update.isFinished()) {
        logging(LOGLEVEL_INFO, "Update successfully completed. Rebooting.", true);
      } else {
        logging(LOGLEVEL_WARN, "Update not finished? Something went wrong!", true);
      }
    } else {
      logging(LOGLEVEL_ERROR, "Error Occurred. Error #: " + String(Update.getError()), true);
    }

  } else {
    logging(LOGLEVEL_ERROR, "Not enough space to begin OTA", true);
  }
}


void updateFromFS() {
  if (flagLittleFSExist) {
    File updateBin = LittleFS.open("/update.bin", "r");
    if (updateBin) {
      if (updateBin.isDirectory()) {
        logging(LOGLEVEL_ERROR, "Error, update.bin is not a file", true);
        updateBin.close();
        return;
      }

      size_t updateSize = updateBin.size();

      if (updateSize > 0) {
        logging(LOGLEVEL_INFO, "Try to start update", true);
        performUpdate(updateBin, updateSize);
      } else {
        logging(LOGLEVEL_ERROR, "Error, file is empty", true);
      }

      updateBin.close();

      // whe finished remove the binary from sd card to indicate end of the process
      deleteFile(LittleFS, "/update.bin");
    } else {
      logging(LOGLEVEL_ERROR, "Could not load update.bin from root", true);
    }
  }
}

Besser wenn du dein Problem im Titel zeigst, dann wird er besser gefunden.
Und du solltest eigentlich wissen, das der Sketch ins Forum gehört und nicht irgendwo auf einen externen Server.

Schon prima dass du den kompletten Sketch gepostest hast.
Der Sketch ist auch halbwegs in functions unterteilt.
Trotzdem die Frage:

In welchen Programmzeilen befindet sich denn die Logik die den Hotspot öffnet?

In welchen Programmzeilen befindet sich die Logik die überprüft ob schon SSID und Passwort vorhanden sind?

Wenn du diese Zeilennummern angibst machst du es deinen potentiellen Helfern sehr viel leichter Unterstützung zu geben.

Dein Code macht eine Menge Datenlogging.
Dieses Datenlogging schreibt auch auf den seriellen Monitor.
Diese Logdaten auch als Code-Section posten.
Dadurch gibst du Informationen über das was wirklich im Programm abläuft.

Ändere mal das Abwarten auf connected von 10 Sekunden auf 1 Minute.

vgs

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.