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