#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "mqtt.thingsboard.cloud"; // Serveur MQTT
const char* mqtt_user = "lp69wt9ertu3u7ocogtq"; // Remplace par ton access token
const char* mqtt_topic = "v1/devices/me/telemetry"; // Topic MQTT
WiFiClient WOKWI_Client;
PubSubClient client(WOKWI_Client);
#define WIFI_LED 2 // LED rouge pour connexion WiFi
#define MQTT_LED 15 // LED bleue pour connexion MQTT
void setup_wifi() {
Serial.begin(115200);
Serial.println("\nConnexion au WiFi...");
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connecté !");
Serial.println("IP address: " + WiFi.localIP().toString());
}
void reconnect() {
while (!client.connected()) {
Serial.print("Connexion à MQTT...");
if (client.connect("ESP32_Client", mqtt_user, "")) {
Serial.println(" Connecté à MQTT !");
} else {
Serial.print(" Échec, code erreur = ");
Serial.print(client.state());
Serial.println(". Nouvelle tentative dans 5s...");
delay(5000);
}
}
}
void checkWiFi() {
digitalWrite(WIFI_LED, WiFi.status() == WL_CONNECTED ? HIGH : LOW);
}
void checkMQTT() {
digitalWrite(MQTT_LED, client.connected() ? HIGH : LOW);
}
// Fonction pour publier un message sur ThinkBoard
void publishMessage() {
if (client.connected()) {
String message = "{\"temperature\": 30.3, \"humidity\": 70}";
client.publish(mqtt_topic, message.c_str());
Serial.println(" Message envoyé : " + message);
}
}
void setup() {
pinMode(WIFI_LED, OUTPUT);
pinMode(MQTT_LED, OUTPUT);
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void loop() {
checkWiFi();
reconnect();
checkMQTT();
client.loop();
// Simulation de déconnexion WiFi après 10 secondes
if (millis() > 10000) {
WiFi.disconnect();
}
// Simulation de déconnexion MQTT après 15 secondes
if (millis() > 15000) {
client.disconnect();
}
// Envoie un message toutes les 10 secondes
static unsigned long lastPublish = 0;
if (millis() - lastPublish > 10000) {
lastPublish = millis();
publishMessage();
}
}
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
led1:A
led1:C
r1:1
r1:2
led2:A
led2:C
r2:1
r2:2