[GH-ISSUE #1536] Parameters aren't showing on the portal. - *wm:[ERROR] WiFiManagerParameter is out of scope #1309

Closed
opened 2026-02-28 01:29:31 +03:00 by kerem · 4 comments
Owner

Originally created by @bentodman on GitHub (Dec 22, 2022).
Original GitHub issue: https://github.com/tzapu/WiFiManager/issues/1536

Basic Infos

Hardware

WiFimanager Branch/Release: Master

Esp8266

Hardware: ESP-12e, esp01, esp25

Core Version: 2.0.3

Description

Everything seems to compile and upload fine.
When i navigate to the portal i'm unable to see any parameters / input forms.
In the serial monitor I'm getting an error *wm:[ERROR] WiFiManagerParameter is out of scope.
I've tried stripping this back out and i'm struggling to get it to work, sorry i can't be anymore detailed but happy to test etc as needed!

Settings in IDE

Module: Wemos D1 Mini (Clone)

Additional libraries:

Sketch

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

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

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

//define your default values here, if there are different values in config.json, they are overwritten.
char mqtt_server[40] = "connect.mybroker.com";
char mqtt_port[6] = "1883";
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;
}


const char* mqtt_username = "USERNAME";
const char* mqtt_password = "PASSWORD";
const char* deviceId = "0001";
String command;

WiFiManager wifiManager;
WiFiClient espClient;
PubSubClient client(espClient);


void setup() {
  Serial.begin(115200);
  Serial.println();
  //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);

 #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"]);
          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);

  //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");
 #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["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");
    }

#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("local ip");
  Serial.println(WiFi.localIP());
 // IO Setup
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
 //MQTT Server
  client.setServer(mqtt_server, atoi(mqtt_port));
  client.setCallback(mqttMSGcallback);
}

// Run when we receive a msg
void mqttMSGcallback(char* topic, byte* payload, unsigned int length) {
 // Add data to variable
  String message;
  for (int i = 0; i < length; i++) {
    message += (char)payload[i];
  }

  if (message == "1") {
  addCredit();
  }

}

// Adding a credit
void addCredit() {
Serial.print("Credit Added \n");  
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
  digitalWrite(LED_BUILTIN, HIGH);
}

// Handing MQTT connection and status. 
void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting Cloud Connection...");
    if (client.connect(deviceId, mqtt_username, mqtt_password)) {
      Serial.println("Connected To Cloud");
      client.subscribe(deviceId);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}


void loop() { 
// Check if we have MQTT connection.
 if (!client.connected()) {
    reconnect();
  }
  client.loop();

// Backdoor commands via serial.
 if(Serial.available()){
        command = Serial.readStringUntil('\n');
         
        if(command.equals("settings")){
         wifiManager.startConfigPortal(deviceId);
        }
    }

}

Debug Messages

