Connecting to Mosquitto fails when rebooting Raspberry Pi

I have a Raspberry Pi 3B that I run Hassbian on. In addition, I also run a Mosquitto server on the RPi. In my garage I have a Node MCU controller that monitors the garage door state, which connects to Home Assistant using MQTT and the Mosquitto server.

My problem is that every time I reboot the RPi, the NodeMCU in the garage becomes unavailable in HA. I have to reboot the NodeMCU also to get it back in HA. What can be the problem here? I would think that no matter if it’s HA or Mosquitto that’s first up and running when the RPi reboots, HA would read an available message from the NodeMCU. The NodeMCU is set up with a Last Will message that sets it as unavailable when connection to Mosquitto is lost (I would guess this also includes when the server reboots). But it also sets itself as available with retain flag set to true when connecting again.

So I don’t get why it’s still unavailable. Anybody got an idea here?

It is the responsibility of the MQTT client on the Node MCU to:

  • detect the loss of the MQTT connection
  • periodically attempt to reconnect to a broker until a new connection is established
  • resubscribe to topics after an outage
  • publish / republish messages (optional … as requirements dictate).

I work with Particle nodes and probably a different MQTT library, so I’m not sure a code sample will be of much use … but my MQTT code block is in this .ino file: edison.ino

Thanks for the input, @rwpalmer. I have to admit I found the problem. I actually didn’t set the retain flag on the “online” message, only on the “offline” message. So I guess the Mosquitto server got up and running first, and the NodeMCU sent its “online” message without retain. So when HA got up and running, the server still reported “offline”. Doh

But thanks again. Your answer will help in improving the MQTT connection.