(SOLVED) Project not reconnecting with ESP32

Hello All,

I have a SCD-30 CO2 sensor a Miflora plant sensor a DS18B20 and a SSR-40A-relay.
The SCD-30 and the Miflora plant sensors are reconnecting when the connection is lost.
The Relay and DS18B20 are nor reconnecting.
I think the problem is within mosquitto, but i need to be sure of this.
I do see in the serial monitor “Reconnecting” every 5 seconds.

This is my code for the rely and DS18B20.

Relay:

#include <WiFi.h>
#include <PubSubClient.h>
 
//Wifi Settings
const char* ssid = "MySSID";
const char* password =  "MyPass";

//MQTT Settings
const char* mqttServer = "IP";
const int mqttPort = 1883;
const char* mqttUser = "USer";
const char* mqttPassword = "Passwd";
 
WiFiClient espClient;
PubSubClient client(espClient);


long lastReconnectAttempt = 0;

uint64_t chipid = ESP.getEfuseMac(); // MAC address of ESP32
uint16_t chip = (uint16_t)(chipid>>32);
char clientid[25];

boolean reconnect() {
  if (client.connect(clientid, mqttUser, mqttPassword )) {
    // Once connected, publish an announcement...
    client.publish("relay/Info","Reconnected", true);
  }
  return client.connected();
}

void setup() {
 
 
  Serial.begin(115200);
  pinMode(4, OUTPUT);
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");

  snprintf(clientid,25,"ESP32-%08X",chip);
 
  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);
 
 
  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");

    if (client.connect(clientid, mqttUser, mqttPassword )) {
 
      Serial.println("connected");  
 
    } else {
 
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
      lastReconnectAttempt = 0;
    }

  }
 
  client.subscribe("relay");

}
 
void callback(char* topic, byte* payload, unsigned int length) {



  Serial.print("Message arrived in topic: ");
  Serial.println(topic);

  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }

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

  if (payload[0] == '1') {
    digitalWrite(4, HIGH);
  }
  else if (payload[0] == '0') {
    digitalWrite(4, LOW);
  }
Serial.println(digitalRead(4) ? "HIGH" : "LOW"); // <<<<<<< NEW
}




 

 
void loop(){

    if (!client.connected()) {
    unsigned long now = millis();
    if (now - lastReconnectAttempt > 5000UL) {
      lastReconnectAttempt = now;
      // Attempt to reconnect
      Serial.print("Reconnecting");
      client.publish("relay/Info1","Reconnecting", true);
      if (reconnect()) {
        lastReconnectAttempt = 0;
      }
    }
  } else {
    // Client connected
  client.loop();
}
}

DS18B20:

#include <OneWire.h>
#include <DallasTemperature.h>
#include <WiFi.h>
#include <PubSubClient.h>


//Wifi Settings
const char* ssid = "MySSID";
const char* password =  "MyPass";

//MQTT Settings
const char* mqttServer = "IP";
const int mqttPort = 1883;
const char* mqttUser = "USer";
const char* mqttPassword = "Passwd";
 
WiFiClient espClient;
PubSubClient client(espClient);


long lastReconnectAttempt = 0;

uint64_t chipid = ESP.getEfuseMac(); // MAC address of ESP32
uint16_t chip = (uint16_t)(chipid>>32);
char clientid[25];

boolean reconnect() {
  if (client.connect(clientid, mqttUser, mqttPassword )) {
    // Once connected, publish an announcement...
    client.publish("DS18B20/Info","Reconnected", true);
  }
  return client.connected();
}

// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;     

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);

// Pass our oneWire reference to Dallas Temperature sensor 
DallasTemperature sensors(&oneWire);

void setup() {
  // Start the Serial Monitor
  Serial.begin(115200);
  // Start the DS18B20 sensor
  sensors.begin();

  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");

  snprintf(clientid,25,"ESP32-%08X",chip);
 
  client.setServer(mqttServer, mqttPort);

 
 
  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");

    if (client.connect(clientid, mqttUser, mqttPassword )) {
 
      Serial.println("connected");  
 
    } else {
 
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
      lastReconnectAttempt = 0;
    }

  }
  
}