messages here
Originally created by @bentodman on GitHub (Dec 22, 2022). Original GitHub issue: https://github.com/tzapu/WiFiManager/issues/1536 ### Basic Infos #### Hardware WiFimanager Branch/Release: Master Esp8266 Hardware: ESP-12e, esp01, esp25 Core Version: 2.0.3 ### Description Everything seems to compile and upload fine. When i navigate to the portal i'm unable to see any parameters / input forms. In the serial monitor I'm getting an error *wm:[ERROR] WiFiManagerParameter is out of scope. I've tried stripping this back out and i'm struggling to get it to work, sorry i can't be anymore detailed but happy to test etc as needed! ### Settings in IDE Module: Wemos D1 Mini (Clone) Additional libraries: ### Sketch ```cpp #include <FS.h> //this needs to be first, or it all crashes and burns... #include <WiFiManager.h> //https://github.com/tzapu/WiFiManager 2.0.14 Beta #include <ESP8266WiFi.h> #include <PubSubClient.h> #ifdef ESP32 #include <SPIFFS.h> #endif #include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson 6.19.4 //define your default values here, if there are different values in config.json, they are overwritten. char mqtt_server[40] = "connect.mybroker.com"; char mqtt_port[6] = "1883"; 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; } const char* mqtt_username = "USERNAME"; const char* mqtt_password = "PASSWORD"; const char* deviceId = "0001"; String command; WiFiManager wifiManager; WiFiClient espClient; PubSubClient client(espClient); void setup() { Serial.begin(115200); Serial.println(); //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); #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"]); 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); //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"); #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["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"); } #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("local ip"); Serial.println(WiFi.localIP()); // IO Setup pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, HIGH); //MQTT Server client.setServer(mqtt_server, atoi(mqtt_port)); client.setCallback(mqttMSGcallback); } // Run when we receive a msg void mqttMSGcallback(char* topic, byte* payload, unsigned int length) { // Add data to variable String message; for (int i = 0; i < length; i++) { message += (char)payload[i]; } if (message == "1") { addCredit(); } } // Adding a credit void addCredit() { Serial.print("Credit Added \n"); digitalWrite(LED_BUILTIN, LOW); delay(500); digitalWrite(LED_BUILTIN, HIGH); } // Handing MQTT connection and status. void reconnect() { while (!client.connected()) { Serial.print("Attempting Cloud Connection..."); if (client.connect(deviceId, mqtt_username, mqtt_password)) { Serial.println("Connected To Cloud"); client.subscribe(deviceId); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); delay(5000); } } } void loop() { // Check if we have MQTT connection. if (!client.connected()) { reconnect(); } client.loop(); // Backdoor commands via serial. if(Serial.available()){ command = Serial.readStringUntil('\n'); if(command.equals("settings")){ wifiManager.startConfigPortal(deviceId); } } } ``` ### Debug Messages ``` messages here ```
kerem closed this issue 2026-02-28 01:29:31 +03:00
Author
Owner

@tablatronix commented on GitHub (Dec 22, 2022):

You are setting up params in setup, but starting the portal in loop, so they ARE out of scope

<!-- gh-comment-id:1362320316 --> @tablatronix commented on GitHub (Dec 22, 2022): You are setting up params in setup, but starting the portal in loop, so they ARE out of scope
Author
Owner

@bentodman commented on GitHub (Dec 22, 2022):

Doh! That makes sense, Thank you!

<!-- gh-comment-id:1363259466 --> @bentodman commented on GitHub (Dec 22, 2022): Doh! That makes sense, Thank you!
Author
Owner

@MEHUL95 commented on GitHub (Jan 1, 2023):

@bentodman did you found out a solution for this issue? I tried separating wifimanager configuration in a different function and calling that function from void.setup() from void.loop() but it didn't work, setup tab seems blank, I cannot fill any custom parameters.

<!-- gh-comment-id:1368411213 --> @MEHUL95 commented on GitHub (Jan 1, 2023): @bentodman did you found out a solution for this issue? I tried separating wifimanager configuration in a different function and calling that function from void.setup() from void.loop() but it didn't work, setup tab seems blank, I cannot fill any custom parameters.
Author
Owner

@Bruce17 commented on GitHub (Jan 2, 2023):

@MEHUL95 I had the same issue even with the example code OnDemandConfigPortal.ino

I moved the WiFiManagerParameter into the global scope f.e.:

WiFiManagerParameter *custom_mqtt_server;
WiFiManagerParameter *custom_mqtt_port;

... and changed the code inside the setup to something like:

custom_mqtt_server = new WiFiManagerParameter("server", "mqtt server", "", 40);
custom_mqtt_port = new WiFiManagerParameter("port", "mqtt port", "", 6);

// ...
wm.addParameter(custom_mqtt_server);
wm.addParameter(custom_mqtt_port);
Adjusted code example
/**
 * This is a kind of unit test for DEV for now
 * It contains many of the public methods
 *
 */
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <time.h>
#include <stdio.h>

#define USEOTA
// enable OTA
#ifdef USEOTA
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#endif

unsigned long mtime = 0;

WiFiManager wm;

// TEST OPTION FLAGS
bool TEST_CP = false;     // always start the configportal, even if ap found
int TESP_CP_TIMEOUT = 90; // test cp timeout

