#include <WiFi.h>
#include <PubSubClient.h>
#include <ESP32Servo.h>
const char* SSID = "Wokwi-GUEST";
const char* BROKER = "test.mosquitto.org";
const char* BASE = "m2rt/Bx"; // remplacer Bx
const int PIN_LED = 2, PIN_RELAIS = 26, PIN_SERVO = 18;
WiFiClient reseau;
PubSubClient mqtt(reseau);
Servo servo;
void publierEtat(const char* nom, const String& valeur) {
String topic = String(BASE) + "/etat/" + nom;
mqtt.publish(topic.c_str(), valeur.c_str(), true); // retained
}
void recevoir(char* topic, byte* donnees, unsigned int taille) {
String msg;
for (unsigned int i = 0; i < taille; i++) msg += (char)donnees[i];
msg.trim();
String t = topic;
Serial.printf("Recu [%s] : %s\n", topic, msg.c_str());
if (t.endsWith("/led")) {
bool on = msg.equalsIgnoreCase("ON");
digitalWrite(PIN_LED, on ? HIGH : LOW);
publierEtat("led", on ? "ON" : "OFF");
} else if (t.endsWith("/relais")) {
bool on = msg.equalsIgnoreCase("ON");
digitalWrite(PIN_RELAIS, on ? HIGH : LOW);
publierEtat("relais", on ? "ON" : "OFF");
} else if (t.endsWith("/servo")) {
int angle = constrain((int)msg.toInt(), 0, 180);
servo.write(angle);
publierEtat("servo", String(angle));
}
}
void connecterMQTT() {
String will = String(BASE) + "/etat/connexion";
while (!mqtt.connected()) {
String id = "esp32-act-" + String(random(0xffff), HEX);
// connect(id, topicWill, qosWill, retainWill, messageWill)
if (mqtt.connect(id.c_str(), will.c_str(), 1, true, "hors-ligne")) {
mqtt.publish(will.c_str(), "en-ligne", true);
String cmd = String(BASE) + "/cmd/#";
mqtt.subscribe(cmd.c_str(), 1);
// QoS 1
Serial.println("Broker connecte, abonne a " + cmd);
} else {
delay(2000);
}
}
}
void setup() {
Serial.begin(115200);
pinMode(PIN_LED, OUTPUT);
pinMode(PIN_RELAIS, OUTPUT);
servo.attach(PIN_SERVO);
servo.write(0);
WiFi.begin(SSID, "");
while (WiFi.status() != WL_CONNECTED) delay(250);
mqtt.setServer(BROKER, 1883);
mqtt.setCallback(recevoir);
}
void loop() {
if (!mqtt.connected()) connecterMQTT();
mqtt.loop();
}Loading
esp32-devkit-c-v4
esp32-devkit-c-v4