#include "LittleFS.h"
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <WiFi.h>

int Ledverte = 33;

#include <ESP32Servo.h>
Servo myservo;

const char *ssid = "......";  // "Votre Nom_du_routeur"
const char *password = "......";  // "Votre Mot_de_passe_du_routeur"
AsyncWebServer server(80);

int ValeurRange = 0;

void setup() {
  Serial.begin(115200);
  myservo.attach(23);
  pinMode(Ledverte, OUTPUT);

  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  // Imprimer l'adresse IP locale ESP
  Serial.println(WiFi.localIP());

  if (!LittleFS.begin()) {
    Serial.println("An Error has occurred while mounting LittleFS");
    return;
  }

  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send(LittleFS, "/index.html", "text/html");
  });

  server.on("/script.js", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send(LittleFS, "/script.js", "text/javascript");
  });

  server.on("/read_ValueRange", HTTP_GET, [](AsyncWebServerRequest *request) {
    String message = String(ValeurRange);
    request->send(200, "text/plain", message);
  });


  server.on("/write_ValueRange", HTTP_POST, [](AsyncWebServerRequest *request) {
    if (request->hasParam("ValueRange", true)) {
      String message;
      message = request->getParam("ValueRange", true)->value();
      ValeurRange = message.toInt();
    }
    request->send(204);
  });


  // Démarrer le serveur
  server.begin();
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    digitalWrite(Ledverte, HIGH);  
  } else {
    digitalWrite(Ledverte, LOW);
  }
  myservo.write(ValeurRange);
}