async def test_create_async_httpx_client_with_ssl_and_cookies(hass):
    """Test init async client with ssl and cookies."""
    client.get_async_client(hass)

    httpx_client = client.create_async_httpx_client(hass, cookies={"bla": True})
    assert isinstance(httpx_client, httpx.AsyncClient)
    assert hass.data[client.DATA_ASYNC_CLIENT] != httpx_client
async def test_create_async_httpx_client_without_ssl_and_cookies(hass):
    """Test init async client without ssl and cookies."""
    client.get_async_client(hass, verify_ssl=False)

    httpx_client = client.create_async_httpx_client(
        hass, verify_ssl=False, cookies={"bla": True}
    )
    assert isinstance(httpx_client, httpx.AsyncClient)
    assert hass.data[client.DATA_ASYNC_CLIENT_NOVERIFY] != httpx_client
async def test_get_async_client_cleanup(hass):
    """Test init async client with ssl."""
    client.get_async_client(hass)

    assert isinstance(hass.data[client.DATA_ASYNC_CLIENT], httpx.AsyncClient)

    hass.bus.async_fire(EVENT_HOMEASSISTANT_CLOSE)
    await hass.async_block_till_done()

    assert hass.data[client.DATA_ASYNC_CLIENT].is_closed
async def test_get_async_client_cleanup_without_ssl(hass):
    """Test init async client without ssl."""
    client.get_async_client(hass, verify_ssl=False)

    assert isinstance(hass.data[client.DATA_ASYNC_CLIENT_NOVERIFY], httpx.AsyncClient)

    hass.bus.async_fire(EVENT_HOMEASSISTANT_CLOSE)
    await hass.async_block_till_done()

    assert hass.data[client.DATA_ASYNC_CLIENT_NOVERIFY].is_closed
Пример #5
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Enphase Envoy from a config entry."""

    config = entry.data
    name = config[CONF_NAME]

    envoy_reader = EnvoyReader(
        config[CONF_HOST],
        config[CONF_USERNAME],
        config[CONF_PASSWORD],
        inverters=True,
        async_client=get_async_client(hass),
    )

    async def async_update_data():
        """Fetch data from API endpoint."""
        data = {}
        async with async_timeout.timeout(30):
            try:
                await envoy_reader.getData()
            except httpx.HTTPStatusError as err:
                raise ConfigEntryAuthFailed from err
            except httpx.HTTPError as err:
                raise UpdateFailed(
                    f"Error communicating with API: {err}") from err

            for condition in SENSORS:
                if condition != "inverters":
                    data[condition] = await getattr(envoy_reader, condition)()
                else:
                    data[
                        "inverters_production"] = await envoy_reader.inverters_production(
                        )

            _LOGGER.debug("Retrieved data from API: %s", data)

            return data

    coordinator = DataUpdateCoordinator(
        hass,
        _LOGGER,
        name=f"envoy {name}",
        update_method=async_update_data,
        update_interval=SCAN_INTERVAL,
    )

    try:
        await coordinator.async_config_entry_first_refresh()
    except ConfigEntryAuthFailed:
        envoy_reader.get_inverters = False
        await coordinator.async_config_entry_first_refresh()

    hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {
        COORDINATOR: coordinator,
        NAME: name,
    }

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Пример #6
0
def get_api(hass, entry):
    """Return the api from glances_api."""
    params = entry.copy()
    params.pop(CONF_NAME)
    verify_ssl = params.pop(CONF_VERIFY_SSL, True)
    httpx_client = get_async_client(hass, verify_ssl=verify_ssl)
    return Glances(httpx_client=httpx_client, **params)
Пример #7
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up the denonavr components from a config entry."""
    hass.data.setdefault(DOMAIN, {})

    # Connect to receiver
    connect_denonavr = ConnectDenonAVR(
        entry.data[CONF_HOST],
        DEFAULT_TIMEOUT,
        entry.options.get(CONF_SHOW_ALL_SOURCES, DEFAULT_SHOW_SOURCES),
        entry.options.get(CONF_ZONE2, DEFAULT_ZONE2),
        entry.options.get(CONF_ZONE3, DEFAULT_ZONE3),
        lambda: get_async_client(hass),
    )
    try:
        await connect_denonavr.async_connect_receiver()
    except (AvrNetworkError, AvrTimoutError) as ex:
        raise ConfigEntryNotReady from ex
    receiver = connect_denonavr.receiver

    undo_listener = entry.add_update_listener(update_listener)

    hass.data[DOMAIN][entry.entry_id] = {
        CONF_RECEIVER: receiver,
        UNDO_UPDATE_LISTENER: undo_listener,
    }

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Пример #8
0
async def get_axis_device(
    hass: HomeAssistant,
    config: MappingProxyType[str, Any],
) -> axis.AxisDevice:
    """Create a Axis device."""
    session = get_async_client(hass, verify_ssl=False)

    device = axis.AxisDevice(
        Configuration(
            session,
            config[CONF_HOST],
            port=config[CONF_PORT],
            username=config[CONF_USERNAME],
            password=config[CONF_PASSWORD],
        ))

    try:
        async with async_timeout.timeout(30):
            await device.vapix.initialize()

        return device

    except axis.Unauthorized as err:
        LOGGER.warning("Connected to device at %s but not registered",
                       config[CONF_HOST])
        raise AuthenticationRequired from err

    except (asyncio.TimeoutError, axis.RequestError) as err:
        LOGGER.error("Error connecting to the Axis device at %s",
                     config[CONF_HOST])
        raise CannotConnect from err

    except axis.AxisException as err:
        LOGGER.exception("Unknown Axis communication error occurred")
        raise AuthenticationRequired from err
