[GH-ISSUE #1124] Help with AutoConnectWithFSParameters example with simple modification. #961

Closed
opened 2026-02-28 01:27:52 +03:00 by kerem · 10 comments
Owner

Originally created by @Shalabyer on GitHub (Sep 13, 2020).
Original GitHub issue: https://github.com/tzapu/WiFiManager/issues/1124

Esp8266/Esp32:

  • ESP8266
    **Hardware:
  • ESP12 E/F/S (nodemcu, wemos, feather)

Description

In the great example AutoConnectWithFSParameters it tries to save SSID, Password, localIP, gatewayIP and subnetMask of a WI-FI network for the ESP8266 by giving these data via web while the ESP acts as a hotspot.
Well that's all okay but what i need help with and i need to do is to give these data to the ESP to save via code and not via link,
here is an example of what i want to do :


#include <FS.h>          // this needs to be first, or it all crashes and burns...
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h> // https://github.com/bblanchon/ArduinoJson

#ifdef ESP32
  #include <SPIFFS.h>
#endif

void(* resetFunc) (void) = 0; //declare reset function @ address 0
void setup()
{
String SSIDName="test";
String Password="test";
String localIPs="192.168.1.10";
String gatewayIPs="192.168.1.1";
String subnetMasks="255.255.255.0";

}
void loop()
{
if(true)
{
   WiFiManager wifiManager;    
    wifiManager.resetSettings();
    //HERE save new SSIDName, Password, localIPs, gatewayIPs and subnetMasks to the ESP8266
    //the above line is the code that i want please if you may help
  resetFunc();
}
}

Originally created by @Shalabyer on GitHub (Sep 13, 2020). Original GitHub issue: https://github.com/tzapu/WiFiManager/issues/1124 **Esp8266/Esp32:** - [x] ESP8266 **Hardware: - [x] ESP12 E/F/S (nodemcu, wemos, feather) ### Description In the great example AutoConnectWithFSParameters it tries to save SSID, Password, localIP, gatewayIP and subnetMask of a WI-FI network for the ESP8266 by giving these data via web while the ESP acts as a hotspot. Well that's all okay but what i need help with and i need to do is to give these data to the ESP to save via code and not via link, here is an example of what i want to do : ``` #include <FS.h> // this needs to be first, or it all crashes and burns... #include <WiFiManager.h> // https://github.com/tzapu/WiFiManager #include <ArduinoJson.h> // https://github.com/bblanchon/ArduinoJson #ifdef ESP32 #include <SPIFFS.h> #endif void(* resetFunc) (void) = 0; //declare reset function @ address 0 void setup() { String SSIDName="test"; String Password="test"; String localIPs="192.168.1.10"; String gatewayIPs="192.168.1.1"; String subnetMasks="255.255.255.0"; } void loop() { if(true) { WiFiManager wifiManager; wifiManager.resetSettings(); //HERE save new SSIDName, Password, localIPs, gatewayIPs and subnetMasks to the ESP8266 //the above line is the code that i want please if you may help resetFunc(); } } ```
kerem closed this issue 2026-02-28 01:27:52 +03:00
Author
Owner

@tablatronix commented on GitHub (Sep 13, 2020):

Then just use the esp functions for this

<!-- gh-comment-id:691723112 --> @tablatronix commented on GitHub (Sep 13, 2020): Then just use the esp functions for this
Author
Owner

@Shalabyer commented on GitHub (Sep 13, 2020):

Thank for your help,
i searched throught all the public function on the library and found non to set SSID name and Password of the Wi-Fi
But i have made it to save a new IP address here is the new code

#include <FS.h>          // this needs to be first, or it all crashes and burns...
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h> // https://github.com/bblanchon/ArduinoJson

#ifdef ESP32
  #include <SPIFFS.h>
#endif

void(* resetFunc) (void) = 0; //declare reset function @ address 0
void setup()
{
String SSIDName="test";
String Password="test";
String localIPs="192.168.1.10";
String gatewayIPs="192.168.1.1";
String subnetMasks="255.255.255.0";

}
void loop()
{
if(true)
{
 
         WiFiManager wifiManager;    
    wifiManager.resetSettings();
    
     #ifdef ARDUINOJSON_VERSION_MAJOR >= 6
    DynamicJsonDocument json(1024);
  #else
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
  #endif


    json["ip"] ="192.168.43.99";
    json["gateway"] = "192.168.43.1";
    json["subnet"] = "255.255.255.0";

    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }
  #ifdef ARDUINOJSON_VERSION_MAJOR >= 6
    serializeJson(json, Serial);
    serializeJson(json, configFile);
  #else
    json.printTo(Serial);
    json.printTo(configFile);
  #endif
    configFile.close();
//    wifiManager.wifiConnectNew("testSSID","testPassword");  
//this is a private function that i found but i can't use it as It's Private
  resetFunc();
}
}

