Se rendre au contenu

Dimmer with ESP8266/ESP32 MQTT – Publish and Subscribe with Arduino IDE. Connecting to Home Assistant, Node-RED, Amazon AWS, and openHAB

28 mars 2025 par
Dimmer with ESP8266/ESP32 MQTT – Publish and Subscribe with Arduino IDE. Connecting to Home Assistant, Node-RED, Amazon AWS, and openHAB
Administrator
| Aucun commentaire pour l'instant

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.


  1. #include <RBDdimmer.h>
  2. #define outputPin 4
  3. #define zerocross 5
  4. dimmerLamp dimmer(outputPin, zerocross); //initialisation du port pour le variateur pour les cartes ESP8266, ESP32, Arduino Due
  5. #include <WiFi.h> // Pour ESP8266 #include <ESP8266WiFi.h>
  6. #include <PubSubClient.h>
  7. // Identifiants du réseau WiFi
  8. const char *ssid = "REPLACE_WITH_YOUR_SSID"; // nom de votre réseau WiFi
  9. const char *password = "REPLACE_WITH_YOUR_PASSWORD"; // mot de passe du réseau WiFi
  10. // Identifiants du serveur MQTT.
  11. // const char *HA_USER = "_____";
  12. // const char *HA_PASS = "_____";
  13. IPAddress broker(XXX,XXX,XXX,XXX); // Adresse IP de votre broker MQTT, par ex.
  14. const char *ID = "Example_Dimmer"; // Nom de notre appareil, doit être unique !!!
  15. char *STATE_TOPIC = "dimmer/power/state"; // Topic pour publier l'état de l'éclairage
  16. char msg[50];
  17. WiFiClient wclient;
  18. PubSubClient client(wclient); // Configuration du client MQTT
  19. // Traitement des messages entrants du broker
  20. void callback(char* topic, byte* payload, unsigned int length) {
  21. String response;
  22. int power_L;
  23. for (int i = 0; i < length; i++) {
  24. response += (char)payload[i];
  25. }
  26. Serial.print("Message arrived [");
  27. Serial.print(topic);
  28. Serial.print("] ");
  29. Serial.println(response);
  30. power_L=response.toInt();
  31. dimmer.setPower(power_L);
  32. delay(50);
  33. snprintf (msg, 50, "%ld", dimmer.getPower());
  34. client.publish(STATE_TOPIC, msg);
  35. Serial.print("State ");
  36. Serial.println(msg);
  37. }
  38. // Connexion au réseau WiFi
  39. void setup_wifi() {
  40. Serial.print("\nConnecting to ");
  41. Serial.println(ssid);
  42. WiFi.mode(WIFI_STA);
  43. WiFi.begin(ssid, password);
  44. while (WiFi.status() != WL_CONNECTED) { // Attente de la connexion
  45. delay(500);
  46. Serial.print(".");
  47. }
  48. Serial.println();
  49. Serial.println("WiFi connected");
  50. Serial.print("IP address: ");
  51. Serial.println(WiFi.localIP());
  52. }
  53. // Reconnexion au client
  54. void reconnect() {
  55. // Boucle jusqu'à la reconnexion
  56. while (!client.connected()) {
  57. Serial.print("Attempting MQTT connection...");
  58. // Tentative de connexion
  59. if(client.connect(ID,HA_USER,HA_PASS)) {
  60. client.subscribe(TOPIC);
  61. Serial.println("connected");
  62. Serial.print("Subcribed to: ");
  63. Serial.println(TOPIC);
  64. Serial.println('\n');
  65. } else {
  66. Serial.println(" try again in 5 seconds");
  67. // Attendre 5 secondes avant de réessayer
  68. delay(5000);
  69. }
  70. }
  71. }
  72. void setup() {
  73. dimmer.begin(NORMAL_MODE, OND); //Initialisation du variateur
  74. Serial.begin(115200); // Démarrer la communication série à 115200 bauds
  75. delay(100);
  76. setup_wifi(); // Connexion au réseau
  77. client.setServer(broker, 1883);
  78. client.setCallback(callback);// Initialisation de la routine de callback
  79. }
  80. void loop() {
  81. if (!client.connected()) // Reconnexion en cas de perte de connexion
  82. {
  83. reconnect();
  84. }
  85. client.loop();
  86. }

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 :

  1. char *STATE_TOPIC1 = "dimmer/power1/state";
  2. char *STATE_TOPIC2 = "dimmer/power2/state";
  3. char *STATE_TOPIC3 = "dimmer/power3/state";
  4. char *STATE_TOPIC4 = "dimmer/power4/state";
Partager cet article
Se connecter pour laisser un commentaire.