(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.
All connected to my mosquitto.
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, when the connection has been lost.
I use the same mosquitto user for al my sensors.

This is my code for the 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);


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 my relay code:

#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();
}
}

This is my 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.

Ultimately because this is a problem with specific devices communicating with Mosquitto, you will find better support on an Arduino/ESP forum or a Mosquitto forum. openHAB is not involved at all in this problem.

If you are using an ESP microcontroller you could use something like Espurna or Tasmota that have been around for a long time and are very reliable. If you don’t have an ESP I suggest a Wemos D1 Mini as they are breadboard friendly and easy to use for custom projects.

Thanks for the reply.
Yes is asked on the Arduino forum fist. But got the tip to change the delay() to Millis. Witch i did, but that didn’t help. Got no further replays so i tried it here as many ppl here use mosquitto to.
Also treid at " Eclipse Community Forums)" But after 2900 views have 0 reply’s

Greetings

Thanks for the reply.
Yes i no Tasmato. But this way i also learn allot, when i use Arduino.

Greetings

So I read through your code and log, looks like you keep losing the connection on a socket error. Are you monitoring the Serial log on the device? Is it crashing?

Have you looked into the Wi-Fi code to see if it also has a loop that needs to be run periodically? If so I don’t see it being called anywhere, which would mean the Wi-Fi connection would keep getting dropped.

1 Like

Thanks for the reply.
Yes i keep getting socket errors.
Do you mean the serial monitor of IDE ? Reuploaded the skets now with core debug level, debug.
In the void loop, it is checked if the esp is still connected to the wifi, if not the the “boolean reconnect” tries to reconnect. But it wont make a new connection ( it tries it every 5 seconds)

I use the same reconnect in my skets for the scd-30 co2 sensor, and that one is reconnecting fine.

Greetings

Yes, serial monitor of the IDE via the hardware/usb port. It can give more detail on crashes if the device is crashing.

Your reconnect function only reconnects MQTT, but if you are using this elsewhere without problems then I doubt that is the issue.

Thanks for the reply.
Yes my mistake, its the mqtt that reconnects.
And yes i use the IDE serial monitor, when the connection is lost i see in the monitor the message “reconnecting” every 5 second, so it is working. But the new connection is never made.

Greetings

Well I’m out of ideas from my own experience. See this example from the pubsubclient github repo and add some more logging to your serial log to see if you can get a log telling you what the client is seeing when it disconnects. Your code looks to be based on this example, but they are doing more serial logging especially in the reconnect function.

Thanks for the reply.
Will try to get more serial logging in the code.
The reconnect is indeed made from this github, but then the nonblocking one.

Greetings

Hello

When the connection is lost now with debug on i see in the serial monitor"

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

But my CO2 sensor just keeps posting data, so the mosqiutto 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

I was thinking it was a Wi-Fi problem and not an MQTT problem, based on your logs. You are beyond my experience now, but at least you’re on the right track. Good luck.

Thanks for the help.
Have to wait to see what happens on the other router. Ones i find out all post back. Just in case someone else gets this problem.

Greetings

Hello,

took some time.
But 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

2 Likes

I was right with my first guess :stuck_out_tongue:

Glad you have it working now

1 Like