Better handling of connection failures (thanks smoolak)

close connection and retry to connect up to 3 times for each failed device id