Dear Community,
I have an ESP (D1 Mini) which connects to my MQTT Mosquito broker.
The thing worked. I did not change anything. Now it does not work anymore.
It can not connect to the Broker, client.state() gives back error -2 which stands for MQTT_CONNECTION_REFUSED_BAD_USERNAME_OR_PASSWORD.
The same credentials are working in MQTT Explorer. (And they were working on the D1 Mini as well)
connects flawlessly.
I see all things published by my PCs sensors and so on. Only the ESPs do not connect, so they are not listed.
The minimal example ESP code
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Wi-Fi network credentials
// MQTT broker settings
const char* mqtt_server = "homeassistant";
const int mqtt_port = 1883;
const char* mqtt_username = "mqtt";
const char* mqtt_password = "Dreierpack1!";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
connectToWiFi();
// Connect to MQTT broker
client.setServer(mqtt_server, mqtt_port);
connectToMQTTBroker();
}
void loop() {
if (!client.connected()) {
connectToMQTTBroker();
}
client.loop();
}
void connectToWiFi() {
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Wi-Fi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void connectToMQTTBroker() {
while (!client.connected()) {
Serial.print("Connecting to MQTT broker...");
if (client.connect("WemosD1Mini", mqtt_username, mqtt_password)) {
Serial.println("Connected");
} else {
Serial.print("Failed, rc=");
Serial.print(client.state());
Serial.println(" Trying again in 5 seconds");
delay(5000);
}
}
}
Connects to the Wifi and delivers the Eroor code -2 when trying to connect to MQTT.
Why so?