bool TEST_NET = true;      // do a network test after connect, (gets ntp time)
bool ALLOWONDEMAND = true; // enable on demand
int ONDDEMANDPIN = 0;      // gpio for button
bool WMISBLOCKING = true;  // use blocking or non blocking mode, non global params wont work in non blocking

// char ssid[] = "*************";  //  your network SSID (name)
// char pass[] = "********";       // your network password

// Forward declaration: required to make C compiler happy ¯\_(ツ)_/¯
void getTime();
void wifiInfo();
void handleRoute();

// Define WifiManagerParameters here ourside to access them also for the on-demand config portal
WiFiManagerParameter *custom_html;
WiFiManagerParameter *custom_mqtt_server;
WiFiManagerParameter *custom_mqtt_port;
WiFiManagerParameter *custom_token;
WiFiManagerParameter *custom_tokenb;
WiFiManagerParameter *custom_ipaddress;
WiFiManagerParameter *custom_input_type;
WiFiManagerParameter *custom_checkbox;
WiFiManagerParameter *custom_html_inputs;

void saveWifiCallback()
{
  Serial.println("[CALLBACK] saveCallback fired");
}

// gets called when WiFiManager enters configuration mode
void configModeCallback(WiFiManager *myWiFiManager)
{
  Serial.println("[CALLBACK] configModeCallback fired");
}

void saveParamCallback()
{
  Serial.println("[CALLBACK] saveParamCallback fired");
  // wm.stopConfigPortal();
}

void bindServerCallback()
{
  wm.server->on("/custom", handleRoute); // this is now crashing esp32 for some reason
  // wm.server->on("/info",handleRoute); // you can override wm!
}

void handleRoute()
{
  Serial.println("[HTTP] handle route");
  wm.server->send(200, "text/plain", "hello from user code");
}

void handlePreOtaUpdateCallback()
{
  Update.onProgress([](unsigned int progress, unsigned int total)
                    { Serial.printf("CUSTOM Progress: %u%%\r", (progress / (total / 100))); });
}

