Timer for the connectivity checks // Private API
516733
function validateCallback (name, callback) {
          if (callback === null || !OT.$.isFunction(callback) ) {
            throw new Error('The Rumor.Socket ' + name +
              ' callback must be a valid function or null');
          }
        }
232406
private void checkTimer()
    {
        try
        {
            serviceThreadLock.lock();

            if ( watchdogTimer == null )
            {
                // if there is NOT an active timer
                if ( !issuedWatchdogWrappers.allValues().isEmpty() )
                {
                    // if there are active providers.
                    LOGGER.debug( "starting up " + THREAD_NAME + ", " + watchdogFrequency + "ms check frequency" );

                    // create a new timer
                    startWatchdogThread();
                }
            }
        }
        finally
        {
            serviceThreadLock.unlock();
        }
    }
519992
function checkConnected(peripheral, callback){
  if (peripheral.state === 'connected') {
    debug(' - connected');
    if (callback) { callback(); }
  } else if (peripheral.state === 'connecting'){
    debug(' - connecting....');
    //wait until the connection completes, invoke callback    
    peripheral.once('connect', function(){
      if (callback){
        callback();
      }
    }) 
  } 
  else { //not connected
    debug(' - not connected');
    //if peripheral is lost by noble
    if (! noble._peripherals[peripheral.id]) {
        console.log('No such peripheral! This should not happen, restart manually...');
        return
    }

    peripheral.connect( function(error) {
        if (error) {
          debug('checkconnected -> reconnect error !'.red + error)
        } else {
          debug('checkconnected -> reconnect');          
        }
        if (callback) { callback(error); };
    });
  } 
}
559026
function checkClientsHeartbeat() {
    var now = Date.now();
    _.forOwn(_this.socks, function (sock) {
      if (sock.hb + _this.clientTimeout < now) {
        logout(sock);
      }
    });
    setTimeout(checkClientsHeartbeat, 1000)
  }
330390
public void checkConnection() {
        long start = Time.currentTimeMillis();

        while (clientChannel == null) {

            tcpSocketConsumer.checkNotShutdown();

            if (start + timeoutMs > Time.currentTimeMillis())
                try {
                    condition.await(1, TimeUnit.MILLISECONDS);

                } catch (InterruptedException e) {
                    throw new IORuntimeException("Interrupted");
                }
            else
                throw new IORuntimeException("Not connected to " + socketAddressSupplier);
        }

        if (clientChannel == null)
            throw new IORuntimeException("Not connected to " + socketAddressSupplier);
    }
256194
private void addReconnectTimer()
    {
        int rcIvl = getNewReconnectIvl();
        ioObject.addTimer(rcIvl, RECONNECT_TIMER_ID);

        // resolve address again to take into account other addresses
        // besides the failing one (e.g. multiple dns entries).
        try {
            addr.resolve(options.ipv6);
        }
        catch (Exception ignored) {
            // This will fail if the network goes away and the
            // address cannot be resolved for some reason. Try
            // not to fail as the event loop will quit
        }

        socket.eventConnectRetried(addr.toString(), rcIvl);
        timerStarted = true;
    }