What i want here is to save new SSID name and Password to the ESP8266 file manually without the need to enter the data through ESP Access Point.
If you could please help me with function names that i can use to save these two paramters.

<!-- gh-comment-id:691734744 --> @Shalabyer commented on GitHub (Sep 13, 2020): Thank for your help, i searched throught all the public function on the library and found non to set SSID name and Password of the Wi-Fi But i have made it to save a new IP address here is the new code ``` #include <FS.h> // this needs to be first, or it all crashes and burns... #include <WiFiManager.h> // https://github.com/tzapu/WiFiManager #include <ArduinoJson.h> // https://github.com/bblanchon/ArduinoJson #ifdef ESP32 #include <SPIFFS.h> #endif void(* resetFunc) (void) = 0; //declare reset function @ address 0 void setup() { String SSIDName="test"; String Password="test"; String localIPs="192.168.1.10"; String gatewayIPs="192.168.1.1"; String subnetMasks="255.255.255.0"; } void loop() { if(true) { WiFiManager wifiManager; wifiManager.resetSettings(); #ifdef ARDUINOJSON_VERSION_MAJOR >= 6 DynamicJsonDocument json(1024); #else DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); #endif json["ip"] ="192.168.43.99"; json["gateway"] = "192.168.43.1"; json["subnet"] = "255.255.255.0"; File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { Serial.println("failed to open config file for writing"); } #ifdef ARDUINOJSON_VERSION_MAJOR >= 6 serializeJson(json, Serial); serializeJson(json, configFile); #else json.printTo(Serial); json.printTo(configFile); #endif configFile.close(); // wifiManager.wifiConnectNew("testSSID","testPassword"); //this is a private function that i found but i can't use it as It's Private resetFunc(); } } ``` **What** i want here is to save new SSID name and Password to the ESP8266 file manually without the need to enter the data through ESP Access Point. If you could please help me with function names that i can use to save these two paramters.
Author
Owner

@tablatronix commented on GitHub (Sep 13, 2020):

WiFi.begin()
WiFi.setConfig()

These are not wm functions

<!-- gh-comment-id:691735561 --> @tablatronix commented on GitHub (Sep 13, 2020): WiFi.begin() WiFi.setConfig() These are not wm functions
Author
Owner

@Shalabyer commented on GitHub (Sep 13, 2020):

For WiFi.setConfig() function, i didn't found any info, hope you mean WiFi.config() which only do config the IP address.
now for the WiFi.begin() function,
i added it to my code like the following:

configFile.close();
 WiFi.begin("testSSID","testPass");
  Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED)
{
  delay(500);
  Serial.print(".");
}
Serial.println();

Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
resetFunc();

It prints that it connected successfully which is good but the bad thing here that it doesn't save these two parameters as when it resets it enters AP mode as it didn't save the SSID and PASS but it saved All the new IP Addresses .
This is what i get when it resets to make it more clear:

reading config file
opened config file
{"ip":"192.168.43.99","gateway":"192.168.43.1","subnet":"255.255.255.0"}
parsed json
setting custom ip from config
192.168.43.99
*WM: [1] AutoConnect
*WM: [1] No Credentials are Saved, skipping connect
*WM: [2] Starting Config Portal
*WM: [2] AccessPoint set password is VALID
*WM: [1] password
*WM: [3] WIFI station disconnect
*WM: [3] WiFi station enable
*WM: [2] Disabling STA
*WM: [2] Enabling AP

NOTE: "192.168.43.99" is the new IP address

What i need is a way to save the SSID and Password to the ESP like we saved the IP addresses, i.e: with code.