void setup()
{
  // WiFi.mode(WIFI_STA); // explicitly set mode, esp can default to STA+AP

  // put your setup code here, to run once:
  Serial.begin(115200);

  // Serial.setDebugOutput(true);

  Serial.println("\n Starting");

  wm.setDebugOutput(true);
  wm.debugPlatformInfo();

  // reset settings - for testing
  //  wm.resetSettings();
  //  wm.erase();

  // setup some parameters
  custom_html = new WiFiManagerParameter("<p style=\"color:pink;font-weight:Bold;\">This Is Custom HTML</p>"); // only custom html
  custom_mqtt_server = new WiFiManagerParameter("server", "mqtt server", "", 40);
  custom_mqtt_port = new WiFiManagerParameter("port", "mqtt port", "", 6);
  custom_token = new WiFiManagerParameter("api_token", "api token", "", 16);
  custom_tokenb = new WiFiManagerParameter("invalid token", "invalid token", "", 0);                                                  // id is invalid, cannot contain spaces
  custom_ipaddress = new WiFiManagerParameter("input_ip", "input IP", "", 15, "pattern='\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'"); // custom input attrs (ip mask)
  custom_input_type = new WiFiManagerParameter("input_pwd", "input pass", "", 15, "type='password'");                                 // custom input attrs (ip mask)

  const char _customHtml_checkbox[] = "type=\"checkbox\"";
  custom_checkbox = new WiFiManagerParameter("my_checkbox", "My Checkbox", "T", 2, _customHtml_checkbox, WFM_LABEL_AFTER);

  const char *bufferStr = R"(
  <!-- INPUT CHOICE -->
  <br/>
  <p>Select Choice</p>
  <input style='display: inline-block;' type='radio' id='choice1' name='program_selection' value='1'>
  <label for='choice1'>Choice1</label><br/>
  <input style='display: inline-block;' type='radio' id='choice2' name='program_selection' value='2'>
  <label for='choice2'>Choice2</label><br/>
  <!-- INPUT SELECT -->
  <br/>
  <label for='input_select'>Label for Input Select</label>
  <select name="input_select" id="input_select" class="button">
  <option value="0">Option 1</option>
  <option value="1" selected>Option 2</option>
  <option value="2">Option 3</option>
  <option value="3">Option 4</option>
  </select>
  )";

  custom_html_inputs = new WiFiManagerParameter(bufferStr);

  // callbacks
  wm.setAPCallback(configModeCallback);
  wm.setWebServerCallback(bindServerCallback);
  wm.setSaveConfigCallback(saveWifiCallback);
  wm.setSaveParamsCallback(saveParamCallback);
  wm.setPreOtaUpdateCallback(handlePreOtaUpdateCallback);

  // add all your parameters here
  wm.addParameter(custom_html);
  wm.addParameter(custom_mqtt_server);
  wm.addParameter(custom_mqtt_port);
  wm.addParameter(custom_token);
  wm.addParameter(custom_tokenb);
  wm.addParameter(custom_ipaddress);
  wm.addParameter(custom_checkbox);
  wm.addParameter(custom_input_type);
  wm.addParameter(custom_html_inputs);

  // set values later if you want
  custom_html->setValue("test", 4);
  custom_token->setValue("test", 4);

  // set custom html menu content , inside menu item "custom", see setMenu()
  const char *menuhtml = "<form action='/custom' method='get'><button>Custom</button></form><br/>\n";
  wm.setCustomMenuHTML(menuhtml);

  std::vector<const char *> menu = {"wifi", "wifinoscan", "info", "param", "custom", "close", "sep", "erase", "update", "restart", "exit"};
  wm.setMenu(menu); // custom menu, pass vector

  // wm.setParamsPage(true); // move params to seperate page, not wifi, do not combine with setmenu!

  // set Hostname
  wm.setHostname(("WM_" + wm.getDefaultAPName()).c_str());
  // wm.setHostname("WM_RANDO_1234");

  if (!WMISBLOCKING)
  {
    wm.setConfigPortalBlocking(false);
  }

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

  wm.setBreakAfterConfig(true); // needed to use saveWifiCallback

  wifiInfo();

  // to preload autoconnect with credentials
  // wm.preloadWiFi("ssid","password");

  if (!wm.autoConnect("WM_AutoConnectAP", "12345678"))
  {
    Serial.println("failed to connect and hit timeout");
  }
  else if (TEST_CP)
  {
    // start configportal always
    delay(1000);
    Serial.println("TEST_CP ENABLED");
    wm.setConfigPortalTimeout(TESP_CP_TIMEOUT);
    wm.startConfigPortal("WM_ConnectAP", "12345678");
  }
  else
  {
    // if you get here you have connected to the WiFi
    Serial.println("connected...yeey :)");
  }

  wifiInfo();
  pinMode(ONDDEMANDPIN, INPUT_PULLUP);

#ifdef USEOTA
  ArduinoOTA.begin();
#endif
}

void wifiInfo()
{
  // can contain gargbage on esp32 if wifi is not ready yet
  Serial.println("[WIFI] WIFI INFO DEBUG");
  // WiFi.printDiag(Serial);
  Serial.println("[WIFI] SAVED: " + (String)(wm.getWiFiIsSaved() ? "YES" : "NO"));
  Serial.println("[WIFI] SSID: " + (String)wm.getWiFiSSID());
  Serial.println("[WIFI] PASS: " + (String)wm.getWiFiPass());
  Serial.println("[WIFI] HOSTNAME: " + (String)WiFi.getHostname());
}

