Weird mqtt connection problem

Hello folks,
I have a relatively long code. It runs on an ESP8266. A WCS1800 sensor and an LCD display are connected.
In principle it runs perfectly. A website is displayed where you can enter and save some values.

however, when i start the device, i.e. plug it in, there is apparently a mqtt connection problem. it then displays the following message in very quick succession:

Bootvorgang startet...
09:16:26.946 -> Firmware Version: 10.0.0
09:16:26.990 -> Konfiguration geladen.
09:16:27.595 -> .....................WiFi verbunden
09:16:31.308 -> IP-Adresse: 192.168.178.64
09:16:31.350 -> Starte Nullpunkt-Kalibrierung...
09:16:32.359 -> Kalibrierter Offset: 2.771 V
09:16:32.359 -> Echter Wert: 0.00 A | Gerundeter Wert: 0 A
09:16:32.359 -> Fehler beim Senden der Nachricht.
09:16:32.404 -> MQTT-Verbindung verloren. Versuche erneut...
09:16:32.404 -> Verbindung zum MQTT-Server wird hergestellt...verbunden!
09:16:32.436 -> MQTT-Verbindung verloren. Versuche erneut...
09:16:32.436 -> Verbindung zum MQTT-Server wird hergestellt...verbunden!
09:16:32.436 -> MQTT-Verbindung verloren. Versuche erneut...
09:16:32.436 -> Verbindung zum MQTT-Server wird hergestellt...verbunden!
09:16:32.470 -> MQTT-Verbindung verloren. Versuche erneut...
09:16:32.470 -> Verbindung zum MQTT-Server wird hergestellt...verbunden!
09:16:32.470 -> MQTT-Verbindung verloren. Versuche erneut...
09:16:32.470 -> Verbindung zum MQTT-Server wird hergestellt...verbunden!

if i then go to the web interface and click on ‘speichern’ (means ´save´) once, from then on everything runs stable and the connection remains established and everything is fine.
I have no idea why. :frowning:

09:16:36.507 -> Verbindung zum MQTT-Server wird hergestellt...verbunden!
09:16:36.541 -> Konfiguration gespeichert.
09:16:36.541 -> MQTT-Verbindung verloren. Versuche erneut...
09:16:36.578 -> Verbindung zum MQTT-Server wird hergestellt...verbunden!
09:16:37.371 -> Echter Wert: 0.00 A | Gerundeter Wert: 0 A
09:16:37.371 -> MQTT Nachricht gesendet: home/huawei_magenta - 0 A
09:16:42.350 -> Echter Wert: 0.00 A | Gerundeter Wert: 0 A
09:16:42.350 -> MQTT Nachricht gesendet: home/huawei_magenta - 0 A
09:16:47.331 -> Echter Wert: 0.00 A | Gerundeter Wert: 0 A
09:16:47.331 -> MQTT Nachricht gesendet: home/huawei_magenta - 0 A
09:16:52.330 -> Echter Wert: 0.00 A | Gerundeter Wert: 0 A
09:16:52.330 -> MQTT Nachricht gesendet: home/huawei_magenta - 0 A

here is the code. maybe someone can help me.

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <ESP8266WebServer.h>
#include <LittleFS.h>  

const char* ssid = "fghfghfghfgh";
const char* password = "fhgfhgfhgfgh";
const char* mqttServer = "192.168.178.44";
const int mqttPort = 1883;

// Versionsnummer
const String firmwareVersion = "10.0.0";  // Setze die Versionsnummer

WiFiClient espClient;
PubSubClient client(espClient);
ESP8266WebServer server(80);

LiquidCrystal_I2C lcd(0x27, 16, 2);
const int analogPin = A0;

float realCurrentAmps = 0.0;
int roundedCurrentAmps = 0;
float offsetVoltage = 0.0;  // Offset für Kalibrierung
unsigned long previousMillis = 0;

int threshold = 18;
unsigned long intervalInMillis = 3000;
unsigned long lastMeasurementTime = 0;
unsigned long lastThresholdCheckTime = 0;

String mqttRegularTopic = "home/huawei_magenta";
String mqttThresholdTopic = "home/action";  // Neue Variable für das Schwellwert-Topic

unsigned long lastUpdateTime = 0;
const long displayInterval = 1000;