void loop() {
  sensors.requestTemperatures(); 
  float temperatureC = sensors.getTempCByIndex(0);

    if (!client.connected()) {
    unsigned long now = millis();
    if (now - lastReconnectAttempt > 5000UL) {
      lastReconnectAttempt = now;
      // Attempt to reconnect
      Serial.print("Reconnecting");
       client.publish("DS18B20/Info1","Reconnecting", true);
      if (reconnect()) {
        lastReconnectAttempt = 0;
      }
    }
  } else {
    // Client connected

    client.loop();
  
  Serial.print(temperatureC);
  Serial.println("ºC");
  client.publish("DS18B20/Temp",  String(temperatureC, 2).c_str());
  


  delay(5000);

  }
}

When i only have the Relay and DS18B20 connected and they lose connecting i see the following in my mosquitto logs

1596047074: Sending PINGRESP to ESP32-0000F0DB
1596047078: Received PUBLISH from ESP32-0000CCEE (d0, q0, r0, m0, 'DS18B20/Temp', ... (5 bytes))
1596047078: Sending PUBLISH to 3828c3ea-6cfc-46a6-95e5-3a56116b2930 (d0, q0, r0, m0, 'DS18B20/Temp', ... (5 bytes))
1596047078: Received PINGREQ from ESP32-0000CCEE
1596047078: Sending PINGRESP to ESP32-0000CCEE
1596047084: Received PUBLISH from ESP32-0000CCEE (d0, q0, r0, m0, 'DS18B20/Temp', ... (5 bytes))
1596047084: Sending PUBLISH to 3828c3ea-6cfc-46a6-95e5-3a56116b2930 (d0, q0, r0, m0, 'DS18B20/Temp', ... (5 bytes))
1596047089: Received PINGREQ from ESP32-0000F0DB
1596047089: Sending PINGRESP to ESP32-0000F0DB
1596047090: Received PUBLISH from ESP32-0000CCEE (d0, q0, r0, m0, 'DS18B20/Temp', ... (5 bytes))
1596047090: Sending PUBLISH to 3828c3ea-6cfc-46a6-95e5-3a56116b2930 (d0, q0, r0, m0, 'DS18B20/Temp', ... (5 bytes))
1596047105: Received PINGREQ from 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047105: Sending PINGRESP to 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047112: Client ESP32-0000F0DB has exceeded timeout, disconnecting.
1596047112: Client ESP32-0000CCEE has exceeded timeout, disconnecting.
1596047164: Received PINGREQ from 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047164: Sending PINGRESP to 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047220: Saving in-memory database to /var/lib/mosquitto/mosquitto.db.
1596047224: Received PINGREQ from 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047224: Sending PINGRESP to 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047284: Received PINGREQ from 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047284: Sending PINGRESP to 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047344: Received PINGREQ from 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047344: Sending PINGRESP to 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047404: Received PINGREQ from 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047404: Sending PINGRESP to 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047464: Received PINGREQ from 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047464: Sending PINGRESP to 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047524: Received PINGREQ from 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047524: Sending PINGRESP to 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047584: Received PINGREQ from 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047584: Sending PINGRESP to 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047644: Received PINGREQ from 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047644: Sending PINGRESP to 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047704: Received PINGREQ from 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047704: Sending PINGRESP to 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047764: Received PINGREQ from 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047764: Sending PINGRESP to 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047824: Received PINGREQ from 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047824: Sending PINGRESP to 3828c3ea-6cfc-46a6-95e5-3a56116b2930
1596047884: Received PINGREQ from 3828c3ea-6cfc-46a6-95e5-3a56116b2930

So is this a Mosquitto problem ore a problem with my code.

Greetings

How about calling the disconnect() method before calling connect() again?

Reconnecting to a MQTT server every 5s isn't very clever.

pylon:
How about calling the disconnect() method before calling connect() again?

Reconnecting to a MQTT server every 5s isn’t very clever.

Thanks for the reply.

