check whether connected to peripheral, if not - reconnect, and then invoke peripheral function
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); };
    });
  } 
}
208916
def on_disconnect(self):
        ""
        if self._sock is not None:
            self._sock.close()
            self._sock = None
        if self._buffer is not None:
            self._buffer.close()
            self._buffer = None
        self.encoding = None
204774
function(connectInfo)
			{
				// DEBUG LOG
				console.log('BLE connect state: ' + connectInfo.state);
			
				if (connectInfo.state == 2) // connected
				{
					device.deviceHandle = connectInfo.deviceHandle;
					device.__uuidMap = {};
					device.__serviceMap = {};
					device.__isConnected = true;
					internal.connectedDevices[device.address] = device;

					success(device);
				}
				else if (connectInfo.state == 0) // disconnected
				{
					device.__isConnected = false;
					internal.connectedDevices[device.address] = null;

					// TODO: Perhaps this should be redesigned, as disconnect is
					// more of a status change than an error? What do you think?
					fail && fail(evothings.easyble.error.DISCONNECTED);
				}
			}
664468
def _try_connect(self, connection_string):
        """"""
        if self._parse_conn_string(connection_string):
            self._trigger_callback('on_disconnect', self.id, self._connection_id)

            self.stop_sync()

            if self._mux_func is not None:
                self._mux_func(self._channel)

            if self._device_info is None:
                raise ArgumentError("Missing device name or alias, specify using device=name in port string "
                                    "or -c device=name in connect_direct or debug command",
                                    known_devices=[x for x in DEVICE_ALIASES.keys()])

            try:
                self.jlink = pylink.JLink()
                self.jlink.open(serial_no=self._jlink_serial)
                self.jlink.set_tif(pylink.enums.JLinkInterfaces.SWD)
                self.jlink.connect(self._device_info.jlink_name)
                self.jlink.set_little_endian()
            except pylink.errors.JLinkException as exc:
                if exc.code == exc.VCC_FAILURE:
                    raise HardwareError("No target power detected", code=exc.code,
                                        suggestion="Check jlink connection and power wiring")

                raise
            except:
                raise

            self._control_thread = JLinkControlThread(self.jlink)
            self._control_thread.start()

            self.set_config('probe_required', True)
            self.set_config('probe_supported', True)
27956
def is_disconnect(e, connection, cursor):
    
    if isinstance(e, OperationalError):
        # these error messages from libpq: interfaces/libpq/fe-misc.c.
        # TODO: these are sent through gettext in libpq and we can't
        # check within other locales - consider using connection.closed
        return 'terminating connection' in str(e) or \
                'closed the connection' in str(e) or \
                'connection not open' in str(e) or \
                'could not receive data from server' in str(e)
    elif isinstance(e, InterfaceError):
        # psycopg2 client errors, psycopg2/conenction.h, psycopg2/cursor.h
        return 'connection already closed' in str(e) or \
                'cursor already closed' in str(e)
    elif isinstance(e, ProgrammingError):
        # not sure where this path is originally from, it may
        # be obsolete.   It really says "losed", not "closed".
        return "closed the connection unexpectedly" in str(e)
    else:
        return False
840709
async def reconnect(self):
        """"""
        _LOGGER.debug('starting Connection.reconnect')
        await self._connect()
        while self._closed:
            await self._retry_connection()
        _LOGGER.debug('ending Connection.reconnect')
1335845
function autoReconnect(options, connectionListener)
{
	var reconnectInterval = getOption(options, 'reconnectInterval', 5000);

	var reconnector = new events.EventEmitter();

	function reconnect()
	{
		var client = connect(options);
		var isReconnecting = false;
		
		function tryReconnecting()
		{
			if ( !isReconnecting )
			{
				isReconnecting = true;
				reconnector.emit('close');
			}
		}

		client.on('connect', () => {
			connectionListener(client);
		});

		client.on('close', () => {
			tryReconnecting();
		});

		client.on('error', (e) => {
			tryReconnecting();
		});
	}

	reconnector.on('close', () => {
		setTimeout(() => reconnector.emit('reconnect'), reconnectInterval);
	});

	reconnector.on('reconnect', () => {
		reconnect();
	});
	
	reconnect();
}
411543
def a_standby_console(ctx):
    """"""
    ctx.device.is_console = True
    ctx.ctrl.disconnect()
    raise ConnectionError("Standby console", ctx.ctrl.hostname)
49161
def __check_state(self):
        """"""
        state = self.__read_device()
        if not state:
            raise UnpluggedError(
                "Gamepad %d is not connected" % self.__device_number)
        if state.packet_number != self.__last_state.packet_number:
            # state has changed, handle the change
            self.__handle_changed_state(state)
            self.__last_state = state
