// Smart Room Climate Monitor — XBOTNOW
// Board: ESP32-DevKitC V4 · Core: esp32 v3.x
// Libraries: Adafruit SHT31, Adafruit SSD1306, Adafruit GFX
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Wire.h>
#include <Adafruit_SHT31.h>
#include <Adafruit_SSD1306.h>
#include "secrets.h"

Adafruit_SHT31 sht;
Adafruit_SSD1306 oled(128, 64, &Wire, -1);
WebServer server(80);
float tempC = NAN, hum = NAN;
unsigned long lastRead = 0;

const char PAGE[] PROGMEM = R"HTML(
<!doctype html><meta name=viewport content="width=device-width">
<title>Room climate</title>
<body style="font-family:sans-serif;text-align:center;padding:2em">
<h2>Room climate</h2><p style="font-size:3em"><span id=t>--</span> &deg;C</p>
<p style="font-size:3em"><span id=h>--</span> %</p><small id=s>Live hardware</small>
<script>
setInterval(async()=>{try{const d=await (await fetch('/data')).json();
t.textContent=d.ok?d.t.toFixed(1):'err';h.textContent=d.ok?d.h.toFixed(0):'err';}
catch(e){s.textContent='Connection lost';}},2000);
</script>)HTML";

void handleData() {
  bool ok = !isnan(tempC) && !isnan(hum);
  String json = String("{\"ok\":") + (ok ? "true" : "false") +
                ",\"t\":" + (ok ? String(tempC, 2) : "null") +
                ",\"h\":" + (ok ? String(hum, 1) : "null") + "}";
  server.send(200, "application/json", json);
}

void setup() {
  Serial.begin(115200);
  Wire.begin(21, 22);
  if (!sht.begin(0x44)) Serial.println("SHT31 not found");
  if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) Serial.println("OLED not found");
  oled.setTextColor(SSD1306_WHITE);

  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) { delay(300); Serial.print('.'); }
  MDNS.begin("xbot-climate");
  Serial.printf("\nDashboard: http://xbot-climate.local  (%s)\n", WiFi.localIP().toString().c_str());

  server.on("/", [] { server.send_P(200, "text/html", PAGE); });
  server.on("/data", handleData);
  server.begin();
}

void loop() {
  server.handleClient();
  if (millis() - lastRead < 2000) return;
  lastRead = millis();

  tempC = sht.readTemperature();   // NAN on failure
  hum = sht.readHumidity();

  oled.clearDisplay();
  oled.setTextSize(2);
  oled.setCursor(0, 8);
  if (isnan(tempC)) oled.print("Sensor err");
  else { oled.printf("%.1f C", tempC); oled.setCursor(0, 40); oled.printf("%.0f %%", hum); }
  oled.display();
}