I need to auto-reconnect when the connection is lost.
When the connection is lost then i tries to reconnect every 5 seconds. ( If it re-connects then it wont try to reconnect every 5 seconds)
So i don’t understand why i need to use a disconnect() if the connection has already been lost.

pylon:
How about calling the disconnect() method before calling connect() again?

Then why are my other sensor working correctly if i had to use a disconnect() ?

Quiestion: Did you read my OP ?

Greetings

So i don't understand why i need to use a disconnect() if the connection has already been lost.

Sorry, because of the wrong indenting I misinterpreted the code blocks. Do you know that the IDE has an Auto Format option to fix the indentation?

Then why are my other sensor working correctly if i had to use a disconnect() ?

You didn't post the code that working correctly.

I would first try to remove this line:

       client.publish("DS18B20/Info1","Reconnecting", true);

It doesn't make sense to publish anything while you're not connected.

Remove the delay at the end of loop() and implement a millis() check for the publish to happen only every 5 seconds.

Thanks for the reply.

pylon:

       client.publish("DS18B20/Info1","Reconnecting", true);

It doesn’t make sense to publish anything while you’re not connected.

You are completely right, i have removed this from my code.

Sorry, because of the wrong indenting I misinterpreted the code blocks. Do you know that the IDE has an Auto Format option to fix the indentation?

I did not no, thanks for the tip.

Remove the delay at the end of loop() and implement a millis() check for the publish to happen only every 5 seconds.

Will play around with this.

This is the code that is working correctly

#include <Wire.h>
#include "paulvha_SCD30.h"
#include "SparkFunBME280.h"

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


//////////////////////////////////////////////////////////////////////////
// set SCD30 driver debug level (ONLY NEEDED CASE OF SCD30 ERRORS)      //
//                                                                      //
// 0 : no messages                                                      //
// 1 : request sending and receiving                                    //
// 2 : request sending and receiving + show protocol errors             //
//////////////////////////////////////////////////////////////////////////
#define scd_debug 0

///////////////////////////////////////////////////////////////////////
// define the BME280 address.                                        //
// Use if address jumper is closed : 0x76.                           //
///////////////////////////////////////////////////////////////////////
#define I2CADDR 0x76


//Wifi Settings
const char* ssid = "MySSID";
const char* password =  "MyPass";

//MQTT Settings
const char* mqttServer = "IP";
const int mqttPort = 1883;
const char* mqttUser = "USer";
const char* mqttPassword = "Passwd";

#define alti 3

WiFiClient espClient;
PubSubClient client(espClient);

long lastReconnectAttempt = 0;

uint32_t chipid = ESP.getChipId();
char clientid[25];


boolean reconnect() {
  if (client.connect(clientid, mqttUser, mqttPassword )) {
    // Once connected, publish an announcement...
    client.publish("SCD30/Info", "Reconnected");
  }
  return client.connected();
}



//////////////////////////////////////////////////////////////////////////
//////////////// NO CHANGES BEYOND THIS POINT NEEDED /////////////////////
//////////////////////////////////////////////////////////////////////////

BME280 mySensor; //Global sensor object
SCD30 airSensor;



// hold statistics
float temp_tot = 0;
float temp_cnt = 0;
float hum_tot = 0;
float hum_cnt = 0;
float temp_max = 0;
float hum_max = 0;

// status
int detect_BME280 = 0;

void setup()
{
  char buf[10];

  Wire.begin();

  Serial.begin(115200);
  Serial.println("\nSCD30 + BME280 Example);");




  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");

  snprintf(clientid, 25, "ESP12-%08X", chipid);

  client.setServer(mqttServer, mqttPort);


  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");

    if (client.connect(clientid, mqttUser, mqttPassword )) {

      Serial.println("connected");

    } else {

      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
      lastReconnectAttempt = 0;
    }

  }




  // set I2C address. default is 0x77
  mySensor.setI2CAddress(I2CADDR);

  if (mySensor.beginI2C() == false) // Begin communication over I2C
  {
    Serial.println("The BME280 did not respond. Please check wiring.");
  }
  else
  {
    detect_BME280 = 1;
  }


  // This will cause readings to occur every two seconds and automatic calibration
  // on an ESP8266 must called last to set the clock stretching correct for SCD30
  airSensor.begin(Wire);
  //This will cause SCD30 readings to occur every two seconds
  if (airSensor.begin() == false)
  {
    Serial.println("The SCD30 did not respond. Please check wiring.");
    while (1);
  }

  // Read SCD30 serial number as printed on the device
  // buffer MUST be at least 7 digits (6 serial + 0x0)
  airSensor.getSerialNumber(buf);
  Serial.print("serial number: ");
  Serial.println(buf);



}



