Connect to the websocket, and ensure the account is connected and
        the INBOX is being watched, and then start watchingAll.
769702
def opened(self):
        
        def post_setup((cmds, resps)):
            """Post setup callback."""
            logger.info("Setup complete, listening...")

        self.send_cmds(('connect', CONN_SPEC),
                       ('watchMailboxes', {'account': ACCOUNT,
                                           'list': ['INBOX']}),
                       ('watchAll', {})).then(post_setup)
76586
def _start_loop(self, websocket, event_handler):
		
		log.debug('Starting websocket loop')
		while True:
			try:
				yield from asyncio.wait_for(
					self._wait_for_message(websocket, event_handler),
					timeout=self.options['timeout']
				)
			except asyncio.TimeoutError:
				yield from websocket.pong()
				log.debug("Sending heartbeat...")
				continue
143126
def start(self):
        
        if not self.connection:
            self.create_connection()
        while True:
            try:
                channel = self.connection.channel()
                channel.queue.declare('simple_queue')
                channel.basic.consume(self, 'simple_queue', no_ack=False)
                channel.start_consuming()
                if not channel.consumer_tags:
                    channel.close()
            except amqpstorm.AMQPError as why:
                LOGGER.exception(why)
                self.create_connection()
            except KeyboardInterrupt:
                self.connection.close()
                break
875594
def connect(self):
        
        logger.info("Connecting to Redis on {host}:{port}...".format(
            host=self.host, port=self.port))

        super(RedisSubscriber, self).connect()
        logger.info("Successfully connected to Redis")

        # Subscribe to channel
        self.pubsub = self.client.pubsub()
        self.pubsub.subscribe(self.channel)

        logger.info("Subscribed to [{channel}] Redis channel".format(
            channel=self.channel))

        # Start listening
        t = Thread(target=self.listen)
        t.setDaemon(True)
        t.start()
547038
private void startWatcher() {

        if (m_watcher == null) {
            try {
                m_watcher = new CmsUploadTimeoutWatcher(this);
                m_watcher.start();
            } catch (Exception e) {
                LOG.info(
                    Messages.get().getBundle().key(Messages.LOG_UPLOAD_CREATE_WATCH_DOG_2, getId(), e.getMessage()));
            }
        }
    }
482962
def start_watching
      return if @worker
      @worker = Thread.new do
        loop do
          event = read
          next unless ALLOWED_EVENT_TYPES.include?(event.type)
          case event.type
            when BUTTON_TYPE
              RubyHid::Button.trigger_event(event.code, event.value)
            when AXIS_TYPE
              RubyHid::Axis.trigger_event(event.code, event.value)
          end
        end
      end
    end
349257
public void connect() {

        readyState = ReadyState.CONNECTING;

        try {
            if (webSocketHandler == null) {
                webSocketHandler = new WebSocketHandlerAdapter();
            }

            container.connectToServer(new SimpleWebSocketClientEndpoint(), ClientEndpointConfig.Builder.create().build(), websocketURI);
        } catch (Exception e) {

            readyState = ReadyState.CLOSED;
            // throws DeploymentException, IOException
            throw new RuntimeException("could not establish connection");

        }
    }
291363
void becomeConnected(Sink sink, Socket socket) {
    checkState(this.sink == null, "AsyncSink's becomeConnected should only be called once.");
    this.sink = checkNotNull(sink, "sink");
    this.socket = checkNotNull(socket, "socket");
  }
200487
def start_watching
      return if @worker
      @worker = Thread.new do
        loop do
          event = read
          next unless event.type == 1
          next unless event.value == 1
          RubyBuzz::Button.trigger_key(event.code)
        end
      end
    end
734202
def connect(self, cback, subscribers=None, instance=None):
        
        if subscribers is None:
            subscribers = self.subscribers
        # wrapper
        if self._fconnect is not None:
            def _connect(cback):
                self._connect(subscribers, cback)

            notify = partial(self._notify_one, instance)
            if instance is not None:
                result = self._fconnect(instance, cback, subscribers,
                                        _connect, notify)
            else:
                result = self._fconnect(cback, subscribers, _connect, notify)
            if inspect.isawaitable(result):
                result = pull_result(result)
        else:
            self._connect(subscribers, cback)
            result = None
        return result
912373
def start(self):
        """"""
        self.publish_properties()
        self.subscribe_topics()
        gc.collect()

        self.set_state("ready")

        while True:
            try:
                if not utils.wlan.isconnected():
                    utils.wifi_connect()

                # publish device data
                self.publish_data()

                # check for new mqtt messages
                self.mqtt.check_msg()

                idle()
                sleep(1)
            except KeyboardInterrupt:
                self.set_state("disconnected")
                self.mqtt.disconnect()
