[SOLVED] Mosquitto broker help!!!

Hi everybody,

Taking advantage of staying at home...
I am trying the example Pubsubclient mqtt_esp8266 in order to publish and suscribe some topic through Node-RED. However I am not able to connect to broker, It shows me always the same failure:

Attempting MQTT connection...failed, rc=-2 try again in 5 seconds

I wanted to learn the basic program to publish and suscribe, I installed the mosquitto broker and also Node-RED.

This is the code:

*/

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

// Update these with values suitable for your network.

const char* ssid = "WLAN_2G";
const char* password = "password";
const char* mqtt_server = "XXX.XXX.X.XXX";

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

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  randomSeed(micros());

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

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
   digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is active low on the ESP-01)
  } else {
   digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
 }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(9600);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, 50, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
  }
}

For mqtt_server, I understand that i have to introduced the IPv4, because i have mosquitto running in my computer.
However when i start Node-RED, the console shows:

22 Apr 08:32:48 - [info] Starting flows
22 Apr 08:32:48 - [info] Started flows
22 Apr 08:32:48 - [info] [mqtt-broker:XXXXXX80.9xxxX] Connected to broker: ESP8266Client-@mqtt://localhost:1883
22 Apr 09:32:47 - [info] Stopping flows
22 Apr 09:32:47 - [info] [mqtt-broker:XXXXXX80.9xxxX] Disconnected from broker: ESP8266Client-@mqtt://localhost:1883
22 Apr 09:32:47 - [info] Stopped flows
22 Apr 09:32:47 - [info] Starting flows
22 Apr 09:32:47 - [info] Started flows
22 Apr 09:32:47 - [info] [mqtt-broker:XXXXXX80.9xxxX] Connected to broker: ESP8266Client-@mqtt://localhost:1883

Could you please help me to find the mistake?? I would be very grateful.
Thanks so much.

Does it work if you take Node-RED out of the equation and connect directly to the broker ?

No, it does not work. I do not know why the program cannot connect to the broker. Besides the code does not have any mention to Node-RED.

Could it be due to the client ID?

Thanks for your help.

I have no idea what Node-Red brings to the party but your code works fine for me connecting and publishing to a Mosquitto broker running on a local PC

Thanks for your reply. However the serial show me another different IP when the code execute

Serial.println(WiFi.localIP());

The IP is different than my IP for mqtt_server, it just change the last number. But i do not understand why, because the broker is running in my local PC as well as the nodemcu shield is connecting to the same wifi network.

Thank you so much.

The IP is different than my IP for mqtt_server, it just change the last number. But i do not understand why, because the broker is running in my local PC as well as the nodemcu shield is connecting to the same wifi network.

You are printing the IP address of the Arduino, not the address of the broker

NOTE :

const char* mqtt_server = "XXX.XXX.X.XXX";

expects the name of the broker, not its IP address

Change this to

IPAddress mqtt_server = {A, B, C, D);

where A, B, C, D is the IP address of the broker

Hello again,
I found the mistake... I forgot to configure the TCP connection for port 1883.

If someone has the same error, this is the solution:

  • Through Firewall Windows Defender, open advance configuration.
  • We need to create a new rule for TCP port, the 1883 and allow the connection

This is what I did and my broker is running properly and connecting.

Thanks

Did you also make the change to the IP address of the server as I suggested ?

Yes, I did it and it worked well. Thanks for your help.