void loop()
{
  float co2, temps, hums, tempb, humb, pressure, altitude;

  if (!client.connected()) {
    unsigned long now = millis();
    if (now - lastReconnectAttempt > 5000UL) {
      lastReconnectAttempt = now;
      // Attempt to reconnect
      if (reconnect()) {
        lastReconnectAttempt = 0;
      }
    }
  } else {
    // Client connected

    client.loop();
  }


  if (airSensor.dataAvailable())
  {

    Serial.print(F("SCD30 : co2(ppm) : "));
    Serial.print(airSensor.getCO2());
    co2 = airSensor.getCO2();
    client.publish("SCD30/co2",  String(co2, 0).c_str());

    Serial.print(F("\ttemp(C): "));
    temps = airSensor.getTemperature();
    Serial.print(temps, 2);
    client.publish("SCD30/temperature",  String(temps).c_str());

    Serial.print(F("\thumidity(%): "));
    hums = airSensor.getHumidity();
    Serial.print(hums, 1);
    client.publish("SCD30/humidity",  String(hums).c_str());

    Serial.println();


    // if BME280 was detected include the information & statistics
    if (detect_BME280 == 1)
    {
      Serial.print(F("BME280: Pressure: "));
      pressure = mySensor.readFloatPressure() / 100;
      Serial.print(pressure, 0);
      client.publish("BME280/pressure",  String(pressure).c_str());

      Serial.print(F("\ttemp(C): "));
      tempb = mySensor.readTempC();
      //tempb = mySensor.readTempF();
      Serial.print(tempb, 2);
      client.publish("BME280/temperature",  String(tempb, 2).c_str());

      Serial.print(F("\thumidity(%): "));
      humb = mySensor.readFloatHumidity();
      Serial.print(humb, 1);
      client.publish("BME280/humidity",  String(humb, 2).c_str());

      Serial.print(F("\tAlt(m): "));
      Serial.print(mySensor.readFloatAltitudeMeters(), 1);
      //Serial.print(mySensor.readFloatAltitudeFeet(), 1);
      altitude = mySensor.readFloatAltitudeMeters();
      client.publish("BME280/altitude",  String(altitude, 1).c_str());

      Serial.println();

      // count TOTAL delta
      temp_tot += temps - tempb;
      hum_tot += hums - humb;

      // count samples
      temp_cnt++;
      hum_cnt++;

      // obtain maximum delta
      if (temps > tempb)
      {
        if (temp_max < temps - tempb) temp_max = temps - tempb;
      }
      else
      {
        if (temp_max < tempb - temps) temp_max - tempb - temps;
      }

      if (hums > humb)
      {
        if (hum_max < hums - humb) hum_max = hums - humb;
      }
      else
      {
        if (hum_max < humb - hums) hum_max = humb - hums;
      }

      Serial.print(F("Delta avg temp : "));
      Serial.print(temp_tot / temp_cnt, 2);
      Serial.print(F(" Delta avg humidity : "));
      Serial.print(hum_tot / hum_cnt, 2);
      Serial.print(F(" Biggest delta temp : "));
      Serial.print(temp_max);
      client.publish("BME280/Max-Temp",  String(temp_max, 2).c_str());
      Serial.print(F(" Biggest delta humidity : "));
      Serial.print(hum_max);
      client.publish("BME280/Max-Hum",  String(hum_max, 2).c_str());
      Serial.println("\n");

    }
  }
  else
    Serial.println(F("No SCD30 data"));

  // only every 2 seconds is data available
  delay(2000);
}

