#include <WiFi.h>
#include <PubSubClient.h>
#define MQ2_PIN 34
#define LED_PIN 2
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883;
// Topics MQTT utilisés
const char* TOPIC_ETAT = "/iot/gaz/etat"; // recevoir ON / OFF
const char* TOPIC_VALEUR = "/iot/gaz/valeur"; // envoyer le niveau de gaz
const char* TOPIC_STATUT = "/iot/gaz/statut"; // envoyer l'état du système
WiFiClient espClient;
PubSubClient client(espClient);
bool systemActive = true; // état du système
int seuil = 60; // seuil d'alerte
unsigned long lastPublish = 0;
const unsigned long publishInterval = 2000; // envoi toutes les 2 secondes
// ------------------------
// Connexion Wi-Fi
// ------------------------
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connexion au Wi-Fi : ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
// attendre la connexion
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("Wi-Fi connecté");
Serial.print("Adresse IP : ");
Serial.println(WiFi.localIP());
}
// ------------------------
// Réception des messages MQTT
// ------------------------
void callback(char* topic, byte* payload, unsigned int length) {
String message = "";
// reconstruction du message reçu
for (unsigned int i = 0; i < length; i++) {
message += (char)payload[i];
}
Serial.print("Message reçu [");
Serial.print(topic);
Serial.print("] : ");
Serial.println(message);
// gestion du ON / OFF
if (String(topic) == TOPIC_ETAT) {
if (message == "ON") {
systemActive = true;
client.publish(TOPIC_STATUT, "Systeme active");
Serial.println("Système activé");
}
else if (message == "OFF") {
systemActive = false;
digitalWrite(LED_PIN, LOW); // on éteint la LED
client.publish(TOPIC_STATUT, "Systeme desactive");
Serial.println("Système désactivé");
}
}
}
// ------------------------
// Reconnexion au broker MQTT
// ------------------------
void reconnect() {
while (!client.connected()) {
Serial.print("Connexion au broker MQTT...");
// ID unique pour éviter les conflits
String clientId = "ESP32-GAZ-";
clientId += String((uint32_t)ESP.getEfuseMac(), HEX);
if (client.connect(clientId.c_str())) {
Serial.println(" connecté");
// abonnement au topic de commande
client.subscribe(TOPIC_ETAT);
// message de connexion
client.publish(TOPIC_STATUT, "ESP32 connecte");
} else {
Serial.print(" échec, code = ");
Serial.print(client.state());
Serial.println(" ; nouvelle tentative dans 5 secondes");
delay(5000);
}
}
}
// ------------------------
// Setup
// ------------------------
void setup() {
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}
// ------------------------
// Boucle principale
// ------------------------
void loop() {
// vérifier la connexion MQTT
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned long now = millis();
// envoi périodique des données
if (systemActive && (now - lastPublish >= publishInterval)) {
lastPublish = now;
// lecture du capteur (potentiomètre)
int valeurBrute = analogRead(MQ2_PIN);
// conversion en pourcentage
int niveauGaz = map(valeurBrute, 0, 4095, 0, 100);
// sécurité (reste entre 0 et 100)
niveauGaz = constrain(niveauGaz, 0, 100);
// conversion en texte pour MQTT
char msg[10];
snprintf(msg, sizeof(msg), "%d", niveauGaz);
// envoi de la valeur
client.publish(TOPIC_VALEUR, msg);
// gestion de la LED selon le seuil
if (niveauGaz > seuil) {
digitalWrite(LED_PIN, HIGH);
} else {
digitalWrite(LED_PIN, LOW);
}
// affichage dans le moniteur série
Serial.print("Niveau de gaz : ");
Serial.print(niveauGaz);
Serial.println("%");
}
}