WiFi Manager Custom Parameters are not saved in Memory via OnDemand Portal

I am working on WiFiManager Code using Library Wifi Manager library by tzapu. I wish to work OnDemand and Custom Parameters. After formatting the SPIFFS, the custom parameters get saved in memory during the first configuration. I press the button (FLASH) for OnDemand configuration this time I give different values in the custom Parameters field. It connects and shows these new values of parameters in the serial monitor. But after reset when it automatically connects, the values are shown were of previous and not which are supplied while OnDemand. That means the values supplied during the OnDemand Configuration are not being saved in the memory of NodeMCU. Kindly help me or point me where I am going wrong.


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


// select which pin will trigger the configuration portal when set to LOW
#define TRIGGER_PIN 0
int timeout = 120; // seconds to run for

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

#include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson

//define your default values here, if there are different values in config.json, they are overwritten.
char mqtt_server[40];
char mqtt_port[6] = "8080";
char api_token[34] = "YOUR_API_TOKEN";

//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 setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println();
  pinMode(TRIGGER_PIN, INPUT_PULLUP);

  //clean FS, for testing
  //SPIFFS.format();

  //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);

#ifdef 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"]);
          strcpy(mqtt_port, json["mqtt_port"]);
          strcpy(api_token, json["api_token"]);
        } else {
          Serial.println("failed to load json config");
        }
        configFile.close();
      }
    }
  } else {
    Serial.println("failed to mount FS");
  }
  //end read

  // The extra parameters to be configured (can be either global or just in the setup)
  // After connecting, parameter.getValue() will get you the configured value
  // id/name placeholder/prompt default length
  WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
  WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6);
  WiFiManagerParameter custom_api_token("apikey", "API token", api_token, 32);

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;

  //set config save notify callback
  wifiManager.setSaveConfigCallback(saveConfigCallback);

  //set static ip
  //wifiManager.setSTAStaticIPConfig(IPAddress(10, 0, 1, 99), IPAddress(10, 0, 1, 1), IPAddress(255, 255, 255, 0));

  //add all your parameters here
  wifiManager.addParameter(&custom_mqtt_server);
  wifiManager.addParameter(&custom_mqtt_port);
  wifiManager.addParameter(&custom_api_token);

  //reset settings - for testing
  //wifiManager.resetSettings();

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

  //sets timeout until configuration portal gets turned off
  //useful to make it all retry or go to sleep
  //in seconds
  //wifiManager.setTimeout(120);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
    Serial.println("failed to connect and hit timeout");
    delay(3000);
    //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());
  strcpy(mqtt_port, custom_mqtt_port.getValue());
  strcpy(api_token, custom_api_token.getValue());
  Serial.println("The values in the file are: ");
  Serial.println("\tmqtt_server : " + String(mqtt_server));
  Serial.println("\tmqtt_port : " + String(mqtt_port));
  Serial.println("\tapi_token : " + String(api_token));

  //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["mqtt_server"] = mqtt_server;
    json["mqtt_port"] = mqtt_port;
    json["api_token"] = api_token;

    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();
    //end save
  }

  Serial.println("local ip");
  Serial.println(WiFi.localIP());
}

void loop() {
 
  // is configuration portal requested?
  if ( digitalRead(TRIGGER_PIN) == LOW) {
    WiFiManager wm;
    
    WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
    WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6);
    WiFiManagerParameter custom_api_token("apikey", "API token", api_token, 32);
    
    wm.addParameter(&custom_mqtt_server);
    wm.addParameter(&custom_mqtt_port);
    wm.addParameter(&custom_api_token);


    //reset settings - for testing
    //wm.resetSettings();
  
    // set configportal timeout
    wm.setConfigPortalTimeout(timeout);

    if (!wm.startConfigPortal("OnDemandAP")) {
      Serial.println("failed to connect and hit timeout");
      delay(3000);
      //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 :)");

  }
   // put your main code here, to run repeatedly:

make the parameters global

Sir, Today I tried it many times with NodeMCU. To avoid the problem of depreciacted SPIFFS, I tried it with ESP32. Still same problem..!!

Code is



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


// select which pin will trigger the configuration portal when set to LOW
#define TRIGGER_PIN 0
int timeout = 120; // seconds to run for

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

#include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson

//define your default values here, if there are different values in config.json, they are overwritten.
char mqtt_server[40];
char mqtt_port[6] = "8080";
char api_token[34] = "YOUR_API_TOKEN";

//flag for saving data
bool shouldSaveConfig = false;

WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6);
WiFiManagerParameter custom_api_token("apikey", "API token", api_token, 32);


