Python homeassistant.helpers.aiohttp_client.async_get_clientsession() Examples

The following are 18 code examples of homeassistant.helpers.aiohttp_client.async_get_clientsession(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module homeassistant.helpers.aiohttp_client , or try the search function .
Example #1
Source File: audi_account.py    From audi_connect_ha with MIT License 6 votes vote down vote up
def init_connection(self):
        session = async_get_clientsession(self.hass)
        self.connection = AudiConnectAccount(
            session=session,
            username=self.config_entry.data.get(CONF_USERNAME),
            password=self.config_entry.data.get(CONF_PASSWORD),
            country=self.config_entry.data.get(CONF_REGION),
            spin=self.config_entry.data.get(CONF_SPIN),
        )

        self.hass.services.async_register(
            DOMAIN,
            SERVICE_REFRESH_VEHICLE_DATA,
            self.refresh_vehicle_data,
            schema=SERVICE_REFRESH_VEHICLE_DATA_SCHEMA,
        )
        self.hass.services.async_register(
            DOMAIN,
            SERVICE_EXECUTE_VEHICLE_ACTION,
            self.execute_vehicle_action,
            schema=SERVICE_EXECUTE_VEHICLE_ACTION_SCHEMA,
        )

        self.connection.add_observer(self) 
Example #2
Source File: bind.py    From havcs with Apache License 2.0 6 votes vote down vote up
def async_bind_device(self):
        for uuid in self._hass.data[INTEGRATION][DATA_HAVCS_BIND_MANAGER].discovery:
            p_user_id = uuid.split('@')[0]
            platform = uuid.split('@')[1]
            if platform in self._hass.data[INTEGRATION][DATA_HAVCS_HANDLER] and getattr(self._hass.data[INTEGRATION][DATA_HAVCS_HANDLER].get(platform), 'should_report_when_starup', False) and hasattr(self._hass.data[INTEGRATION][DATA_HAVCS_HANDLER].get(platform), 'bind_device'):
                err_result, devices, entity_ids = self._hass.data[INTEGRATION][DATA_HAVCS_HANDLER][platform].process_discovery_command()
                if err_result:
                    return
                bind_entity_ids, unbind_entity_ids = await self._hass.data[INTEGRATION][DATA_HAVCS_BIND_MANAGER].async_save_changed_devices(entity_ids,platform, p_user_id,True)
                payload = await self._hass.data[INTEGRATION][DATA_HAVCS_HANDLER][platform].bind_device(p_user_id, entity_ids , unbind_entity_ids, devices)
                _LOGGER.debug("[skill] bind device to %s:\nbind_entity_ids = %s, unbind_entity_ids = %s", platform, bind_entity_ids, unbind_entity_ids)

                if payload:
                    url = HAVCS_SERVICE_URL + '/skill/smarthome.php?v=update&AppKey='+self._sync_manager.get('app_key')
                    data = havcs_util.AESCipher(self._sync_manager.get('decrypt_key')).encrypt(json.dumps(payload, ensure_ascii = False).encode('utf8'))
                    try:
                        session = async_get_clientsession(self._hass, verify_ssl=False)
                        with async_timeout.timeout(5, loop=self._hass.loop):
                            response = await session.post(url, data=data)
                            _LOGGER.debug("[skill] get bind device result from %s: %s", platform, await response.text())
                    except(asyncio.TimeoutError, aiohttp.ClientError):
                        _LOGGER.error("[skill] fail to access %s, bind device fail: timeout", url)
                    except:
                        _LOGGER.error("[skill] fail to access %s, bind device fail: %s", url, traceback.format_exc()) 
Example #3
Source File: http.py    From havcs with Apache License 2.0 6 votes vote down vote up
def async_check_http_oauth(self, triggered=None):
        _LOGGER.debug("[%s] check accessibility from local", LOGGER_NAME)
        try:
            if self._retry_remove is not None:
                self._retry_remove()
                self._retry_remove = None

            session = async_get_clientsession(self._hass, verify_ssl=False)
            with async_timeout.timeout(5, loop= self._hass.loop):
                response = await session.get(self._ha_url + '/havcs/auth/authorize')
            if response.status == 401:
                _LOGGER.debug("[%s][check] access success: url = %s, status = %s", LOGGER_NAME, self._ha_url + '/havcs/auth/authorize', response.status)
        except (asyncio.TimeoutError, aiohttp.ClientError):
            _LOGGER.debug("[%s][check] retry check after 15s", LOGGER_NAME)
            self._retry_times -= 1
            if(self._retry_times > 0):
                self._retry_remove = async_track_time_interval(
                    self._hass, self.async_check_http_oauth, timedelta(seconds=15)
                )
            else:
                _LOGGER.error("[%s][check] can not access http, check `ha_url` in configuration.yml", LOGGER_NAME)
        except Exception:
            _LOGGER.exception("[%s][check] unexpected error occur", LOGGER_NAME)
            raise 
Example #4
Source File: config_flow.py    From integration with MIT License 5 votes vote down vote up
def _test_token(self, token):
        """Return true if token is valid."""
        try:
            session = aiohttp_client.async_get_clientsession(self.hass)
            await get_repository(session, token, "hacs/org")
            return True
        except (
            AIOGitHubAPIException,
            AIOGitHubAPIAuthenticationException,
        ) as exception:
            _LOGGER.error(exception)
        return False 
Example #5
Source File: bind.py    From havcs with Apache License 2.0 5 votes vote down vote up
def sync_device(self):
        remove_listener = self._sync_manager.get('remove_listener')
        if remove_listener:
            remove_listener()
    
        @callback
        def report_device(event):
            # _LOGGER.debug("[skill] %s changed, try to report", event.data[ATTR_ENTITY_ID])
            self._hass.add_job(async_report_device(event))

        async def async_report_device(event):
            """report device state when changed. """
            entity = self._hass.states.get(event.data[ATTR_ENTITY_ID])
            if entity is None:
                return
            for platform, handler in self._hass.data[INTEGRATION][DATA_HAVCS_HANDLER].items():
                if hasattr(handler, 'report_device'):
                    device_ids = handler.vcdm.get_entity_related_device_ids(self._hass, entity.entity_id)
                    for device_id in device_ids:
                        payload = handler.report_device(device_id)
                        _LOGGER.debug("[skill] report device to %s: platform = %s, device_id = %s (entity_id = %s), data = %s", platform, device_id, event.data[ATTR_ENTITY_ID], platform, payload)
                        if payload:
                            url = HAVCS_SERVICE_URL + '/skill/'+platform+'.php?v=report&AppKey=' + self._sync_manager.get('app_key')
                            data = havcs_util.AESCipher(self._sync_manager.get('decrypt_key')).encrypt(json.dumps(payload, ensure_ascii = False).encode('utf8'))
                            try:
                                session = async_get_clientsession(self._hass, verify_ssl=False)
                                with async_timeout.timeout(5, loop=self._hass.loop):
                                    response = await session.post(url, data=data)
                                    _LOGGER.debug("[skill] get report device result from %s: %s", platform, await response.text())
                            except(asyncio.TimeoutError, aiohttp.ClientError):
                                _LOGGER.error("[skill] fail to access %s, report device fail: timeout", url)
                            except:
                                _LOGGER.error("[skill] fail to access %s, report device fail: %s", url, traceback.format_exc())
        
        self._sync_manager['remove_listener'] = self._hass.bus.async_listen(EVENT_STATE_CHANGED, report_device) 
Example #6
Source File: sensor.py    From SmartHouse with MIT License 5 votes vote down vote up
def __init__(self, hass, city_card_id, identity_id, name):
    """Initialize the sensor."""
    self.hass = hass
    self.websession = async_get_clientsession(hass)
    self.city_card_id = city_card_id
    self.identity_id = identity_id
    self._lines = []
    self._name = name
    self._expire_at = None
    self._state = STATE_OFF 
Example #7
Source File: sensor.py    From SmartHouse with MIT License 5 votes vote down vote up
def setup_platform(hass, config, add_devices, discovery_info=None):
  username = config.get(CONF_USERNAME)
  password = config.get(CONF_PASSWORD)
  name = config.get(CONF_NAME)

  websession = async_get_clientsession(hass)

  add_devices([LunchingSensor(hass, websession, name, username, password)]) 
Example #8
Source File: sensor.py    From SmartHouse with MIT License 5 votes vote down vote up
def setup_platform(hass, config, add_devices, discovery_info=None):
  account_id = config.get(CONF_ACCOUNT_ID)
  token = config.get(CONF_TOKEN)
  name = config.get(CONF_NAME)

  websession = async_get_clientsession(hass)

  add_devices([HarvestSensor(hass, websession, account_id, token, name)]) 
Example #9
Source File: media_player.py    From SmartHouse with MIT License 5 votes vote down vote up
def setup_platform(hass, config, add_devices, discovery_info=None):
  _LOGGER.error('Setup of the soundbar')
  ip = config.get(CONF_HOST)
  port = config.get(CONF_PORT)
  name = config.get(CONF_NAME)
  max_volume = int(config.get(CONF_MAX_VOLUME))
  session = async_get_clientsession(hass)
  api = MultiRoomApi(ip, port, session, hass)
  add_devices([MultiRoomDevice(name, max_volume, api)], True) 
Example #10
Source File: sensor.py    From SmartHouse with MIT License 5 votes vote down vote up
def __init__(self, hass, name, stop_id, direction):
    """Initialize the sensor."""
    self.hass = hass
    self.websession = async_get_clientsession(hass)
    self._name = name
    self.stop_id = stop_id
    self.direction = direction
    self.data = {
      'stopName': '...',
      'actual': []
    } 
Example #11
Source File: __init__.py    From home-assistant-remote with Apache License 2.0 5 votes vote down vote up
def async_connect(self):
        """Connect to remote home-assistant websocket..."""
        url = self._get_url()

        session = async_get_clientsession(self._hass, self._verify_ssl)
        self._hass.states.async_set(self._connection_state_entity, STATE_CONNECTING, self._instance_attrs)

        while True:
            try:
                _LOGGER.info('Connecting to %s', url)
                self._connection = await session.ws_connect(url)
            except aiohttp.client_exceptions.ClientError as err:
                _LOGGER.error(
                    'Could not connect to %s, retry in 10 seconds...', url)
                self._hass.states.async_set(self._connection_state_entity, STATE_RECONNECTING, self._instance_attrs)
                await asyncio.sleep(10)
            else:
                _LOGGER.info(
                    'Connected to home-assistant websocket at %s', url)
                self._hass.states.async_set(self._connection_state_entity, STATE_CONNECTED, self._instance_attrs)
                break

        async def stop():
            """Close connection."""
            if self._connection is not None:
                await self._connection.close()
            self._hass.states.async_set(self._connection_state_entity, STATE_DISCONNECTED)
        
        self._hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop)

        asyncio.ensure_future(self._recv()) 
