ESP12-F not sending MQTT data after reboot

Hi! Everyone,
Greetings!
I would appreciate it if anyone could help me solve this below issue,

I'm using an ESP12-F board to post some messages (sensor data) to an MQTT server. These are the steps I want to achieve.

  1. At the very first boot the ESP12-F broadcast an Access Point (Web server - 192.168.4.1).

  2. I can put my WiFi credentials and my MQTT server details (MQTT topic, MQTT user, MQTT password) into that webserver.

  3. Then the ESP12-F keeps this information in its permanent memory.

  4. The ESP12-F uses the MQTT info to connect to the MQTT server.

  5. After a successful MQTT connection, the ESP12-F board sends some sensor data to the MQTT server. (I receive the sensor data to my MQTT server successfully)

  6. Then the ESP12-F goes to deep-sleep mode.

  7. When the ESP12-F gets back online it automatically connects to my WiFi and MQTT server (as the credential is already saved in its permanent memory).

  8. Then the ESP board connects to the MQTT server and tries to post the sensor data again but this time the ESP board failed to send the sensor message to the MQTT server. (I need help only in this part)

Here is the code I'm using,

#include <LittleFS.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
#include <ESP8266WiFi.h>
#include <PubSubClient.h> //https://github.com/knolleary/pubsubclient
#include "SparkFun_SHTC3.h"
#include <Wire.h>
#include "DFRobot_VEML7700.h"

DFRobot_VEML7700 als;
SHTC3 mySHTC3;

#define GPIO12 12
#define GPIO13 13

#define ledFlashDelay 200

char mqtt_server[40];
const int mqtt_port = 1883;
char mqtt_user[10];
char mqtt_password[10];
char mqtt_topic[40];
char mqtt_location[40];

WiFiClient espClient;
PubSubClient client(espClient);

WiFiManager wm;

WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
WiFiManagerParameter custom_mqtt_user("user", "mqtt user", mqtt_user, 10);
WiFiManagerParameter custom_mqtt_password("password", "mqtt password", mqtt_password, 10);
WiFiManagerParameter custom_mqtt_topic("topic", "mqtt topic", mqtt_topic, 40);
WiFiManagerParameter custom_mqtt_location("location", "mqtt location", mqtt_location, 40);


bool shouldSaveConfig = false; //Save data flag

float temperature; //temperature
float humidity;    //humidity
float lux;         //lux

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

void setupLittleFS()
{
  delay(1000);
  Serial.println("Mounting FS ...");

  if (LittleFS.begin())
  {
    Serial.println("FS Mounted!");
    if (LittleFS.exists("/config.json"))
    {
      Serial.println("Reading config file ...");
      File configFile = LittleFS.open("/config.json", "r");
      if (configFile)
      {
        Serial.println("Config file opened.");
        size_t size = configFile.size();

        std::unique_ptr<char[]> buf(new char[size]); //Buffer allocation

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

        DynamicJsonBuffer jsonBuffer;
        JsonObject& json = jsonBuffer.parseObject(buf.get());
        json.printTo(Serial);
        if (json.success())
        {
          Serial.println("Parsed JSON!");
          strcpy(mqtt_server, json["mqtt_server"]);
          strcpy(mqtt_user, json["mqtt_user"]);
          strcpy(mqtt_password, json["mqtt_password"]);
          strcpy(mqtt_topic, json["mqtt_topic"]);
          strcpy(mqtt_location, json["mqtt_location"]);
        }
        else
        {
          Serial.println("Failed to load json config file!");
          return;
        }
      }
    }
  }
  else
  {
    Serial.println("FS mounting failed");
  }
}

