#include "AppGlobals.h"
#include "Helpers.h"
#include "WebUi.h"
#include "MqttSensor.h"
#include "WebPages.h"

void setup() {
  Serial.begin(115200);
  delay(200);
  Serial.println();
  Serial.println(F("NodeMCU TempMQTT v1.9 starter"));
  loadConfig();
  pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW);
  restartDht();
  Wire.begin(D2, D1);
  display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR);
  updateDisplay();
  connectWifiOrPortal();
  if (!portalMode && WiFi.isConnected()) { MDNS.begin(cfg.hostname); MDNS.addService("http", "tcp", 80); }
  setupMqtt();
  startWeb();
  logHealth("setup done");
}

void loop() {
  if (portalMode) dnsServer.processNextRequest();
  server.handleClient();
  if (!portalMode) MDNS.update();
  if (!portalMode && WiFi.status() != WL_CONNECTED && millis() - lastWifiAttempt > 10000) {
    lastWifiAttempt = millis(); WiFi.begin(cfg.wifiSsid, cfg.wifiPassword);
  }
  connectMqttNonBlocking();
  mqtt.loop();
  readAndPublish();
  logHealthTimed();
}
