Hello,
I would like to automate my garage door with an ESP8266, Home Assitant and MQTT. I found some code in a french tuto and I modified it a bit tuto ESP8266 + DHT22 + MQTT…. It really helps me to understand how MQTT is working. For now my ESP8266 is connected to a LED but I will change it with a power relay afterwards.
But I have a problem, if my ESP8266 is well connecting to the WiFi and to MOSQUITTO server (installed from HA “add-on store”), when I click on the button, some time the LED is turning ON/OFF sometime not… I need to click several time to succeed to do the action requested.
I made a mistake somewhere but I cannot figure out where is it. I think that maybe because the ESP8266 is not listening all the time the broker.
Thanks is advance for your help.
Lionel
/*
Projet d'apprentissage d'un objet connecté (IoT) pour réaliser une sonde de température
ESP8266 + DHT22 + LED + MQTT + Home-Assistant
Projets DIY (https://www.projetsdiy.fr) - Mai 2016
Licence : MIT
*/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#define wifi_ssid "**********"
#define wifi_password "**************"
#define mqtt_server "192.168.1.199"
#define mqtt_user "**************" //s'il a été configuré sur Mosquitto
#define mqtt_password "******************" //idem
//Buffer qui permet de décoder les messages MQTT reçus
char message_buff[100];
long lastMsg = 0; //Horodatage du dernier message publié sur MQTT
long lastRecu = 0;
bool debug = false; //Affiche sur la console si True
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(9600); //Facultatif pour le debug
pinMode(D2,OUTPUT); //Pin 2
setup_wifi(); //On se connecte au réseau wifi
client.setServer(mqtt_server, 1883); //Configuration de la connexion au serveur MQTT
client.setCallback(callback); //La fonction de callback qui est executée à chaque réception de message
}
//Connexion au réseau WiFi
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connexion a ");
Serial.println(wifi_ssid);
WiFi.begin(wifi_ssid, wifi_password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connexion WiFi etablie ");
Serial.print("=> Addresse IP : ");
Serial.print(WiFi.localIP());
}
//Reconnexion
void reconnect() {
//Boucle jusqu'à obtenur une reconnexion
while (!client.connected()) {
Serial.print("Connexion au serveur MQTT...");
if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
Serial.println("OK");
client.subscribe("homeassistant/switch1");
} else {
Serial.print("KO, erreur : ");
Serial.print(client.state());
Serial.println(" On attend 5 secondes avant de recommencer");
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastRecu > 100 ) {
lastRecu = now;
client.subscribe("homeassistant/switch1");
}
}
void callback(char* topic, byte* payload, unsigned int length) {
int i = 0;
if ( debug ) {
Serial.println("Message recu => topic: " + String(topic));
Serial.print(" | longueur: " + String(length,DEC));
}
// create character buffer with ending null terminator (string)
for(i=0; i<length; i++) {
message_buff[i] = payload[i];
}
message_buff[i] = '\0';
String msgString = String(message_buff);
if ( debug ) {
Serial.println("Payload: " + msgString);
}
if ( msgString == "ON" ) {
digitalWrite(D2,HIGH);
} else {
digitalWrite(D2,LOW);
}
}
Here it is what I added to configuration.yaml :
mqtt:
broker: 192.168.1.199
port: 1883
client_id: home-assistant-1
keepalive: 60
username: ************* #optionnel
password: *********** #optionnel
protocol: 3.1 #par défaut
switch:
platform: mqtt
name: "Garage"
command_topic: "homeassistant/switch1" #Topic sur lequel on publie l'état de l'interrupteur
payload_on: "ON" # A vous de choisir le message envoyé lorsque l'interrupteur est allumé
payload_off: "OFF" # et éteint
optimistic: true # Mettez à true pour maintenir l'état
qos: 0
retain: true
value_template: '{{ value.x }}'