#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include "DHTesp.h"
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Remplace par l'IP de ta machine ou un lien ngrok
const char* serverBaseUrl = "http://10.144.39.70:5000";
const char* uploadUrl = "http://10.144.39.70:5000/upload";
const char* ledUrl = "http://10.144.39.70:5000/led";
const int DHT_PIN = 15;
const int LED_PIN = 2;
DHTesp dhtSensor;
unsigned long lastSend = 0;
const unsigned long sendInterval = 10000; // 10 secondes
unsigned long lastLedCheck = 0;
const unsigned long ledCheckInterval = 3000; // toutes les 3 secondes
void connectWiFi() {
Serial.println();
Serial.print("Connexion au WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connecté");
Serial.print("Adresse IP : ");
Serial.println(WiFi.localIP());
}
void sendSensorData(float temperature, float humidity) {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi non connecté. Envoi annulé.");
return;
}
HTTPClient http;
http.begin(uploadUrl);
http.addHeader("Content-Type", "application/json");
StaticJsonDocument<200> doc;
doc["temperature"] = temperature;
doc["humidity"] = humidity;
String payload;
serializeJson(doc, payload);
Serial.print("Envoi JSON : ");
Serial.println(payload);
int httpResponseCode = http.POST(payload);
Serial.print("Code HTTP : ");
Serial.println(httpResponseCode);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("Réponse serveur :");
Serial.println(response);
} else {
Serial.print("Erreur HTTP : ");
Serial.println(http.errorToString(httpResponseCode));
}
http.end();
}
void syncLedState() {
if (WiFi.status() != WL_CONNECTED) {
return;
}
HTTPClient http;
http.begin(ledUrl);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String response = http.getString();
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, response);
if (!error) {
bool ledEnabled = doc["enabled"] | false;
digitalWrite(LED_PIN, ledEnabled ? HIGH : LOW);
Serial.print("Etat LED synchronisé : ");
Serial.println(ledEnabled ? "ON" : "OFF");
} else {
Serial.println("Erreur parsing JSON LED");
}
}
http.end();
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
connectWiFi();
}
void loop() {
if (millis() - lastSend >= sendInterval) {
lastSend = millis();
TempAndHumidity data = dhtSensor.getTempAndHumidity();
if (isnan(data.temperature) || isnan(data.humidity)) {
Serial.println("Erreur lecture DHT22");
} else {
Serial.print("Température : ");
Serial.print(data.temperature);
Serial.print(" °C | Humidité : ");
Serial.print(data.humidity);
Serial.println(" %");
sendSensorData(data.temperature, data.humidity);
}
}
if (millis() - lastLedCheck >= ledCheckInterval) {
lastLedCheck = millis();
syncLedState();
}
}
Loading
esp32-devkit-v1
esp32-devkit-v1