How to handle an automatic re-join process?

I’ve copied some more reference code into How often should a node do an OTAA Join, and is OTAA better than ABP?

(The mac save should be done before removing the power.)