Example #12
Source File: sensor.py    From HAComponent with Apache License 2.0 5 votes vote down vote up
def async_get_longitude_latitude(self, address_dict):
            
        if address_dict.get(CONF_LONGITUDE_LATITUDE) is not None:
            return address_dict.get(CONF_LONGITUDE_LATITUDE)

        if (address_dict.get(CONF_ADDRESS) is None) or (address_dict.get(CONF_CITY) is None):
            return
            
        url = ("http://restapi.amap.com/v3/geocode/geo?key="
               + self._api_key
               + '&address=' + address_dict.get(CONF_ADDRESS)
               + '&city=' + address_dict.get(CONF_CITY)
               )

        try:
            session = async_get_clientsession(self._hass)
            with async_timeout.timeout(15, loop=self._hass.loop):
                response = yield from session.get( url )

        except(asyncio.TimeoutError, aiohttp.ClientError):
            _LOGGER.error("Error while accessing: %s", url)
            return

        if response.status != 200:
            _LOGGER.error("Error while accessing: %s, status=%d", url, response.status)
            return

        data = yield from response.json()

        if data is None:
            _LOGGER.error("Request api Error: %s", url)
            return
        elif (data['status'] != '1'):
            _LOGGER.error("Error Api return, state=%s, errmsg=%s",
                          data['status'],
                          data['info']
                          )
            return

        return data['geocodes'][0]['location'] 