async def test_warning_close_session_integration(hass, caplog):
    """Test log warning message when closing the session from integration context."""
    with patch(
        "homeassistant.helpers.frame.extract_stack",
        return_value=[
            Mock(
                filename="/home/paulus/homeassistant/core.py",
                lineno="23",
                line="do_something()",
            ),
            Mock(
                filename="/home/paulus/homeassistant/components/hue/light.py",
                lineno="23",
                line="await session.aclose()",
            ),
            Mock(
                filename="/home/paulus/aiohue/lights.py",
                lineno="2",
                line="something()",
            ),
        ],
    ):
        httpx_session = client.get_async_client(hass)
        await httpx_session.aclose()

    assert (
        "Detected integration that closes the Home Assistant httpx client. "
        "Please report issue for hue using this method at "
        "homeassistant/components/hue/light.py, line 23: await session.aclose()"
    ) in caplog.text
Пример #10
0
    async def async_camera_image(self):
        """Return a still image response from the camera."""
        try:
            url = self._still_image_url.async_render(parse_result=False)
        except TemplateError as err:
            _LOGGER.error("Error parsing template %s: %s",
                          self._still_image_url, err)
            return self._last_image

        if url == self._last_url and self._limit_refetch:
            return self._last_image

        try:
            async_client = get_async_client(self.hass,
                                            verify_ssl=self.verify_ssl)
            response = await async_client.get(url,
                                              auth=self._auth,
                                              timeout=GET_IMAGE_TIMEOUT)
            response.raise_for_status()
            self._last_image = response.content
        except httpx.TimeoutException:
            _LOGGER.error("Timeout getting camera image from %s", self._name)
            return self._last_image
        except (httpx.RequestError, httpx.HTTPStatusError) as err:
            _LOGGER.error("Error getting new camera image from %s: %s",
                          self._name, err)
            return self._last_image

        self._last_url = url
        return self._last_image
Пример #11
0
    async def async_update(self, log_errors=True):
        """Get the latest data from REST service with provided method."""
        if not self._async_client:
            self._async_client = get_async_client(self._hass,
                                                  verify_ssl=self._verify_ssl)

        rendered_headers = template.render_complex(self._headers,
                                                   parse_result=False)
        rendered_params = template.render_complex(self._params)

        _LOGGER.debug("Updating from %s", self._resource)
        try:
            response = await self._async_client.request(
                self._method,
                self._resource,
                headers=rendered_headers,
                params=rendered_params,
                auth=self._auth,
                data=self._request_data,
                timeout=self._timeout,
                follow_redirects=True,
            )
            self.data = response.text
            self.headers = response.headers
        except httpx.RequestError as ex:
            if log_errors:
                _LOGGER.error("Error fetching data: %s failed with %s",
                              self._resource, ex)
            self.last_exception = ex
            self.data = None
            self.headers = None
Пример #12
0
async def get_device(hass, host, port, username, password):
    """Create a Axis device."""
    session = get_async_client(hass, verify_ssl=False)

    device = axis.AxisDevice(
        Configuration(session,
                      host,
                      port=port,
                      username=username,
                      password=password))

    try:
        async with async_timeout.timeout(30):
            await device.vapix.initialize()

        return device

    except axis.Unauthorized as err:
        LOGGER.warning("Connected to device at %s but not registered", host)
        raise AuthenticationRequired from err

    except (asyncio.TimeoutError, axis.RequestError) as err:
        LOGGER.error("Error connecting to the Axis device at %s", host)
        raise CannotConnect from err

    except axis.AxisException as err:
        LOGGER.exception("Unknown Axis communication error occurred")
        raise AuthenticationRequired from err