1204443
def _run(self):
        ''''''
        stop = self._stop_evt
        connected = self._connected_evt
        tws = self._tws

        fd = tws.fd()
        pollfd = [fd]

        while not stop.is_set():
            while (not connected.is_set() or not tws.isConnected()) and not stop.is_set():
                connected.clear()
                backoff = 0
                retries = 0

                while not connected.is_set() and not stop.is_set():
                    if tws.reconnect_auto and not tws.reconnect():
                        if backoff < self.MAX_BACKOFF:
                            retries += 1
                            backoff = min(2**(retries + 1), self.MAX_BACKOFF)
                        connected.wait(backoff / 1000.)
                    else:
                        connected.wait(1)
                fd = tws.fd()
                pollfd = [fd]

            if fd > 0:
                try:
                    evtin, _evtout, evterr = select.select(pollfd, [], pollfd, 1)
                except select.error:
                    connected.clear()
                    continue
                else:
                    if fd in evtin:
                        try:
                            if not tws.checkMessages():
                                tws.eDisconnect(stop_polling=False)
                                continue
                        except (SystemExit, SystemError, KeyboardInterrupt):
                            break
                        except:
                            try:
                                self._wrapper.pyError(*sys.exc_info())
                            except:
                                print_exc()
                    elif fd in evterr:
                        connected.clear()
                        continue
1115685
def reconnectRemote(self, remote):
        
        if not isinstance(remote, Remote):
            raise PlenumTypeError('remote', remote, Remote)
        logger.info('{} reconnecting to {}'.format(self, remote))
        public, secret = self.selfEncKeys
        remote.disconnect()
        remote.connect(self.ctx, public, secret)
        self.sendPingPong(remote, is_ping=True)
758374
def is_connected(self):
        
        if self._client is not None:
            try:
                self._client.server_info()
            except ConnectionFailure:
                return False
            return True
        else:
            return False
1156602
function(client, window, reconnectInterval) { 
		this._client = client;        	
		this._window = window;
		this._reconnectInterval = reconnectInterval*1000;
		
		var doTimeout = function (reconnector) {
			return function () {
				return doReconnect.apply(reconnector);
			};
		};
		
		/** @ignore */
		var doReconnect = function() { 
			if (this._client.connected) {
				this._client._trace("Reconnector.doReconnect", "ALREADY CONNECTED");
				this._window.clearTimeout(this.reconnectorTimer);
			} else {
				this._client._trace("Reconnector.doReconnect", "reconnecting");
				if (this._client.connectOptions.uris) {
					this._client.hostIndex = 0;
					this._client._doConnect(this._client.connectOptions.uris[0]);  
				} else {
					this._client._doConnect(this._client.uri);
				}
				this.reconnectorTimer = this._window.setTimeout(doTimeout(this), this._reconnectInterval);
			}
		}
		
		this.reset = function() {
			this._window.clearTimeout(this.reconnectorTimer);
			this.reconnectorTimer = this._window.setTimeout(doTimeout(this), this._reconnectInterval);
		}

		this.cancel = function() {
			this._window.clearTimeout(this.reconnectorTimer);
		}
	 }
1174405
def connect(self, protocol=None):
        """"""
        self._link.enter_debug(STLink.Protocol.SWD)
        self._is_connected = True
790115
def timed_connectivity_check(self, event):
        """"""
        self.status = self._can_connect()
        self.log('Timed connectivity check:', self.status, lvl=verbose)

        if self.status:
            if not self.old_status:
                self.log('Connectivity gained')
                self.fireEvent(backend_nodestate_toggle(STATE_UUID_CONNECTIVITY, on=True, force=True))
        else:
            if self.old_status:
                self.log('Connectivity lost', lvl=warn)
                self.old_status = False
                self.fireEvent(backend_nodestate_toggle(STATE_UUID_CONNECTIVITY, off=True, force=True))

        self.old_status = self.status
1023500
function (obj) {
			if (typeof connHandler === 'function')
				connHandler('disconnect');
			
			SR.Warn('disconnected... obj: ');
			SR.Warn(obj);
			
			// attempt to re-connect
			if (typeof conn_options === 'object') {
				removeEntry(currentEntry);
				currentEntry = undefined;
				SR.Warn('re-connecting websocket with options');
				SR.Warn(conn_options);
				SR.setSocketServer(conn_options);
			}
		}
358842
def ping(self, reconnect=True):
        
        if self._sock is None:
            if reconnect:
                self.connect()
                reconnect = False
            else:
                raise err.Error("Already closed")
        try:
            self._execute_command(COMMAND.COM_PING, "")
            self._read_ok_packet()
        except Exception:
            if reconnect:
                self.connect()
                self.ping(False)
            else:
                raise