HA shows ESP32 MQTT sensors as "unavailable" between readings

I have an ESP32 witch performs the following actions:

  • boot
  • connect to WiFi
  • connect to MQTT broker
  • read and send sensor data
  • got to deep sleep
    • then code repeats.

Problem is that sensor data in HA only shows sensor value shortly after it is received. Then the value goes to "unavailable’ when ESP32 is in deep sleep.

If using HA API instead of MQTT, the instruction say to delete the device and re-add once deep-sleep code has been added. This way HA knows to preserve the sensor reading.
But if using MQTT and there is no “api:” then ESP32 can’t be re-added. HA just doesn’t see it and it can’t be re-added (though MQTT messages continue to be sent).

This is a well documented problem on the forum. You need to mangle the will topic.