ESP8266 WiFi manager configuration issue

Hai everyone,
I have no idea from get dns from the field tab in webpage and store in json in code i declared default dns as 8.8.8.8
then I need same as above for secondary dns.

I have faced three problems.
The first one, on demand, I tried to erase the older configuration but it didn't work.
The second one is static,dns, and custom parameter fields disappear after the initial configuration I declared the true value in the function. it will reappear after erase the configuration from the webpage.
The third one is not able to switching between dynamic and static IP iam trying to switch the IP mode but it does not make it. only static IP is set from the previous configuration
i need checkbox for IP mode selection in webpage its simple.

please help me to complete my project

WiFimanager Branch/Release: 2.0.16-rc.2

Esp8266/Esp32: Esp8266

Hardware: ESP-12e

Core Version: 3.1.2

#include <FS.h>                   //this needs to be first, or it all crashes and burns...
#include <ESP8266WiFi.h>
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager
#include <PubSubClient.h>       // PubSub Library used for MQTT protocol must needed very important.
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson
#include <ESPping.h>
#ifdef ESP32
  #include <SPIFFS.h>
#endif

#define buttonPin 12    // Reset button pin
#define LONG_PRESS_TIME 5000   // long press of reset button time in milliseconds 5000
const char* remote_host = "www.google.com"; //Host name to ping for internet connectivity.
char mqtt_server[40] = "xxxx";
char user[20] = "xxxx";             // Username of MQTT Broker
char pass[30] = "xxxxx";           // Password of MQTT Broker
int wifiStatus;                   // TO check the WiFi status.
WiFiClient espClient;                    
PubSubClient client(espClient);

WiFiManager wifiManager;

//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";
char dns[16]="8.8.8.8";
//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 reconnect() {
  // Loop until we're reconnected
 if (!client.connected()) { 
    Serial.print("Attempting MQTT connection...");
    digitalWrite(BUILTIN_LED, LOW);
    // Create a random client ID
    String clientId = "ESP8266Client-";   
    clientId += String(random(0xffff), HEX);   /*************************** Client Id generated ramdomly *************************/
    // Attempt to connect
    if (client.connect(clientId.c_str(),user,pass)) { /*********************** Connection init to MQTT server *********/
       client.subscribe(sub_topic);  /********************************** Subscribe starts here *****************************/
       wifiStatus = WiFi.status();  
       if(wifiStatus == WL_CONNECTED){
         Serial.println("");
         Serial.println("Your Module is connected!");  
         Serial.print("Connected to ");
         Serial.println(WiFi.SSID());
         Serial.print("Local IP: ");
         Serial.println(WiFi.localIP());
         Serial.print("Gateway IP: ");
         Serial.println(WiFi.gatewayIP());
         Serial.print("Subnet Mask: ");
         Serial.println(WiFi.subnetMask());
         Serial.print("DNS: ");
         Serial.println(WiFi.dnsIP());
         Serial.print("Module MAC address is: ");
         Serial.println(sub_topic);        
        }
       else{
        Serial.println("");
        Serial.println("WiFi not connected");
     }
     if (Ping.ping(remote_host) > 0){ /***************************** Ping the remote host to check the internet status *******/
     Serial.printf("Response time : %d/%.2f/%d ms\n", Ping.minTime(), Ping.averageTime(), Ping.maxTime());
     Serial.println("Ping Success!! ");
     } else {
     Serial.println("Ping Error !");
     }
    }
    else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 1 second");  
      digitalWrite(BUILTIN_LED, HIGH);    
      delay(500);
    }
  }
} 

