/*
  Juni 2025
	14_HTU_WebServer1.ino
	
	Ein Webserver zur Anzeige der HTU-Sensor Daten: Temperatur und Luftfeuchte.

  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp8266-nodemcu-bme680-sensor-arduino/
  
*/

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_HTU21DF.h>
#include <ESP8266WiFi.h>
#include <ESPAsyncWebServer.h>
#include "myHTML.h"

Adafruit_HTU21DF  htu = Adafruit_HTU21DF();     // Sensor Objekt erzeugen

// Replace with your network credentials
const char* ssid     = "HSB-Gast";
const char* password = "";


float temperature=0;
float humidity=0;
float pressure=0;
float gasResistance=0;

AsyncWebServer server(80);
AsyncEventSource events("/events");

unsigned long lastTime = 0;  
unsigned long timerDelay = 6000;  // send readings timer

void getBMEReadings(){
  temperature = htu.readTemperature();
  pressure = 0.0;
  humidity = htu.readHumidity();
  gasResistance = 0.0;
}

// Beschreibt die HTML Seite 
String processor(const String& var){
  getBMEReadings();
  //Serial.println(var);
  if(var == "TEMPERATURE"){
    return String(temperature);
  }
  else if(var == "HUMIDITY"){
    return String(humidity);
  }
  else if(var == "PRESSURE"){
    return String(pressure);
  }
  else if(var == "GAS"){
    return String(gasResistance);
  }
  return String();
}


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

  if (!htu.begin()) {         // Sensor start
    Serial.println("Couldn't find sensor!");
  }

  Serial.println("\n\n14 - HTU-Senosr - WebServer !\n\n");

  // Set the device as a Station and Soft Access Point simultaneously
  WiFi.mode(WIFI_AP_STA);
  
  // Set device as a Wi-Fi Station
  WiFi.begin(ssid, password);
  Serial.print("Setting as a Wi-Fi Station..");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.print("\nWiFi connected to ");
  Serial.print(WiFi.SSID());
  Serial.print("\tStation IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.println();


  // Handle Web Server
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/html", index_html, processor);
  });

  // Handle Web Server Events
  events.onConnect([](AsyncEventSourceClient *client){
    if(client->lastId()){
      Serial.printf("Client reconnected! Last message ID that it got is: %u\n", client->lastId());
    }
    // send event with message "hello!", id current millis
    // and set reconnect delay to 1 second
    client->send("hello!", NULL, millis(), 10000);
  });
  server.addHandler(&events);
  server.begin();
}

void loop() {
  if ((millis() - lastTime) > timerDelay) {
    getBMEReadings();
    Serial.printf("Temperature = %.2f ºC \n", temperature);
    Serial.printf("Humidity = %.2f % \n", humidity);
    Serial.printf("Pressure = %.2f hPa \n", pressure);
    Serial.println();

    // Send Events to the Web Server with the Sensor Readings
    events.send("ping",NULL,millis());
    events.send(String(temperature).c_str(),"temperature",millis());
    events.send(String(humidity).c_str(),"humidity",millis());
    events.send(String(pressure).c_str(),"pressure",millis());
     
    lastTime = millis();
  }
}
