bruhautomation / ESP-MQTT-JSON-Digital-LEDs

(OBSOLETE) ESP8266 MQTT JSON Digital LEDs for Home Assistant
https://youtu.be/9KI36GTgwuQ
Apache License 2.0
512 stars 268 forks source link

Last Will Message - Availability #107

Open smith844 opened 5 years ago

smith844 commented 5 years ago

Is there a simple way to implement a LWT message in the similar way to Tasmota/SONOFF. I have several sonoff devices with Tasmota which give an online/offline message via the LWT which means if a device is out of sync or missing it shows up correctly. I would like to implement this in the code for the lights to allow me to have the correct state in Home Assistant. I have searched a number of threads on the forums but its a bit inconclusive or right at the edge of my knowledge. Thanks in advance for any help you can give me.

Joeboyc2 commented 5 years ago

Hey @smith844 , I have some code for this running on another node, i#ll see if i can find the script this evening and upload the sections for you

smith844 commented 5 years ago

@Joeboyc2 That is very kind. I should add I have looked at lots of pages of code, the source for pubsubclient and various wiki entries for last will messages but its still a little confusing, I dont want to break the existing code with my efforts

Joeboyc2 commented 5 years ago

no worries, here is what you need to do:

Add this line somewhere at the top of the sketch (i added mine under the other topics (line:50ish)) const char* LWT_topic = "tele/topic/LWT"; //name this whatever you want to use

Then replace your reconnect function with this:

void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect(SENSORNAME, mqtt_username, mqtt_password, LWT_topic, 0, 1, "Offline")) { Serial.println("connected"); client.subscribe(light_set_topic); client.publish(LWT_topic, "Online", true); setColor(0, 0, 0); sendState(); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } }

Then add this to the light section you have in home assistant: availability_topic: "tele/topic/LWT" //make sure you match this to the one you added to the sketch

h0jeZvgoxFepBQ2C commented 5 years ago

I'm really a noob in arduino programming, would you mind to make a PR @Joeboyc2 ?

Joeboyc2 commented 5 years ago

Hey @lichtamberg I've raised PR's #111 #112 for this