Mqtt connect and receive messages

Hi all,
I've several issues with coding, but one thing at a time. :wink:

The first issue I would like to solve is the reconnect. I think that the code should only execute if cliente is not connected! Right? But everytime I call this function it performs a reconnection. Why?
Also, I only receive messages if reconnect

I'm just starting with this, maybe saying things with no sense, sorry.

void reconnect() {
  while (!client.connected()) {
    Serial.print("\nA ligar a ");
    Serial.println(broker);
    if (client.connect(broker)) {
      Serial.print("\nLigado a ");
      Serial.println(broker);
      client.subscribe(topic);
    } else {
      Serial.print("\nTentando nova ligação");
      delay(5000);
    }
  }
}

This is my code (messy, I know):

////////////////////////////
//INCLUDE
#include "libs.h"

///////////////////////////
// Add your MQTT Broker IP address, example:
const char* broker = "test.mosquitto.org";
const char* topic = "Ismael_Weather";
WiFiClient espClient;
PubSubClient client(espClient);
byte mqttoutpin = 32;
//Mqtt
const long interval = 16000;
unsigned long previousMillismqtt = 0;
unsigned long previousMillisleitura = 0;
unsigned long previousMillisligacao = 0;
boolean Rflag;

String mqttmess = "";
///////////////////////////
//DTH22
#define DHTPIN 23
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
String my_str1 = "";
////////////////////////////
//BMP280
#define P0 1013.25
Adafruit_BMP280 bmp;
String my_str2 = "";
////////////////////////////
//Sensor chuva
#define rainpin 4
boolean chuva;
String my_str3 = "";
////////////////////////////
//Sensor UV
float uvvolt;
float uvvalue;
String my_str4 = "";  //UV

void reconnect() {
  while (!client.connected()) {
    Serial.print("\nA ligar a ");
    Serial.println(broker);
    if (client.connect(broker)) {
      Serial.print("\nLigado a ");
      Serial.println(broker);
      client.subscribe(topic);
    } else {
      Serial.print("\nTentando nova ligação");
      delay(5000);
    }
  }
}

void callback(char* topic, byte* payload, unsigned int lenght) {
  Serial.print("Mensagem recebida; ");
  char messageBuffer[lenght];              //somewhere to put the message
  memcpy(messageBuffer, payload, lenght);  //copy in the payload
  messageBuffer[lenght] = '\0';            //convert copied payload to a C style string
  String led = messageBuffer;
  Serial.println(messageBuffer);  //print the buffer if you want to
  if (led == "on") {
    Serial.println("Ligar");
    digitalWrite(mqttoutpin, HIGH);
  }
  if (led == "off") {
    Serial.println("Desligar");
    digitalWrite(mqttoutpin, LOW);
  }
}

void leituras() {
  /////////////////////////////////////
  //DHT
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();
  if (isnan(humidity) || isnan(temperature)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }
  my_str1 = " ----- DHT22 >>> Temp.: ";
  my_str1 += temperature;
  my_str1 += "ºC - Humid.: ";
  my_str1 += humidity;
  my_str1 += "%";

    //BMP
  float temp = bmp.readTemperature();
  float press = bmp.readPressure();
  float alt = bmp.readAltitude(1017);
  my_str2 = " ----- BMP280 >>> ";
  my_str2 += "T: ";
  my_str2 += temp;
  my_str2 += "ºC <> P:";
  my_str2 += press;
  my_str2 += " Pa <> Alt:";
  my_str2 += alt;
  my_str2 += "m";

  //Sensor de chuva
  chuva = digitalRead(rainpin);
  my_str3 = " ----- Sensor de chuva: ";
  if (chuva == 1) {
    my_str3 += "Não chove";
  } else {
    my_str3 += "Esta a chover";
  }

  //UV
  uvvalue = analogRead(36);
  byte uvind = map(uvvalue, 0, 4095, 0, 10);
  my_str4 = " ----- UV: ";
  my_str4 += uvind;
  my_str4 += ".";

  //Envio das leituras pelo serial
  Serial.println(my_str1);
  Serial.println(my_str2);
  Serial.println(my_str3);
  Serial.println(my_str4);
  Serial.println();  // linha extra a separar conjunto de leituras
  
}

                      //////////////////// SETUP ////////////////