<!-- gh-comment-id:691742745 --> @Shalabyer commented on GitHub (Sep 13, 2020): For WiFi.setConfig() function, i didn't found any info, hope you mean WiFi.config() which only do config the IP address. now for the WiFi.begin() function, i added it to my code like the following: ``` configFile.close(); WiFi.begin("testSSID","testPass"); Serial.print("Connecting"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.print("Connected, IP address: "); Serial.println(WiFi.localIP()); resetFunc(); ``` It prints that it connected successfully which is good but the bad thing here that it doesn't save these two parameters as when it resets it enters AP mode as it didn't save the SSID and PASS but it saved All the new IP Addresses . This is what i get when it resets to make it more clear: > reading config file > opened config file > {"ip":"192.168.43.99","gateway":"192.168.43.1","subnet":"255.255.255.0"} > parsed json > setting custom ip from config > 192.168.43.99 > *WM: [1] AutoConnect > *WM: [1] No Credentials are Saved, skipping connect > *WM: [2] Starting Config Portal > *WM: [2] AccessPoint set password is VALID > *WM: [1] password > *WM: [3] WIFI station disconnect > *WM: [3] WiFi station enable > *WM: [2] Disabling STA > *WM: [2] Enabling AP > **NOTE**: "192.168.43.99" is the new IP address What i need is a way to save the SSID and Password to the ESP like we saved the IP addresses, i.e: with code.
Author
Owner

@tablatronix commented on GitHub (Sep 14, 2020):

Sorry I meant WiFi.config it takes all addresses

<!-- gh-comment-id:691754825 --> @tablatronix commented on GitHub (Sep 14, 2020): Sorry I meant WiFi.config it takes all addresses
Author
Owner

@Shalabyer commented on GitHub (Sep 14, 2020):

Iam sorry man but what about saving wifi data like ssid and password, Wifi.begin doesn't save these data it just starts the connection for one time.

<!-- gh-comment-id:691799679 --> @Shalabyer commented on GitHub (Sep 14, 2020): Iam sorry man but what about saving wifi data like ssid and password, Wifi.begin doesn't save these data it just starts the connection for one time.
Author
Owner

@tablatronix commented on GitHub (Sep 14, 2020):

No it saves it

<!-- gh-comment-id:692020835 --> @tablatronix commented on GitHub (Sep 14, 2020): No it saves it
Author
Owner

@Shalabyer commented on GitHub (Sep 14, 2020):

Allrigth here is my full code if you please may help me with that if iam getting it wrong

#include <FS.h>                   //this needs to be first, or it all crashes and burns...

#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager
#include <SPI.h> //What is used to communicate witht he WiFi chip
#include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson

//default custom static IP
char static_ip[16] = "10.0.1.56";
char static_gw[16] = "10.0.1.1";
char static_sn[16] = "255.255.255.0";
//flag for saving data
bool shouldSaveConfig = false;

//callback notifying us of the need to save config
void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;
}
void(* resetFunc) (void) = 0; //declare reset function @ address 0
int status = WL_IDLE_STATUS; //status of wifi
WiFiServer server(80); //declare server object and spedify port, 80 is port used for internet
void setup() {
    WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP  

  Serial.begin(115200);
  delay(10);
if (SPIFFS.begin()) {
    Serial.println("mounted file system");
    if (SPIFFS.exists("/config.json")) {
      //file exists, reading and loading
      Serial.println("reading config file");
      File configFile = SPIFFS.open("/config.json", "r");
      if (configFile) {
        Serial.println("opened config file");
        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);

        #ifdef ARDUINOJSON_VERSION_MAJOR >= 6
          DynamicJsonDocument json(1024);
          DeserializationError deserializeError = deserializeJson(json, buf.get());
          serializeJson(json, Serial);
          if (!deserializeError) {
        #else
          DynamicJsonBuffer jsonBuffer;
          JsonObject& json = jsonBuffer.parseObject(buf.get());
          json.printTo(Serial);
          if (json.success()) {
        #endif
          Serial.println("\nparsed json");
        if (json["ip"]) {
            Serial.println("setting custom ip from config");
            strcpy(static_ip, json["ip"]);
            strcpy(static_gw, json["gateway"]);
            strcpy(static_sn, json["subnet"]);
            Serial.println(static_ip);
          } else {
            Serial.println("no custom ip in config");
          }
        } else {
          Serial.println("failed to load json config");
        }
      }
    }
  } else {
   // SendState();
  
    Serial.println("failed to mount FS");
  }
  WiFiManager wifiManager;

  wifiManager.setSaveConfigCallback(saveConfigCallback);

  //set static ip
  IPAddress _ip, _gw, _sn;
  _ip.fromString(static_ip);
  _gw.fromString(static_gw);
  _sn.fromString(static_sn);

  wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);

  //set minimu quality of signal so it ignores AP's under that quality
  //defaults to 8%
  wifiManager.setMinimumSignalQuality();

    wifiManager.setBreakAfterConfig(true);

  if (!wifiManager.autoConnect("TTTT", "password")) {
    Serial.println("failed to connect and hit timeout");
    delay(3000);
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(5000);
  }

  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");
 //save the custom parameters to FS
  if (shouldSaveConfig) {
    Serial.println("saving config");

  #ifdef ARDUINOJSON_VERSION_MAJOR >= 6
    DynamicJsonDocument json(1024);
  #else
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
  #endif


    json["ip"] = WiFi.localIP().toString();
    json["gateway"] = WiFi.gatewayIP().toString();
    json["subnet"] = WiFi.subnetMask().toString();

    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }


  #ifdef ARDUINOJSON_VERSION_MAJOR >= 6
    serializeJson(json, Serial);
    serializeJson(json, configFile);
    
 // resetFunc();
  #else
    json.printTo(Serial);
    json.printTo(configFile);
  #endif
    configFile.close();
    //end save
  }

  server.begin();
  Serial.println("Server started");
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
}