void loop()
{

  if (!WMISBLOCKING)
  {
    wm.process();
  }

#ifdef USEOTA
  ArduinoOTA.handle();
#endif
  // is configuration portal requested?
  if (ALLOWONDEMAND && digitalRead(ONDDEMANDPIN) == LOW)
  {
    delay(100);
    if (digitalRead(ONDDEMANDPIN) == LOW)
    {
      Serial.println("BUTTON PRESSED");

      wm.setConfigPortalTimeout(140);
      wm.setParamsPage(false); // move params to seperate page, not wifi, do not combine with setmenu!

      // disable captive portal redirection
      // wm.setCaptivePortalEnable(false);

      if (!wm.startConfigPortal("OnDemandAP", "12345678"))
      {
        Serial.println("failed to connect and hit timeout");
        delay(3000);
      }
    }
    else
    {
      // if you get here you have connected to the WiFi
      Serial.println("connected...yeey :)");
      getTime();
    }
  }

  // every 10 seconds
  if (millis() - mtime > 10000)
  {
    if (WiFi.status() == WL_CONNECTED)
    {
      getTime();
    }
    else
      Serial.println("No Wifi");
    mtime = millis();
  }
  // put your main code here, to run repeatedly:
  delay(100);
}

void getTime()
{
  time_t now = time(nullptr);
  unsigned timeout = 5000; // try for timeout
  unsigned start = millis();
  configTime("CET-1CEST,M3.5.0/02,M10.5.0/03", "pool.ntp.org", "time.nist.gov");
  Serial.print("Waiting for NTP time sync: ");
  while (now < 8 * 3600 * 2)
  { // what is this ?
    delay(100);
    Serial.print(".");
    now = time(nullptr);
    if ((millis() - start) > timeout)
    {
      Serial.println("\n[ERROR] Failed to get NTP time.");
      return;
    }
  }
  Serial.println("");
  struct tm timeinfo;
  gmtime_r(&now, &timeinfo);
  Serial.print("Current time: ");
  Serial.print(asctime(&timeinfo));
}