Again thanks for the reply’s

Greetings

Hello,

I have been playing around with Millis.
But have not been able to make it working correctly.
When the program starts it will wait 5sec before posting the Temp, but after the first 5 sec it will post the temp every sec, so it is not re-checking the time. What i am doing wrong.

This is the code i have right now.

#include <OneWire.h>
#include <DallasTemperature.h>
#include <WiFi.h>
#include <PubSubClient.h>


//Wifi Settings
const char* ssid = "MySSID";
const char* password =  "MyPass";

//MQTT Settings
const char* mqttServer = "IP";
const int mqttPort = 1883;
const char* mqttUser = "USer";
const char* mqttPassword = "Passwd";

WiFiClient espClient;
PubSubClient client(espClient);


unsigned long startMillis;
unsigned long currentMillis;
const unsigned long period = 5000;  //the value is a number of milliseconds, ie 5 second


long lastReconnectAttempt = 0;

uint64_t chipid = ESP.getEfuseMac(); // MAC address of ESP32
uint16_t chip = (uint16_t)(chipid >> 32);
char clientid[25];

boolean reconnect() {
  if (client.connect(clientid, mqttUser, mqttPassword )) {
    // Once connected, publish an announcement...
    client.publish("DS18B20/Info", "Reconnected", true);
  }
  return client.connected();
}

// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);

// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);

void setup() {
  // Start the Serial Monitor
  Serial.begin(115200);
  // Start the DS18B20 sensor
  sensors.begin();

  startMillis = millis();  //initial start time

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");

  snprintf(clientid, 25, "ESP32-%08X", chip);

  client.setServer(mqttServer, mqttPort);



  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");

    if (client.connect(clientid, mqttUser, mqttPassword )) {

      Serial.println("connected");

    } else {

      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
      lastReconnectAttempt = 0;
    }

  }

}

void loop() {
  sensors.requestTemperatures();
  float temperatureC = sensors.getTempCByIndex(0);

  if (!client.connected()) {
    unsigned long now = millis();
    if (now - lastReconnectAttempt > 5000UL) {
      lastReconnectAttempt = now;
      // Attempt to reconnect
      Serial.print("Reconnecting");
      if (reconnect()) {
        lastReconnectAttempt = 0;
      }
    }
  } else {
    // Client connected

    currentMillis = millis();  //get the current "time" (actually the number of milliseconds since the program started)
    if (currentMillis - startMillis >= period)  //test whether the period has elapsed

    {
      Serial.print(temperatureC);
      Serial.println("ºC");
      client.publish("DS18B20/Temp",  String(temperatureC, 2).c_str());
    }
    client.loop();
  }

Greetings

Hello,

Have been reading some more on the internet.
And came up with this code.
It is posting the temp every 5 seconds.
Don’t no if it will auto-reconnect when the connection is lost, have to wait till the connection is lost.
This is the code i have right now:

#include <OneWire.h>
#include <DallasTemperature.h>
#include <WiFi.h>
#include <PubSubClient.h>


//Wifi Settings
const char* ssid = "MySSID";
const char* password =  "MyPass";

//MQTT Settings
const char* mqttServer = "IP";
const int mqttPort = 1883;
const char* mqttUser = "USer";
const char* mqttPassword = "Passwd";

WiFiClient espClient;
PubSubClient client(espClient);


int period = 5000;
unsigned long time_now = 0;


long lastReconnectAttempt = 0;

uint64_t chipid = ESP.getEfuseMac(); // MAC address of ESP32
uint16_t chip = (uint16_t)(chipid >> 32);
char clientid[25];

boolean reconnect() {
  if (client.connect(clientid, mqttUser, mqttPassword )) {
    // Once connected, publish an announcement...
    client.publish("DS18B20/Info", "Reconnected", true);
  }
  return client.connected();
}

// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);

// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);

void setup() {
  // Start the Serial Monitor
  Serial.begin(115200);
  // Start the DS18B20 sensor
  sensors.begin();



  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");

  snprintf(clientid, 25, "ESP32-%08X", chip);

  client.setServer(mqttServer, mqttPort);



  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");

    if (client.connect(clientid, mqttUser, mqttPassword )) {

      Serial.println("connected");

    } else {

      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
      lastReconnectAttempt = 0;
    }

  }

}

