/*
  NodeMCU TempMQTT WebConfig
  Version: 1.9
  Jens Krogsgaard / ChatGPT

  ESP8266 NodeMCU + DHT11 + OLED SSD1306 + LED

  Pins:
    DHT11 data: D5 / GPIO14
    OLED SCL:   D1 / GPIO5
    OLED SDA:   D2 / GPIO4
    LED:        D4 / GPIO2

  Libraries:
    ESP8266 core, DHTesp, PubSubClient, ArduinoJson,
    Adafruit_GFX, Adafruit_SSD1306
*/

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <Updater.h>
#include <ESP8266mDNS.h>
#include <DNSServer.h>
#include <WiFiClientSecureBearSSL.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <EEPROM.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHTesp.h>

#define APP_NAME       "NodeMCU TempMQTT"
#define APP_VERSION    "1.9"

const char ICON_TEMP_MQTT[] PROGMEM = R"SVG(<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 128 128'><rect x='7' y='7' width='114' height='114' rx='21' fill='white' stroke='#dfe5ea' stroke-width='5'/><g fill='none' stroke='#e11' stroke-width='8' stroke-linecap='round' stroke-linejoin='round'><path d='M36 72V25a12 12 0 0 1 24 0v47'/><path d='M42 39h18M42 52h18M42 65h18'/><circle cx='48' cy='87' r='20' fill='#ff2b12'/><path d='M48 72V31'/></g><g fill='none' stroke='#0b74e8' stroke-width='9' stroke-linecap='round'><path d='M76 28c15 0 26 11 26 26'/><path d='M76 47c7 0 12 5 12 12'/></g><circle cx='74' cy='65' r='8' fill='#0b74e8'/><path d='M92 70c11 15 19 27 19 37a21 21 0 0 1-42 0c0-10 10-24 23-37z' fill='#0b74e8'/><path d='M82 106c0 9 6 13 13 13' fill='none' stroke='white' stroke-width='5' stroke-linecap='round'/></svg>)SVG";
// Flagene tegnes med CSS i v1.6 for at spare RAM/heap.
#define EEPROM_SIZE    3072
#define DEFAULT_DHT_PIN D5
#define LED_PIN        D4
#define OLED_ADDR      0x3C
#define SCREEN_WIDTH   128
#define SCREEN_HEIGHT  64

struct AppConfig {
  uint32_t magic;
  char hostname[32];
  char language[4];
  char wifiSsid[64];
  char wifiPassword[64];
  char mqttHost[96];
  uint16_t mqttPort;
  char mqttUser[64];
  char mqttPassword[64];
  bool mqttTls;
  char topicTemp[128];
  char topicHum[128];
  char topicLed[128];
  uint32_t publishIntervalMs;
  bool retained;
  char sensorName[32];
  uint8_t dhtPin;
  uint8_t dhtType; // 11 = DHT11, 22 = DHT22 / AM2302
};

const uint32_t CONFIG_MAGIC = 0x544D5132; // TMQ2
AppConfig cfg;

ESP8266WebServer server(80);
DNSServer dnsServer;
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
DHTesp dht;

WiFiClient plainClient;
BearSSL::WiFiClientSecure secureClient;
PubSubClient mqtt;

bool portalMode = false;
bool ledState = false;
float lastTemp = NAN;
float lastHum = NAN;
unsigned long lastPublish = 0;
unsigned long lastWifiAttempt = 0;
unsigned long lastMqttAttempt = 0;
unsigned long lastLog = 0;
uint32_t minFreeHeap = 0xFFFFFFFF;
uint32_t lastFreeHeap = 0;
String lastDhtStatus = "-";
String lastMqttStatus = "-";