817431
function() {
                var asyncGetReadyTime = new Date().getTime();

                asyncClient = new Async({
                    protocol: protocol,
                    queueHost: queueHost,
                    queuePort: queuePort,
                    queueUsername: queueUsername,
                    queuePassword: queuePassword,
                    queueReceive: queueReceive,
                    queueSend: queueSend,
                    queueConnectionTimeout: queueConnectionTimeout,
                    socketAddress: socketAddress,
                    serverName: serverName,
                    deviceId: deviceId,
                    wsConnectionWaitTime: wsConnectionWaitTime,
                    connectionRetryInterval: connectionRetryInterval,
                    connectionCheckTimeout: connectionCheckTimeout,
                    connectionCheckTimeoutThreshold: connectionCheckTimeoutThreshold,
                    messageTtl: messageTtl,
                    reconnectOnClose: reconnectOnClose,
                    asyncLogging: asyncLogging
                });

                asyncClient.on('asyncReady', function() {
                    if (actualTimingLog) {
                        Utility.chatStepLogger('Async Connection ', new Date().getTime() - asyncGetReadyTime);
                    }

                    peerId = asyncClient.getPeerId();

                    if (!userInfo) {
                        var getUserInfoTime = new Date().getTime();

                        getUserInfo(function(userInfoResult) {
                            if (actualTimingLog) {
                                Utility.chatStepLogger('Get User Info ', new Date().getTime() - getUserInfoTime);
                            }
                            if (!userInfoResult.hasError) {
                                userInfo = userInfoResult.result.user;

                                /**
                                 * Check if user has KeyId stored in their cache or not?
                                 */
                                if (canUseCache) {
                                    if (db) {
                                        db.users
                                            .where('id')
                                            .equals(userInfo.id)
                                            .toArray()
                                            .then(function(users) {
                                                if (users.length > 0 && typeof users[0].keyId != 'undefined') {
                                                    var user = users[0];

                                                    getEncryptionKey({
                                                        keyId: user.keyId
                                                    }, function(result) {
                                                        if (!result.hasError) {
                                                            cacheSecret = result.secretKey;
                                                        }
                                                        else {
                                                            if (result.message != '') {
                                                                try {
                                                                    var response = JSON.parse(result.message);
                                                                    if (response.error == 'invalid_param') {
                                                                        generateEncryptionKey({
                                                                            keyAlgorithm: 'AES',
                                                                            keySize: 256
                                                                        });
                                                                    }
                                                                }
                                                                catch (e) {
                                                                    console.log(e);
                                                                }
                                                            }
                                                        }
                                                    });
                                                }
                                                else {
                                                    generateEncryptionKey({
                                                        keyAlgorithm: 'AES',
                                                        keySize: 256
                                                    });
                                                }
                                            })
                                            .catch(function(error) {
                                                fireEvent('error', {
                                                    code: error.errorCode,
                                                    message: error.errorMessage,
                                                    error: error
                                                });
                                            });
                                    }
                                    else {
                                        fireEvent('error', {
                                            code: 6601,
                                            message: CHAT_ERRORS[6601],
                                            error: null
                                        });
                                    }
                                }

                                chatState = true;
                                fireEvent('chatReady');
                                chatSendQueueHandler();
                            }
                        });
                    }
                    else if (userInfo.id > 0) {
                        chatState = true;
                        fireEvent('chatReady');
                        chatSendQueueHandler();
                    }
                });

                asyncClient.on('stateChange', function(state) {
                    fireEvent('chatState', state);
                    chatFullStateObject = state;

                    switch (state.socketState) {
                        case 1: // CONNECTED
                            if (state.deviceRegister && state.serverRegister) {
                                chatState = true;
                                ping();
                            }
                            break;
                        case 0: // CONNECTING
                        case 2: // CLOSING
                        case 3: // CLOSED
                            chatState = false;
                            break;
                    }
                });

                asyncClient.on('connect', function(newPeerId) {
                    asyncGetReadyTime = new Date().getTime();
                    peerId = newPeerId;
                    fireEvent('connect');
                    ping();
                });

                asyncClient.on('disconnect', function(event) {
                    oldPeerId = peerId;
                    peerId = undefined;
                    fireEvent('disconnect', event);
                });

                asyncClient.on('reconnect', function(newPeerId) {
                    peerId = newPeerId;
                    fireEvent('reconnect');
                });

                asyncClient.on('message', function(params, ack) {
                    receivedAsyncMessageHandler(params);
                    ack && ack();
                });

                asyncClient.on('error', function(error) {
                    fireEvent('error', {
                        code: error.errorCode,
                        message: error.errorMessage,
                        error: error.errorEvent
                    });
                });
            }
1260148
def checkTimeout(self, now):
        """"""
        log.debug("checking for timeout on session %s", self)
        if now - self.last_update > self.timeout:
            raise TftpTimeout("Timeout waiting for traffic")
964540
def _check_connection(self):
        
        # check if connection is expired
        reset = False
        if self._force_recon:
            self.logger.warning(
                "[%s:%s] Error communicating with socket, resetting "
                "connection",
                self.fn or self.host, self.port)
            reset = True

        elif self.heartbeat_controller.is_expired():
            self.logger.warning(
                "[%s:%s] Heartbeat timeout, resetting connection",
                self.fn or self.host, self.port)
            reset = True

        if reset:
            for channel in self._open_channels:
                self.disconnect_channel(channel)
            self._report_connection_status(
                ConnectionStatus(CONNECTION_STATUS_LOST,
                                 NetworkAddress(self.host, self.port)))
            try:
                self.initialize_connection()
            except ChromecastConnectionError:
                self.stop.set()
            return False
        return True
240775
def wait_for_net(self, timeout=None, wait_polling_interval=None):
        
        if timeout is None:
            timeout = self._timeout
        if wait_polling_interval is None:
            wait_polling_interval = self._wait_polling_interval

        self._logger.info("Waiting for network connection")
        poll_wait(self.get_ip_address, timeout=timeout)