void loop()
{
  WiFiClient client = server.available();   // listen for incoming clients(Returns a Client object that has data available for reading if no Client has data available for reading this object will evaluate to false)
  //if client has data to be read then it will be true (WiFiClient client) Creates a client that can connect to a specified internet IP address and port
  if (client) {                             // if you get a client,
   // Serial.println("new client");          // print a message out the serial port
    String currentLine = "";   
    while (client.connected()) {       // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,Returns the number of bytes available for reading
        char c = client.read();             // read a byte, then (Read the next byte received from the server the client is connected to (after the last call to read()).or -1 if none is available.)
     if (c == '\n') {                    // if the byte is a newline character
        }
        else if (c != '\r') {    // if you got anything else but a carriage return character" Carriage Return ("CR") moves the cursor to the beginning of the line without advancing to the next line",
          currentLine += c;
         // add it to the end of the currentLine
        }
      if (currentLine.endsWith("GET /v")) {
       
         WiFiManager wifiManager;    
    wifiManager.resetSettings();
    
     #ifdef ARDUINOJSON_VERSION_MAJOR >= 6
    DynamicJsonDocument json(1024);
  #else
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
  #endif
 wifiManager.setSaveConfigCallback(saveConfigCallback);
    wifiManager.setBreakAfterConfig(true);
    
  IPAddress _ip, _gw, _sn;
  _ip.fromString("192.168.43.99");
  _gw.fromString("192.168.43.1");
  _sn.fromString("255.255.255.0");

  wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);
 WiFi.begin("Xperia","88888888m");
    Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());

    json["ip"] = "192.168.43.99";
    json["gateway"] = "192.168.43.1";
    json["subnet"] = "255.255.255.0";

    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }
  #ifdef ARDUINOJSON_VERSION_MAJOR >= 6
    serializeJson(json, Serial);
    serializeJson(json, configFile);
  #else
    json.printTo(Serial);
    json.printTo(configFile);
  #endif
    configFile.close();
  
  resetFunc();
        }
      
         }
    }
    // close the connection:
    client.stop();
  }
}

Now let us consider that it has default data and connected with local ip "192.168.43.60" which i give it to the esp via the web link now here is the data that i get on Serial monitor with the following porecedures:
1.reset the esp
2.hitting "192.168.43.60/v" via my laptop.
What should i expect is that it will reset the esp configration then tries to change the local ip to 192.168.43.99 then reconnect to the Wi-Fi -and at this point i will change the wi-fi SSID and PASS to the new given one in the code but i didn't here in this example-.
Anyway here is what i get on the serial monitor :

