Algorithm for managing Wifi and Cloud connections

@ScruffR thank you for the help on this previously. If you have a moment I would appreciate some direction if you have any advice.

I'm revisiting this issue and giving it another go. Everything seemed perfectly logical in my attempts, but after a few router reboots some photons would go into an indefinite blinking blue. Seems that this was an issue for others and I'm thinking that the culprit is an out of sockets issue related to the MQTT library. I haven't been able to prove this but it seems all to similar to others (links below) who were using TCPClient and had photons "lock up" on them. If I use automatic mode then I have no issues, but in my manual mode with threads enabled I'm will encounter this issue within a few days on most photons.

I'm using this fairly well known MQTT library GitHub - hirotakaster/MQTT: MQTT for Photon, Spark Core. Although this library seems to properly call client.stop as needed, perhaps it's worth a review.

Any help would be appreciated.
-Andy