[GH-ISSUE #724] WifiManager not working with code having EEPROM and PubSubClient library added #604

Open
opened 2026-02-28 01:26:11 +03:00 by kerem · 8 comments
Owner

Originally created by @amguamgu on GitHub (Sep 11, 2018).
Original GitHub issue: https://github.com/tzapu/WiFiManager/issues/724

Basic Infos

I am using basic sketch to on/off the relay. I have used EERPROM.h to save the last state of relay and also PubSubClient.h library to drive the circuit using MQTT.

I have addded WifManager library to manage the credentials of wifi only.
But code is not working.. some issue is there no debug is also coming...

Hardware

ESP-01, relay module

WiFimanager Branch/Release:

  • Master

Esp8266/Esp32:

  • ESP8266

Hardware: ESP-12e, esp01, esp25

  • ESP01

ESP Core Version: 2.4.0, staging

  • 2.4.0

Description

Basically i am trying to use your library to manage wifi credentials. My device is working on MQTT protocol and also saving device state using EEPROM library

Please help as WifiManager is not working

Settings in IDE

Module: NodeMcu, Wemos D1

EERPROM.h, PubSubClient.h

Sketch



/*
    Created and managed by Amit Gupta
    Will use ESP8266-01 as the wifi module
    MQTT has been used as communication protocol
    Plug and Play device code 
    WiFiManage has also been used to configure connectivity to wifi

*/ 


#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ESP8266Ping.h>

#include <DNSServer.h>            //Local DNS Server used for redirecting all requests to the configuration    
#include <ESP8266WebServer.h>     //Local WebServer used to serve the configuration portal
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager WiFi Configuration Magic


// write these with values suitable for your network.

#define GPIO0 0
#define GPIO2 2


int gpio0_add = 0;
int gpio2_add = 1;

const char* mqtt_server = "XXXXXXXXXX"; 
const char* mqtt_username = "XXXXXXX";
const char* mqtt_password = "XXXXXXXX";


IPAddress ip(10, 0, 4, 17); // where xx is the desired IP Address
IPAddress gateway(10, 0, 4, 1); // set gateway to match your network
//Serial.print(F("Setting static ip to : "));
//Serial.println(ip);
IPAddress subnet(255, 255, 255, 0); // set subnet mask to match your

IPAddress dns1(4, 2, 2, 2); // set subnet mask to match your
IPAddress dns2(8, 8, 8, 8); // set subnet mask to match your

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;


// Will be called only for first time ...
void resetEEPROM(){
      EEPROM.write(gpio0_add, LOW);
      EEPROM.write(gpio2_add, LOW);     
}



//Method will called some message is recived in the topic to take any action
void callback(char* topic, byte* payload, unsigned int length) {
 
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  char tt[10];
  strcpy(tt,topic);
  
 Serial.println(tt);
 if(!strcmp(tt,"PP_ON_OFF")){
  
       // Switch on the LED if an 1 was received as first characte
       Serial.println("1");
        if ((char)payload[0] == '1') {
          EEPROM.write(gpio2_add,LOW);
          digitalWrite(GPIO2, LOW);   // Turn the LED on (Note that LOW is the voltage level
          // but actually the LED is on; this is because
          // it is acive low on the ESP-01) 
        } else {
           EEPROM.write(gpio2_add,HIGH);
          digitalWrite(GPIO2, HIGH);  // Turn the LED off by making the voltage HIGH
        }
        EEPROM.commit();
        
}else{
   Serial.println("Un- Known");
}
       
}


// Method will be called when MQTT protocal need to do connection/re-connection to MQTT Broker
void reconnect() {
  digitalWrite(GPIO0, HIGH); 
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(), mqtt_username, mqtt_password)) {
      Serial.println("connected");
     
      // Once connected, publish an announcement...
      //--------------  client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("PP_ON_OFF");

      digitalWrite(GPIO0, LOW); 
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      
      delay(5000);
    }
  }
}

// Mehotd called when ESP8266 is in config mode
void configModeCallback (WiFiManager *myWiFiManager) {
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());

  Serial.println(myWiFiManager->getConfigPortalSSID());
}

//============== SETUP METHOD ===============================