//callback notifying us of the need to save config
void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println();
  pinMode(TRIGGER_PIN, INPUT_PULLUP);

  //clean FS, for testing
  //SPIFFS.format();

  //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);

#ifdef 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"]);
          strcpy(mqtt_port, json["mqtt_port"]);
          strcpy(api_token, json["api_token"]);
        } else {
          Serial.println("failed to load json config");
        }
        configFile.close();
      }
    }
  } else {
    Serial.println("failed to mount FS");
  }
  //end read

  // The extra parameters to be configured (can be either global or just in the setup)
  // After connecting, parameter.getValue() will get you the configured value
  // id/name placeholder/prompt default length

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;

  //set config save notify callback
  wifiManager.setSaveConfigCallback(saveConfigCallback);

  //set static ip
  //wifiManager.setSTAStaticIPConfig(IPAddress(10, 0, 1, 99), IPAddress(10, 0, 1, 1), IPAddress(255, 255, 255, 0));

  //add all your parameters here
  wifiManager.addParameter(&custom_mqtt_server);
  wifiManager.addParameter(&custom_mqtt_port);
  wifiManager.addParameter(&custom_api_token);

  //reset settings - for testing
  //wifiManager.resetSettings();

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

  //sets timeout until configuration portal gets turned off
  //useful to make it all retry or go to sleep
  //in seconds
  //wifiManager.setTimeout(120);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
    Serial.println("failed to connect and hit timeout");
    delay(3000);
    //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());
  strcpy(mqtt_port, custom_mqtt_port.getValue());
  strcpy(api_token, custom_api_token.getValue());
  Serial.println("The values in the file are: ");
  Serial.println("\tmqtt_server : " + String(mqtt_server));
  Serial.println("\tmqtt_port : " + String(mqtt_port));
  Serial.println("\tapi_token : " + String(api_token));

  //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["mqtt_server"] = mqtt_server;
    json["mqtt_port"] = mqtt_port;
    json["api_token"] = api_token;

    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();
    //end save
  }

  Serial.println("local ip");
  Serial.println(WiFi.localIP());
}

void loop() {
 
  // is configuration portal requested?
  if ( digitalRead(TRIGGER_PIN) == LOW) {
    WiFiManager wm;
    
    WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
    WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6);
    WiFiManagerParameter custom_api_token("apikey", "API token", api_token, 32);
    
    wm.addParameter(&custom_mqtt_server);
    wm.addParameter(&custom_mqtt_port);
    wm.addParameter(&custom_api_token);


    //reset settings - for testing
    //wm.resetSettings();
  
    // set configportal timeout
    wm.setConfigPortalTimeout(timeout);

    if (!wm.startConfigPortal("OnDemandAP")) {
      Serial.println("failed to connect and hit timeout");
      delay(3000);
      //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());
  strcpy(mqtt_port, custom_mqtt_port.getValue());
  strcpy(api_token, custom_api_token.getValue());
  Serial.println("The values in the file are: ");
  Serial.println("\tmqtt_server : " + String(mqtt_server));
  Serial.println("\tmqtt_port : " + String(mqtt_port));
  Serial.println("\tapi_token : " + String(api_token));

  //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["mqtt_server"] = mqtt_server;
    json["mqtt_port"] = mqtt_port;
    json["api_token"] = api_token;

    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();
    //end save
  }

  Serial.println("local ip");
  Serial.println(WiFi.localIP());


  }
   // put your main code here, to run repeatedly:
  Serial.println("The values in the file are: ");
  Serial.println("\tmqtt_server : " + String(mqtt_server));
  Serial.println("\tmqtt_port : " + String(mqtt_port));
  Serial.println("\tapi_token : " + String(api_token));
  delay(2000);
}

add shouldSaveConfig = true; after wm.startConfigPortal("OnDemandAP")