void debugchipid()
{
  WiFi.mode(WIFI_AP);
  WiFi.enableAP(true);
  delay(500);
  delay(1000);
  WiFi.printDiag(Serial);
  delay(60000);
  ESP.restart();
}
<!-- gh-comment-id:1368752001 --> @Bruce17 commented on GitHub (Jan 2, 2023): @MEHUL95 I had the same issue even with the example code [OnDemandConfigPortal.ino](https://github.com/tzapu/WiFiManager/blob/v2.0.15-rc.1/examples/Super/OnDemandConfigPortal/OnDemandConfigPortal.ino) I moved the `WiFiManagerParameter` into the global scope f.e.: ```cpp WiFiManagerParameter *custom_mqtt_server; WiFiManagerParameter *custom_mqtt_port; ``` ... and changed the code inside the setup to something like: ```cpp custom_mqtt_server = new WiFiManagerParameter("server", "mqtt server", "", 40); custom_mqtt_port = new WiFiManagerParameter("port", "mqtt port", "", 6); // ... wm.addParameter(custom_mqtt_server); wm.addParameter(custom_mqtt_port); ``` <details> <summary>Adjusted code example</summary> ```cpp /** * This is a kind of unit test for DEV for now * It contains many of the public methods * */ #include <WiFiManager.h> // https://github.com/tzapu/WiFiManager #include <time.h> #include <stdio.h> #define USEOTA // enable OTA #ifdef USEOTA #include <WiFiUdp.h> #include <ArduinoOTA.h> #endif unsigned long mtime = 0; WiFiManager wm; // TEST OPTION FLAGS bool TEST_CP = false; // always start the configportal, even if ap found int TESP_CP_TIMEOUT = 90; // test cp timeout bool TEST_NET = true; // do a network test after connect, (gets ntp time) bool ALLOWONDEMAND = true; // enable on demand int ONDDEMANDPIN = 0; // gpio for button bool WMISBLOCKING = true; // use blocking or non blocking mode, non global params wont work in non blocking // char ssid[] = "*************"; // your network SSID (name) // char pass[] = "********"; // your network password // Forward declaration: required to make C compiler happy ¯\_(ツ)_/¯ void getTime(); void wifiInfo(); void handleRoute(); // Define WifiManagerParameters here ourside to access them also for the on-demand config portal WiFiManagerParameter *custom_html; WiFiManagerParameter *custom_mqtt_server; WiFiManagerParameter *custom_mqtt_port; WiFiManagerParameter *custom_token; WiFiManagerParameter *custom_tokenb; WiFiManagerParameter *custom_ipaddress; WiFiManagerParameter *custom_input_type; WiFiManagerParameter *custom_checkbox; WiFiManagerParameter *custom_html_inputs; void saveWifiCallback() { Serial.println("[CALLBACK] saveCallback fired"); } // gets called when WiFiManager enters configuration mode void configModeCallback(WiFiManager *myWiFiManager) { Serial.println("[CALLBACK] configModeCallback fired"); } void saveParamCallback() { Serial.println("[CALLBACK] saveParamCallback fired"); // wm.stopConfigPortal(); } void bindServerCallback() { wm.server->on("/custom", handleRoute); // this is now crashing esp32 for some reason // wm.server->on("/info",handleRoute); // you can override wm! } void handleRoute() { Serial.println("[HTTP] handle route"); wm.server->send(200, "text/plain", "hello from user code"); } void handlePreOtaUpdateCallback() { Update.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("CUSTOM Progress: %u%%\r", (progress / (total / 100))); }); } void setup() { // WiFi.mode(WIFI_STA); // explicitly set mode, esp can default to STA+AP // put your setup code here, to run once: Serial.begin(115200); // Serial.setDebugOutput(true); Serial.println("\n Starting"); wm.setDebugOutput(true); wm.debugPlatformInfo(); // reset settings - for testing // wm.resetSettings(); // wm.erase(); // setup some parameters custom_html = new WiFiManagerParameter("<p style=\"color:pink;font-weight:Bold;\">This Is Custom HTML</p>"); // only custom html custom_mqtt_server = new WiFiManagerParameter("server", "mqtt server", "", 40); custom_mqtt_port = new WiFiManagerParameter("port", "mqtt port", "", 6); custom_token = new WiFiManagerParameter("api_token", "api token", "", 16); custom_tokenb = new WiFiManagerParameter("invalid token", "invalid token", "", 0); // id is invalid, cannot contain spaces custom_ipaddress = new WiFiManagerParameter("input_ip", "input IP", "", 15, "pattern='\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'"); // custom input attrs (ip mask) custom_input_type = new WiFiManagerParameter("input_pwd", "input pass", "", 15, "type='password'"); // custom input attrs (ip mask) const char _customHtml_checkbox[] = "type=\"checkbox\""; custom_checkbox = new WiFiManagerParameter("my_checkbox", "My Checkbox", "T", 2, _customHtml_checkbox, WFM_LABEL_AFTER); const char *bufferStr = R"( <!-- INPUT CHOICE --> <br/> <p>Select Choice</p> <input style='display: inline-block;' type='radio' id='choice1' name='program_selection' value='1'> <label for='choice1'>Choice1</label><br/> <input style='display: inline-block;' type='radio' id='choice2' name='program_selection' value='2'> <label for='choice2'>Choice2</label><br/> <!-- INPUT SELECT --> <br/> <label for='input_select'>Label for Input Select</label> <select name="input_select" id="input_select" class="button"> <option value="0">Option 1</option> <option value="1" selected>Option 2</option> <option value="2">Option 3</option> <option value="3">Option 4</option> </select> )"; custom_html_inputs = new WiFiManagerParameter(bufferStr); // callbacks wm.setAPCallback(configModeCallback); wm.setWebServerCallback(bindServerCallback); wm.setSaveConfigCallback(saveWifiCallback); wm.setSaveParamsCallback(saveParamCallback); wm.setPreOtaUpdateCallback(handlePreOtaUpdateCallback); // add all your parameters here wm.addParameter(custom_html); wm.addParameter(custom_mqtt_server); wm.addParameter(custom_mqtt_port); wm.addParameter(custom_token); wm.addParameter(custom_tokenb); wm.addParameter(custom_ipaddress); wm.addParameter(custom_checkbox); wm.addParameter(custom_input_type); wm.addParameter(custom_html_inputs); // set values later if you want custom_html->setValue("test", 4); custom_token->setValue("test", 4); // set custom html menu content , inside menu item "custom", see setMenu() const char *menuhtml = "<form action='/custom' method='get'><button>Custom</button></form><br/>\n"; wm.setCustomMenuHTML(menuhtml); std::vector<const char *> menu = {"wifi", "wifinoscan", "info", "param", "custom", "close", "sep", "erase", "update", "restart", "exit"}; wm.setMenu(menu); // custom menu, pass vector // wm.setParamsPage(true); // move params to seperate page, not wifi, do not combine with setmenu! // set Hostname wm.setHostname(("WM_" + wm.getDefaultAPName()).c_str()); // wm.setHostname("WM_RANDO_1234"); if (!WMISBLOCKING) { wm.setConfigPortalBlocking(false); } // sets timeout until configuration portal gets turned off // useful to make it all retry or go to sleep in seconds wm.setConfigPortalTimeout(120); wm.setBreakAfterConfig(true); // needed to use saveWifiCallback wifiInfo(); // to preload autoconnect with credentials // wm.preloadWiFi("ssid","password"); if (!wm.autoConnect("WM_AutoConnectAP", "12345678")) { Serial.println("failed to connect and hit timeout"); } else if (TEST_CP) { // start configportal always delay(1000); Serial.println("TEST_CP ENABLED"); wm.setConfigPortalTimeout(TESP_CP_TIMEOUT); wm.startConfigPortal("WM_ConnectAP", "12345678"); } else { // if you get here you have connected to the WiFi Serial.println("connected...yeey :)"); } wifiInfo(); pinMode(ONDDEMANDPIN, INPUT_PULLUP); #ifdef USEOTA ArduinoOTA.begin(); #endif } void wifiInfo() { // can contain gargbage on esp32 if wifi is not ready yet Serial.println("[WIFI] WIFI INFO DEBUG"); // WiFi.printDiag(Serial); Serial.println("[WIFI] SAVED: " + (String)(wm.getWiFiIsSaved() ? "YES" : "NO")); Serial.println("[WIFI] SSID: " + (String)wm.getWiFiSSID()); Serial.println("[WIFI] PASS: " + (String)wm.getWiFiPass()); Serial.println("[WIFI] HOSTNAME: " + (String)WiFi.getHostname()); } void loop() { if (!WMISBLOCKING) { wm.process(); } #ifdef USEOTA ArduinoOTA.handle(); #endif // is configuration portal requested? if (ALLOWONDEMAND && digitalRead(ONDDEMANDPIN) == LOW) { delay(100); if (digitalRead(ONDDEMANDPIN) == LOW) { Serial.println("BUTTON PRESSED"); wm.setConfigPortalTimeout(140); wm.setParamsPage(false); // move params to seperate page, not wifi, do not combine with setmenu! // disable captive portal redirection // wm.setCaptivePortalEnable(false); if (!wm.startConfigPortal("OnDemandAP", "12345678")) { Serial.println("failed to connect and hit timeout"); delay(3000); } } else { // if you get here you have connected to the WiFi Serial.println("connected...yeey :)"); getTime(); } } // every 10 seconds if (millis() - mtime > 10000) { if (WiFi.status() == WL_CONNECTED) { getTime(); } else Serial.println("No Wifi"); mtime = millis(); } // put your main code here, to run repeatedly: delay(100); } void getTime() { time_t now = time(nullptr); unsigned timeout = 5000; // try for timeout unsigned start = millis(); configTime("CET-1CEST,M3.5.0/02,M10.5.0/03", "pool.ntp.org", "time.nist.gov"); Serial.print("Waiting for NTP time sync: "); while (now < 8 * 3600 * 2) { // what is this ? delay(100); Serial.print("."); now = time(nullptr); if ((millis() - start) > timeout) { Serial.println("\n[ERROR] Failed to get NTP time."); return; } } Serial.println(""); struct tm timeinfo; gmtime_r(&now, &timeinfo); Serial.print("Current time: "); Serial.print(asctime(&timeinfo)); } void debugchipid() { WiFi.mode(WIFI_AP); WiFi.enableAP(true); delay(500); delay(1000); WiFi.printDiag(Serial); delay(60000); ESP.restart(); } ``` </details>
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#1309
No description provided.