/***************************************************
  Juni 2025
  HTU Sensor mit MQTT Broker Verbindung
  Ausgabe am seriellen Monitor
 ****************************************************/

#include <Wire.h>
#include <Adafruit_HTU21DF.h>
#include "myMQTT.h"

// Connect Vin to 3-5VDC
// Connect GND to ground
// Connect SCL to I2C clock pin (A5 on UNO)
// Connect SDA to I2C data pin (A4 on UNO)

Adafruit_HTU21DF htu = Adafruit_HTU21DF();

unsigned long lastSensorTime = 0;
const int intervalSensor = 15000;  // 15 sek
unsigned long lastTestTime = 0;
const int intervalMQTT_Test = 60000;  // 1 min

unsigned long counterDisconnect = 0;

//--------- setup
void setup() {
  Serial.begin(115200);
  Serial.println("\n\n************  HTU21D-F Test mit MQTT - Verbindung");
  pinMode(BUILT_IN_LED, OUTPUT);

  if (!htu.begin()) {
    Serial.println("Couldn't find sensor!");
    while (1);  // Endlosschleife
  }

  // WLAN Verbindung herstellen
  Serial.print("\nWiFi try to connect...");
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    digitalWrite(BUILT_IN_LED, !digitalRead(BUILT_IN_LED));
  }

  digitalWrite(BUILT_IN_LED, HIGH);  // LED aus

  Serial.print("\nWiFi connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.print("MAC address:  ");
  Serial.println(WiFi.macAddress());
  str_WiFi_IP = WiFi.localIP().toString();

  // MQTT Verbindung herstellen
  startMQTT();    // siehe myMQTT.h

  Serial.println("\nStart loop...\n ");
}

//------------- main loop
void loop() {
  // MQTT Verbindung prüfen und wiederherstellen, wenn nötig.  kein delay() verwenden
  if (millis() > lastTestTime + intervalMQTT_Test) {
    if (!client.connected()) {
      counterDisconnect++;
      reconnect();      // Verbindung wieder herstellen, wenn getrennt
    } else {
      Serial.println("MQTT still connected.");
      publishMessage(mqtt_LWT_Topic, "online", retain);
      publishMessage(mqtt_DeviceName_Topic, deviceName, retain);
      publishMessage(mqtt_DevicePlace_Topic, devicePlace, retain);  
      publishMessage(mqtt_debug_Topic, String(counterDisconnect), retain);
    }
    lastTestTime = millis();
  }
  client.loop();

  // Sensor Abfrage in bestimmten Zeitinterval, kein delay() verwenden
  if (millis() > lastSensorTime + intervalSensor) {
    float temp = htu.readTemperature();
    float rel_hum = htu.readHumidity();

    Serial.print("Temp: ");
    Serial.print(temp);
    Serial.print(" °C");
    Serial.print("\t\t");

    Serial.print("Humidity: ");
    Serial.print(rel_hum);
    Serial.println(" \%rel");

    publishMessage(mqtt_DHT_Temp_Topic, String(temp, 1).c_str(), retain);
    publishMessage(mqtt_DHT_Luft_Topic, String(rel_hum, 0).c_str(), retain);

    lastSensorTime = millis();
  }
}