471765
def _wait_until_connectable(self, timeout=30):
        """"""
        count = 0
        while not utils.is_connectable(self.profile.port):
            if self.process.poll() is not None:
                # Browser has exited
                raise WebDriverException(
                    "The browser appears to have exited "
                    "before we could connect. If you specified a log_file in "
                    "the FirefoxBinary constructor, check it for details.")
            if count >= timeout:
                self.kill()
                raise WebDriverException(
                    "Can't load the profile. Possible firefox version mismatch. "
                    "You must use GeckoDriver instead for Firefox 48+. Profile "
                    "Dir: %s If you specified a log_file in the "
                    "FirefoxBinary constructor, check it for details."
                    % (self.profile.path))
            count += 1
            time.sleep(1)
        return True
427589
def __on_connect(self, client, userdata, flags, result_code):
        # pylint: disable=W0613
        
        if result_code:
            # result_code != 0: something wrong happened
            _logger.error(
                "Error connecting the MQTT server: %s (%d)",
                paho.connack_string(result_code),
                result_code,
            )
        else:
            # Connection is OK: stop the reconnection timer
            self.__stop_timer()

        # Notify the caller, if any
        if self.on_connect is not None:
            try:
                self.on_connect(self, result_code)
            except Exception as ex:
                _logger.exception("Error notifying MQTT listener: %s", ex)
158567
def a_connection_timeout(ctx):
    """"""
    prompt = ctx.ctrl.after
    ctx.msg = "Received the jump host prompt: '{}'".format(prompt)
    ctx.device.connected = False
    ctx.finished = True
    raise ConnectionTimeoutError("Unable to connect to the device.", ctx.ctrl.hostname)
