Reliable bluetooth autoconnect

I am programming a little app that'd I'd like to automatically connect to an arduino via a bluetooth. The arduino has to be switched on via a web request to a shelly smart plug. So essentially start app click button 1 start the shelly realay to get the arduino to turn on, then automatically connect to the arduino via the hc 05 bluetooth module.
Everything works fine but I cant get it to reliably connect via bluetooth. Sometimes it works, sometimes the module just keeps flashing in paring mode and trying to send commands will result in Error 516:Unable to write:Broken pipe.
Closing the app while leaving the relay on fixes the issue the bluetooth connects every time.


This is the little function I use to connect. Is there a better way to autoconnect to a bluetooth module? I have been trying to get this to work for ever.
Thanks a lot.

Do not use a while loop... use an if statement instead


An if statement doesn't work thats what I tried first. The relay switches the arduino and the bluetooth module on. After that It takes maybe 2-3 seconds before I can see the bluetooth module blinking which means it is waiting for connections from paired devices. That's why I used the while loop. So the app keeps trying to connect to the module till it succeeds.

How about an If in a Clock Timer?

I am not sure if this was the implementation you were suggesting but I added a delay and while it is not perfect (still sometimes throwing an error) it works much better
Thanks for your help!