#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>

const char *ssid = "XXXXXX";        // 设置WiFi账号  Set up WiFi account
const char *password = "XXXXXXXX";  // 设置WiFi密码  Set WiFi password
const int ledPin = 13;              // LED控制引脚  LED control pin
const int ldrPin = 12;              // 光敏电阻连接的引脚  Photoresistor connected pin
int threshold = 4095 * 0.7;         // 如果sensorValue小于70%的阈值  If sensorValue is less than the 70% threshold
AsyncWebServer server(80);          // 创建AsyncWebServer对象  Create an AsyncWebServer object

// 生成网页的HTML代码 Generates the HTML code for the web page
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
  <style>
    html {
     font-family: Arial;
     display: inline-block;
     margin: 0px auto;
     text-align: center;
    }
    h2 { font-size: 3.0rem; }
    p { font-size: 3.0rem; }
    .units { font-size: 1.2rem; }
    .dht-labels{
      font-size: 1.5rem;
      vertical-align:middle;
      padding-bottom: 15px;
    }
  </style>
</head>
<body>
  <h2>ESP32 Light Control</h2>
  <p>
    <i id="ledIcon" class="fas fa-lightbulb" style="color:#808080;"></i> 
    <span class="dht-labels" id="ledText">LED OFF</span>
  </p>
  <p>
    <i id="ldrIcon" class="fas fa-sun" style="color:#FFD700;"></i> 
    <span class="dht-labels">Brightness</span>
    <span id="brightness">%BRIGHTNESS%</span>
    <sup class="units">%</sup>
  </p>
  <p style="font-size: 1rem;">When the light intensity is below 70%, the LED will be turned on.</p>
</body>
<script>
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var brightness = parseInt(this.responseText);
      document.getElementById("brightness").innerHTML = brightness;
      if (brightness < 70) {
        document.getElementById("ledIcon").style.color = "#059e8a"; // 设置为彩色
        document.getElementById("ledText").innerHTML = "LED ON";
        digitalWrite(ledPin, HIGH);
      } else {
        document.getElementById("ledIcon").style.color = "#808080"; // 设置为灰色
        document.getElementById("ledText").innerHTML = "LED OFF";
        digitalWrite(ledPin, LOW);
      }
    }
  };
  xhttp.open("GET", "/brightness", true);
  xhttp.send();
}, 1000);
</script>
</html>
)rawliteral";

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);    // 定义引脚工作模式  Define the pin operation mode
  digitalWrite(ledPin, LOW);  // 确保LED初始状态为关闭  Ensure that the LED is initially off
  pinMode(ldrPin, INPUT);     // 设置光敏电阻引脚为输入模式  Set the photoresistor pin to input mode

  // 设置 WiFi 连接 Setting up WiFi connection
  WiFi.begin(ssid, password);
  Serial.println("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println(".");
  }

  Serial.println(WiFi.localIP());  //打印IP地址 Printing IP addresses

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

  server.on("/brightness", HTTP_GET, [](AsyncWebServerRequest *request) {
    int sensorValue = analogRead(ldrPin);                          // 读取光敏电阻的值（0-4095之间）  Read photoresistor values (0-4095)
    int brightnessPercentage = map(sensorValue, 0, 4095, 0, 100);  // 将值映射到百分比范围（0-100）  Map values to a percentage range (0-100)
    String brightnessString = String(brightnessPercentage);        // 将百分比转换为字符串  Convert percentages to strings
    request->send(200, "text/plain", brightnessString);            // 发送亮度百分比到客户端  Send the brightness percentage to the client

    if (sensorValue < threshold) {  //如果检测到亮度低于70%  If the brightness is detected below 70%
      digitalWrite(ledPin, HIGH);   //点亮LED灯  Light up the LED
    } else {                        //否则  otherwise
      digitalWrite(ledPin, LOW);    //熄灭LED灯  Turn off the LED lights
    }
  });

  //启用服务器
  server.begin();
}

void loop() {
}
