#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#include "DHT.h"

// Wi-Fi credentials
const char *ssid = "KimNamHyeong";
const char *password = "12345678";
WiFiServer server(80);

// MQ-5 가스 센서, DHT22 온습도 센서, 불꽃 감지 센서 및 서보 모터 설정
#define MQ5_PIN 32
#define DHTPIN 14
#define DHTTYPE DHT22
#define FLAME_SENSOR_PIN 4

// 서보 모터 설정
const int servoPin1 = 15;
const int servoPin2 = 16;
const int pwmFreq = 50;        // 50Hz
const int pwmResolution = 16; // 16비트 해상도

const int numSamples = 10;
DHT dht(DHTPIN, DHTTYPE);

// 서보 모터 1 제어를 위한 함수
void moveServo(int servoPin, int startAngle, int endAngle) {
  for (int angle = startAngle; angle <= endAngle; angle++) {
    int duty = map(angle, 0, 180, 2000, 7000);
    ledcWrite(servoPin, duty);
    delay(10);
  }
}

void moveServoReverse(int servoPin, int startAngle, int endAngle) {
  for (int angle = startAngle; angle >= endAngle; angle--) {
    int duty = map(angle, 0, 180, 2000, 7000);
    ledcWrite(servoPin, duty);
    delay(10);
  }
}

// 서보 모터 2 제어를 위한 태스크
TaskHandle_t ServoTaskHandle2 = NULL;
volatile bool servoMoveFlag2 = false;

void operateServoTask2(void *parameter) {
  for (;;) {
    if (servoMoveFlag2) {
      // 서보 모터 2 제어 루프
      for (int angle = 0; angle <= 90; angle++) {
        int duty = map(angle, 0, 180, 2000, 7000);
        ledcWrite(servoPin2, duty);
        delay(10);
      }
      for (int angle = 90; angle >= 0; angle--) {
        int duty = map(angle, 0, 180, 2000, 7000);
        ledcWrite(servoPin2, duty);
        delay(10);
      }
      servoMoveFlag2 = false; // 동작 완료 후 플래그 초기화
    }
    vTaskDelay(10 / portTICK_PERIOD_MS); // Task 딜레이
  }
}

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

  // Wi-Fi 연결
  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: ");
  Serial.println(WiFi.localIP());

  server.begin();
  dht.begin();
  pinMode(MQ5_PIN, INPUT);
  pinMode(FLAME_SENSOR_PIN, INPUT);

  // 서보 모터 PWM 설정
  ledcAttach(servoPin1, pwmFreq, pwmResolution);
  ledcAttach(servoPin2, pwmFreq, pwmResolution);

  // 서보 모터 2 태스크 생성
  xTaskCreatePinnedToCore(
      operateServoTask2,   // Task 함수
      "ServoTask2",        // Task 이름
      10000,               // Stack 크기
      NULL,                // Task 입력 매개변수
      1,                   // Task 우선순위
      &ServoTaskHandle2,   // Task 핸들
      0                    // 코어 지정
  );
}