729647
def run(self):
        """"""
        if ProfileCollection and isinstance(self.mloginfo.logfile,
                                            ProfileCollection):
            print("\n    not available for system.profile collections\n")
            return

        ip_opened = defaultdict(lambda: 0)
        ip_closed = defaultdict(lambda: 0)

        socket_exceptions = 0

        START_TIME_EMPTY = -11
        END_TIME_ALREADY_FOUND = -111
        MIN_DURATION_EMPTY = 9999999999
        MAX_DURATION_EMPTY = -1

        end_connid_pattern = re.compile(r'\[conn(\d+)\]')

        genstats = self.mloginfo.args['connstats']
        if genstats:
            connections_start = defaultdict(lambda: START_TIME_EMPTY)
            ipwise_sum_durations = defaultdict(lambda: 0)
            ipwise_count = defaultdict(lambda: 0)
            ipwise_min_connection_duration = defaultdict(lambda:
                                                         MIN_DURATION_EMPTY)
            ipwise_max_connection_duration = defaultdict(lambda:
                                                         MAX_DURATION_EMPTY)

            min_connection_duration = MIN_DURATION_EMPTY
            max_connection_duration = MAX_DURATION_EMPTY

            sum_durations = 0
            fullconn_counts = 0

        for logevent in self.mloginfo.logfile:
            line = logevent.line_str

            pos = line.find('connection accepted')
            if pos != -1:
                # connection was opened, increase counter
                tokens = line[pos:pos + 100].split(' ')
                if tokens[3] == 'anonymous':
                    ip = 'anonymous'
                else:
                    ip, _ = tokens[3].split(':')
                ip_opened[ip] += 1

                if genstats:
                    connid = tokens[4].strip('#')
                    dt = logevent.datetime

                    # Sanity checks
                    if connid.isdigit() is False or dt is None:
                        continue

                    if connections_start[connid] != START_TIME_EMPTY:
                        errmsg = ("Multiple start datetimes found for the "
                                  "same connection ID. Consider analysing one "
                                  "log sequence.")
                        raise NotImplementedError(errmsg)

                    connections_start[connid] = dt

            pos = line.find('end connection')
            if pos != -1:
                # connection was closed, increase counter
                tokens = line[pos:pos + 100].split(' ')
                if tokens[2] == 'anonymous':
                    ip = 'anonymous'
                else:
                    ip, _ = tokens[2].split(':')
                ip_closed[ip] += 1

                if genstats:

                    # Sanity check
                    if end_connid_pattern.search(line, re.M | re.I) is None:
                        continue

                    # The connection id value is stored just before end
                    # connection -> [conn385] end connection
                    end_connid = (end_connid_pattern.
                                  search(line, re.M | re.I).group(1))
                    dt = logevent.datetime

                    # Sanity checks
                    if (end_connid.isdigit() is False or dt is None or
                            connections_start[end_connid] == START_TIME_EMPTY):
                        continue

                    if connections_start[end_connid] == END_TIME_ALREADY_FOUND:
                        errmsg = ("Multiple end datetimes found for the same "
                                  "connection ID %s. Consider analysing one "
                                  "log sequence.")
                        raise NotImplementedError(errmsg % (end_connid))

                    dur = dt - connections_start[end_connid]
                    dur_in_sec = dur.seconds

                    if dur_in_sec < min_connection_duration:
                        min_connection_duration = dur_in_sec

                    if dur_in_sec > max_connection_duration:
                        max_connection_duration = dur_in_sec

                    if dur_in_sec < ipwise_min_connection_duration[ip]:
                        ipwise_min_connection_duration[ip] = dur_in_sec

                    if dur_in_sec > ipwise_max_connection_duration[ip]:
                        ipwise_max_connection_duration[ip] = dur_in_sec

                    sum_durations += dur.seconds
                    fullconn_counts += 1

                    ipwise_sum_durations[ip] += dur_in_sec
                    ipwise_count[ip] += 1

                    connections_start[end_connid] = END_TIME_ALREADY_FOUND

            if "SocketException" in line:
                socket_exceptions += 1

        # calculate totals
        total_opened = sum(ip_opened.values())
        total_closed = sum(ip_closed.values())

        unique_ips = set(ip_opened.keys())
        unique_ips.update(ip_closed.keys())

        # output statistics
        print("     total opened: %s" % total_opened)
        print("     total closed: %s" % total_closed)
        print("    no unique IPs: %s" % len(unique_ips))
        print("socket exceptions: %s" % socket_exceptions)
        if genstats:
            if fullconn_counts > 0:
                print("overall average connection duration(s): %s"
                      % (sum_durations / fullconn_counts))
                print("overall minimum connection duration(s): %s"
                      % min_connection_duration)
                print("overall maximum connection duration(s): %s"
                      % max_connection_duration)
            else:
                print("overall average connection duration(s): -")
                print("overall minimum connection duration(s): -")
                print("overall maximum connection duration(s): -")
        print('')

        for ip in sorted(unique_ips, key=lambda x: ip_opened[x], reverse=True):
            opened = ip_opened[ip] if ip in ip_opened else 0
            closed = ip_closed[ip] if ip in ip_closed else 0

            if genstats:
                covered_count = (
                    ipwise_count[ip]
                    if ip in ipwise_count
                    else 1)
                connection_duration_ip = (
                    ipwise_sum_durations[ip]
                    if ip in ipwise_sum_durations
                    else 0)
                ipwise_min_connection_duration_final = (
                    ipwise_min_connection_duration[ip]
                    if ipwise_min_connection_duration[ip] != MIN_DURATION_EMPTY
                    else 0)
                ipwise_max_connection_duration_final = (
                    ipwise_max_connection_duration[ip]
                    if ipwise_max_connection_duration[ip] != MAX_DURATION_EMPTY
                    else 0)

                print("%-15s  opened: %-8i  closed: %-8i dur-avg(s): %-8i "
                      "dur-min(s): %-8i dur-max(s): %-8i"
                      % (ip, opened, closed,
                         connection_duration_ip / covered_count,
                         ipwise_min_connection_duration_final,
                         ipwise_max_connection_duration_final))
            else:
                print("%-15s  opened: %-8i  closed: %-8i"
                      % (ip, opened, closed))

        print('')
535378
def _start_check_timer(self):
        
        if self.timer:
            self.timer.cancel()
        self.timer = threading.Timer(2.5, self.check_complete)
        self.timer.daemon = True
        self.timer.start()
1265706
void statsCloseConnection(long duration,int requests)
    {
        synchronized(_statsLock)
        {
            _connections++;
            _connectionsOpen--;
            _connectionsDurationTotal+=duration;
            if (_connectionsOpen<0)
                _connectionsOpen=0;
            if (_connectionsOpen<_connectionsOpenMin)
                _connectionsOpenMin=_connectionsOpen;
            if (_connectionsDurationMin==0 || duration<_connectionsDurationMin)
                _connectionsDurationMin=duration;
            if (duration>_connectionsDurationMax)
                _connectionsDurationMax=duration;
            if (_connectionsRequestsMin==0 || requests<_connectionsRequestsMin)
                _connectionsRequestsMin=requests;
            if (requests>_connectionsRequestsMax)
                _connectionsRequestsMax=requests;
        }
    }
800230
function () {
        var that = this;
        this.socket.setNoDelay(true);
        this.socket.setKeepAlive(true, 15 * 1000); //every 15 second(s)
        this.socket.on('error', function (err) {
            that.disconnect("socket error " + err);
        });

        this.socket.on('close', function (err) { that.disconnect("socket close " + err); });
        this.socket.on('timeout', function (err) { that.disconnect("socket timeout " + err); });

        this.handshake();
    }