Thank you very much..!! I can sleep well now. it is working..
the code is

 if (!wm.startConfigPortal("OnDemandAP")) {
      Serial.println("failed to connect and hit timeout");
      delay(3000);
      //reset and try again, or maybe put it to deep sleep
      ESP.restart();
      delay(5000);
    }
    shouldSaveConfig = true;

I think I placed it in right place.

To also save the params when using the /param page add this method

    wifiManager.setPreSaveConfigCallback(saveConfigCallback);

This will also call the saveConfigCallback method when only updating the param page.
This can be the same method as used with the initial setup.

@wvtbg Dear Sir, Thank you for taking interest in this issue. I hope I have to write this command below

wifiManager.setSaveConfigCallback(saveConfigCallback);

Actually, I am making a timer that operates a relay and time can be set from Wifi-Manager Portal. The custom parameters are Relay Pin, TimeSetLed, WifiIndicator and On-time and Off-time. Relay Pin will operate the machine as per the timer. TimesetLed will indicate whether time got set or not from NTP. And WifiIndicator Led will show whether a live wifi connection is available or got disconnected. I would like to set a time during Autoconnect or during OnDemand. However, I face problems.

  1. Though I uncomment SPIFFS.format(); and wifiManager.resetSettings(); during testing purposes, it gets connected to the previous wifi credentials.
  2. The labels are not shown on the custom parameter’s field.

Today evening I had a plan to once again test and verify consciously before asking the issue here, but out of excitement, I am asking early.

The complete code is:

#include <FS.h>                   
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager
//#include <ESP8266WiFi.h>            
#include <time.h>                   

/* Configuration of NTP */
#define MY_NTP_SERVER "in.pool.ntp.org" //"at.pool.ntp.org"
       
#define MY_TZ "IST-5:30"  // I added this for Indian Standard Time

time_t now;                         // this is the epoch
tm tm;                              // the structure tm holds time information in a more convient way
/* Configuration of NTP end */

// select which pin will trigger the configuration portal when set to LOW
#define TRIGGER_PIN 0
int timeout = 120; // seconds to run for

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

#include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson

//define your default values here, if there are different values in config.json, they are overwritten.
char relay[3]="16";
char wifiOnOffLED[3] = "14";
char timeSetIndiLED[3] = "15";
char onTime[3] = "11";
char offTime[3] = "06";

WiFiManagerParameter custom_WiFirelay("relay", "Relay Connected Pin", relay, 3);
WiFiManagerParameter custom_wifiOnOffLED("wifiOnOffLED", "Wifi Indicator", wifiOnOffLED, 3);
WiFiManagerParameter custom_timeSetIndiLED("timeSetIndiLED", "Time Set Indicator", timeSetIndiLED, 3);
WiFiManagerParameter custom_onTime("onTime", "Enter ON Time (eg. 0600)", onTime, 3);
WiFiManagerParameter custom_offTime("offTime", "Enter OFF Time (eg. 1100)", offTime, 3);
    
// Wifi connection/disconnection event handler
WiFiEventHandler gotIpEventHandler, disconnectedEventHandler;
bool wifiIndicator;

//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 showTime() {
  time(&now);                       // read the current time
  localtime_r(&now, &tm);           // update the structure tm with the current time
  Serial.print("year:");
  Serial.print(tm.tm_year + 1900);  // years since 1900
  Serial.print("\tmonth:");
  Serial.print(tm.tm_mon + 1);      // January = 0 (!)
  Serial.print("\tday:");
  Serial.print(tm.tm_mday);         // day of month
  Serial.print("\thour:");
  Serial.print(tm.tm_hour);         // hours since midnight  0-23
  Serial.print("\tmin:");
  Serial.print(tm.tm_min);          // minutes after the hour  0-59
  Serial.print("\tsec:");
  Serial.print(tm.tm_sec);          // seconds after the minute  0-61*
  Serial.print("\twday");
  Serial.print(tm.tm_wday);         // days since Sunday 0-6
  if (tm.tm_isdst == 1)             // Daylight Saving Time flag
    Serial.print("\tDST");
  else
    Serial.print("\tstandard");
  Serial.println();
}

uint32_t sntp_update_delay_MS_rfc_not_less_than_15000 ()
{
  return 24 * 60 * 60 * 1000UL; // 24 hours
}

