Then it’s probably with your broker
Try connecting to it after a power failure. BEFORE rebooting it again. With a utility like mqtt fx or mqtt explorer
If you can connect to your broker then it’s your devices. You code seems ok but you might want to flash one with something like tasmota to see if the problem occurs.
If you can’t connect to your broker after a power cut but you can after a reboot then your power cuts have probably damaged something in the SD card and there is boot/start-up problem.
You MUST protect linux machines from power cuts. If the power cat happens during a read/write of the SD card/Hard drive your system can be bricked. I suggest that you invest in a power bank (The type for mobile phone) to protect your pi. The ESPs will be fine. Make sure that you get one that can be charged and supply power at the same time (Not all can).
Then create a script to ping your router every minute. It it pings OK then the power in on. If no ping then the power is off and start a shut down sudo shutdown -h now
to cleanly shutdown linux.
Once the power is back, disconnect the pi from the power bank, connect it again. and off you go again.