async def test_get_async_client_patched_close(hass):
    """Test closing the async client does not work."""

    with patch("httpx.AsyncClient.aclose") as mock_aclose:
        httpx_session = client.get_async_client(hass)
        assert isinstance(hass.data[client.DATA_ASYNC_CLIENT], httpx.AsyncClient)

        with pytest.raises(RuntimeError):
            await httpx_session.aclose()

        assert mock_aclose.call_count == 0
async def test_get_async_client_context_manager(hass):
    """Test using the async client with a context manager does not close the session."""

    with patch("httpx.AsyncClient.aclose") as mock_aclose:
        httpx_session = client.get_async_client(hass)
        assert isinstance(hass.data[client.DATA_ASYNC_CLIENT], httpx.AsyncClient)

        async with httpx_session:
            pass

        assert mock_aclose.call_count == 0
Пример #15
0
def get_api(hass: HomeAssistant, config_data: dict) -> AbstractGateApi:
    """Get an api object for config data."""
    gate_class = GogoGate2Api

    if config_data[CONF_DEVICE] == DEVICE_TYPE_ISMARTGATE:
        gate_class = ISmartGateApi

    return gate_class(
        config_data[CONF_IP_ADDRESS],
        config_data[CONF_USERNAME],
        config_data[CONF_PASSWORD],
        httpx_async_client=get_async_client(hass),
    )
Пример #16
0
    async def async_step_connect(self,
                                 user_input: dict[str, Any] | None = None
                                 ) -> FlowResult:
        """Connect to the receiver."""
        connect_denonavr = ConnectDenonAVR(
            self.host,
            self.timeout,
            self.show_all_sources,
            self.zone2,
            self.zone3,
            lambda: get_async_client(self.hass),
        )

        try:
            success = await connect_denonavr.async_connect_receiver()
        except (AvrNetworkError, AvrTimoutError):
            success = False
        if not success:
            return self.async_abort(reason="cannot_connect")
        receiver = connect_denonavr.receiver

        if not self.serial_number:
            self.serial_number = receiver.serial_number
        if not self.model_name:
            self.model_name = (receiver.model_name).replace("*", "")

        if self.serial_number is not None:
            unique_id = self.construct_unique_id(self.model_name,
                                                 self.serial_number)
            await self.async_set_unique_id(unique_id)
            self._abort_if_unique_id_configured()
        else:
            _LOGGER.error(
                "Could not get serial number of host %s, "
                "unique_id's will not be available",
                self.host,
            )
            for entry in self._async_current_entries():
                if entry.data[CONF_HOST] == self.host:
                    return self.async_abort(reason="already_configured")

        return self.async_create_entry(
            title=receiver.name,
            data={
                CONF_HOST: self.host,
                CONF_TYPE: receiver.receiver_type,
                CONF_MODEL: self.model_name,
                CONF_MANUFACTURER: receiver.manufacturer,
                CONF_SERIAL_NUMBER: self.serial_number,
            },
        )
    async def _async_camera_image(self):
        """Return a still image response from the camera."""
        if not self.enabled:
            return self._last_url, self._last_image
        new_state = self._state
        try:
            url = self._still_image_url.async_render(
                **self._template_variables)
        except TemplateError as err:
            _LOGGER.error("Error parsing template %s: %s",
                          self._still_image_url, err)
            return self._last_url, self._last_image

        try:
            new_state = self._state_template.async_render(parse_result=False, )
        except TemplateError as err:
            _LOGGER.error("Error parsing template %s: %s",
                          self._state_template, err)
            new_state = STATE_PROBLEM
        if new_state != self._state:
            self._state = new_state
            self.async_schedule_update_ha_state()

        if (url == self._last_url and self._limit_refetch) or url == "None":
            return self._last_url, self._last_image

        response = None
        try:
            async_client = get_async_client(self.hass,
                                            verify_ssl=self.verify_ssl)
            response = await async_client.get(url,
                                              auth=self._auth,
                                              timeout=GET_IMAGE_TIMEOUT)
            response.raise_for_status()
            image = response.content
        except httpx.TimeoutException:
            _LOGGER.error("Timeout getting camera image from %s", self._name)
            self._state = STATE_PROBLEM
            return self._last_url, self._last_image
        except (httpx.RequestError, httpx.HTTPStatusError) as err:
            _LOGGER.error("Error getting new camera image from %s: %s",
                          self._name, err)
            self._state = STATE_PROBLEM
            return self._last_url, self._last_image
        finally:
            if response:
                await response.aclose()

        return url, image
