Hi, so I'm having some trouble while trying to connect to my local mosquitto broker and I literally don't know what the problem is. I've been reading some other posts with the same issue, but couldn't find any solution. Does anyone knows what the problem can be?
Here's my code plus my mosquitto config
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "XXXX"; // your network SSID (name)
const char* password = "XXXXX"; // your network password
const char *mqtt_broker = "XXXXXX";
const char *topic = "test";
const int mqtt_port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastTime = 0;
unsigned long timerDelay = 7500;
int D1 = 5;
void setup() {
Serial.begin(115200); //Initialize serial
WiFi.mode(WIFI_STA);
pinMode(D1, OUTPUT);
digitalWrite(D1,LOW);
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
}
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char) payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
void loop() {
if ((millis() - lastTime) > timerDelay) {
// Connect or reconnect to WiFi
if(WiFi.status() != WL_CONNECTED){
Serial.print("Attempting to connect...");
while(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, password);
delay(5000);
}
Serial.println("\nConnected.");
}
if (!client.connected()) {
String client_id = "esp32-client-";
client_id += String(WiFi.macAddress());
Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
if (client.connect(client_id.c_str())) {
Serial.println("Public emqx mqtt broker connected");
} else {
Serial.print("failed with state ");
Serial.println(client.state());
}
client.loop();
lastTime = millis();
}
}
}
My mosquitto.conf changes:
listener 1883
log_dest file \mosquitto\mosquitto.log
log_type all
log_timestamp true
allow_anonymous true
Glad if someone can help me.