0

I'm working on ESP32 Arduino IDE. I'm trying to get the message from my MQTT broker using PubSubClient.h and it seems like the callback() function is not working. But when I tried to publish the topic in the Arduino IDE it received the messages from the broker fine. Here is the code:

#include <WiFi.h>
#include <PubSubClient.h>
 
const char* ssid = "XXXX";
const char* password = "XXXX";
const char* mqttServer = "XXXX";
const int mqttPort = 1883;
const char* mqttUser = "";
const char* mqttPassword = "";
 
WiFiClient espClient;
PubSubClient client(espClient);
 
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("-----------------------");
}
 
void setup() {
 
  Serial.begin(115200);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");
 
  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);
 
  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");
 
    if (client.connect("ESP32Client", mqttUser, mqttPassword )) {
      Serial.println("connected " + String(client.state()));
    } 
    
    else {
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
    }
  }
  client.subscribe("XXXX");
}
 
void loop() {
  client.loop();
  delay(500);
}

The problem is I want to get every messages from my broker. Thank you in adavance.

Theus
  • 1
  • 1
  • I solved the problem by calling subscribe again in the reconnect part instead. Here is the code: while (!client.connected()) { Serial.println("Connecting to MQTT..."); if (client.connect("ESP32Client", mqttUser, mqttPassword )) { Serial.println("connected " + String(client.state())); client.subscribe(topic, "XXXX"); } else { Serial.print("failed with state "); Serial.print(client.state()); delay(2000); } – Theus May 25 '22 at 04:42
  • If you had mentioned that the problem happened after disconnecting you might have gotten help with the problem. – romkey May 25 '22 at 19:17

0 Answers0