void setup() {
   EEPROM.begin(512);
   
   WiFiManager wifiManager;
   
    wifiManager.setMinimumSignalQuality(10);
    wifiManager.setRemoveDuplicateAPs(false);
    wifiManager.setAPCallback(configModeCallback);

if (!wifiManager.autoConnect("WIFI_DEVICE", "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);
}
  
  // resetEEPROM();
   
  pinMode(GPIO0, OUTPUT); // Initialize the BUILTIN_LED pin as an output
  pinMode(GPIO2, OUTPUT); 
  
  digitalWrite(GPIO2, EEPROM.read(gpio2_add)); 
  Serial.begin(115200);

  //setup_wifi();
    
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  
}

//========= SETUP METHOD END =============================



//=========== LOOP METHOD=============================
// Main loop method ESP8266-01
void loop() {

  if (!client.connected()) {
    reconnect();
    //digitalWrite(ISCONNECTED, HIGH); 
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 3000) {
    lastMsg = now;
    

 int  gpio0_status = digitalRead(GPIO0);
 int  gpio2_status = digitalRead(GPIO2);



   Serial.println("--currst---");


String currst = "";
  currst.concat(gpio0_status);
  currst.concat(gpio2_status);

   
   char const* finalstatus = currst.c_str();
     client.publish("PP_ON_OFF_STATUS", finalstatus);
    return;
  }
}
//===== LOOP METHOD END================

Debug Messages

No debug messages are coming on serial montor

Originally created by @amguamgu on GitHub (Sep 11, 2018). Original GitHub issue: https://github.com/tzapu/WiFiManager/issues/724 ### Basic Infos I am using basic sketch to on/off the relay. I have used EERPROM.h to save the last state of relay and also PubSubClient.h library to drive the circuit using MQTT. I have addded WifManager library to manage the credentials of wifi only. But code is not working.. some issue is there no debug is also coming... #### Hardware ESP-01, relay module **WiFimanager Branch/Release:** - [x] Master **Esp8266/Esp32:** - [x] ESP8266 **Hardware: ESP-12e, esp01, esp25** - [x] ESP01 **ESP Core Version: 2.4.0, staging** - [x] 2.4.0 ### Description Basically i am trying to use your library to manage wifi credentials. My device is working on MQTT protocol and also saving device state using EEPROM library Please help as WifiManager is not working ### Settings in IDE Module: NodeMcu, Wemos D1 EERPROM.h, PubSubClient.h ### Sketch ```cpp /* Created and managed by Amit Gupta Will use ESP8266-01 as the wifi module MQTT has been used as communication protocol Plug and Play device code WiFiManage has also been used to configure connectivity to wifi */ #include <EEPROM.h> #include <ESP8266WiFi.h> #include <PubSubClient.h> #include <ESP8266Ping.h> #include <DNSServer.h> //Local DNS Server used for redirecting all requests to the configuration #include <ESP8266WebServer.h> //Local WebServer used to serve the configuration portal #include <WiFiManager.h> //https://github.com/tzapu/WiFiManager WiFi Configuration Magic // write these with values suitable for your network. #define GPIO0 0 #define GPIO2 2 int gpio0_add = 0; int gpio2_add = 1; const char* mqtt_server = "XXXXXXXXXX"; const char* mqtt_username = "XXXXXXX"; const char* mqtt_password = "XXXXXXXX"; IPAddress ip(10, 0, 4, 17); // where xx is the desired IP Address IPAddress gateway(10, 0, 4, 1); // set gateway to match your network //Serial.print(F("Setting static ip to : ")); //Serial.println(ip); IPAddress subnet(255, 255, 255, 0); // set subnet mask to match your IPAddress dns1(4, 2, 2, 2); // set subnet mask to match your IPAddress dns2(8, 8, 8, 8); // set subnet mask to match your WiFiClient espClient; PubSubClient client(espClient); long lastMsg = 0; char msg[50]; int value = 0; // Will be called only for first time ... void resetEEPROM(){ EEPROM.write(gpio0_add, LOW); EEPROM.write(gpio2_add, LOW); } //Method will called some message is recived in the topic to take any action void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); char tt[10]; strcpy(tt,topic); Serial.println(tt); if(!strcmp(tt,"PP_ON_OFF")){ // Switch on the LED if an 1 was received as first characte Serial.println("1"); if ((char)payload[0] == '1') { EEPROM.write(gpio2_add,LOW); digitalWrite(GPIO2, LOW); // Turn the LED on (Note that LOW is the voltage level // but actually the LED is on; this is because // it is acive low on the ESP-01) } else { EEPROM.write(gpio2_add,HIGH); digitalWrite(GPIO2, HIGH); // Turn the LED off by making the voltage HIGH } EEPROM.commit(); }else{ Serial.println("Un- Known"); } } // Method will be called when MQTT protocal need to do connection/re-connection to MQTT Broker void reconnect() { digitalWrite(GPIO0, HIGH); // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Create a random client ID String clientId = "ESP8266Client-"; clientId += String(random(0xffff), HEX); // Attempt to connect if (client.connect(clientId.c_str(), mqtt_username, mqtt_password)) { Serial.println("connected"); // Once connected, publish an announcement... //-------------- client.publish("outTopic", "hello world"); // ... and resubscribe client.subscribe("PP_ON_OFF"); digitalWrite(GPIO0, LOW); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } // Mehotd called when ESP8266 is in config mode void configModeCallback (WiFiManager *myWiFiManager) { Serial.println("Entered config mode"); Serial.println(WiFi.softAPIP()); Serial.println(myWiFiManager->getConfigPortalSSID()); } //============== SETUP METHOD =============================== void setup() { EEPROM.begin(512); WiFiManager wifiManager; wifiManager.setMinimumSignalQuality(10); wifiManager.setRemoveDuplicateAPs(false); wifiManager.setAPCallback(configModeCallback); if (!wifiManager.autoConnect("WIFI_DEVICE", "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); } // resetEEPROM(); pinMode(GPIO0, OUTPUT); // Initialize the BUILTIN_LED pin as an output pinMode(GPIO2, OUTPUT); digitalWrite(GPIO2, EEPROM.read(gpio2_add)); Serial.begin(115200); //setup_wifi(); client.setServer(mqtt_server, 1883); client.setCallback(callback); } //========= SETUP METHOD END ============================= //=========== LOOP METHOD============================= // Main loop method ESP8266-01 void loop() { if (!client.connected()) { reconnect(); //digitalWrite(ISCONNECTED, HIGH); } client.loop(); long now = millis(); if (now - lastMsg > 3000) { lastMsg = now; int gpio0_status = digitalRead(GPIO0); int gpio2_status = digitalRead(GPIO2); Serial.println("--currst---"); String currst = ""; currst.concat(gpio0_status); currst.concat(gpio2_status); char const* finalstatus = currst.c_str(); client.publish("PP_ON_OFF_STATUS", finalstatus); return; } } //===== LOOP METHOD END================ ``` ### Debug Messages No debug messages are coming on serial montor
Author
Owner

@tablatronix commented on GitHub (Sep 11, 2018):

your sketch does not have a serial begin

<!-- gh-comment-id:420256803 --> @tablatronix commented on GitHub (Sep 11, 2018): your sketch does not have a serial begin
Author
Owner

@amguamgu commented on GitHub (Sep 12, 2018):

Serial.begin(115200); is present in setup method, please check

<!-- gh-comment-id:420526285 --> @amguamgu commented on GitHub (Sep 12, 2018): Serial.begin(115200); is present in setup method, please check
Author
Owner

@tablatronix commented on GitHub (Sep 12, 2018):

you need to put it earlier

post any output when you get some

<!-- gh-comment-id:420679955 --> @tablatronix commented on GitHub (Sep 12, 2018): you need to put it earlier post any output when you get some
Author
Owner

@tablatronix commented on GitHub (Oct 12, 2018):

can this be closed?

<!-- gh-comment-id:429462389 --> @tablatronix commented on GitHub (Oct 12, 2018): can this be closed?
Author
Owner

@PProvost commented on GitHub (Jan 23, 2019):

I know there are a lot of open issues on this topic, but after doing some digging I think I've found a workaround (and possibly some guidance to the library owners on what the issue is).

I saw a number of posts where people said the mode was wrong, but force setting STA mode didn't help for me (either before or after the call to autoConnect()).

I started sprinkling serial debugging into a few libraries and finally discovered that within PubSubClient.cpp, when given a hostname, it uses WiFiClient::connect() to open the port. Unless it is given an IPAddress struct, it will do WiFi.connect(const char*, uint16_t) which called WiFi.hostByName(...).

For some reason this DNS lookup is failing when called from PubSubClient. (You can confirm by putting a Serial.println(...) inside of WiFiClient::connect(), before the second return statement.)

But here's the funny part... if I call WiFi.hostByName() in my own code, after autoConnect() finished, IT WILL WORK!

So the gist of my solution is this:

After you call WiFiManager::autoConnect() and before you call PubSubClient::connect(), convert the hostname (string) into an IPAddress struct and pass that into connect().

This is the block of code I added just before calling PubSubClient::connect().

    IPAddress ipAddr;
    if (WiFi.hostByName(get_mqttServer().c_str(), ipAddr) != 1)
        Serial.println("ERROR: Unable to resolve host name!");
    else
        Serial.printf("INFO: Host name resolved successfuly - %s\n", ipAddr.toString().c_str());

    // snipped

    mqtt_client.setServer(ipAddr, 1883);

Hopefully this will help people work around this issues, and maybe help the library devs figure out what is going on.

Thanks for the great work!

<!-- gh-comment-id:456617855 --> @PProvost commented on GitHub (Jan 23, 2019): I know there are a lot of open issues on this topic, but after doing some digging I think I've found a workaround (and possibly some guidance to the library owners on what the issue is). I saw a number of posts where people said the mode was wrong, but force setting STA mode didn't help for me (either before or after the call to `autoConnect()`). I started sprinkling serial debugging into a few libraries and finally discovered that within PubSubClient.cpp, when given a hostname, it uses `WiFiClient::connect()` to open the port. Unless it is given an `IPAddress` struct, it will do `WiFi.connect(const char*, uint16_t)` which called `WiFi.hostByName(...)`. For some reason this DNS lookup is failing when called from PubSubClient. (You can confirm by putting a `Serial.println(...)` inside of `WiFiClient::connect()`, before the second return statement.) But here's the funny part... if I call `WiFi.hostByName()` in my own code, after `autoConnect()` finished, IT WILL WORK! So the gist of my solution is this: After you call `WiFiManager::autoConnect()` and before you call `PubSubClient::connect()`, convert the hostname (string) into an `IPAddress` struct and pass that into connect(). This is the block of code I added just before calling `PubSubClient::connect()`. ```cpp IPAddress ipAddr; if (WiFi.hostByName(get_mqttServer().c_str(), ipAddr) != 1) Serial.println("ERROR: Unable to resolve host name!"); else Serial.printf("INFO: Host name resolved successfuly - %s\n", ipAddr.toString().c_str()); // snipped mqtt_client.setServer(ipAddr, 1883); ``` Hopefully this will help people work around this issues, and maybe help the library devs figure out what is going on. Thanks for the great work!
Author
Owner

@tablatronix commented on GitHub (Jan 23, 2019):

I hate libraries that implement their own connection handling

<!-- gh-comment-id:456637406 --> @tablatronix commented on GitHub (Jan 23, 2019): I hate libraries that implement their own connection handling
Author
Owner

@tablatronix commented on GitHub (Jan 23, 2019):

This is strange , have you tried giving dns a delay to start? Before pubsub connect, delay 2 seconds? I am wondering why hostname resolution would be failing, there are some other issues that have been reported similarly very odd

<!-- gh-comment-id:456657837 --> @tablatronix commented on GitHub (Jan 23, 2019): This is strange , have you tried giving dns a delay to start? Before pubsub connect, delay 2 seconds? I am wondering why hostname resolution would be failing, there are some other issues that have been reported similarly very odd
Author
Owner

@0x2f0713 commented on GitHub (Apr 26, 2020):

    IPAddress ipAddr;
    if (WiFi.hostByName(get_mqttServer().c_str(), ipAddr) != 1)
        Serial.println("ERROR: Unable to resolve host name!");
    else
        Serial.printf("INFO: Host name resolved successfuly - %s\n", ipAddr.toString().c_str());

    // snipped

    mqtt_client.setServer(ipAddr, 1883);

Many thanks, this code worked for me!

<!-- gh-comment-id:619571960 --> @0x2f0713 commented on GitHub (Apr 26, 2020): > ```c++ > IPAddress ipAddr; > if (WiFi.hostByName(get_mqttServer().c_str(), ipAddr) != 1) > Serial.println("ERROR: Unable to resolve host name!"); > else > Serial.printf("INFO: Host name resolved successfuly - %s\n", ipAddr.toString().c_str()); > > // snipped > > mqtt_client.setServer(ipAddr, 1883); > ``` Many thanks, this code worked for me!
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#604
No description provided.