void setup() {
  Serial.begin(115200);
  Wire.begin();
  lcd.begin(16, 2);
  lcd.setBacklight(1);

  // Zeige die Versionsnummer einmalig beim Booten auf der seriellen Konsole
  Serial.println("Bootvorgang startet...");
  Serial.print("Firmware Version: ");
  Serial.println(firmwareVersion);  // Zeigt die Versionsnummer an

  if (!LittleFS.begin()) {
    Serial.println("Fehler beim Mounten des Dateisystems!");
    return;
  }

  loadConfig();  // Konfiguration laden
  setupWiFi();
  client.setServer(mqttServer, mqttPort);
  lcd.clear();
  lcd.print("Starte...");

  calibrateSensor();  // Nullpunkt-Kalibrierung
  
  server.begin();
  server.on("/", HTTP_GET, handleRoot);
  server.on("/save", HTTP_POST, handleSave);
  server.on("/currentAmps", HTTP_GET, handleCurrentAmps);
}

void loop() {
  server.handleClient();
  client.loop();

  unsigned long currentMillis = millis();

  if (currentMillis - lastMeasurementTime >= intervalInMillis) {
    lastMeasurementTime = currentMillis;
    
    realCurrentAmps = getRealCurrentAmps();
    roundedCurrentAmps = round(realCurrentAmps);

    Serial.print("Echter Wert: ");
    Serial.print(realCurrentAmps, 2);
    Serial.print(" A | Gerundeter Wert: ");
    Serial.print(roundedCurrentAmps);
    Serial.println(" A");

    sendData();
  }

  if (currentMillis - lastThresholdCheckTime >= intervalInMillis) {
    lastThresholdCheckTime = currentMillis;
    if (roundedCurrentAmps > threshold) {
      sendThresholdActionMessage();
    }
  }

  if (currentMillis - lastUpdateTime >= displayInterval) {
    lastUpdateTime = currentMillis;
    updateDisplay();
  }

  if (!client.connected()) {
    Serial.println("MQTT-Verbindung verloren. Versuche erneut...");
    reconnect();
  }
}

void setupWiFi() {
  delay(10);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print("...");
  }
  Serial.println("WiFi verbunden");
  Serial.print("IP-Adresse: ");
  Serial.println(WiFi.localIP());
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Verbindung zum MQTT-Server wird hergestellt...");
    if (client.connect("ESP8266Client")) {
      Serial.println("verbunden!");
      client.subscribe(mqttRegularTopic.c_str());
    } else {
      Serial.print("Fehler, rc=");
      Serial.print(client.state());
      delay(5000);
    }
  }
}

// Nullpunkt-Kalibrierung durchführen
void calibrateSensor() {
  Serial.println("Starte Nullpunkt-Kalibrierung...");
  float sumVoltage = 0;
  int numReadings = 100;

  for (int i = 0; i < numReadings; i++) {
    sumVoltage += (analogRead(analogPin) / 1024.0) * 3.3;
    delay(10);
  }

  offsetVoltage = sumVoltage / numReadings;
  Serial.print("Kalibrierter Offset: ");
  Serial.print(offsetVoltage, 3);
  Serial.println(" V");
}

// Strommessung mit Offset-Kompensation
float getRealCurrentAmps() {
  int sensorValue = analogRead(analogPin);
  float voltage = (sensorValue / 1024.0) * 3.3;
  float current = (voltage - offsetVoltage) / 0.185;

  if (abs(current) < 0.1) { // Werte unter 0.1 A als 0 betrachten
    current = 0.0;
  }

  return current;
}

void sendData() {
  char payload[10];
  snprintf(payload, sizeof(payload), "%d", roundedCurrentAmps);
  if (client.publish(mqttRegularTopic.c_str(), payload)) {
    Serial.println("MQTT Nachricht gesendet: " + mqttRegularTopic + " - " + String(roundedCurrentAmps) + " A");
  } else {
    Serial.println("Fehler beim Senden der Nachricht.");
  }
}

void sendThresholdActionMessage() {
  char payload[10];
  snprintf(payload, sizeof(payload), "%d", roundedCurrentAmps);
  if (client.publish(mqttThresholdTopic.c_str(), payload)) {
    Serial.println("Schwellwert-Action Nachricht gesendet!");
  } else {
    Serial.println("Fehler beim Senden der Schwellwert-Action Nachricht.");
  }
}