void loop() {
  WiFiClient client = server.available();

  // 가스 센서 값이 3700을 초과하는지 확인
  int sensorValue = 0;
  for (int i = 0; i < numSamples; i++) {
    sensorValue += analogRead(MQ5_PIN);
    delay(10);
  }
  sensorValue /= numSamples;

  // 가스 센서 값이 3700 초과 시 서보 모터 1과 2 작동
  if (sensorValue > 3700) {
    moveServo(servoPin1, 0, 90);
    servoMoveFlag2 = true;
  }

  if (client) {
    Serial.println("New Client.");
    String currentLine = "";
    String request = "";
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        if (c == '\n') {
          if (currentLine.length() == 0) {
            // 요청된 URL 확인
            if (request.indexOf("GET /gas") >= 0) {
              client.println("HTTP/1.1 200 OK");
              client.println("Access-Control-Allow-Origin: *");  // CORS 설정
              client.println("Content-type:text/html; charset=UTF-8");
              client.println();
              client.printf("<html><body>MQ-5 가스 센서 값: %d</body></html>", sensorValue);
            } else if (request.indexOf("GET /temp") >= 0) {
              float temp = dht.readTemperature();
              client.println("HTTP/1.1 200 OK");
              client.println("Access-Control-Allow-Origin: *");  // CORS 설정
              client.println("Content-type:text/html; charset=UTF-8");
              client.println();
              client.printf("<html><body>온도: %.2f ºC</body></html>", temp);
            } else if (request.indexOf("GET /humi") >= 0) {
              float humi = dht.readHumidity();
              client.println("HTTP/1.1 200 OK");
              client.println("Access-Control-Allow-Origin: *");  // CORS 설정
              client.println("Content-type:text/html; charset=UTF-8");
              client.println();
              client.printf("<html><body>습도: %.2f%%</body></html>", humi);
            } else if (request.indexOf("GET /flame") >= 0) {
              int flameState = digitalRead(FLAME_SENSOR_PIN);
              String flameStatus = (flameState == LOW) ? "불꽃 있음": "불꽃 없음";
              client.println("HTTP/1.1 200 OK");
              client.println("Access-Control-Allow-Origin: *");  // CORS 설정
              client.println("Content-type:text/html; charset=UTF-8");
              client.println();
              client.printf("<html><body>불꽃 감지 상태: %s</body></html>", flameStatus.c_str());
            } else if (request.indexOf("GET /servo1/up") >= 0) {
              moveServo(servoPin1, 0, 90);
              client.println("HTTP/1.1 200 OK");
              client.println("Access-Control-Allow-Origin: *");  // CORS 설정
              client.println("Content-type:text/html; charset=UTF-8");
              client.println();
              client.println("<html><body>서보 모터 1: 0도 -> 90도 이동</body></html>");
            } else if (request.indexOf("GET /servo1/down") >= 0) {
              moveServoReverse(servoPin1, 90, 0);
              client.println("HTTP/1.1 200 OK");
              client.println("Access-Control-Allow-Origin: *");  // CORS 설정
              client.println("Content-type:text/html; charset=UTF-8");
              client.println();
              client.println("<html><body>서보 모터 1: 90도 -> 0도 이동</body></html>");
            } else if (request.indexOf("GET /servo2") >= 0) {
              servoMoveFlag2 = true;
              client.println("HTTP/1.1 200 OK");
              client.println("Access-Control-Allow-Origin: *");  // CORS 설정
              client.println("Content-type:text/html; charset=UTF-8");
              client.println();
              client.println("<html><body>서보 모터 2 작동 중...</body></html>");
            } else {
              client.println("HTTP/1.1 200 OK");
              client.println("Access-Control-Allow-Origin: *");  // CORS 설정
              client.println("Content-type:text/html; charset=UTF-8");
              client.println();
              client.println("<html><body><h1>센서 데이터</h1>");
              client.println("<ul>");
              client.println("<li><a href=\"/gas\">MQ-5 가스 센서</a></li>");
              client.println("<li><a href=\"/temp\">온도</a></li>");
              client.println("<li><a href=\"/humi\">습도</a></li>");
              client.println("<li><a href=\"/flame\">불꽃 감지 상태</a></li>");
              client.println("<li><a href=\"/servo1/up\">서보 모터 1 위로 이동</a></li>");
              client.println("<li><a href=\"/servo1/down\">서보 모터 1 아래로 이동</a></li>");
              client.println("<li><a href=\"/servo2\">서보 모터 2 작동</a></li>");
              client.println("</ul></body></html>");
            }
            client.println();
            break;
          } else {
            currentLine = "";
          }
        } else if (c != '\r') {
          currentLine += c;
          if (currentLine.startsWith("GET ")) {
            request = currentLine;
          }
        }
      }
    }
    client.stop();
    Serial.println("Client Disconnected.");
  }
}