#include <WiFi.h>
#include <WiFiClientSecure.h>
#include "DHTesp.h"
#include <HTTPClient.h>
// ⚙️ Simulation Wi-Fi (Wokwi)
const char* WIFI_SSID = "Wokwi-GUEST";
const char* WIFI_PASS = "";
// 🌐 URL FastAPI (Tunnelmole/ngrok)
const char* TUNNEL_URL = "https://haqanp-ip-154-125-86-208.tunnelmole.net";
// GPIOs
const int DHT_PIN = 15;
const int LED_PIN = 13;
WiFiClientSecure client; // Utiliser WiFiClientSecure pour HTTPS
DHTesp dht;
bool ledStatus = false;
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
dht.setup(DHT_PIN, DHTesp::DHT22);
WiFi.begin(WIFI_SSID, WIFI_PASS);
Serial.print("🔌 Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\n✅ WiFi connected");
client.setInsecure(); // Désactive la validation du certificat (pour test uniquement)
}
void loop() {
float temperature = dht.getTemperature();
float humidity = dht.getHumidity();
Serial.printf("🌡 %.1f°C 💧 %.1f%% LED=%s\n",
temperature, humidity, ledStatus ? "ON" : "OFF");
if (WiFi.status() == WL_CONNECTED) {
// --- POST /update ---
HTTPClient http;
String url = String(TUNNEL_URL) + "/update";
String payload = "{";
payload += "\"temperature\":" + String(temperature, 1) + ",";
payload += "\"humidity\":" + String(humidity, 1) + ",";
payload += "\"state\":" + String(ledStatus ? "true" : "false");
payload += "}";
Serial.println("POST URL: " + url);
Serial.println("Payload: " + payload);
if (http.begin(client, url)) {
http.addHeader("Content-Type", "application/json");
int httpCode = http.POST(payload);
Serial.printf("POST /update code: %d\n", httpCode);
if (httpCode > 0) {
String response = http.getString();
Serial.println("Response: " + response);
} else {
Serial.println("POST failed: " + http.errorToString(httpCode));
}
http.end();
} else {
Serial.println("HTTP begin failed");
}
// --- GET /led ---
HTTPClient getClient;
String ledUrl = String(TUNNEL_URL) + "/led";
Serial.println("GET URL: " + ledUrl);
if (getClient.begin(client, ledUrl)) {
int code = getClient.GET();
Serial.printf("GET /led code: %d\n", code);
if (code == 200) {
String resp = getClient.getString();
Serial.println("GET Response: " + resp);
bool newState = ledStatus;
if (resp.indexOf("\"state\":true") >= 0) newState = true;
else if (resp.indexOf("\"state\":false") >= 0) newState = false;
if (newState != ledStatus) {
ledStatus = newState;
digitalWrite(LED_PIN, ledStatus ? HIGH : LOW);
Serial.printf("💡 LED updated: %s\n", ledStatus ? "ON" : "OFF");
}
} else {
Serial.println("GET /led failed");
}
getClient.end();
} else {
Serial.println("HTTP begin failed for GET");
}
}
delay(10000); // toutes les 10s
}