Пример #18
0
async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
    """Validate the user input allows us to connect."""
    envoy_reader = EnvoyReader(
        data[CONF_HOST],
        data[CONF_USERNAME],
        data[CONF_PASSWORD],
        inverters=False,
        async_client=get_async_client(hass),
    )

    try:
        await envoy_reader.getData()
    except httpx.HTTPStatusError as err:
        raise InvalidAuth from err
    except (RuntimeError, httpx.HTTPError) as err:
        raise CannotConnect from err
Пример #19
0
    async def async_step_settings(self, user_input=None):
        options_schema = vol.Schema({
            vol.Required(CONF_IP_ADDRESS,
                         default=self.config_entry.options.get(
                             CONF_IP_ADDRESS, "")):
            str,
            vol.Required(CONF_PASSWORD,
                         default=self.config_entry.options.get(
                             CONF_PASSWORD, "")):
            str,
            vol.Optional(CONF_SCAN_INTERVAL,
                         default=self.config_entry.options.get(
                             CONF_SCAN_INTERVAL, SCAN_INTERVAL)):
            cv.positive_int,
            vol.Optional(CONF_TIMEOUT,
                         default=self.config_entry.options.get(
                             CONF_TIMEOUT, DEFAULT_TIMEOUT)):
            cv.positive_int,
            vol.Optional(CONF_LAST_ACTIVITY_DAYS,
                         default=self.config_entry.options.get(
                             CONF_LAST_ACTIVITY_DAYS, DEFAULT_LAST_ACTIVITY_DAYS)):
            cv.positive_int,
            vol.Optional(CONF_FORCE_LOAD_REPEATER_DEVICES,
                         default=self.config_entry.options.get(
                             CONF_FORCE_LOAD_REPEATER_DEVICES, False)):
            cv.boolean,
        })

        if user_input:
            client = Luci(self.hass, get_async_client(self.hass, False),
                          user_input[CONF_IP_ADDRESS],
                          user_input[CONF_PASSWORD])

            try:
                await client.login()
            except exceptions.LuciConnectionError as e:
                return await self._prepare_error('ip_address.not_matched', e,
                                                 options_schema)
            except exceptions.LuciTokenError as e:
                return await self._prepare_error('password.not_matched', e,
                                                 options_schema)

            return self.async_create_entry(title='', data=user_input)

        return self.async_show_form(step_id="settings",
                                    data_schema=options_schema)
Пример #20
0
async def validate_input(hass: core.HomeAssistant,
                         data: dict[str, Any]) -> dict[str, str]:
    """Validate the user input allows us to connect.

    Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
    """
    zeroconf_instance = await zeroconf.async_get_instance(hass)
    async_client = get_async_client(hass)

    device = Device(data[CONF_IP_ADDRESS], zeroconf_instance=zeroconf_instance)

    await device.async_connect(session_instance=async_client)
    await device.async_disconnect()

    return {
        SERIAL_NUMBER: str(device.serial_number),
        TITLE: device.hostname.split(".")[0],
    }
Пример #21
0
    async def async_update(self, log_errors=True):
        """Get the latest data from REST service with provided method."""
        if not self._async_client:
            self._async_client = get_async_client(
                self._hass, verify_ssl=self._verify_ssl
            )

        if self._form_submit_config is None or self._skip_form:
            if self._skip_form:
                _LOGGER.debug("Skip submitting form for resource: %s", self._resource)
            await self._async_update_data()

        else:
            page = await self._async_get_form_page()
            form = self._get_form_data(page)

            if not form:
                await self._async_update_data()
            else:
                form_action = form[0]
                form_method = form[1]
                form_data = form[2]

                submit_resource = self._determine_submit_resource(form_action)
                form_data.update(self._form_input)

                result = await self._submit_form(
                    submit_resource, form_method, form_data
                )

                if not self._form_resource:
                    self.data = result.data
                else:
                    await self._async_update_data()

        try:
            self.soup = BeautifulSoup(self.data, self._parser)
            self.soup.prettify()
        except Exception as e:
            _LOGGER.error("Unable to parse response.")
            _LOGGER.debug("Exception parsing resonse: %s", e)