SDK:2.2.2-dev(38a443e)/Core:2.7.2-7-g5d3af165=20702007/lwIP:STABLE-2_1_2_RELEASE/glue:1.2-30-g92add50/BearSSL:5c771be
mounted file system
reading config file
opened config file
{"ip":"192.168.43.60","gateway":"192.168.43.1","subnet":"255.255.255.0"}
parsed json
setting custom ip from config
192.168.43.60
*WM: [1] AutoConnect
*WM: [2] Connecting as wifi client...
*WM: [3] STA static IP: 192.168.43.60
*WM: [2] Custom static IP/GW/Subnet/DNS
*WM: [2] Custom STA IP/GW/Subnet
*WM: [1] STA IP set: 192.168.43.60
*WM: [1] Connecting to SAVED AP: Xperia
*WM: [3] Using Password: 88888888m
*WM: [3] WiFi station enable
*WM: [3] enableSTA PERSISTENT ON
scandone
*WM: [1] connectTimeout not set, ESP waitForConnectResult...
scandone
state: 0 -> 2 (b0)
state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 1
cnt

connected with Xperia, channel 13
ip:192.168.43.60,mask:255.255.255.0,gw:192.168.43.1
ip:192.168.43.60,mask:255.255.255.0,gw:192.168.43.1
*WM: [2] Connection result: WL_CONNECTED
*WM: [3] lastconxresult: WL_CONNECTED
*WM: [1] AutoConnect: SUCCESS
*WM: [1] STA IP Address: 192.168.43.60
connected...yeey :)
Server started
Use this URL to connect: http://192.168.43.60/
*WM: [3] unloading
pm open,type:2 0
*WM: [1] resetSettings //HERE WHEN I HIT "192.168.43.60/V" WITH MY LAPTOP
*WM: [3] WiFi station enable
*WM: [3] enableSTA PERSISTENT ON
state: 5 -> 0 (0)
rm 0
pm close 7
del if0
usl
mode : null
*WM: [1] SETTINGS ERASED
mode : sta(84:0d:8e:8d:ed:80)
ip:192.168.43.60,mask:255.255.255.0,gw:192.168.43.1
add if0
Connecting......scandone
state: 0 -> 2 (b0)
.state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 1
cnt

connected with Xperia, channel 13
ip:192.168.43.60,mask:255.255.255.0,gw:192.168.43.1
.
Connected, IP address: 192.168.43.60
{"ip":"192.168.43.99","gateway":"192.168.43.1","subnet":"255.255.255.0"}
ets Jan 8 2013,rst cause:4, boot mode:(3,6)

wdt reset
load 0x4010f000, len 3584, room 16
tail 0
chksum 0xb0
csum 0xb0
v5d3af165
~ld

SDK:2.2.2-dev(38a443e)/Core:2.7.2-7-g5d3af165=20702007/lwIP:STABLE-2_1_2_RELEASE/glue:1.2-30-g92add50/BearSSL:5c771be
mounted file system
reading config file
opened config file
{"ip":"192.168.43.99","gateway":"192.168.43.1","subnet":"255.255.255.0"}
parsed json
setting custom ip from config
192.168.43.99
*WM: [1] AutoConnect
*WM: [1] No Credentials are Saved, skipping connect
*WM: [2] Starting Config Portal
*WM: [2] AccessPoint set password is VALID
*WM: [1] password
*WM: [3] WIFI station disconnect
*WM: [3] WiFi station enable
del if0
usl
mode : null
*WM: [2] Disabling STA
*WM: [2] Enabling AP
*WM: [1] StartAP with SSID: TTTT
mode : softAP(86:0d:8e:8d:ed:80)
add if1
dhcp server start:(ip:192.168.4.1,mask:255.255.255.0,gw:192.168.4.1)
bcn 100
bcn 0
del if1
usl
add if1
dhcp server start:(ip:192.168.4.1,mask:255.255.255.0,gw:192.168.4.1)
bcn 100
*WM: [1] SoftAP Configuration
*WM: [1] --------------------
*WM: [1] ssid: TTTT
*WM: [1] password: password
*WM: [1] ssid_len: 4
*WM: [1] channel: 1
*WM: [1] authmode: 3
*WM: [1] ssid_hidden:
*WM: [1] max_connection: 4
*WM: [1] country: CN
*WM: [1] beacon_interval: 100(ms)
*WM: [1] --------------------
*WM: [1] AP IP address: 192.168.4.1
*WM: [3] setupConfigPortal
*WM: [1] Starting Web Portal
*WM: [3] dns server started with ip: 192.168.4.1
*WM: [2] HTTP server started
mode : sta(84:0d:8e:8d:ed:80) + softAP(86:0d:8e:8d:ed:80)
add if0
scandone
*WM: [2] WiFi Scan completed in 2187 ms

