Add documentation and change structure of the code

Move all code into functions.
Add a startEvent function to avoid duplicated code.
Add some global variables.
Only continue if we can get a connection to the Arduino and the
database.
Add some try-statements.