Пример #22
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up SENZ from a config entry."""
    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry))
    session = config_entry_oauth2_flow.OAuth2Session(hass, entry,
                                                     implementation)
    auth = SENZConfigEntryAuth(httpx_client.get_async_client(hass), session)
    senz_api = SENZAPI(auth)

    async def update_thermostats() -> dict[str, Thermostat]:
        """Fetch SENZ thermostats data."""
        try:
            thermostats = await senz_api.get_thermostats()
        except RequestError as err:
            raise UpdateFailed from err
        return {
            thermostat.serial_number: thermostat
            for thermostat in thermostats
        }

    try:
        account = await senz_api.get_account()
    except RequestError as err:
        raise ConfigEntryNotReady from err

    coordinator = SENZDataUpdateCoordinator(
        hass,
        _LOGGER,
        name=account.username,
        update_interval=UPDATE_INTERVAL,
        update_method=update_thermostats,
    )

    await coordinator.async_config_entry_first_refresh()

    hass.data[DOMAIN][entry.entry_id] = coordinator

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Пример #23
0
async def validate_input(hass: core.HomeAssistant,
                         data: dict[str, str]) -> dict[str, str]:
    """Validate the user input allows us to connect."""
    iotawatt = Iotawatt(
        "",
        data[CONF_HOST],
        httpx_client.get_async_client(hass),
        data.get(CONF_USERNAME),
        data.get(CONF_PASSWORD),
    )
    try:
        is_connected = await iotawatt.connect()
    except CONNECTION_ERRORS:
        return {"base": "cannot_connect"}
    except Exception:  # pylint: disable=broad-except
        _LOGGER.exception("Unexpected exception")
        return {"base": "unknown"}

    if not is_connected:
        return {"base": "invalid_auth"}

    return {}
Пример #24
0
    async def _async_update_data(self):
        """Fetch sensors from IoTaWatt device."""
        if self.api is None:
            api = Iotawatt(
                self.entry.title,
                self.entry.data[CONF_HOST],
                httpx_client.get_async_client(self.hass),
                self.entry.data.get(CONF_USERNAME),
                self.entry.data.get(CONF_PASSWORD),
            )
            try:
                is_authenticated = await api.connect()
            except CONNECTION_ERRORS as err:
                raise UpdateFailed("Connection failed") from err

            if not is_authenticated:
                raise UpdateFailed("Authentication error")

            self.api = api

        await self.api.update()
        return self.api.getSensors()
Пример #25
0
    async def async_step_auth(self, user_input):
        if user_input is None:
            return self.cur_step

        client = Luci(self.hass, get_async_client(self.hass, False),
                      user_input[CONF_IP_ADDRESS], user_input[CONF_PASSWORD])

        try:
            await client.login()
        except exceptions.LuciConnectionError as e:
            return await self._prepare_error('ip_address.not_matched', e)
        except exceptions.LuciTokenError as e:
            return await self._prepare_error('password.not_matched', e)

        entry = await self.async_set_unique_id(user_input[CONF_IP_ADDRESS])

        if entry:
            self.hass.config_entries.async_update_entry(entry, data=user_input)

            return self.async_abort(reason='account_updated')

        return self.async_create_entry(title=user_input[CONF_IP_ADDRESS],
                                       data=user_input)
Пример #26
0
    async def async_update(self):
        """Get the latest data from REST service with provided method."""
        if not self._async_client:
            self._async_client = get_async_client(self._hass,
                                                  verify_ssl=self._verify_ssl)

        _LOGGER.debug("Updating from %s", self._resource)
        try:
            response = await self._async_client.request(
                self._method,
                self._resource,
                headers=self._headers,
                params=self._params,
                auth=self._auth,
                data=self._request_data,
                timeout=self._timeout,
            )
            self.data = response.text
            self.headers = response.headers
        except httpx.RequestError as ex:
            _LOGGER.error("Error fetching data: %s failed with %s",
                          self._resource, ex)
            self.data = None
            self.headers = None
async def test_get_async_client_with_ssl(hass):
    """Test init async client with ssl."""
    client.get_async_client(hass)

    assert isinstance(hass.data[client.DATA_ASYNC_CLIENT], httpx.AsyncClient)
Пример #28
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up devolo Home Network from a config entry."""
    hass.data.setdefault(DOMAIN, {})
    zeroconf_instance = await zeroconf.async_get_async_instance(hass)
    async_client = get_async_client(hass)

    try:
        device = Device(ip=entry.data[CONF_IP_ADDRESS],
                        zeroconf_instance=zeroconf_instance)
        await device.async_connect(session_instance=async_client)
    except DeviceNotFound as err:
        raise ConfigEntryNotReady(
            f"Unable to connect to {entry.data[CONF_IP_ADDRESS]}") from err

    async def async_update_connected_plc_devices() -> dict[str, Any]:
        """Fetch data from API endpoint."""
        try:
            async with async_timeout.timeout(10):
                return await device.plcnet.async_get_network_overview(
                )  # type: ignore[no-any-return, union-attr]
        except DeviceUnavailable as err:
            raise UpdateFailed(err) from err

    async def async_update_wifi_connected_station() -> dict[str, Any]:
        """Fetch data from API endpoint."""
        try:
            async with async_timeout.timeout(10):
                return await device.device.async_get_wifi_connected_station(
                )  # type: ignore[no-any-return, union-attr]
        except DeviceUnavailable as err:
            raise UpdateFailed(err) from err

    async def async_update_wifi_neighbor_access_points() -> dict[str, Any]:
        """Fetch data from API endpoint."""
        try:
            async with async_timeout.timeout(30):
                return await device.device.async_get_wifi_neighbor_access_points(
                )  # type: ignore[no-any-return, union-attr]
        except DeviceUnavailable as err:
            raise UpdateFailed(err) from err

    async def disconnect(event: Event) -> None:
        """Disconnect from device."""
        await device.async_disconnect()

    coordinators: dict[str, DataUpdateCoordinator] = {}
    if device.plcnet:
        coordinators[CONNECTED_PLC_DEVICES] = DataUpdateCoordinator(
            hass,
            _LOGGER,
            name=CONNECTED_PLC_DEVICES,
            update_method=async_update_connected_plc_devices,
            update_interval=LONG_UPDATE_INTERVAL,
        )
    if device.device and "wifi1" in device.device.features:
        coordinators[CONNECTED_WIFI_CLIENTS] = DataUpdateCoordinator(
            hass,
            _LOGGER,
            name=CONNECTED_WIFI_CLIENTS,
            update_method=async_update_wifi_connected_station,
            update_interval=SHORT_UPDATE_INTERVAL,
        )
        coordinators[NEIGHBORING_WIFI_NETWORKS] = DataUpdateCoordinator(
            hass,
            _LOGGER,
            name=NEIGHBORING_WIFI_NETWORKS,
            update_method=async_update_wifi_neighbor_access_points,
            update_interval=LONG_UPDATE_INTERVAL,
        )

    hass.data[DOMAIN][entry.entry_id] = {
        "device": device,
        "coordinators": coordinators
    }

    for coordinator in coordinators.values():
        await coordinator.async_config_entry_first_refresh()

    await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

    entry.async_on_unload(
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, disconnect))

    return True
