#include <WiFi.h>
#include <WebServer.h>
#include <littleFFS.h>
#include "DHT.h"
#include "PubSubClient.h"
#include "ArduinoJson.h"
#include <ArduinoJson.h>
const char* ssid = "Wokwi-GUEST"; // Enter your WiFi credentials
const char* password = "";
const char* mqttServer = "broker.hivemq.com";
const int mqttPort = 1883;
const char* mqttUser = "";
const char* mqttPassword = "";
const char* mqttClientId = "esp32-weather-demo";
const char* mqttTopic = "wokwi-weather";
struct DeviceSettings {
char wifiSSID[50];
char wifiPassword[50];
int highTemperatureThreshold;
int lowHumidityThreshold;
int desiredPressure;
char mqttServer[50];
int mqttPort;
char mqttUser[50];
char mqttPassword[50];
};
DeviceSettings settings;
#define DHTPIN 4
#define DHTTYPE DHT22
#define LED_PIN 2 // Use pin 2 for the LED
#define WATER_PUMP_PIN 5
DHT dht(DHTPIN, DHTTYPE);
WebServer server(80);
WiFiClient espClient;
PubSubClient client(espClient);
float temperature;
float humidity;
float pressure=0;
int highTemperatureThreshold = 21;
int lowHumidityThreshold = 50;
int desiredPressure = 1000;
void setup() {
Serial.begin(115200);
delay(100);
pinMode(DHTPIN, INPUT);
dht.begin();
WiFi.begin(ssid, password);
Serial.println("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected!");
Serial.print("Got IP: ");
Serial.println(WiFi.localIP());
server.on("/settings", HTTP_GET,handle_Settings);
server.on("/save-settings", HTTP_POST, handle_SaveSettings);
if (!littleFS.begin(true)) {
Serial.println("An error occurred while mounting littleFFS");
return;
}
loadSettings();
client.setServer(mqttServer, mqttPort);
server.on("/", handle_OnConnect);
server.on("/settings", handle_Settings);
server.onNotFound(handle_NotFound);
server.begin();
Serial.println("HTTP server started");
pinMode(LED_PIN, OUTPUT);
pinMode(WATER_PUMP_PIN, OUTPUT);
}
void loop() {
server.handleClient();
if (!client.connected()) {
reconnect();
}
client.loop();
delay(2000);
float newTemperature = dht.readTemperature();
float newHumidity = dht.readHumidity();
if (!isnan(newTemperature) && !isnan(newHumidity)) {
temperature = newTemperature;
humidity = newHumidity;
String jsonMessage = "{";
jsonMessage += "\"temp\":" + String(temperature) + ",";
jsonMessage += "\"humidity\":" + String(humidity) + ",";
jsonMessage += "\"pressure\":" + String(pressure);
jsonMessage += "}";
if (client.publish(mqttTopic, jsonMessage.c_str())) {
Serial.println("Published MQTT message with sensor readings");
} else {
Serial.println("Failed to publish MQTT message with sensor readings");
}
if (temperature > highTemperatureThreshold && humidity < lowHumidityThreshold && pressure > desiredPressure) {
digitalWrite(WATER_PUMP_PIN, HIGH);
String pumpMessage = "Pump activated! Temp: " + String(temperature) + "°C, Humidity: " + String(humidity) + "%, Pressure: " + String(pressure) + "hPa";
if (client.publish("irrigationTopic", pumpMessage.c_str())) {
Serial.println("Pump activated! Published MQTT message with sensor values");
} else {
Serial.println("Pump activated! Failed to publish MQTT message");
}
} else {
digitalWrite(WATER_PUMP_PIN, LOW);
String pumpMessage = "Pump deactivated! Temp: " + String(temperature) + "°C, Humidity: " + String(humidity) + "%, Pressure: " + String(pressure) + "hPa";
if (client.publish("irrigationTopic", pumpMessage.c_str())) {
Serial.println("Pump deactivated! Published MQTT message with sensor values");
} else {
Serial.println("Pump deactivated! Failed to publish MQTT message");
}
}
} else {
Serial.println("Failed to read from DHT sensor");
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect(mqttClientId, mqttUser, mqttPassword)) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void handle_OnConnect() {
server.send(200, "text/html", SendHTML(temperature, humidity));
}
void handle_SaveSettings() {
if (server.method() == HTTP_POST) {
for (uint8_t i = 0; i < server.args(); i++) {
if (server.argName(i) == "wifiSSID") {
String newSSID = server.arg(i);
newSSID.toCharArray(settings.wifiSSID, sizeof(settings.wifiSSID));
} else if (server.argName(i) == "wifiPassword") {
String newPass = server.arg(i);
newPass.toCharArray(settings.wifiPassword, sizeof(settings.wifiPassword));
} else if (server.argName(i) == "tempThreshold") {
highTemperatureThreshold = server.arg(i).toInt();
} else if (server.argName(i) == "humidityThreshold") {
lowHumidityThreshold = server.arg(i).toInt();
} else if (server.argName(i) == "pressureThreshold") {
desiredPressure = server.arg(i).toInt();
}
}
saveSettings(); // Sauvegarde des paramètres dans le fichier config.json
}
server.sendHeader("Location", "/settings", true);
server.send(303);
}
void handle_NotFound() {
server.send(404, "text/plain", "Not found");
}
String SendHTML(float temp, float hum) {
String html = "<!DOCTYPE html> <html>\n";
html += "<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">\n";
html += "<title>ESP32 Weather Report</title>\n";
html += "<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}\n";
html += "body{margin-top: 50px;} h1 {color: #444444;margin: 50px auto 30px;}\n";
html += "p {font-size: 24px;color: #444444;margin-bottom: 10px;}\n";
html += "</style>\n";
html += "</head>\n";
html += "<body>\n";
html += "<div id=\"webpage\">\n";
html += "<h1>ESP32 Weather Report</h1>\n";
html += "<p>Temperature: ";
html += (int)temp;
html += "°C</p>";
html += "<p>Humidity: ";
html += (int)hum;
html += "%</p>";
html += "</div>\n";
html += "</body>\n";
html += "</html>\n";
return html;
}
String SettingsHTML() {
String html = "<!DOCTYPE html> <html>\n";
html += "<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">\n";
html += "<title>Settings</title>\n";
html += "<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}\n";
html += "body{margin-top: 50px;} h2 {color: #444444;margin: 50px auto 30px;}\n";
html += "p {font-size: 24px;color: #444444;margin-bottom: 10px;}\n";
html += "input[type=number] { width: 30%;padding: 12px 20px;margin: 8px 0;box-sizing: border-box;border: 2px solid #ccc;border-radius: 4px;}\n";
html += "input[type=submit] { width: 20%;background-color: #4CAF50;color: white;padding: 14px 20px;margin: 8px 0;border: none;border-radius: 4px;cursor: pointer;}\n";
html += "</style>\n";
html += "</head>\n";
html += "<body>\n";
html += "<div id=\"webpage\">\n";
html += "<h2>Settings</h2>\n";
html += "<form action=\"/settings\" method=\"get\">\n";
html += "<label for='wifiSSID'>WiFi SSID:</label><br>";
html += "<input type='text' id='wifiSSID' name='wifiSSID' value='" + String(settings.wifiSSID) + "'><br>";
html += "<label for='wifiPassword'>WiFi Password:</label><br>";
html += "<input type='password' id='wifiPassword' name='wifiPassword' value='" + String(settings.wifiPassword) + "'><br>";
html += "<label for='tempThreshold'>High Temperature Threshold:</label><br>";
html += "<input type='number' id='tempThreshold' name='tempThreshold' value='" + String(highTemperatureThreshold) + "'><br>";
html += "<label for='humidityThreshold'>Low Humidity Threshold:</label><br>";
html += "<input type='number' id='humidityThreshold' name='humidityThreshold' value='" + String(lowHumidityThreshold) + "'><br>";
html += "<label for='pressureThreshold'>Desired Pressure Threshold:</label><br>";
html += "<input type='number' id='pressureThreshold' name='pressureThreshold' value='" + String(desiredPressure) + "'><br><br>";
html += "<input type='submit' value='Submit'>\n";
html += "</form>\n";
html += "</div>\n";
html += "</body>\n";
html += "</html>\n";
return html;
}
void handle_Settings() {
String html = SettingsHTML();
server.send(200, "text/html", html);
}
bool loadSettings() {
File configFile = SPIFFS.open("/config.json", "r");
if (!configFile) {
return false; // Échec du chargement
}
size_t size = configFile.size();
if (size > 1024) {
return false; // Taille du fichier incorrecte
}
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
StaticJsonDocument<1024> jsonDoc;
DeserializationError error = deserializeJson(jsonDoc, buf.get());
if (error) {
return false; // Erreur de désérialisation JSON
}
strcpy(settings.wifiSSID, jsonDoc["wifiSSID"]);
strcpy(settings.wifiPassword, jsonDoc["wifiPassword"]);
settings.highTemperatureThreshold = jsonDoc["highTemperatureThreshold"];
settings.lowHumidityThreshold = jsonDoc["lowHumidityThreshold"];
settings.desiredPressure = jsonDoc["desiredPressure"];
strcpy(settings.mqttServer, jsonDoc["mqttServer"]);
settings.mqttPort = jsonDoc["mqttPort"];
strcpy(settings.mqttUser, jsonDoc["mqttUser"]);
strcpy(settings.mqttPassword, jsonDoc["mqttPassword"]);
// Autres paramètres à charger
return true; // Chargement réussi
}
void saveSettings() {
StaticJsonDocument<1024> jsonDoc;
jsonDoc["wifiSSID"] = settings.wifiSSID;
jsonDoc["wifiPassword"] = settings.wifiPassword;
jsonDoc["highTemperatureThreshold"] = settings.highTemperatureThreshold;
jsonDoc["lowHumidityThreshold"] = settings.lowHumidityThreshold;
jsonDoc["desiredPressure"] = settings.desiredPressure;
jsonDoc["mqttServer"] = settings.mqttServer;
jsonDoc["mqttPort"] = settings.mqttPort;
jsonDoc["mqttUser"] = settings.mqttUser;
jsonDoc["mqttPassword"] = settings.mqttPassword;
// Autres paramètres à sauvegarder
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
return; // Impossible d'ouvrir le fichier en écriture
}
serializeJson(jsonDoc, configFile);
}