# main.ino

- Project: [esp8266-dht22](https://flashesp.com/explore/r5zDq4dMc70eYikmCnHve.md) by Mikrobot.pl
- Board: NodeMCU 1.0 (ESP-12E Module)
- Language: Arduino (C++)
- Web page: https://flashesp.com/explore/r5zDq4dMc70eYikmCnHve/files/7V7yHRTcgfrPLljGhnJpO

```cpp
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>

#include <DHT.h>
#include <Adafruit_Sensor.h>

// -------------------- Wi-Fi Captive Portal settings --------------------
static const char* AP_SSID = "DHT22-Portal";
static const char* AP_PASS = ""; // empty = open network

static const byte DNS_PORT = 53;
DNSServer dnsServer;
ESP8266WebServer webServer(80);

IPAddress apIP(192, 168, 4, 1);
IPAddress netMsk(255, 255, 255, 0);

// -------------------- DHT22 settings --------------------
// GPIO4 = D2 on NodeMCU / Wemos D1 mini
#define DHT_PIN   4
#define DHT_TYPE  DHT22

DHT dht(DHT_PIN, DHT_TYPE);

float lastTempC = NAN;
float lastHum = NAN;
unsigned long lastReadMs = 0;

static const unsigned long READ_INTERVAL_MS = 2000;

// -------------------- Helpers --------------------
String formatFloat(float v, uint8_t decimals = 1) {
  if (isnan(v)) return "N/A";
  return String(v, decimals);
}

void readDHTIfDue() {
  unsigned long now = millis();

  if (lastReadMs != 0 && now - lastReadMs < READ_INTERVAL_MS) {
    return;
  }

  lastReadMs = now;

  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (!isnan(h)) lastHum = h;
  if (!isnan(t)) lastTempC = t;

  Serial.print("DHT22 -> T: ");
  Serial.print(formatFloat(lastTempC));
  Serial.print(" C, H: ");
  Serial.print(formatFloat(lastHum));
  Serial.println(" %");
}

// -------------------- Web handlers --------------------
void handleRoot() {
  String page =
    "<!doctype html><html><head>"
    "<meta charset='utf-8'/>"
    "<meta name='viewport' content='width=device-width,initial-scale=1'/>"
    "<title>DHT22 Captive Portal</title>"
    "<style>"
    "body{font-family:Arial,sans-serif;margin:16px;background:#f7f7f7;}"
    ".card{max-width:720px;padding:16px;border:1px solid #ddd;border-radius:12px;background:white;}"
    ".row{display:flex;gap:12px;flex-wrap:wrap;}"
    ".pill{display:inline-block;padding:6px 10px;border-radius:999px;border:1px solid #ccc;}"
    ".big{font-size:28px;font-weight:700;margin:16px 0;line-height:1.4;}"
    "</style>"
    "</head><body>"
    "<div class='card'>"
    "<h2>ESP8266 DHT22 Captive Portal</h2>"
    "<div class='row'>"
    "<div class='pill'>SSID: <b>" + String(AP_SSID) + "</b></div>"
    "<div class='pill'>IP: <b>" + apIP.toString() + "</b></div>"
    "</div>"

    "<p>Odczyty odświeżają się automatycznie.</p>"

    "<div class='big'>"
    "Temp: <span id='t'>--</span> &deg;C<br/>"
    "Humidity: <span id='h'>--</span> %"
    "</div>"

    "<div id='meta' class='pill'>Loading...</div>"

    "<p style='margin-top:12px;'>Jeżeli portal nie otworzy się automatycznie, wejdź na "
    "<b>http://" + apIP.toString() + "/</b></p>"

    "</div>"

    "<script>"
    "function refresh(){"
    "  fetch('/data')"
    "    .then(function(r){ return r.json(); })"
    "    .then(function(j){"
    "      document.getElementById('t').textContent = j.temp_c === null ? 'N/A' : j.temp_c.toFixed(1);"
    "      document.getElementById('h').textContent = j.hum === null ? 'N/A' : j.hum.toFixed(1);"
    "      document.getElementById('meta').textContent = 'Age: ' + j.age_ms + ' ms';"
    "    })"
    "    .catch(function(e){"
    "      document.getElementById('meta').textContent = 'Error: ' + e;"
    "    });"
    "}"
    "setInterval(refresh, 1000);"
    "refresh();"
    "</script>"

    "</body></html>";

  webServer.send(200, "text/html", page);
}

void handleData() {
  readDHTIfDue();

  unsigned long age = lastReadMs == 0 ? 0 : millis() - lastReadMs;

  String json = "{";

  if (isnan(lastTempC)) {
    json += "\"temp_c\":null,";
  } else {
    json += "\"temp_c\":" + String(lastTempC, 1) + ",";
  }

  if (isnan(lastHum)) {
    json += "\"hum\":null,";
  } else {
    json += "\"hum\":" + String(lastHum, 1) + ",";
  }

  json += "\"age_ms\":" + String(age);
  json += "}";

  webServer.send(200, "application/json", json);
}

void redirectToRoot() {
  webServer.sendHeader("Location", String("http://") + apIP.toString() + "/", true);
  webServer.send(302, "text/plain", "");
}

void handleNotFound() {
  redirectToRoot();
}

void setupCaptivePortal() {
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(apIP, apIP, netMsk);

  delay(100);

  if (strlen(AP_PASS) == 0) {
    WiFi.softAP(AP_SSID);
  } else {
    // ESP8266 wymaga hasła WPA/WPA2 minimum 8 znaków
    WiFi.softAP(AP_SSID, AP_PASS);
  }

  delay(500);

  dnsServer.start(DNS_PORT, "*", apIP);

  webServer.on("/", handleRoot);
  webServer.on("/data", handleData);

  // Typowe adresy sprawdzające captive portal:
  webServer.on("/generate_204", redirectToRoot);              // Android
  webServer.on("/gen_204", redirectToRoot);                   // Android
  webServer.on("/hotspot-detect.html", handleRoot);           // iOS/macOS
  webServer.on("/library/test/success.html", handleRoot);     // iOS
  webServer.on("/ncsi.txt", handleRoot);                      // Windows
  webServer.on("/connecttest.txt", handleRoot);               // Windows

  webServer.onNotFound(handleNotFound);

  webServer.begin();
}

void setup() {
  Serial.begin(115200);
  delay(200);

  Serial.println();
  Serial.println("Starting...");

  dht.begin();

  setupCaptivePortal();

  Serial.println("Captive portal started.");
  Serial.print("Connect to AP: ");
  Serial.println(AP_SSID);
  Serial.print("Open: http://");
  Serial.println(apIP);

  readDHTIfDue();
}

void loop() {
  dnsServer.processNextRequest();
  webServer.handleClient();
  readDHTIfDue();
}
```