void reconnect()
{
  client.setServer(custom_mqtt_server.getValue(), mqtt_port);

  if (!client.connected())
  {
    Serial.println("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()), custom_mqtt_user.getValue(), custom_mqtt_password.getValue())
    {
      Serial.println("Connected to MQTT Server");
    }
    else
    {
      Serial.println("MQTT Server Connection Failed!");
      //3 LED Flash
      //      digitalWrite(GPIO12, HIGH);
      //      delay(ledFlashDelay);
      //      digitalWrite(GPIO12, LOW);
      //      delay(ledFlashDelay);
      //      digitalWrite(GPIO12, HIGH);
      //      delay(ledFlashDelay);
      //      digitalWrite(GPIO12, LOW);
      //      delay(ledFlashDelay);
      //      digitalWrite(GPIO12, HIGH);
      //      delay(ledFlashDelay);
      //      digitalWrite(GPIO12, LOW);
    }
  }
}

void errorDecoder(SHTC3_Status_TypeDef message)                             // The errorDecoder function prints "SHTC3_Status_TypeDef" resultsin a human-friendly way
{
  switch (message)
  {
    case SHTC3_Status_Nominal : Serial.print("Nominal"); break;
    case SHTC3_Status_Error : Serial.print("Error"); break;
    case SHTC3_Status_CRC_Fail : Serial.print("CRC Fail"); break;
    default : Serial.print("Unknown return code"); break;
  }
}

void espWipeData()
{
  int espWipe = digitalRead(GPIO13);
  if (espWipe == 1)
  {
    //Wipe WiFi Credentials
    wm.resetSettings();

    //Format File System
    LittleFS.format();

    Serial.println("GPIO13 = high! Wiping File System!");
  }
}

void readSensors()
{
  SHTC3_Status_TypeDef result = mySHTC3.update();

  if (mySHTC3.lastStatus == SHTC3_Status_Nominal)  // You can also assess the status of the last command by checking the ".lastStatus" member of the object
  {
    temperature = mySHTC3.toDegC();              // "toDegF" and "toDegC" return the temperature as a flaoting point number in deg F and deg C respectively
    humidity = mySHTC3.toPercent();              // "toPercent" returns the percent humidity as a floating point number
  }
  else
  {
    Serial.print("Update failed, error: ");
    errorDecoder(mySHTC3.lastStatus);
    Serial.println();
  }

  als.getALSLux(lux);

  Serial.println("-----------------------SENSORS---------------------");
  Serial.print("Lux:");
  Serial.println(lux);
  Serial.print("Temperature:");
  Serial.println(temperature);
  Serial.print("Humidity:");
  Serial.println(humidity);
  Serial.println("---------------------------------------------------");
}

void publishSensorData()
{
  SHTC3_Status_TypeDef result = mySHTC3.update();
  StaticJsonBuffer<300> JSONbuffer;
  JsonObject& JSONencoder = JSONbuffer.createObject();
  JSONencoder["location"] = custom_mqtt_location.getValue();
  JSONencoder["temperature"] = temperature;
  JSONencoder["humidity"] = humidity;
  JSONencoder["lux"] = lux;

  char JSONmessageBuffer[300];
  JSONencoder.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
  Serial.println("Sending message to MQTT topic..");
  Serial.println(JSONmessageBuffer);

  if (client.publish(custom_mqtt_topic.getValue(), JSONmessageBuffer) == true) {
    Serial.println("Success sending message");
  } else {
    Serial.println("Error sending message");
  }

  client.loop();
}

void setup()
{
  Serial.begin(115200);
  als.begin();
  Wire.begin();
  errorDecoder(mySHTC3.begin());
  delay(5000); //Give time to read the device ID.
  pinMode (GPIO12, OUTPUT);
  pinMode (GPIO13, INPUT);
  //  digitalWrite(GPIO13, LOW);

  //Wipe ESP Data
  espWipeData();

  WiFi.mode(WIFI_STA);

  setupLittleFS();

  wm.setSaveConfigCallback(saveConfigCallback);

  wm.addParameter(&custom_mqtt_server);
  wm.addParameter(&custom_mqtt_user);
  wm.addParameter(&custom_mqtt_password);
  wm.addParameter(&custom_mqtt_topic);
  wm.addParameter(&custom_mqtt_location);

  if (!wm.autoConnect())
  {
    Serial.println("WiFi Connection failed!");
    //2 LED Flash
    digitalWrite(GPIO12, HIGH);
    delay(ledFlashDelay);
    digitalWrite(GPIO12, LOW);
    delay(ledFlashDelay);
    digitalWrite(GPIO12, HIGH);
    delay(ledFlashDelay);
    digitalWrite(GPIO12, LOW);
    Serial.println("Restarting ESP ...");
    ESP.restart();
  }
  else
  {
    Serial.println("WiFi Connected!");
  }

  Serial.println("Connection Established!");
  strcpy(mqtt_server, custom_mqtt_server.getValue());
  strcpy(mqtt_user, custom_mqtt_user.getValue());
  strcpy(mqtt_password, custom_mqtt_password.getValue());
  strcpy(mqtt_topic, custom_mqtt_topic.getValue());
  strcpy(mqtt_location, custom_mqtt_location.getValue());
  
  if (shouldSaveConfig)
  {
    Serial.println("Saving config ...");
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    json["mqtt_server"] = mqtt_server;
    json["mqtt_user"] = mqtt_user;
    json["mqtt_password"] = mqtt_password;
    json["mqtt_topic"] = mqtt_topic;
    json["mqtt_location"] = mqtt_location;

    File configFile = LittleFS.open("/config.json", "w");
    if (!configFile)
    {
      Serial.println("Can not open config file!");
    }

    json.prettyPrintTo(Serial);
    json.printTo(configFile);
    configFile.close();
    shouldSaveConfig = false;
  }

  Serial.print("\nLocal IP:");
  Serial.println(WiFi.localIP());
  Serial.print("Gateway IP:");
  Serial.println(WiFi.gatewayIP());
  Serial.print("Subnet Mask:");
  Serial.println(WiFi.subnetMask());
}

void loop()
{
  if (!client.connected())
  {
    reconnect();
  }
  else
    Serial.println("MQTT is already connected");

  delay(5000); //Wait 5 seconds before reading the sensor

  readSensors();

  publishSensorData();

  ESP.deepSleep(10e6);
}

Here is the Serial Monitor output I get from this code,

Thanks in advance for your precious time. Your support is highly encouraged.
Best Regards,
Asif Ahmed

I am a bit worried about the garbage output in your screen shot.
Printing something that has not been initialized?

@drmpf Thank you for the reply. The garbage output happened when the ESP goes to deep sleep mode.

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