#include <ESP32Servo.h>
#define POT_PIN 2
Servo servo;  // create servo object to control a servo

  //Seuil CO2 (Scenario 1)
const int CO2_UNDER_7500 = 45;
const int CO2_UNDER_10000 = 90;
const int CO2_UNDER_15000 = 135;
// L'angle d'ouvertures courante du servo 
int CURRENT_ANGLE = 0;
  //co2 controler
   int angleFromPot(){

  //lire valeur du potentiometre
 int potValue = analogRead(POT_PIN);

  Serial.println(potValue);
  potValue = map(potValue, 0, 4095, 0, 17000);//concentration du CO2 (0ppm - 3000ppm)
  
  //choisir l'angle d'ouverture de la fenetre
  int angle = 0;
  if(potValue <400){
    angle = 0;
    Serial.println("CO2 concentration below 400ppm, close window");
  }else if(potValue < 7500){
    angle = CO2_UNDER_7500;
    Serial.print("CO2 concentration below 7500ppm, open window by ");
    Serial.println(CO2_UNDER_7500);
  }else if(potValue < 10000){
    angle = CO2_UNDER_10000;
    Serial.print("CO2 concentration below 10000ppm, open window by ");
    Serial.println(CO2_UNDER_10000);
  }else if(potValue < 15000){
    angle = CO2_UNDER_15000;
    Serial.print("CO2 concentration below 15000ppm, open window by ");
    Serial.println(CO2_UNDER_15000);
  }else{
    Serial.println("CO2 concentration over 15000ppm, open window fully");
    angle = 180;
  }

  return angle;

}
void fenetre(){

  //angle d'ouverture selon concentration CO2
  int firstAngle = angleFromPot();

  

  //changer l'angle d'ouverture du servo
  int difference = CURRENT_ANGLE - angle;
  if(difference < 0){
    ouvrirServo(abs(difference));
  }else{
    fermerServo(difference);
  }
  CURRENT_ANGLE = angle;
  
}
void ouvrirServo(int angle) {
  for (int i = 0; i <= angle; i++) {
    servo.write(CURRENT_ANGLE + i);
    delay(15);
  }
}

void fermerServo(int angle) {
  for (int i = 0; i <= angle; i++) {
    servo.write(CURRENT_ANGLE - i);
    delay(15);
  }
}
void setup() {
  Serial.begin(115200);
  //initialisation du servo
   servo.attach(SERVO_PIN);
  servo.write(0);
}