Also i tried to put this line:
WiFi.begin("Xperia","88888888m");
after the this line:
configFile.close();
and still the same response , No save for the SSID and PASS.
I would be pleased for help,Thanks anyway :)

<!-- gh-comment-id:692189831 --> @Shalabyer commented on GitHub (Sep 14, 2020): Allrigth here is my full code if you please may help me with that if iam getting it wrong ``` #include <FS.h> //this needs to be first, or it all crashes and burns... #include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino //needed for library #include <DNSServer.h> #include <ESP8266WebServer.h> #include <WiFiManager.h> //https://github.com/tzapu/WiFiManager #include <SPI.h> //What is used to communicate witht he WiFi chip #include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson //default custom static IP char static_ip[16] = "10.0.1.56"; char static_gw[16] = "10.0.1.1"; char static_sn[16] = "255.255.255.0"; //flag for saving data bool shouldSaveConfig = false; //callback notifying us of the need to save config void saveConfigCallback () { Serial.println("Should save config"); shouldSaveConfig = true; } void(* resetFunc) (void) = 0; //declare reset function @ address 0 int status = WL_IDLE_STATUS; //status of wifi WiFiServer server(80); //declare server object and spedify port, 80 is port used for internet void setup() { WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP Serial.begin(115200); delay(10); if (SPIFFS.begin()) { Serial.println("mounted file system"); if (SPIFFS.exists("/config.json")) { //file exists, reading and loading Serial.println("reading config file"); File configFile = SPIFFS.open("/config.json", "r"); if (configFile) { Serial.println("opened config file"); 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); #ifdef ARDUINOJSON_VERSION_MAJOR >= 6 DynamicJsonDocument json(1024); DeserializationError deserializeError = deserializeJson(json, buf.get()); serializeJson(json, Serial); if (!deserializeError) { #else DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.parseObject(buf.get()); json.printTo(Serial); if (json.success()) { #endif Serial.println("\nparsed json"); if (json["ip"]) { Serial.println("setting custom ip from config"); strcpy(static_ip, json["ip"]); strcpy(static_gw, json["gateway"]); strcpy(static_sn, json["subnet"]); Serial.println(static_ip); } else { Serial.println("no custom ip in config"); } } else { Serial.println("failed to load json config"); } } } } else { // SendState(); Serial.println("failed to mount FS"); } WiFiManager wifiManager; wifiManager.setSaveConfigCallback(saveConfigCallback); //set static ip IPAddress _ip, _gw, _sn; _ip.fromString(static_ip); _gw.fromString(static_gw); _sn.fromString(static_sn); wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn); //set minimu quality of signal so it ignores AP's under that quality //defaults to 8% wifiManager.setMinimumSignalQuality(); wifiManager.setBreakAfterConfig(true); if (!wifiManager.autoConnect("TTTT", "password")) { Serial.println("failed to connect and hit timeout"); delay(3000); //reset and try again, or maybe put it to deep sleep ESP.reset(); delay(5000); } //if you get here you have connected to the WiFi Serial.println("connected...yeey :)"); //save the custom parameters to FS if (shouldSaveConfig) { Serial.println("saving config"); #ifdef ARDUINOJSON_VERSION_MAJOR >= 6 DynamicJsonDocument json(1024); #else DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); #endif json["ip"] = WiFi.localIP().toString(); json["gateway"] = WiFi.gatewayIP().toString(); json["subnet"] = WiFi.subnetMask().toString(); File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { Serial.println("failed to open config file for writing"); } #ifdef ARDUINOJSON_VERSION_MAJOR >= 6 serializeJson(json, Serial); serializeJson(json, configFile); // resetFunc(); #else json.printTo(Serial); json.printTo(configFile); #endif configFile.close(); //end save } server.begin(); Serial.println("Server started"); Serial.print("Use this URL to connect: "); Serial.print("http://"); Serial.print(WiFi.localIP()); Serial.println("/"); } void loop() { WiFiClient client = server.available(); // listen for incoming clients(Returns a Client object that has data available for reading if no Client has data available for reading this object will evaluate to false) //if client has data to be read then it will be true (WiFiClient client) Creates a client that can connect to a specified internet IP address and port if (client) { // if you get a client, // Serial.println("new client"); // print a message out the serial port String currentLine = ""; while (client.connected()) { // loop while the client's connected if (client.available()) { // if there's bytes to read from the client,Returns the number of bytes available for reading char c = client.read(); // read a byte, then (Read the next byte received from the server the client is connected to (after the last call to read()).or -1 if none is available.) if (c == '\n') { // if the byte is a newline character } else if (c != '\r') { // if you got anything else but a carriage return character" Carriage Return ("CR") moves the cursor to the beginning of the line without advancing to the next line", currentLine += c; // add it to the end of the currentLine } if (currentLine.endsWith("GET /v")) { WiFiManager wifiManager; wifiManager.resetSettings(); #ifdef ARDUINOJSON_VERSION_MAJOR >= 6 DynamicJsonDocument json(1024); #else DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); #endif wifiManager.setSaveConfigCallback(saveConfigCallback); wifiManager.setBreakAfterConfig(true); IPAddress _ip, _gw, _sn; _ip.fromString("192.168.43.99"); _gw.fromString("192.168.43.1"); _sn.fromString("255.255.255.0"); wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn); WiFi.begin("Xperia","88888888m"); Serial.print("Connecting"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.print("Connected, IP address: "); Serial.println(WiFi.localIP()); json["ip"] = "192.168.43.99"; json["gateway"] = "192.168.43.1"; json["subnet"] = "255.255.255.0"; File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { Serial.println("failed to open config file for writing"); } #ifdef ARDUINOJSON_VERSION_MAJOR >= 6 serializeJson(json, Serial); serializeJson(json, configFile); #else json.printTo(Serial); json.printTo(configFile); #endif configFile.close(); resetFunc(); } } } // close the connection: client.stop(); } } ``` **Now** let us consider that it has default data and connected with local ip "192.168.43.60" which i give it to the esp via the web link now here is the data that i get on Serial monitor with the following porecedures: 1.reset the esp 2.hitting "192.168.43.60/v" via my laptop. What should i expect is that it will reset the esp configration then tries to change the local ip to 192.168.43.99 then reconnect to the Wi-Fi -and at this point i will change the wi-fi SSID and PASS to the new given one in the code but i didn't here in this example-. Anyway here is what i get on the serial monitor : > SDK:2.2.2-dev(38a443e)/Core:2.7.2-7-g5d3af165=20702007/lwIP:STABLE-2_1_2_RELEASE/glue:1.2-30-g92add50/BearSSL:5c771be > mounted file system > reading config file > opened config file > {"ip":"192.168.43.60","gateway":"192.168.43.1","subnet":"255.255.255.0"} > parsed json > setting custom ip from config > 192.168.43.60 > *WM: [1] AutoConnect > *WM: [2] Connecting as wifi client... > *WM: [3] STA static IP: 192.168.43.60 > *WM: [2] Custom static IP/GW/Subnet/DNS > *WM: [2] Custom STA IP/GW/Subnet > *WM: [1] STA IP set: 192.168.43.60 > *WM: [1] Connecting to SAVED AP: Xperia > *WM: [3] Using Password: 88888888m > *WM: [3] WiFi station enable > *WM: [3] enableSTA PERSISTENT ON > scandone > *WM: [1] connectTimeout not set, ESP waitForConnectResult... > scandone > state: 0 -> 2 (b0) > state: 2 -> 3 (0) > state: 3 -> 5 (10) > add 0 > aid 1 > cnt > > connected with Xperia, channel 13 > ip:192.168.43.60,mask:255.255.255.0,gw:192.168.43.1 > ip:192.168.43.60,mask:255.255.255.0,gw:192.168.43.1 > *WM: [2] Connection result: WL_CONNECTED > *WM: [3] lastconxresult: WL_CONNECTED > *WM: [1] AutoConnect: SUCCESS > *WM: [1] STA IP Address: 192.168.43.60 > connected...yeey :) > Server started > Use this URL to connect: http://192.168.43.60/ > *WM: [3] unloading > pm open,type:2 0 > *WM: [1] resetSettings //HERE WHEN I HIT "192.168.43.60/V" WITH MY LAPTOP > *WM: [3] WiFi station enable > *WM: [3] enableSTA PERSISTENT ON > state: 5 -> 0 (0) > rm 0 > pm close 7 > del if0 > usl > mode : null > *WM: [1] SETTINGS ERASED > mode : sta(84:0d:8e:8d:ed:80) > ip:192.168.43.60,mask:255.255.255.0,gw:192.168.43.1 > add if0 > Connecting......scandone > state: 0 -> 2 (b0) > .state: 2 -> 3 (0) > state: 3 -> 5 (10) > add 0 > aid 1 > cnt > > connected with Xperia, channel 13 > ip:192.168.43.60,mask:255.255.255.0,gw:192.168.43.1 > . > Connected, IP address: 192.168.43.60 > {"ip":"192.168.43.99","gateway":"192.168.43.1","subnet":"255.255.255.0"} > ets Jan 8 2013,rst cause:4, boot mode:(3,6) > > wdt reset > load 0x4010f000, len 3584, room 16 > tail 0 > chksum 0xb0 > csum 0xb0 > v5d3af165 > ~ld > > SDK:2.2.2-dev(38a443e)/Core:2.7.2-7-g5d3af165=20702007/lwIP:STABLE-2_1_2_RELEASE/glue:1.2-30-g92add50/BearSSL:5c771be > mounted file system > reading config file > opened config file > {"ip":"192.168.43.99","gateway":"192.168.43.1","subnet":"255.255.255.0"} > parsed json > setting custom ip from config > 192.168.43.99 > *WM: [1] AutoConnect > *WM: [1] No Credentials are Saved, skipping connect > *WM: [2] Starting Config Portal > *WM: [2] AccessPoint set password is VALID > *WM: [1] password > *WM: [3] WIFI station disconnect > *WM: [3] WiFi station enable > del if0 > usl > mode : null > *WM: [2] Disabling STA > *WM: [2] Enabling AP > *WM: [1] StartAP with SSID: TTTT > mode : softAP(86:0d:8e:8d:ed:80) > add if1 > dhcp server start:(ip:192.168.4.1,mask:255.255.255.0,gw:192.168.4.1) > bcn 100 > bcn 0 > del if1 > usl > add if1 > dhcp server start:(ip:192.168.4.1,mask:255.255.255.0,gw:192.168.4.1) > bcn 100 > *WM: [1] SoftAP Configuration > *WM: [1] -------------------- > *WM: [1] ssid: TTTT > *WM: [1] password: password > *WM: [1] ssid_len: 4 > *WM: [1] channel: 1 > *WM: [1] authmode: 3 > *WM: [1] ssid_hidden: > *WM: [1] max_connection: 4 > *WM: [1] country: CN > *WM: [1] beacon_interval: 100(ms) > *WM: [1] -------------------- > *WM: [1] AP IP address: 192.168.4.1 > *WM: [3] setupConfigPortal > *WM: [1] Starting Web Portal > *WM: [3] dns server started with ip: 192.168.4.1 > *WM: [2] HTTP server started > mode : sta(84:0d:8e:8d:ed:80) + softAP(86:0d:8e:8d:ed:80) > add if0 > scandone > *WM: [2] WiFi Scan completed in 2187 ms > Also i tried to put this line: ` WiFi.begin("Xperia","88888888m"); ` after the this line: ` configFile.close(); ` and still the same response , No save for the SSID and PASS. I would be pleased for help,Thanks anyway :)
Author
Owner

@Shalabyer commented on GitHub (Sep 25, 2020):

Any help :)

<!-- gh-comment-id:698899499 --> @Shalabyer commented on GitHub (Sep 25, 2020): Any help :)
Author
Owner

@tablatronix commented on GitHub (Sep 25, 2020):

alot going on here, first off why are you parsing the web server, you can just add a route and a callback and then check if the arguments exist for querystrings. There are web server functions to do this.

It looks like you are still connected after resetsettings, that is odd, maybe it is ok after reboot.

Not sure when you say not saved, WiFi.begin("Xperia","88888888m"); is saved by the esp

Maybe your flash is corrupt

You will need to present this in smaller pieces, its hard to follow

<!-- gh-comment-id:698943430 --> @tablatronix commented on GitHub (Sep 25, 2020): alot going on here, first off why are you parsing the web server, you can just add a route and a callback and then check if the arguments exist for querystrings. There are web server functions to do this. It looks like you are still connected after resetsettings, that is odd, maybe it is ok after reboot. Not sure when you say not saved, `WiFi.begin("Xperia","88888888m");` is saved by the esp Maybe your flash is corrupt You will need to present this in smaller pieces, its hard to follow
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
starred/WiFiManager#961
No description provided.