void loop() {
  time_now = millis();
  sensors.requestTemperatures();
  float temperatureC = sensors.getTempCByIndex(0);

  if (!client.connected()) {
    unsigned long now = millis();
    if (now - lastReconnectAttempt > 5000UL) {
      lastReconnectAttempt = now;
      // Attempt to reconnect
      Serial.print("Reconnecting");
      if (reconnect()) {
        lastReconnectAttempt = 0;
      }
    }
  } else {
    // Client connected

    while (millis() < time_now + period) {
      //wait approx. [period] ms
    }

    {
      Serial.print(temperatureC);
      Serial.println("ºC");
      client.publish("DS18B20/Temp",  String(temperatureC, 2).c_str());

    }

  }
  client.loop();
}

Don’t no if this is the best way of doing it, but it works. (Temp is posted every 5 seconds)
If there is a better way of doing this, please point me in the right direction.

Greetings

Hello,

I still have the same problem. When the connection is lost, it
tries to reconnect every 5 seconds. But it won’t get a connection.
I still think the problem is with-in mosquito.

#include <OneWire.h>
#include <DallasTemperature.h>
#include <WiFi.h>
#include <PubSubClient.h>


//Wifi Settings
const char* ssid = "MySSID";
const char* password =  "MyPass";

//MQTT Settings
const char* mqttServer = "IP";
const int mqttPort = 1883;
const char* mqttUser = "USer";
const char* mqttPassword = "Passwd";

WiFiClient espClient;
PubSubClient client(espClient);


int period = 5000;
unsigned long time_now = 0;


long lastReconnectAttempt = 0;

uint64_t chipid = ESP.getEfuseMac(); // MAC address of ESP32
uint16_t chip = (uint16_t)(chipid >> 32);
char clientid[25];

boolean reconnect() {
  if (client.connect(clientid, mqttUser, mqttPassword )) {
    // Once connected, publish an announcement...
    client.publish("DS18B20/Info", "Reconnected", true);
  }
  return client.connected();
}

// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);

// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);

void setup() {
  // Start the Serial Monitor
  Serial.begin(115200);
  // Start the DS18B20 sensor
  sensors.begin();



  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");

  snprintf(clientid, 25, "ESP32-%08X", chip);

  client.setServer(mqttServer, mqttPort);



  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");

    if (client.connect(clientid, mqttUser, mqttPassword )) {

      Serial.println("connected");

    } else {

      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
      lastReconnectAttempt = 0;
    }

  }

}

void loop() {
  time_now = millis();
  sensors.requestTemperatures();
  float temperatureC = sensors.getTempCByIndex(0);

  if (!client.connected()) {
    unsigned long now = millis();
    if (now - lastReconnectAttempt > 5000UL) {
      lastReconnectAttempt = now;
      // Attempt to reconnect
      Serial.print("Reconnecting");
      if (reconnect()) {
        lastReconnectAttempt = 0;
      }
    }
  } else {
    // Client connected

    while (millis() < time_now + period) {
      //wait approx. [period] ms
    }

    {
      Serial.print(temperatureC);
      Serial.println("ºC");
      client.publish("DS18B20/Temp",  String(temperatureC, 2).c_str());

    }

  }
  client.loop();
}

This is in myt mosquitto log"