void wifiOnOff(){
 
  if ((tm.tm_year + 1900)>1970){  // Runs When time set 

    if(tm.tm_hour>atoi(offTime) || tm.tm_hour<atoi(onTime)) {
    digitalWrite(atoi(relay), HIGH);   // Operates Relay
    }
    else{
       digitalWrite(atoi(relay), LOW);  /// Operates Relay
    }
  }
  else{
    Serial.println("Time not set");            // Runs when time not set 
     digitalWrite(atoi(timeSetIndiLED), HIGH);
     delay(1500);
     digitalWrite(atoi(timeSetIndiLED), LOW);
     delay(1500);
     }
   }

void setup() {
    // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println();
  pinMode(TRIGGER_PIN, INPUT_PULLUP);

  //clean FS, for testing
  SPIFFS.format();

  //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);

#ifdef 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(relay, json["relay"]);
          strcpy(wifiOnOffLED, json["wifiOnOffLED"]);
          strcpy(timeSetIndiLED, json["timeSetIndiLED"]);
          strcpy(onTime, json["onTime"]);
          strcpy(offTime, json["offTime"]);
           
          
        } else {
          Serial.println("failed to load json config");
        }
        configFile.close();
      }
    }
  } else {
    Serial.println("failed to mount FS");
  }
  
  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;

  //set config save notify callback
  wifiManager.setSaveConfigCallback(saveConfigCallback);

  //set static ip
  //wifiManager.setSTAStaticIPConfig(IPAddress(10, 0, 1, 99), IPAddress(10, 0, 1, 1), IPAddress(255, 255, 255, 0));

  //add all your parameters here
  wifiManager.addParameter(&custom_WiFirelay);
  wifiManager.addParameter(&custom_wifiOnOffLED);
  wifiManager.addParameter(&custom_timeSetIndiLED);
  wifiManager.addParameter(&custom_onTime);
  wifiManager.addParameter(&custom_offTime);

  //reset settings - for testing
  wifiManager.resetSettings();

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

  //sets timeout until configuration portal gets turned off
  //useful to make it all retry or go to sleep
  //in seconds
  //wifiManager.setTimeout(120);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
    Serial.println("failed to connect and hit timeout");
    delay(3000);
    //reset and try again, or maybe put it to deep sleep
    ESP.restart();
    delay(5000);
  }

   //read updated parameters
  strcpy(relay, custom_WiFirelay.getValue());
  strcpy(wifiOnOffLED, custom_wifiOnOffLED.getValue());
  strcpy(timeSetIndiLED, custom_timeSetIndiLED.getValue());
  strcpy(onTime, custom_onTime.getValue());
  strcpy(offTime, custom_offTime.getValue());
  
  Serial.println("The values in the file are: ");
  Serial.println("\tConnect Relay to : " + String(relay));
  Serial.println("\tWiFi indicator LED is : " + String(wifiOnOffLED));
  Serial.println("\tOn time is : " + String(onTime));
  Serial.println("\tOff time is : " + String(offTime));

 pinMode(atoi(relay), OUTPUT);
 pinMode(atoi(wifiOnOffLED), OUTPUT);
 pinMode(atoi(timeSetIndiLED), OUTPUT);

 digitalWrite(atoi(relay), LOW);
 digitalWrite(atoi(wifiOnOffLED), LOW);
 digitalWrite(atoi(timeSetIndiLED), LOW);

  //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["relay"] = relay;
    json["wifiOnOffLED"] = wifiOnOffLED;
    json["timeSetIndiLED"] = timeSetIndiLED;
    json["onTime"] = onTime;
    json["offTime"] = offTime;

    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();
    //end save
  }

  Serial.println("local ip");
  Serial.println(WiFi.localIP());

   //if you get here you have connected to the WiFi
 Serial.println("connected...yeey :)");
 configTime(MY_TZ, MY_NTP_SERVER); // --> Connected.. now get time 