Example #13
Source File: sensor.py    From homeassistant-config with The Unlicense 5 votes vote down vote up
def async_setup_platform(hass, config, async_add_entities,
                               discovery_info=None):
    using_wu = CONF_API_KEY in config
    session = None
    if using_wu:
        session = async_get_clientsession(hass)
        if not await _async_get_wu_data(
                hass, session, config[CONF_API_KEY], [], config[CONF_QUERY]):
            return False

    async_add_entities([IlluminanceSensor(using_wu, config, session)], True) 
Example #14
Source File: device_tracker.py    From HomeAssistantConfig with MIT License 4 votes vote down vote up
def async_setup_scanner(hass, config, async_see, discovery_info=None):
    """Validate the configuration and return an Automatic scanner."""
    import aioautomatic

    hass.http.register_view(AutomaticAuthCallbackView())

    scope = FULL_SCOPE if config.get(CONF_CURRENT_LOCATION) else DEFAULT_SCOPE

    client = aioautomatic.Client(
        client_id=config[CONF_CLIENT_ID],
        client_secret=config[CONF_SECRET],
        client_session=async_get_clientsession(hass),
        request_kwargs={'timeout': DEFAULT_TIMEOUT})

    filename = AUTOMATIC_CONFIG_FILE.format(config[CONF_CLIENT_ID], config[CONF_NAME])
    refresh_token = yield from hass.async_add_job(
        _get_refresh_token_from_file, hass, filename)

    if refresh_token is not None:
        try:
            session = yield from client.create_session_from_refresh_token(
                refresh_token)
            account = AutomaticAccount(config[CONF_NAME], hass, filename, client, session, async_see, config.get(CONF_DEVICES))
            yield from account.initialize_data()
            return True
        except aioautomatic.exceptions.AutomaticError as err:
            _LOGGER.error(str(err))

    configurator = hass.components.configurator
    request_id = configurator.async_request_config(
        "Automatic", description=(
            "Authorization required for Automatic device tracker" + (" " + config.get(CONF_NAME)) if CONF_NAME in config else "."),
        link_name="Click here to authorize Home Assistant" + (" " + config.get(CONF_NAME)) if CONF_NAME in config else ".",
        link_url=client.generate_oauth_url(scope),
        entity_picture="/static/images/logo_automatic.png",
    )

    if DATA_CONFIGURING not in hass.data:
        hass.data[DATA_CONFIGURING] = {}

    account = AutomaticAccount(config[CONF_NAME], hass, filename, client, None, async_see, config.get(CONF_DEVICES), request_id)
    hass.data[DATA_CONFIGURING][client.state] = account
    return True 
