#include <ESP32Servo.h>
#include "DHT.h"

#define DHT_PIN 2
#define DHTTYPE DHT22
DHT dht(DHT_PIN, DHTTYPE);

const int SERVO_PIN = 17;
const int POTENTIOMETER_PIN = 35;
const int RGB_R = 25;
const int RGB_G = 33;
const int RGB_B = 32;

float hum=10;
float temp=10;

Servo servo;

float co2Threshold = 350;
float temperatureThreshold = 30;

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

  pinMode(POTENTIOMETER_PIN, INPUT);

  pinMode(RGB_R, OUTPUT);
  pinMode(RGB_G, OUTPUT);
  pinMode(RGB_B, OUTPUT);

  servo.attach(SERVO_PIN);
  servo.write(90);
}

void loop() {
  // Scenario 1: CO2 élevé
  int potentiometerValue = analogRead(POTENTIOMETER_PIN);
  potentiometerValue = map(potentiometerValue, 0, 1023, 0, 180);
  Serial.println(potentiometerValue);
  if (potentiometerValue > co2Threshold) {
    servo.write(0); // Servo ouvre complètement les fenêtres
    delay(1000);    // Attendre 1 seconde
    servo.write(90); // Revenir à la position fermée
  } else {
    servo.write(90);
  }

  // Scenario 2: Température
  //TempAndHumidity  data = dhtSensor.getTempAndHumidity();
   hum = dht.readHumidity();
   temp = dht.readTemperature();  
  if (isnan(hum) || isnan(temp)  ){
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }
  else{
  Serial.println("Temp: " + String(temp, 2) + "°C");
  Serial.println("Humidity: " + String(hum, 1) + "%");
  if(temp > 25){
      Serial.println("bigger then threshold (23 °C) => Cooling");
      analogWrite(RGB_R,   0);
      analogWrite(RGB_G, 0);
      analogWrite(RGB_B,  255);
    }else{
      Serial.println("smaller then threshold (23 °C) => Heating");
      analogWrite(RGB_R,   255);
      analogWrite(RGB_G, 0);
      analogWrite(RGB_B,  0);
    }
  }
    
  
}