So i have a sketch where i try to make a smart light using home assistant and mqtt broker. I need to configure the availability_topic, but for some reason when i add these lines in my sketch , the entity doesent apear any more in home assistant. Without the availability topic it worked fine . here is my discovery function:
void sendDiscoveryMessages() {
for (int i = 0; i < deviceCount; i++) {
char macStr[18];
snprintf(macStr, sizeof(macStr),
"%02x%02x%02x%02x%02x%02x",
deviceList[i].macAddr[0], deviceList[i].macAddr[1],
deviceList[i].macAddr[2], deviceList[i].macAddr[3],
deviceList[i].macAddr[4], deviceList[i].macAddr[5]);
String topic;
String payload = "{";
Serial.print("Free heap before: ");
Serial.println(ESP.getFreeHeap());
if (deviceList[i].deviceType == 1) { // Light device
topic = "homeassistant/light/" + String(macStr) + "/config";
payload += "\"name\":\"ESP32 Light\",";
payload += "\"unique_id\":\"" + String(macStr) + "\",";
payload += "\"command_topic\":\"home/" + String(macStr) + "/set\",";
payload += "\"state_topic\":\"home/" + String(macStr) + "/state\",";
payload += "\"brightness_command_topic\":\"home/" + String(macStr) + "/brightness/set\",";
payload += "\"availability_topic\":\"home/" + String(macStr) + "/availability\",";
// payload += "\"availability_mode\":\"latest\",";
payload += "\"payload_available\":\"Online\",";
payload += "\"payload_not_available\":\"Offline\",";
} else { // Sensor device
topic = "homeassistant/sensor/" + String(macStr) + "/config";
payload += "\"name\":\"ESP32 Sensor\",";
payload += "\"unique_id\":\"" + String(macStr) + "\",";
payload += "\"state_topic\":\"home/" + String(macStr) + "/state\",";
payload += "\"device_class\":\"sensor\",";
payload += "\"unit_of_measurement\":\"unit\",";
}
payload += "\"platform\":\"mqtt\"";
payload += "}";
Serial.print("Free heap after: ");
Serial.println(ESP.getFreeHeap());
Serial.println("Payload:");
Serial.println(payload);
String availabilityTopic = "home/" + String(macStr) + "/availability";
if (client.publish(availabilityTopic.c_str(), "Online", true)) {
Serial.print("Published initial availability (on) for ");
Serial.println(macStr);
} else {
Serial.print("Failed to publish availability for ");
Serial.println(macStr);
}
// Publicăm cu retain=true
client.publish(topic.c_str(), payload.c_str(), true);
Serial.println("Published discovery for " + String(macStr));
}
}
. When i coment this lines , the entity apears again.
payload += "\"availability_topic\":\"home/" + String(macStr) + "/availability\",";
// payload += "\"availability_mode\":\"latest\",";
payload += "\"payload_available\":\"Online\",";
payload += "\"payload_not_available\":\"Offline\",";
``` i checked the payload in serial and it looks fine , also if i manualy publish the payload everithink works, but when i try to publish the message from the esp with the availability_topic it doesent publish the config to the broker