void setup() {
  pinMode(mqttoutpin, OUTPUT);
  digitalWrite(mqttoutpin, LOW);
  ///////////////////////////
  //Serial
  Serial.begin(115200);
  ///////////////////////////
  //Wifi
  if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
    Serial.println("STA Failed to configure");
  }
  WiFi.begin(ssid, password);
  delay(1000);

  client.setServer(broker, 1883);
  client.setCallback(callback);

//OTA
#include "ota.h"
  ///////////////////////////
  //DTH22
  dht.begin();

  //BMP280
  unsigned status;
  //status = bmp.begin(BMP280_ADDRESS_ALT, BMP280_CHIPID);
  status = bmp.begin(0x76);
  if (!status) {
    Serial.println(F("Could not find a valid BMP280 sensor, check wiring or "
                     "try a different address!"));
    Serial.print("SensorID was: 0x");
    Serial.println(bmp.sensorID(), 16);
    Serial.print("        ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n");
    Serial.print("   ID of 0x56-0x58 represents a BMP 280,\n");
    Serial.print("        ID of 0x60 represents a BME 280.\n");
    Serial.print("        ID of 0x61 represents a BME 680.\n");
    while (1) delay(10);
  }

  /* Default settings from datasheet. */
  bmp.setSampling(Adafruit_BMP280::MODE_NORMAL,     /* Operating Mode. */
                  Adafruit_BMP280::SAMPLING_X2,     /* Temp. oversampling */
                  Adafruit_BMP280::SAMPLING_X16,    /* Pressure oversampling */
                  Adafruit_BMP280::FILTER_X16,      /* Filtering. */
                  Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */
}

void loop() {
  unsigned long Millisleitura = millis();
  if (Millisleitura - previousMillisleitura >= 4000) {
    // save the last time a message was sent
    previousMillisleitura = Millisleitura;
    leituras();
  }

  unsigned long Millisligacao = millis();
  if (Millisligacao - previousMillisligacao >= 32000) {
    // save the last time a message was sent
    previousMillisligacao = Millisligacao;
    reconnect();
  }

  //MQTT
  unsigned long Millismqtt = millis();
  if (Millismqtt - previousMillismqtt >= 16000) {
    // save the last time a message was sent
    previousMillismqtt = Millismqtt;
    Serial.print("Sending message to topic: ");
    Serial.println(topic);
    // send message, the Print interface can be used to set the message contents
    String mqttmessy = my_str1 += my_str2 += my_str3 += my_str4;
    char mqttmess[mqttmessy.length() + 1];
    mqttmessy.toCharArray(mqttmess, mqttmessy.length() + 1);
    Serial.println(mqttmess);
    client.publish(topic, mqttmess);
  }
  client.loop();
  //OTA
  ArduinoOTA.handle();
}

Welcome to the forum

Your topic was MOVED to its current forum category which is more appropriate than the original as it has nothing to do with Installation and Troubleshooting of the IDE

1 Like

Replace:

reconnect();

By:

  if (!client.connected()) {
    reconnect();
  }
1 Like

That's how it was at beginning, but same results. Also, only send / receive messages when reconnects.

Anyway, I've changed. Now is like you've wrote.

Personally I would simply call reconnect() at the start of loop(). If the MQTT client is already connected then the function will do nothing

I would also use C style strings rather than Strings to avoid clumsy lines of code like this

    char mqttmess[mqttmessy.length() + 1];
    mqttmessy.toCharArray(mqttmess, mqttmessy.length() + 1);
1 Like

Thank you for your help, but there's the point. I did that and the system tries reconnect over and over 'till reboot the ESP.

The question, I think, is why is always disconnected?

About the clumsy code, thank you, I'll see that as soon as this is solved.

I've only a couple of weeks with an ESP :slight_smile:

Maybe because your client ID is not unique on broker. Try add an different ID.

    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str()))

Instead:

const char* broker = "test.mosquitto.org";

if (client.connect(broker))
1 Like

Sorry, can't make that work.
broker is the variable with the address of the server

client.setServer(broker, 1883);

Can't make it accept anything else but broker.
My fault, for sure.

SOLVED, Thank you
You're right, of course.

if (client.connect("Ismakokonut")) {

And working perfect

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