ESP-MQTT-JSON-Digital-LEDs
ESP-MQTT-JSON-Digital-LEDs copied to clipboard
Last Will Message - Availability
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.
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
@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
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
I'm really a noob in arduino programming, would you mind to make a PR @Joeboyc2 ?
Hey @lichtamberg I've raised PR's #111 #112 for this