             @emit 'error', error
 
         @ws.on 'open', =>
+            @_connecting = false
+            @_reconnecting = false
             @connected = true
             @emit 'connected'
             @_connAttempts = 0
             @_lastPong = Date.now()
             @logger.info 'Starting pinger...'
             @_pongTimeout = setInterval =>
-                if not @connected then return
-
-                @logger.info 'ping'
-                @_send {"action": "ping"}
-                if @_lastPong? and Date.now() - @_lastPong > (2*@_pingInterval)
+                if not @connected
+                    @logger.error 'Not connected in pongTimeout'
+                    @reconnect()
+                    return
+                if @_lastPong? and (Date.now() - @_lastPong) > (2*@_pingInterval)
                     @logger.error "Last pong is too old: %d", (Date.now() - @_lastPong) / 1000
                     @authenticated = false
                     @connected = false
                     @reconnect()
+                else
+                    @logger.info 'ping'
+                    @_send {"action": "ping"}
             , @_pingInterval
 
         @ws.on 'message', (data, flags) =>

            @emit 'close', code, message
            @connected = false
            @socketUrl = null

        return true

    reconnect: ->
        if @_pongTimeout
            clearInterval @_pongTimeout
            @_pongTimeout = null

                        callback({'id': null, 'error': 'API response: '+res.statusCode}, res.headers)

        req.on 'error', (error) =>
            if callback? then callback({'id': null, 'error': error.errno}, {})

        req.write('' + post_data)
        req.end()
