I have been trying to connect my ESP32 board to my laptop via MQTT. I have installed Mosquitto MQTT broker on my laptop but I fail to connect my ESP32 every time. This is the test code I am using to check MQTT connection.
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "......"; //WiFi Name
const char* password = "......"; //WiFi Password
const char* server= "xxx.xxx.xx.xx"; //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")){
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();
}
void loop() {
send_mqtt();
delay(10000); //Wait 10 secs before next transmission
}
But each time I get the error
failed, rc=-2
I have been trying to do the same for the past 2 months or so but to no success. Meanwhile, I have searched the internet extensively, to see what was it that I am doing wrong. I make sure that both the devices are on the same LAN.