void updateDisplay() {
  lcd.setCursor(0, 0);
  lcd.print("Strom: ");
  lcd.print(roundedCurrentAmps);
  lcd.print(" A");

  lcd.setCursor(0, 1);
  lcd.print(WiFi.localIP());
}

void handleRoot() {
  String html = "<html><head><meta charset='UTF-8'>";
  html += "<style>";
  html += "body { font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px; }";
  html += "h1 { color: #333; }";
  html += "form { background-color: #fff; padding: 20px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); max-width: 400px; margin: 0 auto; }";
  html += "input[type='text'], input[type='number'] { width: 100%; padding: 10px; margin: 10px 0; border: 1px solid #ccc; border-radius: 5px; }";
  html += "input[type='submit'] { background-color: #4CAF50; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; }";
  html += "input[type='submit']:hover { background-color: #45a049; }";
  html += "h2 { margin-top: 20px; color: #333; font-size: 1.2em; }";
  html += ".icon { font-size: 24px; margin-right: 10px; }";
  html += "</style>";
  html += "</head><body>";
  html += "<h1>Setup Strommessgerät</h1>";
  html += "<form action='/save' method='POST'>";
  html += "<label><span class='icon'>📡</span>MQTT Topic (Normal): <input type='text' name='mqttRegularTopic' value='" + String(mqttRegularTopic) + "'></label>";
  html += "<label><span class='icon'>⚠️</span>MQTT Topic (Schwellwert - Notfall): <input type='text' name='mqttThresholdTopic' value='" + String(mqttThresholdTopic) + "'></label>";
  html += "<label><span class='icon'>⚡</span>Schwellwert (A): <input type='number' name='threshold' value='" + String(threshold) + "'></label>";
  html += "<label><span class='icon'>⏱️</span>Intervall (s): <input type='number' name='repeatInterval' value='" + String(intervalInMillis / 1000) + "'></label>";
  html += "<input type='submit' value='Speichern'>";
  html += "</form>";

  // Version auf der Weboberfläche anzeigen
  html += "<h2>Firmware Version: " + firmwareVersion + "</h2>";

  html += "</body></html>";
  server.send(200, "text/html", html);
}

void handleSave() {
  if (server.hasArg("mqttRegularTopic")) {
    mqttRegularTopic = server.arg("mqttRegularTopic");
  }
  if (server.hasArg("mqttThresholdTopic")) {
    mqttThresholdTopic = server.arg("mqttThresholdTopic");
  }
  if (server.hasArg("threshold")) {
    threshold = server.arg("threshold").toInt();
  }
  if (server.hasArg("repeatInterval")) {
    intervalInMillis = server.arg("repeatInterval").toInt() * 1000;
  }
  saveConfig();
  server.send(200, "text/html", "<html><head><meta charset='UTF-8'></head><body><h1>Änderungen gespeichert</h1><p><a href='/'>Zurück</a></p></body></html>");
}

void handleCurrentAmps() {
  String jsonResponse = "{\"currentAmps\": " + String(roundedCurrentAmps) + "}";
  server.send(200, "application/json", jsonResponse);
}

void saveConfig() {
  File configFile = LittleFS.open("/config.txt", "w");
  if (!configFile) {
    Serial.println("Fehler beim Speichern der Konfiguration!");
    return;
  }

  configFile.println(mqttRegularTopic);
  configFile.println(mqttThresholdTopic);  // Speichern des neuen Topics
  configFile.println(threshold);
  configFile.println(intervalInMillis);

  configFile.close();
  Serial.println("Konfiguration gespeichert.");
}

void loadConfig() {
  File configFile = LittleFS.open("/config.txt", "r");
  if (!configFile) {
    Serial.println("Fehler beim Laden der Konfiguration!");
    return;
  }

  mqttRegularTopic = configFile.readStringUntil('\n');
  mqttThresholdTopic = configFile.readStringUntil('\n');  // Laden des neuen Topics
  threshold = configFile.readStringUntil('\n').toInt();
  intervalInMillis = configFile.readStringUntil('\n').toInt();

  configFile.close();
  Serial.println("Konfiguration geladen.");
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.