void setup() {
  Serial.begin(115200);
  Serial.println();
  pinMode(buttonPin, INPUT_PULLUP);
  digitalWrite(buttonPin, LOW); /******************* During start up the PIN is LOW state after pressing it this becomes HIGH *********/
  client.setServer(mqtt_server, 1883);        /******************** MQTT server connects in 1883 port *****************************/

  //read configuration from FS json
  Serial.println("mounting FS...");

  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);
   #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6
        DynamicJsonDocument json(1024);
        auto 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");
          
          strcpy(mqtt_server, json["mqtt_server"]);

          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 {
    Serial.println("failed to mount FS");
  }
  //end read
  Serial.println(static_ip);
  WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
 
  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;
  
  wifiManager.setShowStaticFields(true);  // show Static IP  user Field 
  wifiManager.setShowDnsFields(true); // show DNS  user Field 
  //set config save notify callback
  wifiManager.setSaveConfigCallback(saveConfigCallback);
    
  //set static ip
  IPAddress _ip, _gw, _sn, _dns;
  _ip.fromString(static_ip);
  _gw.fromString(static_gw);
  _sn.fromString(static_sn);
  _dns.fromString(dns);
  wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn, _dns);
  
  //add all your parameters here
  wifiManager.addParameter(&custom_mqtt_server);

  /*fetches ssid and pass and tries to connect
  if it does not connect it starts an access point with the specified name
  here  "AP Mode"
  and goes into a blocking loop awaiting configuration */

  if (!wifiManager.autoConnect("AP Mode")) {
    Serial.println("failed to connect and hit timeout");
    delay(1000);
    //reset and try again, or maybe put it to deep sleep
    ESP.restart();
    delay(5000);
  }
  
  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");
  
  //read updated parameters
  strcpy(mqtt_server, custom_mqtt_server.getValue());

  //save the custom parameters to FS
  if (shouldSaveConfig) {
    Serial.println("saving config");
 #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6
    DynamicJsonDocument json(1024);
 #else
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
 #endif
    json["mqtt_server"] = mqtt_server;
    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");
    }

 #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6
    serializeJson(json, Serial);
    serializeJson(json, configFile);
 #else
    json.printTo(Serial);
    json.printTo(configFile);
 #endif
    configFile.close();
    //end save
  }
  Serial.println("\n");
  Serial.print("Connected to ");
  Serial.println(WiFi.SSID());
  Serial.print("Local IP: ");
  Serial.println(WiFi.localIP());
  Serial.print("Gateway IP: ");
  Serial.println(WiFi.gatewayIP());
  Serial.print("Subnet Mask: ");
  Serial.println(WiFi.subnetMask());
  Serial.print("DNS: ");
  Serial.println(WiFi.dnsIP());
 }

void loop() {
  static unsigned long buttonPressStartTime = 0;
  static bool buttonPressed = false;

  if (digitalRead(buttonPin) == HIGH) {
    if (!buttonPressed) {
      Serial.println("AP Button is Pressed");
      buttonPressed = true;
      buttonPressStartTime = millis();
    }
    if (millis() - buttonPressStartTime > LONG_PRESS_TIME) {
      WiFi.disconnect();
      WiFi.mode(WIFI_AP);
      WiFi.softAP("AP Mode");
      WiFiManager wifiManager;
      wifiManager.resetSettings();      //reset settings  
      wifiManager.startConfigPortal("AP Mode");
    }
      }
   else {
    buttonPressed = false;
  }
  if (!client.connected()) {     
    reconnect();
    client.publish(pub_topic, "{\"status\" : \"online\"}");
    Serial.println("online");
  }

  delay(1000);  
  client.loop(); 
}

Does the example AutoConnectWithFSParametersAndCustomIP.ino work ?

same issue continue on the AutoConnectWithFSParametersAndCustomIP.ino. please help me to find out the sloution.

To 'clean' a previously used ESP8266 you can upload a new sketch with "Erase All Flash Content".
In IDE 1.8.19 you can find it under tools>Erase Flash.
Put things back to "Only Sketch" after uploading.

Not saying it will fix your problem.
Leo..

thanks for reply,
I clean the previous sketch with Erase All Flash Content in IDE 2.0.5 but not working.

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