#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>

// Wi-Fi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";

// HTTP server endpoint
const char* serverName = "https://moodlog-backend.onrender.com/data/predict";

// DHT sensor configuration
#define DHT_SENSOR_PIN  32 // ESP32 pin GPIO32 connected to DHT22 sensor
#define DHT_SENSOR_TYPE DHT22

DHT dht_sensor(DHT_SENSOR_PIN, DHT_SENSOR_TYPE);

// LED pin configuration
int led_red = 18;
int led_green = 17;
int led_blue = 16;

// Temperature threshold in Celsius
const float TEMP_THRESHOLD = 30.0;

void setup() {
  Serial.begin(115200);
  Serial.println("Hello, ESP32!");

  // Initialize DHT sensor
  dht_sensor.begin();

  // Initialize LED pins
  pinMode(led_red, OUTPUT);
  pinMode(led_green, OUTPUT);
  pinMode(led_blue, OUTPUT);

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("Connected to WiFi");
}

void loop() {
  // Read temperature in Celsius
  float tempC = dht_sensor.readTemperature();

  // Check if reading was successful
  if (isnan(tempC)) {
    Serial.println("Error reading the sensor");
  } else {
    Serial.print("Temperature: ");
    Serial.print(tempC);
    Serial.println("°C");

    // Check temperature threshold
    if (tempC >= TEMP_THRESHOLD) {
      digitalWrite(led_red, HIGH); // Turn on red LED
    } else {
      digitalWrite(led_red, LOW);  // Turn off red LED
    }
  }

  // Read humidity
  float humidity = dht_sensor.readHumidity();
  if (isnan(humidity)) {
    Serial.println("Error reading the sensor");
  } else {
    Serial.print("Humidity: ");
    Serial.print(humidity);
    Serial.println(" %");
  }

  // Send data to server if WiFi is connected
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;

    // Begin HTTP connection
    http.begin(serverName);

    // Specify content-type header
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");

    // Data to send in the POST request
    String httpRequestData = "temperature=" + String(tempC) + "&humidity=" + String(humidity);

    // Send POST request
    int httpResponseCode = http.POST(httpRequestData);

    // Print response
    if (httpResponseCode > 0) {
      String response = http.getString();
      Serial.println(httpResponseCode);
      Serial.println(response);
    } else {
      Serial.print("Error on sending POST: ");
      Serial.println(httpResponseCode);
    }

    // Free resources
    http.end();
  } else {
    Serial.println("WiFi Disconnected");
  }

  delay(2000); // Wait for 2 seconds
}
esp:VIN
esp:GND.2
esp:D13
esp:D12
esp:D14
esp:D27
esp:D26
esp:D25
esp:D33
esp:D32
esp:D35
esp:D34
esp:VN
esp:VP
esp:EN
esp:3V3
esp:GND.1
esp:D15
esp:D2
esp:D4
esp:RX2
esp:TX2
esp:D5
esp:D18
esp:D19
esp:D21
esp:RX0
esp:TX0
esp:D22
esp:D23
dht1:VCC
dht1:SDA
dht1:NC
dht1:GND
led1:A
led1:C
r1:1
r1:2