Example #15
Source File: sensor.py    From HAComponent with Apache License 2.0 4 votes vote down vote up
def async_update(self, now):
        """Get the latest data and updates the states."""

        date = now.strftime("%Y-%m-%d")
        params = {
            "key": self.key,
            "date": date,
            }

        try:
            session = async_get_clientsession(self.hass)
            with async_timeout.timeout(15, loop=self.hass.loop):
                response = yield from session.post( self.url, data=params )

        except(asyncio.TimeoutError, aiohttp.ClientError):
            _LOGGER.error("Error while accessing: %s", self.url)
            return

        if response.status != 200:
            _LOGGER.error("Error while accessing: %s, status=%d", url, response.status)
            return

        result = yield from response.json()

        if result is None:
            _LOGGER.error("Request api Error: %s", url)
            return
        elif (result["error_code"] != 0):
            _LOGGER.error("Error API return, errorcode=%s, reson=%s",
                          result["error_code"],
                          result["reason"],
                          )
            return
        
        
        self.yangli = result["result"]["yangli"]
        self.yinli = result["result"]["yinli"]
        self.wuxing = result["result"]["wuxing"].replace(" ","、")
        self.chongsha = result["result"]["chongsha"]
        self.baiji = result["result"]["baiji"].replace(" ","、")
        self.jishen = result["result"]["jishen"].replace(" ","、")
        self.yi = result["result"]["yi"].replace(" ","、")
        self.xiongshen = result["result"]["xiongshen"].replace(" ","、")
        self.ji = result["result"]["ji"].replace(" ","、") 
Example #16
Source File: hachina9.py    From HAComponent with Apache License 2.0 4 votes vote down vote up
def async_update(self, now):
        """从远程更新信息."""
        _LOGGER.info("Update from JingdongWangxiang's OpenAPI...")

        """
        # 异步模式的测试代码
        import time
        _LOGGER.info("before time.sleep")
        time.sleep(40)
        _LOGGER.info("after time.sleep and before asyncio.sleep")
        asyncio.sleep(40)
        _LOGGER.info("after asyncio.sleep and before yield from asyncio.sleep")
        yield from asyncio.sleep(40)
        _LOGGER.info("after yield from asyncio.sleep")
        """

        # 通过HTTP访问,获取需要的信息
        # 此处使用了基于aiohttp库的async_get_clientsession
        try:
            session = async_get_clientsession(self._hass)
            with async_timeout.timeout(15, loop=self._hass.loop):
                response = yield from session.post(
                    self._url, data=self._params)

        except(asyncio.TimeoutError, aiohttp.ClientError):
            _LOGGER.error("Error while accessing: %s", self._url)
            return

        if response.status != 200:
            _LOGGER.error("Error while accessing: %s, status=%d",
                          self._url,
                          response.status)
            return

        try:
            result = yield from response.json()
        except(aiohttp.client_exceptions.ContentTypeError):
            _LOGGER.error("Error return type: %s", str(response))
            return

        if result is None:
            _LOGGER.error("Request api Error")
            return
        elif result["code"] != "10000":
            _LOGGER.error("Error API return, code=%s, msg=%s",
                          result["code"],
                          result["msg"])
            return

        # 根据http返回的结果,更新数据
        all_result = result["result"]["HeWeather5"][0]
        self._temprature = all_result["now"]["tmp"]
        self._humidity = all_result["now"]["hum"]
        self._pm25 = all_result["aqi"]["city"]["pm25"]
        self._updatetime = all_result["basic"]["update"]["loc"] 
