
Ce projet montre comment utiliser le protocole de communication MQTT avec l'ESP32 pour publier des messages et s'abonner à des topics d'un broker MQTT sur des serveurs tels que Home Assistant, Node RED, Amazon AWS et openHAB. À titre d'exemple, nous allons contrôler le variateur. Le serveur peut être local ou dans le cloud.
The ESP32 we’ll be programmed using Arduino IDE. The PubSubClient library provides a client for doing simple publish/subscribe messaging with a server that supports MQTT.
Vous pouvez téléverser le code suivant sur votre ESP32. Le code est commenté aux endroits où vous devez apporter des modifications.
Vous devez modifier le code avec votre propre SSID, mot de passe et adresse IP du broker MQTT.
- #include <RBDdimmer.h>
- #define outputPin 4
- #define zerocross 5
- dimmerLamp dimmer(outputPin, zerocross); //initialisation du port pour le variateur pour les cartes ESP8266, ESP32, Arduino Due
- #include <WiFi.h> // Pour ESP8266 #include <ESP8266WiFi.h>
- #include <PubSubClient.h>
- // Identifiants du réseau WiFi
- const char *ssid = "REPLACE_WITH_YOUR_SSID"; // nom de votre réseau WiFi
- const char *password = "REPLACE_WITH_YOUR_PASSWORD"; // mot de passe du réseau WiFi
- // Identifiants du serveur MQTT.
- // const char *HA_USER = "_____";
- // const char *HA_PASS = "_____";
- IPAddress broker(XXX,XXX,XXX,XXX); // Adresse IP de votre broker MQTT, par ex.
- const char *ID = "Example_Dimmer"; // Nom de notre appareil, doit être unique !!!
- char *STATE_TOPIC = "dimmer/power/state"; // Topic pour publier l'état de l'éclairage
- char msg[50];
- WiFiClient wclient;
- PubSubClient client(wclient); // Configuration du client MQTT
- // Traitement des messages entrants du broker
- void callback(char* topic, byte* payload, unsigned int length) {
- String response;
- int power_L;
- for (int i = 0; i < length; i++) {
- response += (char)payload[i];
- }
- Serial.print("Message arrived [");
- Serial.print(topic);
- Serial.print("] ");
- Serial.println(response);
- power_L=response.toInt();
- dimmer.setPower(power_L);
- delay(50);
- snprintf (msg, 50, "%ld", dimmer.getPower());
- client.publish(STATE_TOPIC, msg);
- Serial.print("State ");
- Serial.println(msg);
- }
- // Connexion au réseau WiFi
- void setup_wifi() {
- Serial.print("\nConnecting to ");
- Serial.println(ssid);
- WiFi.mode(WIFI_STA);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) { // Attente de la connexion
- delay(500);
- Serial.print(".");
- }
- Serial.println();
- Serial.println("WiFi connected");
- Serial.print("IP address: ");
- Serial.println(WiFi.localIP());
- }
- // Reconnexion au client
- void reconnect() {
- // Boucle jusqu'à la reconnexion
- while (!client.connected()) {
- Serial.print("Attempting MQTT connection...");
- // Tentative de connexion
- if(client.connect(ID,HA_USER,HA_PASS)) {
- client.subscribe(TOPIC);
- Serial.println("connected");
- Serial.print("Subcribed to: ");
- Serial.println(TOPIC);
- Serial.println('\n');
- } else {
- Serial.println(" try again in 5 seconds");
- // Attendre 5 secondes avant de réessayer
- delay(5000);
- }
- }
- }
- void setup() {
- dimmer.begin(NORMAL_MODE, OND); //Initialisation du variateur
- Serial.begin(115200); // Démarrer la communication série à 115200 bauds
- delay(100);
- setup_wifi(); // Connexion au réseau
- client.setServer(broker, 1883);
- client.setCallback(callback);// Initialisation de la routine de callback
- }
- void loop() {
- if (!client.connected()) // Reconnexion en cas de perte de connexion
- {
- reconnect();
- }
- client.loop();
- }
Le broker MQTT publie la valeur du variateur (0~100) dans le topic dimmer/power/state. L'ESP32 est abonné à ces topics. Ainsi, l'ESP32 reçoit la valeur de variation (0~100).
Pour utiliser le variateur avec 2 à 4 canaux ou plus, il faut ajouter les topics et modifier la fonction callback pour lire les topics :
- char *STATE_TOPIC1 = "dimmer/power1/state";
- char *STATE_TOPIC2 = "dimmer/power2/state";
- char *STATE_TOPIC3 = "dimmer/power3/state";
- char *STATE_TOPIC4 = "dimmer/power4/state";