Hello,
I've been working on connecting my ESP8266 to an MQTT broker (eclipse-mosquitto) running in Docker on Windows. However, I'm encountering constant connection issues with an error code of -2, and I'm unable to establish a connection. Previously, I had successfully connected to Adafruit IO without any problems, so my internet connection appears to be fine. I also attempted to connect using Curl on Termux (Android phone) within the same network, but it failed to connect as well. I'm unsure whether the issue lies with my code, configuration, or possibly my WiFi network. I've tried various solutions found online, but none have resolved my problem.
Could you please provide some guidance on how to further investigate the issue?
Here is the code I use for testing purpose:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
const char* ssid = "ssid";
const char* password = "password";
const char* mqttServer = "172.17.0.7";
const int mqttPort = 1883;
// const char* mqttUser = "admin";
// const char* mqttPassword = "admin";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT Broker...");
if (client.connect("ESP8266Client")) {
Serial.println("Connected to MQTT Broker");
} else {
Serial.print("Failed, rc=");
Serial.print(client.state());
Serial.println(" Retrying in 5 seconds...");
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
int lightValue = analogRead(A0);
StaticJsonDocument<200> jsonDocument;
jsonDocument["value"] = lightValue;
char buffer[200];
serializeJson(jsonDocument, buffer);
client.publish("LIGHTSENSOR/values", buffer);
delay(1000);
}
void callback(char* topic, byte* payload, unsigned int length) {
// Obsługa otrzymanych wiadomości MQTT
}
void reconnect() {
while (!client.connected()) {
Serial.println("Connecting to MQTT Broker...");
if (client.connect("ESP8266Client")) {
Serial.println("Connected to MQTT Broker");
} else {
Serial.print("Failed, rc=");
Serial.print(client.state());
Serial.println(" Retrying in 5 seconds...");
delay(5000);
}
}
}