1598871070: Socket error on client ESP12-00313D81, disconnecting.
1598871070: New connection from 192.168.178.227 on port 1883.
1598871070: New client connected from 192.168.178.227 as ESP12-00313D81 (p2, c1, k15, u'openhab').
1598871070: No will message specified.
1598871070: Sending CONNACK to ESP12-00313D81 (0, 0)
1598871074: Socket error on client ESP12-00313D81, disconnecting.
1598871074: New connection from 192.168.178.227 on port 1883.
1598871074: New client connected from 192.168.178.227 as ESP12-00313D81 (p2, c1, k15, u'openhab').
1598871074: No will message specified.
1598871074: Sending CONNACK to ESP12-00313D81 (0, 0)
1598871075: New connection from 192.168.178.206 on port 1883.
1598871075: Client miflora-client already connected, closing old connection.
1598871075: New client connected from 192.168.178.206 as miflora-client (p2, c1, k15, u'openhab2').
1598871075: No will message specified.
1598871075: Sending CONNACK to miflora-client (0, 0)
1598871077: New connection from 192.168.178.227 on port 1883.
1598871077: Client ESP12-00313D81 already connected, closing old connection.
1598871077: New client connected from 192.168.178.227 as ESP12-00313D81 (p2, c1, k15, u'openhab').
1598871077: No will message specified.
1598871077: Sending CONNACK to ESP12-00313D81 (0, 0)

Greetings

Hello

i have re-uploaded the skets with debug on.
When the connection is lost isee in the serial monitor:

Reconnecting[E][WiFiClient.cpp:232] connect(): connect on fd 60, errno: 118, "Host is unreachable"

But the CO2 sensor keeps posting, so mosquitto is still active.

Edit:
Looks like its a wifi problem and not mqtt. Will try to connect the ESP to my other router and see what happens.

Greetings

You can check the Wifi connection by calling WiFi.isConnected(). If that's false you can call WiFi.reconnect() to get a new connection.

pylon:
You can check the Wifi connection by calling WiFi.isConnected(). If that’s false you can call WiFi.reconnect() to get a new connection.

Thanks for the reply.
The problem in within the esp32 library, the wifi code wont auto-reconnect.
As a solution you can add this to the loop.

  if (WiFi.status() != WL_CONNECTED) {
    WiFi.begin(ssid, password);
  }

So my code is now:

#include <OneWire.h>
#include <DallasTemperature.h>
#include <WiFi.h>
#include <PubSubClient.h>


//Wifi Settings
const char* ssid = "MySSID";
const char* password =  "MyPass";

//MQTT Settings
const char* mqttServer = "IP";
const int mqttPort = 1883;
const char* mqttUser = "USer";
const char* mqttPassword = "Passwd";

WiFiClient espClient;
PubSubClient client(espClient);


int period = 5000;
unsigned long time_now = 0;

long lastReconnectAttempt = 0;

uint64_t chipid = ESP.getEfuseMac(); // MAC address of ESP32
uint16_t chip = (uint16_t)(chipid >> 32);
char clientid[25];

boolean reconnect() {
  if (client.connect(clientid, mqttUser, mqttPassword )) {
    // Once connected, publish an announcement...
    client.publish("DS18B20/Info", "Reconnected", true);
  }
  return client.connected();
}

// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);

// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);

void setup() {
  // Start the Serial Monitor
  Serial.begin(115200);
  // Start the DS18B20 sensor
  sensors.begin();



  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");

  snprintf(clientid, 25, "ESP32-%08X", chip);

  client.setServer(mqttServer, mqttPort);



  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");

    if (client.connect(clientid, mqttUser, mqttPassword )) {

      Serial.println("connected");

    } else {

      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
      lastReconnectAttempt = 0;
    }

  }

}

void loop() {
  time_now = millis();
  sensors.requestTemperatures();
  float temperatureC = sensors.getTempCByIndex(0);

  if (WiFi.status() != WL_CONNECTED) {
    WiFi.begin(ssid, password);
  }


  if (!client.connected()) {
    unsigned long now = millis();
    if (now - lastReconnectAttempt > 5000UL) {
      lastReconnectAttempt = now;
      // Attempt to reconnect
      Serial.print("Reconnecting");
      if (reconnect()) {
        lastReconnectAttempt = 0;
      }
    }
  } else {
    // Client connected

    while (millis() < time_now + period) {
      //wait approx. [period] ms
    }

    {
      Serial.print(temperatureC);
      Serial.println("ºC");
      client.publish("DS18B20/Temp",  String(temperatureC, 2).c_str());

    }

  }
  client.loop();
}

Greetings