59766
def _watch(self):
        
        async def _all_watcher():
            try:
                allwatcher = client.AllWatcherFacade.from_connection(
                    self.connection())
                while not self._watch_stopping.is_set():
                    try:
                        results = await utils.run_with_interrupt(
                            allwatcher.Next(),
                            self._watch_stopping,
                            loop=self._connector.loop)
                    except JujuAPIError as e:
                        if 'watcher was stopped' not in str(e):
                            raise
                        if self._watch_stopping.is_set():
                            # this shouldn't ever actually happen, because
                            # the event should trigger before the controller
                            # has a chance to tell us the watcher is stopped
                            # but handle it gracefully, just in case
                            break
                        # controller stopped our watcher for some reason
                        # but we're not actually stopping, so just restart it
                        log.warning(
                            'Watcher: watcher stopped, restarting')
                        del allwatcher.Id
                        continue
                    except websockets.ConnectionClosed:
                        monitor = self.connection().monitor
                        if monitor.status == monitor.ERROR:
                            # closed unexpectedly, try to reopen
                            log.warning(
                                'Watcher: connection closed, reopening')
                            await self.connection().reconnect()
                            if monitor.status != monitor.CONNECTED:
                                # reconnect failed; abort and shutdown
                                log.error('Watcher: automatic reconnect '
                                          'failed; stopping watcher')
                                break
                            del allwatcher.Id
                            continue
                        else:
                            # closed on request, go ahead and shutdown
                            break
                    if self._watch_stopping.is_set():
                        try:
                            await allwatcher.Stop()
                        except websockets.ConnectionClosed:
                            pass  # can't stop on a closed conn
                        break
                    for delta in results.deltas:
                        try:
                            delta = get_entity_delta(delta)
                            old_obj, new_obj = self.state.apply_delta(delta)
                            await self._notify_observers(delta, old_obj, new_obj)
                        except KeyError as e:
                            log.debug("unknown delta type: %s", e.args[0])
                    self._watch_received.set()
            except CancelledError:
                pass
            except Exception:
                log.exception('Error in watcher')
                raise
            finally:
                self._watch_stopped.set()

        log.debug('Starting watcher task')
        self._watch_received.clear()
        self._watch_stopping.clear()
        self._watch_stopped.clear()
        self._connector.loop.create_task(_all_watcher())
324830
public void onOpen() {
    LOGGER.d("webSocket established...");
    connectionEstablished = true;
    retryConnectionCount = 0;
    for (AVConnectionListener listener: connectionListeners.values()) {
      listener.onWebSocketOpen();
    }

    resetConnectingStatus(true);

    // auto send login packet.
    LoginPacket lp = new LoginPacket();
    lp.setAppId(AVOSCloud.getApplicationId());
    lp.setInstallationId(AVInstallation.getCurrentInstallation().getInstallationId());
    this.sendPacket(lp);
  }
311050
def _connected(self, watcher, events):
        """"""
        self.connected = True
        self._finish()
        self.deferred.callback(self.sock)
1161486
function initiateSubscribe(clientObj) {
  this.__channels = {};
  var self = this;
  clientObj.subscribe('internalPing');
  clientObj.on('message', function(channelName, message) {
    if (channelName === 'internalPing') return;  // this is our internal channel for ping
    if (typeof self.__channels[channelName] === 'undefined') return; // we have no channel.
    try {
      var data = JSON.parse(message);
    } catch (e) {
      data = message;
    }
    for (var i = 0; i < self.__channels[channelName].length; i++) {
      self.__channels[channelName][i](data);
    }
  });
}
571501
async def start(self):
        """"""
        if self.connection.connected:
            return

        await self.connection.connect()

        # In case credentials have been given externally (i.e. not by pairing
        # with a device), then use that client id
        if self.service.device_credentials:
            self.srp.pairing_id = Credentials.parse(
                self.service.device_credentials).client_id

        # The first message must always be DEVICE_INFORMATION, otherwise the
        # device will not respond with anything
        msg = messages.device_information(
            'pyatv', self.srp.pairing_id.decode())
        await self.send_and_receive(msg)
        self._initial_message_sent = True

        # This should be the first message sent after encryption has
        # been enabled
        await self.send(messages.set_ready_state())

        async def _wait_for_updates(_, semaphore):
            # Use a counter here whenever more than one message is expected
            semaphore.release()

        # Wait for some stuff to arrive before returning
        semaphore = asyncio.Semaphore(value=0, loop=self.loop)
        self.add_listener(_wait_for_updates,
                          protobuf.SET_STATE_MESSAGE,
                          data=semaphore,
                          one_shot=True)

        # Subscribe to updates at this stage
        await self.send(messages.client_updates_config())
        await self.send(messages.wake_device())

        try:
            await asyncio.wait_for(
                semaphore.acquire(), 1, loop=self.loop)
        except asyncio.TimeoutError:
            # This is not an issue itself, but I should do something better.
            # Basically this gives the device about one second to respond with
            # some metadata before continuing.
            pass
1197627
async def running(self):
        """"""
        try:
            async with self._session.ws_connect(self._url) as ws:
                self.state = STATE_RUNNING
                async for msg in ws:
                    if msg.type == aiohttp.WSMsgType.TEXT:
                        ensure_future(self._async_callback(
                            json.loads(msg.data)))
                        _LOGGER.debug('Websocket data: %s', msg.data)
                    elif msg.type == aiohttp.WSMsgType.CLOSED:
                        break
                    elif msg.type == aiohttp.WSMsgType.ERROR:
                        break
        except aiohttp.ClientConnectorError:
            if self.state != STATE_STOPPED:
                self.retry()
        except Exception as err:
            _LOGGER.error('Unexpected error %s', err)
            if self.state != STATE_STOPPED:
                self.retry()
        else:
            if self.state != STATE_STOPPED:
                self.retry()