/* Wifi Connection/Dissconnection Event Handler in the Backgfround Start*/

 gotIpEventHandler = WiFi.onStationModeGotIP([](const WiFiEventStationModeGotIP& event)
  {
    Serial.print("Station connected, IP: ");
    Serial.println(WiFi.localIP());
    wifiIndicator=true;
    configTime(MY_TZ, MY_NTP_SERVER); // --> Here is the IMPORTANT ONE LINER needed in your sketch!
  });

  disconnectedEventHandler = WiFi.onStationModeDisconnected([](const WiFiEventStationModeDisconnected& event)
  {
    Serial.println("Station disconnected");
    wifiIndicator=false;
  });
  /* Wifi Connection/Dissconnection Event Handler in the Backgfround Stop*/

}

void loop() {
 
  // is configuration portal requested?
  if ( digitalRead(TRIGGER_PIN) == LOW) {

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wm;

  //set config save notify callback
  wm.setSaveConfigCallback(saveConfigCallback);

  //add all your parameters here
  wm.addParameter(&custom_WiFirelay);
  wm.addParameter(&custom_wifiOnOffLED);
  wm.addParameter(&custom_timeSetIndiLED);
  wm.addParameter(&custom_onTime);
  wm.addParameter(&custom_offTime);

  //reset settings - for testing
  //wifiManager.resetSettings();

  if (!wm.startConfigPortal("OnDemandAP", "password")) {
    Serial.println("failed to connect and hit timeout");
    delay(3000);
    //reset and try again, or maybe put it to deep sleep
    ESP.restart();
    delay(5000);
  }
  shouldSaveConfig = true;

   //read updated parameters
  strcpy(relay, custom_WiFirelay.getValue());
  strcpy(wifiOnOffLED, custom_wifiOnOffLED.getValue());
  strcpy(timeSetIndiLED, custom_timeSetIndiLED.getValue());
  strcpy(onTime, custom_onTime.getValue());
  strcpy(offTime, custom_offTime.getValue());
  
  Serial.println("The values in the file are: ");
  Serial.println("\tConnect Relay to : " + String(relay));
  Serial.println("\tWiFi indicator LED is : " + String(wifiOnOffLED));
  Serial.println("\tOn time is : " + String(onTime));
  Serial.println("\tOff time is : " + String(offTime));

 pinMode(atoi(relay), OUTPUT);
 pinMode(atoi(wifiOnOffLED), OUTPUT);
 pinMode(atoi(timeSetIndiLED), OUTPUT);

 digitalWrite(atoi(relay), LOW);
 digitalWrite(atoi(wifiOnOffLED), LOW);
 digitalWrite(atoi(timeSetIndiLED), LOW);

  //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["relay"] = relay;
    json["wifiOnOffLED"] = wifiOnOffLED;
    json["timeSetIndiLED"] = timeSetIndiLED;
    json["onTime"] = onTime;
    json["offTime"] = offTime;

    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();
    //end save
  }

  Serial.println("local ip");
  Serial.println(WiFi.localIP());

   //if you get here you have connected to the WiFi
 Serial.println("connected...yeey :)");
  }
   // My code to run repeatedly:

  time(&now);                       // read the current time
  localtime_r(&now, &tm);           // update the structure tm with the current time

 if(wifiIndicator){
      showTime();
      delay(1000);
      wifiOnOff();
      digitalWrite(atoi(wifiOnOffLED), HIGH); // Indicates the Wifi is ON
 } 
 else{
      showTime();
      delay(1000);
     wifiOnOff();
     Serial.println("No internet");
     digitalWrite(atoi(wifiOnOffLED), HIGH);
     delay(1500);                             // Led Blinking to indicates loss of Wifi
     digitalWrite(atoi(wifiOnOffLED), LOW);
     delay(1500);
  
    }
}

Sir, I have to make any changes or this is an issue, I am very sorry, it not got clear to me. Do you mean the following code under OnDemand does not save the parameters in the file?

 //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["relay"] = relay;
    json["wifiOnOffLED"] = wifiOnOffLED;
    json["timeSetIndiLED"] = timeSetIndiLED;
    json["onTime"] = onTime;
    json["offTime"] = offTime;

    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();

Ok, Confirmed!, my previous queries stands valid. SPIFFS.format(); and wifiManager.resetSettings(); dose not clean the memory. Two more problem

  1. Though the active wifi connection is available wifi event handler shows wifi disconnected during auto-connect. (Though it gets time from NTP after connection)

  2. Wifi event handler shows true when ESP connects during OnDemand.

This is the snapshot that shows no labels on custom parameters.