Example #17
Source File: config_flow.py    From audi_connect_ha with MIT License 4 votes vote down vote up
def async_step_user(self, user_input=None):
        """Handle a user initiated config flow."""
        errors = {}

        if user_input is not None:
            self._username = user_input[CONF_USERNAME]
            self._password = user_input[CONF_PASSWORD]
            self._spin = user_input.get(CONF_SPIN)
            self._region = user_input.get(CONF_REGION)
            self._scan_interval = user_input[CONF_SCAN_INTERVAL]

            try:
                # pylint: disable=no-value-for-parameter
                session = async_get_clientsession(self.hass)
                connection = AudiConnectAccount(
                    session=session,
                    username=vol.Email()(self._username),
                    password=self._password,
                    country=self._region,
                    spin=self._spin,
                )

                if await connection.try_login(False) == False:
                    raise Exception(
                        "Unexpected error communicating with the Audi server"
                    )

            except vol.Invalid:
                errors[CONF_USERNAME] = "invalid_username"
            except Exception:
                errors["base"] = "invalid_credentials"
            else:
                if self._username in configured_accounts(self.hass):
                    errors["base"] = "user_already_configured"
                else:
                    return self.async_create_entry(
                        title=f"{self._username}",
                        data={
                            CONF_USERNAME: self._username,
                            CONF_PASSWORD: self._password,
                            CONF_SPIN: self._spin,
                            CONF_REGION: self._region,
                            CONF_SCAN_INTERVAL: self._scan_interval,
                        },
                    )

        data_schema = OrderedDict()
        data_schema[vol.Required(CONF_USERNAME, default=self._username)] = str
        data_schema[vol.Required(CONF_PASSWORD, default=self._password)] = str
        data_schema[vol.Optional(CONF_SPIN, default=self._spin)] = str
        data_schema[vol.Optional(CONF_REGION, default=self._region)] = str
        data_schema[
            vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_UPDATE_INTERVAL)
        ] = int

        return self.async_show_form(
            step_id="user", data_schema=vol.Schema(data_schema), errors=errors,
        ) 
Example #18
Source File: config_flow.py    From audi_connect_ha with MIT License 4 votes vote down vote up
def async_step_import(self, user_input):
        """Import a config flow from configuration."""
        username = user_input[CONF_USERNAME]
        password = user_input[CONF_PASSWORD]

        spin = None
        if user_input.get(CONF_SPIN):
            spin = user_input[CONF_SPIN]

        region = "DE"
        if user_input.get(CONF_REGION):
            region = user_input.get(CONF_REGION)

        scan_interval = 10

        if user_input.get(CONF_SCAN_INTERVAL):
            scan_interval = user_input[CONF_SCAN_INTERVAL]

        if scan_interval < 5:
            scan_interval = 5

        try:
            session = async_get_clientsession(self.hass)
            connection = AudiConnectAccount(
                session=session,
                username=username,
                password=password,
                country=region,
                spin=spin,
            )

            if await connection.try_login(False) == False:
                raise Exception("Unexpected error communicating with the Audi server")

        except Exception:
            _LOGGER.error("Invalid credentials for %s", username)
            return self.async_abort(reason="invalid_credentials")

        return self.async_create_entry(
            title=f"{username} (from configuration)",
            data={
                CONF_USERNAME: username,
                CONF_PASSWORD: password,
                CONF_SPIN: spin,
                CONF_REGION: region,
                CONF_SCAN_INTERVAL: scan_interval,
            },
        )