original_docstring: Connect to the IoT broker.
docstring: Connect to the IoT broker.
docstring_tokens: Connect to the IoT broker .
code: def _handle_connection(self):
          """Connect to the IoT broker."""
          hass = self.cloud.hass
  
          try:
              yield from hass.async_add_job(auth_api.check_token, self.cloud)
          except auth_api.Unauthenticated as err:
              _LOGGER.error('Unable to refresh token: %s', err)
  
              hass.components.persistent_notification.async_create(
                  MESSAGE_AUTH_FAIL, 'Home Assistant Cloud',
                  'cloud_subscription_expired')
  
              # Don't await it because it will cancel this task
              hass.async_add_job(self.cloud.logout())
              return
          except auth_api.CloudError as err:
              _LOGGER.warning("Unable to refresh token: %s", err)
              return
  
          if self.cloud.subscription_expired:
              hass.components.persistent_notification.async_create(
                  MESSAGE_EXPIRATION, 'Home Assistant Cloud',
                  'cloud_subscription_expired')
              self.close_requested = True
              return
  
          session = async_get_clientsession(self.cloud.hass)
          client = None
          disconnect_warn = None
  
          try:
              self.client = client = yield from session.ws_connect(
                  self.cloud.relayer, heartbeat=55, headers={
                      hdrs.AUTHORIZATION:
                          'Bearer {}'.format(self.cloud.id_token)
                  })
              self.tries = 0
  
              _LOGGER.info("Connected")
              self.state = STATE_CONNECTED
  
              while not client.closed:
                  msg = yield from client.receive()
  
                  if msg.type in (WSMsgType.CLOSED, WSMsgType.CLOSING):
                      break
  
                  elif msg.type == WSMsgType.ERROR:
                      disconnect_warn = 'Connection error'
                      break
  
                  elif msg.type != WSMsgType.TEXT:
                      disconnect_warn = 'Received non-Text message: {}'.format(
                          msg.type)
                      break
  
                  try:
                      msg = msg.json()
                  except ValueError:
                      disconnect_warn = 'Received invalid JSON.'
                      break
  
                  if _LOGGER.isEnabledFor(logging.DEBUG):
                      _LOGGER.debug("Received message:\n%s\n",
                                    pprint.pformat(msg))
  
                  response = {
                      'msgid': msg['msgid'],
                  }
                  try:
                      result = yield from async_handle_message(
                          hass, self.cloud, msg['handler'], msg['payload'])
  
                      # No response from handler
                      if result is None:
                          continue
  
                      response['payload'] = result
  
                  except UnknownHandler:
                      response['error'] = 'unknown-handler'
  
                  except Exception:  # pylint: disable=broad-except
                      _LOGGER.exception("Error handling message")
                      response['error'] = 'exception'
  
                  if _LOGGER.isEnabledFor(logging.DEBUG):
                      _LOGGER.debug("Publishing message:\n%s\n",
                                    pprint.pformat(response))
                  yield from client.send_json(response)
  
          except client_exceptions.WSServerHandshakeError as err:
              if err.code == 401:
                  disconnect_warn = 'Invalid auth.'
                  self.close_requested = True
                  # Should we notify user?
              else:
                  _LOGGER.warning("Unable to connect: %s", err)
  
          except client_exceptions.ClientError as err:
              _LOGGER.warning("Unable to connect: %s", err)
  
          finally:
              if disconnect_warn is None:
                  _LOGGER.info("Connection closed")
              else:
                  _LOGGER.warning("Connection closed: %s", disconnect_warn)
code_tokens: def _handle_connection ( self ) : hass = self . cloud . hass try : yield from hass . async_add_job ( auth_api . check_token , self . cloud ) except auth_api . Unauthenticated as err : _LOGGER . error ( 'Unable to refresh token: %s' , err ) hass . components . persistent_notification . async_create ( MESSAGE_AUTH_FAIL , 'Home Assistant Cloud' , 'cloud_subscription_expired' ) hass . async_add_job ( self . cloud . logout ( ) ) return except auth_api . CloudError as err : _LOGGER . warning ( "Unable to refresh token: %s" , err ) return if self . cloud . subscription_expired : hass . components . persistent_notification . async_create ( MESSAGE_EXPIRATION , 'Home Assistant Cloud' , 'cloud_subscription_expired' ) self . close_requested = True return session = async_get_clientsession ( self . cloud . hass ) client = None disconnect_warn = None try : self . client = client = yield from session . ws_connect ( self . cloud . relayer , heartbeat = 55 , headers = { hdrs . AUTHORIZATION : 'Bearer {}' . format ( self . cloud . id_token ) } ) self . tries = 0 _LOGGER . info ( "Connected" ) self . state = STATE_CONNECTED while not client . closed : msg = yield from client . receive ( ) if msg . type in ( WSMsgType . CLOSED , WSMsgType . CLOSING ) : break elif msg . type == WSMsgType . ERROR : disconnect_warn = 'Connection error' break elif msg . type != WSMsgType . TEXT : disconnect_warn = 'Received non-Text message: {}' . format ( msg . type ) break try : msg = msg . json ( ) except ValueError : disconnect_warn = 'Received invalid JSON.' break if _LOGGER . isEnabledFor ( logging . DEBUG ) : _LOGGER . debug ( "Received message:\n%s\n" , pprint . pformat ( msg ) ) response = { 'msgid' : msg [ 'msgid' ] , } try : result = yield from async_handle_message ( hass , self . cloud , msg [ 'handler' ] , msg [ 'payload' ] ) if result is None : continue response [ 'payload' ] = result except UnknownHandler : response [ 'error' ] = 'unknown-handler' except Exception : _LOGGER . exception ( "Error handling message" ) response [ 'error' ] = 'exception' if _LOGGER . isEnabledFor ( logging . DEBUG ) : _LOGGER . debug ( "Publishing message:\n%s\n" , pprint . pformat ( response ) ) yield from client . send_json ( response ) except client_exceptions . WSServerHandshakeError as err : if err . code == 401 : disconnect_warn = 'Invalid auth.' self . close_requested = True else : _LOGGER . warning ( "Unable to connect: %s" , err ) except client_exceptions . ClientError as err : _LOGGER . warning ( "Unable to connect: %s" , err ) finally : if disconnect_warn is None : _LOGGER . info ( "Connection closed" ) else : _LOGGER . warning ( "Connection closed: %s" , disconnect_warn )
short_docstring: Connect to the IoT broker.
short_docstring_tokens: Connect to the IoT broker .
comment: """Connect to the IoT broker."""$SEP$# Don't await it because it will cancel this task$SEP$# No response from handler$SEP$# pylint: disable=broad-except$SEP$# Should we notify user?