user73370: For a project I am working on, I need to connect my ESP32 board to another server via MQTT protocol. I am using the Mosquitto MQTT Broker and it is presently on my laptop. Following is the test code I am using, which I'll build around this program.

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

const char* ssid = "*****";              //WiFi Name
const char* password = "********";      //WiFi Password
const char* server= "***.***.**.***";    //RPi or Machine IP on which the broker is

WiFiClient espClient;
PubSubClient client(espClient);

int 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(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.print("Attempting MQTT connection...");
  client.connect("esp32");      
  if (client.connect("esp32")){                 
      Serial.println("connected");
    }
    else {
      Serial.print("failed, rc=");
      Serial.println(client.state());
    }
    return 0;
}

int reconnect() {
  unsigned long startAttemptTime = millis();
  while (!client.connected()) 
  {
    Serial.println("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("esp32")){                 //if (client.connect("esp32", MQTT_USER, MQTT_PASS)) {
      Serial.println("connected");
    } 
    else {
      Serial.print("failed, rc=");
      Serial.println(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
  return 0;
}

int send_mqtt(){
  setup_WiFi();
  char sss[15]="Hello World";
   if (!client.connected()){
    reconnect();
  } 
  client.publish("esp32/test", sss);    //send message
  WiFi.disconnect(true);
  Serial.println("Sent");
  return 0;
}
void setup() {
  Serial.begin(115200);
  client.setServer(server, 1883);   //mqtt server details
  setup_WiFi();
  reconnect();
  send_mqtt();
}

void loop() {
  send_mqtt();
  delay(10000);     //Wait 10 secs before next transmission
}

I tried connection but got this error

Attempting MQTT connection...failed, rc= -2

What am I doing wrong? Any changes I need to make to the .conf file about which I don't know?
Guide me.
Thank You in advance

user76048: The code in your sketch is unlikely to be the problem. It works fine for me after I enter the IP addresses and password for my network.
According to the pubSubClient API documentation, the rc = -2 code returned by client.state() is due to the network connection having failed. As your code has already checked that it is connected to WiFi before trying to contact the MQTT broker, it is probably the communication between the two devices that is the issue, not the WiFi connection itself.  Things to check:

Are both devices are on the same network, and do they have a route to contact each other? From the laptop running the MQTT broker, try running ping XXX.XXX.XXX.XXX (replacing the XXXs with the IP address reported by the ESP32), and check you get a response. You might wish to comment out line 67 of your code so it doesn't disconnect from WiFi after every attempt at sending a message, otherwise you will see lots of lost packets.
Have you got the right IP address for the MQTT broker in your sketch? It should be the IP address for your laptop, not the loopback address, 127.0.0.1.
Can you use another device on the same network to connect to the MQTT server? (e.g. a cellphone running a MQTT dashboard app, or MQTT Explorer in Windows)
Is Mosquitto configured to listen out for remote connections? If you are running v2 of Mosquitto, you have to deliberately configure it to accept incoming connections, otherwise it will only listen to the localhost interface. You would also have to either set up an authentication mechanism or explicitly configure it to allow anonymous connections. This might be why you can connect from the laptop running the broker, but not from other devices.
On the MQTT server, can you see any connection attempts in Mosquitto's log file (/var/log/mosquitto/mosquitto.log)? There might be some error messages that give you further clues.


73370: <p>For a project I am working on, I need to connect my ESP32 board to another server via MQTT protocol. I am using the Mosquitto MQTT Broker and it is presently on my laptop. Following is the test code I am using, which I'll build around this program.</p>
<pre><code>
#include &lt;WiFi.h&gt;
#include &lt;PubSubClient.h&gt;

const char* ssid = &quot;*****&quot;;              //WiFi Name
const char* password = &quot;********&quot;;      //WiFi Password
const char* server= &quot;***.***.**.***&quot;;    //RPi or Machine IP on which the broker is

WiFiClient espClient;
PubSubClient client(espClient);

int setup_WiFi(){
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print(&quot;Connecting to &quot;);
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(&quot;.&quot;);
  }
  Serial.println(&quot;&quot;);
  Serial.println(&quot;WiFi connected&quot;);
  Serial.println(&quot;IP address: &quot;);
  Serial.println(WiFi.localIP());
  Serial.print(&quot;Attempting MQTT connection...&quot;);
  client.connect(&quot;esp32&quot;);      
  if (client.connect(&quot;esp32&quot;)){                 
      Serial.println(&quot;connected&quot;);
    }
    else {
      Serial.print(&quot;failed, rc=&quot;);
      Serial.println(client.state());
    }
    return 0;
}

int reconnect() {
  unsigned long startAttemptTime = millis();
  while (!client.connected()) 
  {
    Serial.println(&quot;Attempting MQTT connection...&quot;);
    // Attempt to connect
    if (client.connect(&quot;esp32&quot;)){                 //if (client.connect(&quot;esp32&quot;, MQTT_USER, MQTT_PASS)) {
      Serial.println(&quot;connected&quot;);
    } 
    else {
      Serial.print(&quot;failed, rc=&quot;);
      Serial.println(client.state());
      Serial.println(&quot; try again in 5 seconds&quot;);
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
  return 0;
}

int send_mqtt(){
  setup_WiFi();
  char sss[15]=&quot;Hello World&quot;;
   if (!client.connected()){
    reconnect();
  } 
  client.publish(&quot;esp32/test&quot;, sss);    //send message
  WiFi.disconnect(true);
  Serial.println(&quot;Sent&quot;);
  return 0;
}
void setup() {
  Serial.begin(115200);
  client.setServer(server, 1883);   //mqtt server details
  setup_WiFi();
  reconnect();
  send_mqtt();
}

void loop() {
  send_mqtt();
  delay(10000);     //Wait 10 secs before next transmission
}
</code></pre>
<p>I tried connection but got this error</p>
<blockquote>
<p>Attempting MQTT connection...failed, rc= -2</p>
</blockquote>
<p>What am I doing wrong? Any changes I need to make to the .conf file about which I don't know?
Guide me.
Thank You in advance</p>
 76048: <p>The code in your sketch is unlikely to be the problem. It works fine for me after I enter the IP addresses and password for my network.</p>
<p>According to the <a href="https://pubsubclient.knolleary.net/api#state" rel="nofollow noreferrer">pubSubClient API documentation</a>, the <code>rc = -2</code> code returned by <code>client.state()</code> is due to the network connection having failed. As your code has already checked that it is connected to WiFi before trying to contact the MQTT broker, it is probably the communication between the two devices that is the issue, not the WiFi connection itself.  Things to check:</p>
<ol>
<li>Are both devices are on the same network, and do they have a route to contact each other? From the laptop running the MQTT broker, try running <code>ping XXX.XXX.XXX.XXX</code> (replacing the XXXs with the IP address reported by the ESP32), and check you get a response. You might wish to comment out line 67 of your code so it doesn't disconnect from WiFi after every attempt at sending a message, otherwise you will see lots of lost packets.</li>
<li>Have you got the right IP address for the MQTT broker in your sketch? It should be the IP address for your laptop, not the loopback address, <code>127.0.0.1</code>.</li>
<li>Can you use another device on the same network to connect to the MQTT server? (e.g. a cellphone running a MQTT dashboard app, or <a href="http://mqtt-explorer.com/" rel="nofollow noreferrer">MQTT Explorer</a> in Windows)</li>
<li>Is Mosquitto configured to listen out for remote connections? If you are running v2 of Mosquitto, you have to deliberately <a href="https://mosquitto.org/documentation/migrating-to-2-0/#listener-behaviour-changes" rel="nofollow noreferrer">configure it</a> to accept incoming connections, otherwise it will only listen to the <code>localhost</code> interface. You would also have to either set up an authentication mechanism or explicitly configure it to allow anonymous connections. This might be why you can connect from the laptop running the broker, but not from other devices.</li>
<li>On the MQTT server, can you see any connection attempts in Mosquitto's log file (<code>/var/log/mosquitto/mosquitto.log</code>)? There might be some error messages that give you further clues.</li>
</ol>