Пример #29
0
        if not isinstance(url, template_helper.Template):
            url = template_helper.Template(url, hass)
        url = url.async_render(parse_result=False)
    except TemplateError as err:
        _LOGGER.warning("Problem rendering template %s: %s", url, err)
        return {CONF_STILL_IMAGE_URL: "template_error"}, None
    try:
        yarl_url = yarl.URL(url)
    except ValueError:
        return {CONF_STILL_IMAGE_URL: "malformed_url"}, None
    if not yarl_url.is_absolute():
        return {CONF_STILL_IMAGE_URL: "relative_url"}, None
    verify_ssl = info[CONF_VERIFY_SSL]
    auth = generate_auth(info)
    try:
        async_client = get_async_client(hass, verify_ssl=verify_ssl)
        async with timeout(GET_IMAGE_TIMEOUT):
            response = await async_client.get(url, auth=auth, timeout=GET_IMAGE_TIMEOUT)
            response.raise_for_status()
            image = response.content
    except (
        TimeoutError,
        RequestError,
        HTTPStatusError,
        TimeoutException,
    ) as err:
        _LOGGER.error("Error getting camera image from %s: %s", url, type(err).__name__)
        return {CONF_STILL_IMAGE_URL: "unable_still_load"}, None

    if not image:
        return {CONF_STILL_IMAGE_URL: "unable_still_load"}, None
async def test_get_async_client_without_ssl(hass):
    """Test init async client without ssl."""
    client.get_async_client(hass, verify_ssl=False)

    assert isinstance(hass.data[client.DATA_ASYNC_CLIENT_NOVERIFY], httpx.AsyncClient)