Esp32 not conected to mqtt node red

I HAVE A PROBLEM CONNECTING TO MY RASPBERRY’S BROKER

#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>


// Replace the next variables with your SSID/Password combination
const char* ssid = "CELERITY_MONTALVAN";
const char* password = "1722510060B.";

// Add your MQTT Broker IP address, example:
//const char* mqtt_server = "192.168.1.144";
const char* mqtt_server = "192.168.1.11";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

//uncomment the following lines if you're using SPI
/*#include <SPI.h>
#define BME_SCK 18
#define BME_MISO 19
#define BME_MOSI 23
#define BME_CS 5*/

//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
float temperature = 0;
float humidity = 0;

// LED Pin
const int ledPin1 = 15;
const int ledPin2 = 2;
const int ledPin3 = 4;
const int ledPin4 = 16;
const int ledPin5 = 17;

void setup() {
  Serial.begin(115200);
  // default settings
  // (you can also pass in a Wire library object like &Wire2)
  //status = bme.begin();  
 
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
  pinMode(ledPin5, OUTPUT);
  
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Conectando a_ _ ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi conectado");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Mensaje recivido en topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;
  
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();

  // Feel free to add more if statements to control more GPIOs with MQTT

  // If a message is received on the topic esp32/output, you check if the message is either "on" or "off". 
  // Changes the output state according to the message
  if (String(topic) == "esp32/output1") {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("on");
      digitalWrite(ledPin1, HIGH);
    }
    else if(messageTemp == "off"){
      Serial.println("off");
      digitalWrite(ledPin1, LOW);
    }
  }
  if (String(topic) == "esp32/output2") {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("on");
      digitalWrite(ledPin2, HIGH);
    }
    else if(messageTemp == "off"){
      Serial.println("off");
      digitalWrite(ledPin2, LOW);
    }
  }
  if (String(topic) == "esp32/output3") {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("on");
      digitalWrite(ledPin3, HIGH);
    }
    else if(messageTemp == "off"){
      Serial.println("off");
      digitalWrite(ledPin3, LOW);
    }
  }
   if (String(topic) == "esp32/output4") {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("on");
      digitalWrite(ledPin4, HIGH);
    }
    else if(messageTemp == "off"){
      Serial.println("off");
      digitalWrite(ledPin4, LOW);
    }
  }
   if (String(topic) == "esp32/output5") {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("on");
      digitalWrite(ledPin5, HIGH);
    }
    else if(messageTemp == "off"){
      Serial.println("off");
      digitalWrite(ledPin5, LOW);
    }
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Subscribe
      client.subscribe("esp32/output1");
      client.subscribe("esp32/output2");
      client.subscribe("esp32/output3");
      client.subscribe("esp32/output4");
      client.subscribe("esp32/output5");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  }

AND IT IS TRYING TO CONNECT TO THE MQTT PROTOCOL BUT IT DOES NOT CONNECT AS SHOWN IN THE SERIAL PORT

NEED HELP
BEFORE THE SAME CODE IF CONNECTED

Can you prove you got a network connection?

Your callback is too long.

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

Using the code to connect an ESP8266to a network is different than connecting a ESP32, they use different WiFI libraries. Question, which MCU are you actually using for the project?

Can you connect to the broker using a notebook on the WiFi? Some routers have device isolation activated by default, so devices on the same WiFi network don’t see each other.

You ask me if I can connect to my Wi-Fi network through a laptop? If so, of course I can.

thanks for your answer, but I don’t think it’s relevant since before with the same code it worked normally

Does the ESP8266 connect to the network?

Can you show proof of a network connection. Of course if the ESP8266 cannot connect to the network then MQTT don’t work.

thanks for your answer. The module that I want to connect is the ESP32, and as I show you in the following image, the module does connect to the network.

1 Like

Thank you for showing proof of a WiFi connection.

void connectToWiFi()
{
  int TryCount = 0;
  //log_i( "connect to wifi" );
  while ( WiFi.status() != WL_CONNECTED )
  {
    TryCount++;
    WiFi.disconnect();
    WiFi.begin( SSID, PASSWORD );
    vTaskDelay( 4000 );
    if ( TryCount == 10 )
    {
      ESP.restart();
    }
  }
  WiFi.onEvent( WiFiEvent );
} // void connectToWiFi()

Is my WiFi connection routine. Notice the WiFi.disconnect()? Whiles disconnect does disconnect if connected the other thing it does is reset the WiFi stack space to default values.

void connectToMQTT()
{
  MQTTclient.setKeepAlive( 90 ); // needs be made before connecting
  byte mac[5];
  WiFi.macAddress(mac); // get mac address
  String clientID = String(mac[0]) + String(mac[4]) ; // use mac address to create clientID
  while ( !MQTTclient.connected() )
  {
    // boolean connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage);
    MQTTclient.connect( clientID.c_str(), mqtt_username, mqtt_password, NULL , 1, true, NULL );
    vTaskDelay( 250 );
  }
  MQTTclient.setCallback( mqttCallback );
  MQTTclient.subscribe( topicOK );
  log_i("MQTT Connected");

Above is my MQTT connection, notice the MQTTclient.setKeepAlive( 90 ); command? I have found the command improves connection stability.

Are you sure your MQTT Broker does not require a user name and password for login?

Have you checked your MQTT Broker logs to see why the Broker may be refusing the connection?

I am also having a similar issue with an ESP32 NodeMCU-32S and RPi4.

I followed two different tutorials and was able to connect to WiFi but not MQTT.
This one uses PubSubClient.h.
This one uses one uses AsyncMqttClient.h.
I have tried commenting out all of the DHT sensor code and adding the setKeepAlive command, but the result was the same. I have also tried allowing anonymous on the broker while not using an MQTT username and password on the client. Still the same result.

I connected an RPi Zero W as a publisher to the same RPi4 that I was trying to use with the ESP32. It worked with no issues and confirmed that the RPi broker port is definitely 1883.

I also have an Adafruit HUZZAH32 Feather board that I can try on Monday.

I’m thinking that the issue is with the ESP32 or something common to PubSubClient.h and AsyncMqttClient.h.

Any help is appreciated, Thanks!

As a follow up:
I got the same results with the Feather, but further troubleshooting showed that this is irrelevant.

The WiFi network I am using requires MAC address registration rather than a password with the SSID. It turns out that I was using the wrong MAC address. There are three MAC addresses for ESP32 boards: WiFi, Ethernet, and Bluetooth. From WiFi.h, you can get the WiFi MAC address with: Serial.println(WiFi.macAddress());

I then ran into another problem: The ESP32 successfully publishes readings after connecting WiFi and MQTT the first time, but subsequent readings after disconnecting and reconnecting do not work. Pressing the enable button on the board (or reset on the Feather) restarts this cycle.

The original code was taken from here. I separated the connect_MQTT function so that the WiFi and MQTT specific code had their own function. After moving connect_WiFi to setup from loop, all readings were publishing.

And then it dawned on me that WiFi was not forced to disconnect the way MQTT is with client.disconnect();, so I added WiFi.disconnect(); right after this line and moved connect_WiFi back under loop. I now have no issues with this program.

No, I asked if you can connect to the MQTT broker (on the Raspberry Pi) using your notebook if connected to WiFi. If that doesn't work, device isolation is active and have to be disabled on the WiFi router.