#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include "DHT.h"
#include <ESP32Servo.h>

// --- WiFi & MQTT ---
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "broker.emqx.io";

// --- Broches capteurs/actionneurs ---
const int redPin = 23;
const int greenPin = 22;
const int photoresistorPin = 34;
const int dhtPin = 15;

const int fanServoPin = 18;   // Servo pour ventilateur (MQTT)
const int servoPin = 19;      // Servo déclenché par bouton (interruption)
const int buttonPin = 21;     // Bouton physique

// --- DHT22 ---
#define DHTTYPE DHT22
DHT dht(dhtPin, DHTTYPE);

// --- Servos ---
Servo myServo;
Servo fanServo;

// --- MQTT ---
WiFiClient espClient;
PubSubClient client(espClient);

// --- Interruption bouton ---
volatile bool buttonPressed = false;

void IRAM_ATTR handleButtonInterrupt() {
  buttonPressed = true;
}

// --- Ventilateur (servo MQTT) ---
void rotateFanServo(int angle = 90) {
  fanServo.write(angle);
  Serial.printf("🌬️ Servo ventilateur → %d°\n", angle);
  delay(1000);
  fanServo.write(0);
}

// --- MQTT Callback ---
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.println("\n📥 Message MQTT reçu");

  Serial.print("📨 Topic: ");
  Serial.println(topic);

  Serial.print("📦 Payload brut: ");
  for (unsigned int i = 0; i < length; i++) Serial.print((char)payload[i]);
  Serial.println();

  StaticJsonDocument<256> doc;
  DeserializationError error = deserializeJson(doc, payload, length);
  if (error) {
    Serial.print("❌ Erreur JSON: ");
    Serial.println(error.c_str());
    return;
  }

  const char* alerte = doc["alerte"];
  int r = doc["led"]["r"] | 0;
  int g = doc["led"]["g"] | 0;

  analogWrite(redPin, 255 - r);
  analogWrite(greenPin, 255 - g);

  int luminosite = analogRead(photoresistorPin);
  float roomTemp = dht.readTemperature();

  Serial.printf("🔔 Alerte: %s | LED: (R:%d, G:%d)\n", alerte, r, g);
  Serial.printf("📊 Luminosité: %d | 🌡️ Température: %.1f°C\n", luminosite, roomTemp);

  if (strcmp(alerte, "bruit_eleve") == 0) {
    rotateFanServo(90);
  } else if (strcmp(alerte, "danger_vital") == 0) {
    rotateFanServo(120);
    if (roomTemp > 28) Serial.println("🔥 Température élevée détectée");
  } else if (strcmp(alerte, "mouvement_detecte") == 0) {
    rotateFanServo(60);
  } else {
    Serial.println("🟢 Aucune action spécifique à exécuter");
  }
}

// --- Connexion Wi-Fi ---
void setup_wifi() {
  WiFi.begin(ssid, password);
  Serial.print("Connexion Wi-Fi...");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\n✅ WiFi connecté");
}

// --- Connexion MQTT ---
void reconnect() {
  while (!client.connected()) {
    Serial.print("🔄 Connexion MQTT...");
    if (client.connect("ESP32ClientActionneur")) {
      Serial.println("✅ Connecté au broker");
      client.subscribe("esp32c6/alerte");
    } else {
      Serial.print("❌ Échec rc=");
      Serial.println(client.state());
      delay(2000);
    }
  }
}

// --- Setup ---
void setup() {
  Serial.begin(115200);

  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);

  myServo.attach(servoPin);      // Servo bouton
  myServo.write(0);
  fanServo.attach(fanServoPin);  // Servo ventilateur
  fanServo.write(0);

  attachInterrupt(digitalPinToInterrupt(buttonPin), handleButtonInterrupt, FALLING);

  analogWrite(redPin, 255);
  analogWrite(greenPin, 255);

  dht.begin();
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

// --- Boucle principale ---
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  if (buttonPressed) {
    buttonPressed = false;
    Serial.println("🛎️ Interruption → Servo déclenché par bouton");
    myServo.write(90);
    delay(1000);
    myServo.write(0);
  }
}
esp:0
esp:2
esp:4
esp:5
esp:12
esp:13
esp:14
esp:15
esp:16
esp:17
esp:18
esp:19
esp:21
esp:22
esp:23
esp:25
esp:26
esp:27
esp:32
esp:33
esp:34
esp:35
esp:3V3
esp:EN
esp:VP
esp:VN
esp:GND.1
esp:D2
esp:D3
esp:CMD
esp:5V
esp:GND.2
esp:TX
esp:RX
esp:GND.3
esp:D1
esp:D0
esp:CLK
rgb1:R
rgb1:COM
rgb1:G
rgb1:B
ldr1:VCC
ldr1:GND
ldr1:DO
ldr1:AO
dht1:VCC
dht1:SDA
dht1:NC
dht1:GND
btn1:1.l
btn1:2.l
btn1:1.r
btn1:2.r
servo1:GND
servo1:V+
servo1:PWM
servo2:GND
servo2:V+
servo2:PWM