custom field - esp WifiManager lib

Hi everyone. I'm using the ESP_WifiManager library to connect ESP32 to Wifi, but I wanted it to save another value besides the SSID and password.

For example, a "user" field in which I type the name and that name is saved as the SSID and password.

I managed to add this new field in the library's HTML, but I don't know how to save what was typed there.

Can someone help me? I searched a lot but didn't find it.

SSID and PWD are saved in the chip ( wifi_ap_record_t (see the function esp_wifi_sta_get_ap_info) and it's specific to only the Wireless connexion attributes so You have to handle storage separately (in SPIFFS, LittleFS, ...)

Thanks!

I found the ESP_WiFiManager library documentation (GitHub - khoih-prog/ESP_WiFiManager: This is an ESP32 / ESP8266 WiFi Connection Manager with fallback web configuration portal. Use this library for configuring ESP32, ESP8266 modules' WiFi, etc. Credentials at runtime. You can also specify static DNS servers, personalized HostName, fixed or random AP WiFi channel. With examples supporting ArduinoJson 6.0.0+ as well as 5.13.5- .) and there explains more or less how to do it. I managed to make a field to add the place:

    ESP_WiFiManager ESP_wifiManager("ConfigOnSwitchFS");
    ESP_wifiManager.setMinimumSignalQuality(-1);
    ESP_WMParameter custom_place("Place", "Place", placeWifi, 60);
    ESP_wifiManager.addParameter(&custom_place);

But I cannot record this information. I don’t know where I might be going wrong. Follow the code for anyone who can help or assist me in something, I really don’t know what it is:

#include <ArduinoJson.h>
#include <SPIFFS.h>
#include <ESP_WiFiManager.h>
#define ESP_getChipId()   ((uint32_t)ESP.getEfuseMac())


String ssid = "ESP_" + String(ESP_getChipId(), HEX);
const char* password = "your_password";
// SSID and PW for your Router
String Router_SSID;
String Router_Pass;
// Indicates whether ESP has WiFi credentials saved from previous session
bool initialConfig = false;
// Use true for dynamic DHCP IP, false to use static IP and  you have to change the IP accordingly to your network
#define USE_DHCP_IP     true
// Use DHCP
IPAddress stationIP   = IPAddress(0, 0, 0, 0);
IPAddress gatewayIP   = IPAddress(192, 168, 2, 1);
IPAddress netMask     = IPAddress(255, 255, 255, 0);
IPAddress dns1IP      = gatewayIP;
IPAddress dns2IP      = IPAddress(8, 8, 8, 8);

bool firstConnection = false;
bool shouldSaveConfig = false;
char placeWifi[60];



void setup() {
  Serial.begin(115200);
  connectWifi();
  if (SPIFFS.begin()) {
    Serial.println("mounted file system");
    if (SPIFFS.exists("/config.json")) {
      readConfigFile();
    }
  } else {
    Serial.println("failed to mount");
  }



}

void loop() {

  if (firstConnection)
  {
    check_status();
  }

  Serial.println("PLACE");
  Serial.println(placeWifi);


}





void heartBeatPrint(void)
{
  static int num = 1;

  if (WiFi.status() == WL_CONNECTED)
    Serial.print("H");        // H means connected to WiFi
  else
    Serial.print("F");        // F means not connected to WiFi

  if (num == 80)
  {
    Serial.println();
    num = 1;
  }
  else if (num++ % 10 == 0)
  {
    Serial.print(" ");
  }
}


/*FUNÇÃO QUE CONECTA O ESP32 A REDE WIFI*/
void check_status() {
  // is configuration portal requested?
  if (firstConnection)
  {
    Serial.println("\nConfiguration portal requested.");
    ESP_WiFiManager ESP_wifiManager("ConfigOnSwitchFS");
    ESP_wifiManager.setMinimumSignalQuality(-1);
    ESP_WMParameter custom_place("Place", "Place", placeWifi, 60);
    ESP_wifiManager.addParameter(&custom_place);
    ESP_wifiManager.setSaveConfigCallback(saveConfigCallback);
    if (shouldSaveConfig)
    {
      writeConfigFile();
    }
    ESP_wifiManager.setSTAStaticIPConfig(stationIP, gatewayIP, netMask, dns1IP, dns2IP);
    Serial.print("Opening configuration portal. ");
    Router_SSID = ESP_wifiManager.WiFi_SSID();
    if (Router_SSID != "")
    {
      ESP_wifiManager.setConfigPortalTimeout(120);
      Serial.println("Got stored Credentials. Timeout 120s");
    }
    else
      Serial.println("No stored Credentials. No timeout");
    if (!ESP_wifiManager.startConfigPortal((const char *) ssid.c_str(), password))
    {
      Serial.println("Not connected to WiFi but continuing anyway.");
    }
    else
    {
      Serial.println("connected...yeey :)");
      Serial.print("Local IP: ");
      Serial.println(WiFi.localIP());
    }
  }

  static ulong checkstatus_timeout = 0;
#define HEARTBEAT_INTERVAL    10000L
  // Print hearbeat every HEARTBEAT_INTERVAL (10) seconds.
  if ((millis() > checkstatus_timeout) || (checkstatus_timeout == 0))
  {
    heartBeatPrint();
    checkstatus_timeout = millis() + HEARTBEAT_INTERVAL;
  }
}

void connectWifi() 
{
  Serial.println("\nStarting ConfigOnSwitch on " + String(ARDUINO_BOARD));

  unsigned long startedAt = millis();

  ESP_WiFiManager ESP_wifiManager("ConfigOnSwitch");

  ESP_wifiManager.setDebugOutput(true);

  ESP_wifiManager.setMinimumSignalQuality(-1);

  Router_SSID = ESP_wifiManager.WiFi_SSID();
  Router_Pass = ESP_wifiManager.WiFi_Pass();

  Serial.println("Stored: SSID = " + Router_SSID + ", Pass = " + Router_Pass);

  ssid.toUpperCase();

  if (Router_SSID == "")
  {
    Serial.println("Open Config Portal without Timeout: No stored Credentials.");
    if (!ESP_wifiManager.startConfigPortal((const char *) ssid.c_str(), password))
      Serial.println("Not connected to WiFi but continuing anyway.");
    else
      Serial.println("WiFi connected...yeey :)");
  }

#define WIFI_CONNECT_TIMEOUT        2000L
#define WHILE_LOOP_DELAY            200L
#define WHILE_LOOP_STEPS            (WIFI_CONNECT_TIMEOUT / ( 3 * WHILE_LOOP_DELAY ))

  startedAt = millis();

  while ( (WiFi.status() != WL_CONNECTED) && (millis() - startedAt < WIFI_CONNECT_TIMEOUT ) )
  {
    WiFi.mode(WIFI_STA);
    WiFi.persistent (true);

    // We start by connecting to a WiFi network

    Serial.print("Connecting to ");
    Serial.println(Router_SSID);

    WiFi.config(stationIP, gatewayIP, netMask);
    //WiFi.config(stationIP, gatewayIP, netMask, dns1IP, dns2IP);

    WiFi.begin(Router_SSID.c_str(), Router_Pass.c_str());

    int i = 0;
    while ((!WiFi.status() || WiFi.status() >= WL_DISCONNECTED) && i++ < WHILE_LOOP_STEPS)
    {
      delay(WHILE_LOOP_DELAY);
    }
  }

  Serial.print("After waiting ");
  Serial.print((millis() - startedAt) / 1000);
  Serial.print(" secs more in setup(), connection result is ");

  if (WiFi.status() == WL_CONNECTED)
  {
    //    conectado = 1;
    Serial.print("connected. Local IP: ");
    Serial.println(WiFi.localIP());

  }
}

void streamTimeoutCallback(bool timeout)
{
  if (timeout) {
    Serial.println("Stream timeout, resume streaming...");
  }
}

bool writeConfigFile()
{
  Serial.println("Saving...");

  DynamicJsonDocument json(1024);

  json["Place"] = placeWifi;

  File f = SPIFFS.open("/placeWifi.json", "w");

  if (!f)
  {
    return false;
  }

  serializeJsonPretty(json, Serial);

  serializeJson(json, f);

  f.close();

  Serial.println("Sucess");
  return true;
}

void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;
}

bool readConfigFile()
{
  File f = SPIFFS.open("/placeWifi.json", "r");

  if (!f)
  {
    Serial.println("Configuration file not found");
    return false;
  }
  else
  {

    size_t size = f.size();
    std::unique_ptr<char[]> buf(new char[size + 1]);

    f.readBytes(buf.get(), size);

    f.close();

    DynamicJsonDocument json(1024);
    auto deserializeError = deserializeJson(json, buf.get());
    if ( deserializeError )
    {
      Serial.println("JSON parseObject() failed");
      return false;
    }
    serializeJson(json, Serial);

    if (json.containsKey("Place"))
    {
      strcpy(placeWifi, json["Place"]);
    }

  }
  Serial.println("\nConfig file was successfully parsed");
  return true;
}

Thanks again.

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