Restructure the code as a state machine

Change the code to handle the device connection in a state machine fashion,
making the structure and flow a bit easier to follow. Clean up the code a bit
and add some comments.