def __init__(self, hass, config):
        """Initialize the scanner."""
        self.last_results = []

        self.username = config[CONF_USERNAME]
        self.password = config[CONF_PASSWORD]

        # The Tado device tracker can work with or without a home_id
        self.home_id = config[CONF_HOME_ID] if CONF_HOME_ID in config else None

        # If there's a home_id, we need a different API URL
        if self.home_id is None:
            self.tadoapiurl = 'https://my.tado.com/api/v2/me'
        else:
            self.tadoapiurl = 'https://my.tado.com/api/v2' \
                              '/homes/{home_id}/mobileDevices'

        # The API URL always needs a username and password
        self.tadoapiurl += '?username={username}&password={password}'

        self.websession = async_create_clientsession(
            hass, cookie_jar=aiohttp.CookieJar(unsafe=True, loop=hass.loop))

        self.success_init = asyncio.run_coroutine_threadsafe(
            self._async_update_info(), hass.loop
        ).result()

        _LOGGER.info("Scanner initialized")
    def __init__(self, hass, config):
        """Initialize the scanner."""
        self.hass = hass
        self.host = config[CONF_HOST]
        self.password = config[CONF_PASSWORD]

        self.data = {}
        self.token = None

        self.headers = {
            'X-Requested-With': 'XMLHttpRequest',
            'Referer': "http://{}/index.html".format(self.host),
            'User-Agent': ("Mozilla/5.0 (Windows NT 10.0; WOW64) "
                           "AppleWebKit/537.36 (KHTML, like Gecko) "
                           "Chrome/47.0.2526.106 Safari/537.36")
        }

        self.websession = async_create_clientsession(
            hass, auto_cleanup=False,
            cookie_jar=aiohttp.CookieJar(unsafe=True, loop=hass.loop)
        )

        @asyncio.coroutine
        def async_logout(event):
            """Logout from upc connect box."""
            try:
                yield from self._async_ws_function(CMD_LOGOUT)
                self.token = None
            finally:
                self.websession.detach()

        hass.bus.async_listen_once(
            EVENT_HOMEASSISTANT_STOP, async_logout)
async def get_controller(
        hass, host, username, password, port, site, verify_ssl):
    """Create a controller object and verify authentication."""
    import aiounifi

    if verify_ssl:
        session = aiohttp_client.async_get_clientsession(hass)
    else:
        session = aiohttp_client.async_create_clientsession(
            hass, verify_ssl=verify_ssl, cookie_jar=CookieJar(unsafe=True))

    controller = aiounifi.Controller(
        host, username=username, password=password, port=port, site=site,
        websession=session
    )

    try:
        with async_timeout.timeout(5):
            await controller.login()
        return controller

    except aiounifi.Unauthorized:
        LOGGER.warning("Connected to UniFi at %s but not registered.", host)
        raise AuthenticationRequired

    except (asyncio.TimeoutError, aiounifi.RequestError):
        LOGGER.error("Error connecting to the UniFi controller at %s", host)
        raise CannotConnect

    except aiounifi.AiounifiException:
        LOGGER.exception('Unknown UniFi communication error occurred')
        raise AuthenticationRequired
 def __init__(self, ip, password, hass, user="******"):
     self.ip = ip
     self.url = "http://{}/HNAP1/".format(ip)
     self.user = user
     self.password = password
     self.authenticated = None
     self._error_report = False
     self.session = async_create_clientsession(hass)
Exemple #5
0
async def test_sending_named_tuple(hass, aioclient_mock):
    """Test sending a named tuple in json."""
    resp = aioclient_mock.post("http://127.0.0.1/rgb", json={"rgb": RGBColor(4, 3, 2)})
    session = client.async_create_clientsession(hass)
    resp = await session.post("http://127.0.0.1/rgb", json={"rgb": RGBColor(4, 3, 2)})
    assert resp.status == 200
    await resp.json() == {"rgb": RGBColor(4, 3, 2)}
    aioclient_mock.mock_calls[0][2]["rgb"] == RGBColor(4, 3, 2)
async def test_create_clientsession_without_ssl_and_cookies(hass):
    """Test create clientsession without ssl."""
    session = client.async_create_clientsession(hass,
                                                False,
                                                cookies={"bla": True})
    assert isinstance(session, aiohttp.ClientSession)
    assert isinstance(hass.data[client.DATA_CONNECTOR_NOTVERIFY],
                      aiohttp.TCPConnector)
Exemple #7
0
    async def initialize(self, cookies):
        if self._hass is None:
            if self._session is not None:
                await self._session.close()

            self._session = aiohttp.client.ClientSession(cookies=cookies)
        else:
            self._session = async_create_clientsession(hass=self._hass, cookies=cookies)
Exemple #8
0
async def async_setup_entry(hass, config_entry):
    """Set up Cozytouch as config entry."""
    if not config_entry.options:
        hass.config_entries.async_update_entry(
            config_entry,
            options={
                "model": config_entry.data.get(
                    CONF_COZYTOUCH_ACTUATOR, DEFAULT_COZYTOUCH_ACTUATOR
                )
            },
        )

    # To allow users with multiple accounts/hubs, we create a new session so they have separate cookies
    session = async_create_clientsession(hass)
    client = CozytouchClient(
        username=config_entry.data[CONF_USERNAME],
        password=config_entry.data[CONF_PASSWORD],
        server=SUPPORTED_SERVERS["atlantic_cozytouch"],
        session=session,
    )

    coordinator = CozytouchDataUpdateCoordinator(
        hass,
        _LOGGER,
        name=DOMAIN,
        client=client,
        update_interval=SCAN_INTERVAL,
        config_entry_id=config_entry.entry_id,
    )
    await coordinator.async_config_entry_first_refresh()

    hass.data[DOMAIN][config_entry.entry_id] = {
        COZYTOUCH_DATAS: coordinator.data,
        COORDINATOR: coordinator,
    }
    hass.data[DOMAIN][COZYTOUCH_ACTUATOR] = config_entry.options[
        CONF_COZYTOUCH_ACTUATOR
    ]

    device_registry = await dr.async_get_registry(hass)
    for gateway in coordinator.data.gateways.values():
        device_registry.async_get_or_create(
            config_entry_id=config_entry.entry_id,
            identifiers={
                (DOMAIN, gateway.data["placeOID"]),
                (DOMAIN, gateway.data["gatewayId"]),
            },
            manufacturer="Atlantic/Thermor",
            name="Cozytouch",
            sw_version=gateway.data["connectivity"]["protocolVersion"],
        )

    hass.config_entries.async_setup_platforms(config_entry, PLATFORMS)

    if not config_entry.update_listeners:
        config_entry.add_update_listener(async_update_options)

    return True
Exemple #9
0
    async def async_setup(self) -> bool:
        """
        Set up a Crownstone config entry.

        Returns True if the setup was successful.
        """
        email = self.config_entry.data[CONF_EMAIL]
        password = self.config_entry.data[CONF_PASSWORD]

        self.cloud = CrownstoneCloud(
            email=email,
            password=password,
            clientsession=aiohttp_client.async_get_clientsession(self.hass),
        )
        # Login & sync all user data
        try:
            await self.cloud.async_initialize()
        except CrownstoneAuthenticationError as auth_err:
            _LOGGER.error(
                "Auth error during login with type: %s and message: %s",
                auth_err.type,
                auth_err.message,
            )
            return False
        except CrownstoneUnknownError as unknown_err:
            _LOGGER.error("Unknown error during login")
            raise ConfigEntryNotReady from unknown_err

        # A new clientsession is created because the default one does not cleanup on unload
        self.sse = CrownstoneSSEAsync(
            email=email,
            password=password,
            access_token=self.cloud.access_token,
            websession=aiohttp_client.async_create_clientsession(self.hass),
        )
        # Listen for events in the background, without task tracking
        asyncio.create_task(self.async_process_events(self.sse))
        setup_sse_listeners(self)

        # Set up a Crownstone USB only if path exists
        if self.config_entry.options[CONF_USB_PATH] is not None:
            await self.async_setup_usb()

        # Save the sphere where the USB is located
        # Makes HA aware of the Crownstone environment HA is placed in, a user can have multiple
        self.usb_sphere_id = self.config_entry.options[CONF_USB_SPHERE]

        self.hass.config_entries.async_setup_platforms(self.config_entry,
                                                       PLATFORMS)

        # HA specific listeners
        self.config_entry.async_on_unload(
            self.config_entry.add_update_listener(_async_update_listener))
        self.config_entry.async_on_unload(
            self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP,
                                            self.on_shutdown))

        return True
 async def _test_credentials(self, username, password):
     """Return true if credentials is valid."""
     try:
         session = async_create_clientsession(self.hass)
         client = RitualsGenieApiClient("", session)
         return await client.async_get_hubs(username, password)
     except Exception:  # pylint: disable=broad-except
         pass
     return False
 async def _test_credentials(self, address, username,
                             password) -> TapoApiClient:
     try:
         session = async_create_clientsession(self.hass)
         client = TapoApiClient(address, username, password, session)
         await client.login()
         return client
     except Exception as error:
         raise InvalidAuth from error
 async def async_step_auth(self, user_input):
     """User submited username and password. Or YAML error."""
     if self.yandex is None:
         session = async_create_clientsession(self.hass)
         self.yandex = YandexSession(session)
         
     resp = await self.yandex.login_username(user_input['username'],
                                             user_input['password'])
     return await self._check_yandex_response(resp)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    """Set up the Avanza Stock sensor."""
    session = async_create_clientsession(hass)
    monitored_conditions = config.get(CONF_MONITORED_CONDITIONS)
    stock = config.get(CONF_STOCK)
    entities = []
    if isinstance(stock, int):
        name = config.get(CONF_NAME)
        shares = config.get(CONF_SHARES)
        purchase_price = config.get(CONF_PURCHASE_PRICE)
        conversion_currency = config.get(CONF_CONVERSION_CURRENCY)
        invert_conversion_currency = config.get(CONF_INVERT_CONVERSION_CURRENCY)
        currency = config.get(CONF_CURRENCY)
        if name is None:
            name = DEFAULT_NAME + " " + str(stock)
        entities.append(
            AvanzaStockSensor(
                hass,
                stock,
                name,
                shares,
                purchase_price,
                conversion_currency,
                invert_conversion_currency,
                currency,
                monitored_conditions,
                session,
            )
        )
        _LOGGER.info("Tracking %s [%d] using Avanza" % (name, stock))
    else:
        for s in stock:
            id = s.get(CONF_ID)
            name = s.get(CONF_NAME)
            if name is None:
                name = DEFAULT_NAME + " " + str(id)
            shares = s.get(CONF_SHARES)
            purchase_price = s.get(CONF_PURCHASE_PRICE)
            conversion_currency = s.get(CONF_CONVERSION_CURRENCY)
            invert_conversion_currency = s.get(CONF_INVERT_CONVERSION_CURRENCY)
            currency = s.get(CONF_CURRENCY)
            entities.append(
                AvanzaStockSensor(
                    hass,
                    id,
                    name,
                    shares,
                    purchase_price,
                    conversion_currency,
                    invert_conversion_currency,
                    currency,
                    monitored_conditions,
                    session,
                )
            )
            _LOGGER.info("Tracking %s [%d] using Avanza" % (name, id))
    async_add_entities(entities, True)
Exemple #14
0
async def check_authentication(hass, username, password, serial):
    """Check if provided username an password are corrects."""
    return await pymultimatic.systemmanager.SystemManager(
        username,
        password,
        async_create_clientsession(hass),
        DEFAULT_SMART_PHONE_ID,
        serial,
    ).login(True)
Exemple #15
0
    async def _async_update_info(self):
        """
        Query Tado for device marked as at home.

        Returns boolean if scanning successful.
        """
        _LOGGER.debug("Requesting Tado")

        if self.websession is None:
            self.websession = async_create_clientsession(
                self.hass, cookie_jar=aiohttp.CookieJar(unsafe=True))

        last_results = []

        try:
            with async_timeout.timeout(10):
                # Format the URL here, so we can log the template URL if
                # anything goes wrong without exposing username and password.
                url = self.tadoapiurl.format(home_id=self.home_id,
                                             username=self.username,
                                             password=self.password)

                response = await self.websession.get(url)

                if response.status != HTTPStatus.OK:
                    _LOGGER.warning("Error %d on %s", response.status,
                                    self.tadoapiurl)
                    return False

                tado_json = await response.json()

        except (asyncio.TimeoutError, aiohttp.ClientError):
            _LOGGER.error("Cannot load Tado data")
            return False

        # Without a home_id, we fetched an URL where the mobile devices can be
        # found under the mobileDevices key.
        if "mobileDevices" in tado_json:
            tado_json = tado_json["mobileDevices"]

        # Find devices that have geofencing enabled, and are currently at home.
        for mobile_device in tado_json:
            if mobile_device.get(
                    "location") and mobile_device["location"]["atHome"]:
                device_id = mobile_device["id"]
                device_name = mobile_device["name"]
                last_results.append(Device(device_id, device_name))

        self.last_results = last_results

        _LOGGER.debug(
            "Tado presence query successful, %d device(s) at home",
            len(self.last_results),
        )

        return True
Exemple #16
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up the UniFi Protect config entries."""

    async_start_discovery(hass)
    session = async_create_clientsession(hass,
                                         cookie_jar=CookieJar(unsafe=True))
    protect = ProtectApiClient(
        host=entry.data[CONF_HOST],
        port=entry.data[CONF_PORT],
        username=entry.data[CONF_USERNAME],
        password=entry.data[CONF_PASSWORD],
        verify_ssl=entry.data[CONF_VERIFY_SSL],
        session=session,
        subscribed_models=DEVICES_FOR_SUBSCRIBE,
        override_connection_host=entry.options.get(CONF_OVERRIDE_CHOST, False),
        ignore_stats=not entry.options.get(CONF_ALL_UPDATES, False),
        ignore_unadopted=False,
    )
    _LOGGER.debug("Connect to UniFi Protect")
    data_service = ProtectData(hass, protect, SCAN_INTERVAL, entry)

    try:
        nvr_info = await protect.get_nvr()
    except NotAuthorized as err:
        raise ConfigEntryAuthFailed(err) from err
    except (asyncio.TimeoutError, ClientError, ServerDisconnectedError) as err:
        raise ConfigEntryNotReady from err

    if nvr_info.version < MIN_REQUIRED_PROTECT_V:
        _LOGGER.error(
            OUTDATED_LOG_MESSAGE,
            nvr_info.version,
            MIN_REQUIRED_PROTECT_V,
        )
        return False

    await async_migrate_data(hass, entry, protect)
    if entry.unique_id is None:
        hass.config_entries.async_update_entry(entry, unique_id=nvr_info.mac)

    await data_service.async_setup()
    if not data_service.last_update_success:
        raise ConfigEntryNotReady

    hass.data.setdefault(DOMAIN, {})[entry.entry_id] = data_service
    await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
    async_setup_services(hass)
    hass.http.register_view(ThumbnailProxyView(hass))
    hass.http.register_view(VideoProxyView(hass))

    entry.async_on_unload(entry.add_update_listener(_async_options_updated))
    entry.async_on_unload(
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP,
                                   data_service.async_stop))

    return True
Exemple #17
0
    async def initialize(self, cookies, session_id):
        _LOGGER.debug("Initializing WS connection")

        try:
            self._shutting_down = False

            self._session_id = session_id
            if self._hass is None:
                self._session = aiohttp.client.ClientSession(cookies=cookies)
            else:
                self._session = async_create_clientsession(hass=self._hass, cookies=cookies)

        except Exception as ex:
            _LOGGER.warning(f"Failed to create session of EdgeOS WS, Error: {str(ex)}")

        connection_attempt = 1

        while self.is_initialized and not self._shutting_down:
            try:
                if connection_attempt > 1:
                    await asyncio.sleep(10)

                if connection_attempt < MAXIMUM_RECONNECT:
                    _LOGGER.info(f"Connection attempt #{connection_attempt}")

                    async with self._session.ws_connect(self._ws_url,
                                                        origin=self._edgeos_url,
                                                        ssl=False,
                                                        max_msg_size=MAX_MSG_SIZE,
                                                        timeout=SCAN_INTERVAL_WS_TIMEOUT) as ws:

                        self._is_connected = True

                        self._ws = ws
                        await self.listen()

                    connection_attempt = connection_attempt + 1
                else:
                    _LOGGER.error(f"Failed to connect on retry #{connection_attempt}")
                    await self.close()

                self._is_connected = False

            except Exception as ex:
                self._is_connected = False

                error_message = str(ex)

                if error_message == ERROR_SHUTDOWN:
                    _LOGGER.warning(f"{error_message}")
                    break

                elif error_message != "":
                    _LOGGER.warning(f"Failed to listen EdgeOS, Error: {error_message}")

        _LOGGER.info("WS Connection terminated")
Exemple #18
0
async def async_setup(hass, config):
    """Set up Netgear LTE component."""
    if DATA_KEY not in hass.data:
        websession = async_create_clientsession(
            hass, cookie_jar=aiohttp.CookieJar(unsafe=True))
        hass.data[DATA_KEY] = LTEData(websession)

        async def delete_sms_handler(service):
            """Apply a service."""
            host = service.data[ATTR_HOST]
            conf = {CONF_HOST: host}
            modem_data = hass.data[DATA_KEY].get_modem_data(conf)

            if not modem_data:
                _LOGGER.error("%s: host %s unavailable", SERVICE_DELETE_SMS,
                              host)
                return

            for sms_id in service.data[ATTR_SMS_ID]:
                await modem_data.modem.delete_sms(sms_id)

        hass.services.async_register(DOMAIN,
                                     SERVICE_DELETE_SMS,
                                     delete_sms_handler,
                                     schema=DELETE_SMS_SCHEMA)

    netgear_lte_config = config[DOMAIN]

    # Set up each modem
    tasks = [_setup_lte(hass, lte_conf) for lte_conf in netgear_lte_config]
    await asyncio.wait(tasks)

    # Load platforms for each modem
    for lte_conf in netgear_lte_config:
        # Notify
        for notify_conf in lte_conf[NOTIFY_DOMAIN]:
            discovery_info = {
                CONF_HOST: lte_conf[CONF_HOST],
                CONF_NAME: notify_conf.get(CONF_NAME),
                NOTIFY_DOMAIN: notify_conf,
            }
            hass.async_create_task(
                discovery.async_load_platform(hass, NOTIFY_DOMAIN, DOMAIN,
                                              discovery_info, config))

        # Sensor
        sensor_conf = lte_conf.get(SENSOR_DOMAIN)
        discovery_info = {
            CONF_HOST: lte_conf[CONF_HOST],
            SENSOR_DOMAIN: sensor_conf,
        }
        hass.async_create_task(
            discovery.async_load_platform(hass, SENSOR_DOMAIN, DOMAIN,
                                          discovery_info, config))

    return True
Exemple #19
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 DATA_SCHEMA with values provided by the user.
    """
    user = data[CONF_USERNAME]
    password = data[CONF_PASSWORD]
    host = urlparse(data[CONF_HOST])
    tls_version = data.get(CONF_TLS_VER)

    if host.scheme == SCHEME_HTTP:
        https = False
        port = host.port or HTTP_PORT
        session = aiohttp_client.async_create_clientsession(
            hass, verify_ssl=False, cookie_jar=CookieJar(unsafe=True))
    elif host.scheme == SCHEME_HTTPS:
        https = True
        port = host.port or HTTPS_PORT
        session = aiohttp_client.async_get_clientsession(hass)
    else:
        _LOGGER.error("The isy994 host value in configuration is invalid")
        raise InvalidHost

    # Connect to ISY controller.
    isy_conn = Connection(
        host.hostname,
        port,
        user,
        password,
        use_https=https,
        tls_ver=tls_version,
        webroot=host.path,
        websession=session,
    )

    try:
        async with async_timeout.timeout(30):
            isy_conf_xml = await isy_conn.test_connection()
    except ISYInvalidAuthError as error:
        raise InvalidAuth from error
    except ISYConnectionError as error:
        raise CannotConnect from error

    try:
        isy_conf = Configuration(xml=isy_conf_xml)
    except ISYResponseParseError as error:
        raise CannotConnect from error
    if not isy_conf or "name" not in isy_conf or not isy_conf["name"]:
        raise CannotConnect

    # Return info that you want to store in the config entry.
    return {
        "title": f"{isy_conf['name']} ({host.hostname})",
        "uuid": isy_conf["uuid"]
    }
 async def _test_credentials(self, username, password):
     """Return true if credentials is valid."""
     try:
         session = async_create_clientsession(self.hass)
         client = IntegrationBlueprintApiClient(username, password, session)
         await client.async_get_data()
         return True
     except Exception:  # pylint: disable=broad-except
         pass
     return False
 async def _async_task_fetch_cities(self, url):
     try:
         session = async_create_clientsession(self.hass)
         client = PollenApi(session, url)
         self.data = await client.async_get_data()
         _LOGGER.debug("Fetched data: %s", self.data)
     finally:
         self.hass.async_create_task(
             self.hass.config_entries.flow.async_configure(
                 flow_id=self.flow_id))
 async def _test_credentials(self, username, password):
     """Return true if credentials is valid."""
     try:
         session = async_create_clientsession(self.hass)
         client = {{cookiecutter.class_name_prefix}}ApiClient(username, password, session)
         await client.async_get_data()
         return True
     except Exception:  # pylint: disable=broad-except
         pass
     return False
async def _setup_micloud_entry(hass: HomeAssistant, config_entry):
    data: dict = config_entry.data.copy()

    session = async_create_clientsession(hass)
    hass.data[DOMAIN]['cloud'] = cloud = MiCloud(session, data['servers'])

    if 'service_token' in data:
        # load devices with saved MiCloud auth
        cloud.auth = data
        devices = await cloud.get_devices()
    else:
        devices = None

    if devices is None:
        _LOGGER.debug(f"Login to MiCloud for {config_entry.title}")
        if await cloud.login(data['username'], data['password']):
            # update MiCloud auth in .storage
            data.update(cloud.auth)
            hass.config_entries.async_update_entry(config_entry, data=data)

            devices = await cloud.get_devices()
            if devices is None:
                _LOGGER.error("Can't load devices from MiCloud")

        else:
            _LOGGER.error("Can't login to MiCloud")

    # load devices from or save to .storage
    store = Store(hass, 1, f"{DOMAIN}/{data['username']}.json")
    if devices is None:
        _LOGGER.debug("Loading a list of devices from the .storage")
        devices = await store.async_load()
    else:
        _LOGGER.debug(f"Loaded from MiCloud {len(devices)} devices")
        await store.async_save(devices)

    if devices is None:
        _LOGGER.debug("No devices in .storage")
        return False

    # TODO: Think about a bunch of devices
    if 'devices' not in hass.data[DOMAIN]:
        hass.data[DOMAIN]['devices'] = devices
    else:
        hass.data[DOMAIN]['devices'] += devices

    for device in devices:
        # key - mac for BLE, and did for others
        did = device['did'] if device['pid'] not in '6' else \
            device['mac'].replace(':', '').lower()
        DevicesRegistry.defaults.setdefault(did, {})
        # don't override name if exists
        DevicesRegistry.defaults[did].setdefault('device_name', device['name'])

    return True
Exemple #24
0
    async def async_step_user(self, user_input=None):
        """Handle a flow initiated by the user."""
        if user_input is None:
            return await self._show_setup_form(user_input)

        errors = {}

        session = async_create_clientsession(self.hass)

        secspy = SecSpyServer(
            session,
            user_input[CONF_HOST],
            user_input[CONF_PORT],
            user_input[CONF_USERNAME],
            user_input[CONF_PASSWORD],
        )

        try:
            server_info = await secspy.get_server_information()
        except InvalidCredentials as ex:
            _LOGGER.debug(ex)
            errors["base"] = "connection_error"
            return await self._show_setup_form(errors)
        except RequestError as ex:
            _LOGGER.debug(ex)
            errors["base"] = "nvr_error"
            return await self._show_setup_form(errors)

        if server_info["server_version"] < MIN_SECSPY_VERSION:
            _LOGGER.debug(
                "This version of SecuritySpy is too old. Please upgrade to minimum V%s and try again.",
                MIN_SECSPY_VERSION,
            )
            errors["base"] = "version_old"
            return await self._show_setup_form(errors)

        unique_id = server_info[SERVER_ID]
        server_name = server_info[SERVER_NAME]
        server_ip_address = server_info["server_ip_address"]
        id_name = f"{server_name} ({server_ip_address})"

        await self.async_set_unique_id(unique_id)
        self._abort_if_unique_id_configured()

        return self.async_create_entry(
            title=server_name,
            data={
                CONF_ID: id_name,
                CONF_HOST: user_input[CONF_HOST],
                CONF_PORT: user_input[CONF_PORT],
                CONF_USERNAME: user_input.get(CONF_USERNAME),
                CONF_PASSWORD: user_input.get(CONF_PASSWORD),
                CONF_DISABLE_RTSP: user_input.get(CONF_DISABLE_RTSP),
            },
        )
Exemple #25
0
    async def async_step_user(self, user_input=None):
        """Handle a flow initialized by the user."""
        errors = {}

        if user_input is None:
            return await self._show_setup_form()

        session = async_create_clientsession(self.hass)
        renoweb = RenoWeb(API_KEY_MUNICIPALITIES, API_KEY, session)

        try:
            unique_data = await renoweb.find_renoweb_ids(
                user_input[CONF_MUNICIPALITY],
                user_input[CONF_ZIPCODE],
                user_input[CONF_ROAD_NAME],
                user_input[CONF_HOUSE_NUMBER],
            )
        except MunicipalityError:
            errors["base"] = "municipality_not_supported"
            return await self._show_setup_form(errors)
        except ResultError:
            errors["base"] = "location_not_found"
            return await self._show_setup_form(errors)
        except InvalidApiKey:
            errors["base"] = "connection_error"
            return await self._show_setup_form(errors)
        except RequestError:
            errors["base"] = "request_error"
            return await self._show_setup_form(errors)

        address = unique_data.get("address")
        address_id = unique_data.get("address_id")
        municipality_id = unique_data.get("municipality_id")
        if user_input[CONF_MUNICIPALITY].isnumeric():
            municipality_name = unique_data.get("municipality")
        else:
            municipality_name = user_input[CONF_MUNICIPALITY]
        entries = self._async_current_entries()
        for entry in entries:
            if entry.data[CONF_ADDRESS_ID] == address_id:
                return self.async_abort(reason="name_exists")

        return self.async_create_entry(
            title=address,
            data={
                CONF_ADDRESS: address,
                CONF_ADDRESS_ID: address_id,
                CONF_MUNICIPALITY_ID: municipality_id,
                CONF_MUNICIPALITY: municipality_name,
                CONF_ZIPCODE: user_input.get(CONF_ZIPCODE),
                CONF_ROAD_NAME: user_input.get(CONF_ROAD_NAME),
                CONF_HOUSE_NUMBER: user_input.get(CONF_HOUSE_NUMBER),
                CONF_UPDATE_INTERVAL: user_input.get(CONF_UPDATE_INTERVAL),
            },
        )
Exemple #26
0
 async def _test_user_input(self, apiKey: str, latitude: str,
                            longitude: str):
     """Return true if credentials is valid."""
     try:
         session = async_create_clientsession(self.hass)
         client = KnmiApiClient(apiKey, latitude, longitude, session)
         await client.async_get_data()
         return True
     except Exception:  # pylint: disable=broad-except
         pass
     return False
Exemple #27
0
    def initialize(self):
        try:
            self._session = async_create_clientsession(hass=self._hass)

        except Exception as ex:
            exc_type, exc_obj, tb = sys.exc_info()
            line_number = tb.tb_lineno

            _LOGGER.error(
                f"Failed to initialize BlueIris API, error: {ex}, line: {line_number}"
            )
Exemple #28
0
async def delete_cloud_instance(hass: HomeAssistant, entry: ConfigEntry):
    session = async_create_clientsession(hass)

    instance_id = entry.data[const.CONF_CLOUD_INSTANCE][const.CONF_CLOUD_INSTANCE_ID]
    token = entry.data[const.CONF_CLOUD_INSTANCE][const.CONF_CLOUD_INSTANCE_CONNECTION_TOKEN]

    response = await session.delete(f'{BASE_API_URL}/instance/{instance_id}', headers={
        'Authorization': f'Bearer {token}'
    })
    if response.status != HTTPStatus.OK:
        _LOGGER.error(f'Failed to delete cloud instance, status code: {response.status}')
    def __init__(self, hass: HomeAssistant, user_id: str, token: str):
        self._hass = hass
        self._user_id = user_id
        self._token = token

        self._property_entities = self._get_property_entities()
        self._session = async_create_clientsession(hass)

        self._unsub_pending: CALLBACK_TYPE | None = None
        self._pending = deque()
        self._report_states_job = HassJob(self._report_states)
Exemple #30
0
    async def initialize(self):
        cookie_jar = CookieJar(unsafe=True)

        if self._hass is None:
            self._session = ClientSession(cookie_jar=cookie_jar)
        else:
            self._session = async_create_clientsession(
                hass=self._hass,
                cookies=self._cookies,
                cookie_jar=cookie_jar,
            )
Exemple #31
0
async def async_setup(hass, config):
    """Set up Netgear LTE component."""
    if DATA_KEY not in hass.data:
        websession = async_create_clientsession(
            hass, cookie_jar=aiohttp.CookieJar(unsafe=True))
        hass.data[DATA_KEY] = LTEData(websession)

        async def delete_sms_handler(service):
            """Apply a service."""
            host = service.data[ATTR_HOST]
            conf = {CONF_HOST: host}
            modem_data = hass.data[DATA_KEY].get_modem_data(conf)

            if not modem_data:
                _LOGGER.error(
                    "%s: host %s unavailable", SERVICE_DELETE_SMS, host)
                return

            for sms_id in service.data[ATTR_SMS_ID]:
                await modem_data.modem.delete_sms(sms_id)

        hass.services.async_register(
            DOMAIN, SERVICE_DELETE_SMS, delete_sms_handler,
            schema=DELETE_SMS_SCHEMA)

    netgear_lte_config = config[DOMAIN]

    # Set up each modem
    tasks = [_setup_lte(hass, lte_conf) for lte_conf in netgear_lte_config]
    await asyncio.wait(tasks)

    # Load platforms for each modem
    for lte_conf in netgear_lte_config:
        # Notify
        for notify_conf in lte_conf[NOTIFY_DOMAIN]:
            discovery_info = {
                CONF_HOST: lte_conf[CONF_HOST],
                CONF_NAME: notify_conf.get(CONF_NAME),
                NOTIFY_DOMAIN: notify_conf,
            }
            hass.async_create_task(discovery.async_load_platform(
                hass, NOTIFY_DOMAIN, DOMAIN, discovery_info, config))

        # Sensor
        sensor_conf = lte_conf.get(SENSOR_DOMAIN)
        discovery_info = {
            CONF_HOST: lte_conf[CONF_HOST],
            SENSOR_DOMAIN: sensor_conf,
        }
        hass.async_create_task(discovery.async_load_platform(
            hass, SENSOR_DOMAIN, DOMAIN, discovery_info, config))

    return True
Exemple #32
0
 async def _test_credentials(self, username, password) -> bool:
     """Return true if credentials is valid."""
     try:
         session = async_create_clientsession(self.hass)
         client = AioWeenect(username=username,
                             password=password,
                             session=session)
         await client.login()
         return True
     except Exception as exception:  # pylint: disable=broad-except
         _LOGGER.debug(exception)
     return False
async def async_setup(hass, config):
    """Set up Netgear LTE component."""
    if DATA_KEY not in hass.data:
        websession = async_create_clientsession(
            hass, cookie_jar=aiohttp.CookieJar(unsafe=True))
        hass.data[DATA_KEY] = LTEData(websession)

    tasks = [_setup_lte(hass, conf) for conf in config.get(DOMAIN, [])]
    if tasks:
        await asyncio.wait(tasks)

    return True
Exemple #34
0
    def __init__(self, hass, username, password, serial):
        """Initialize hub."""
        # pylint: disable=import-outside-toplevel
        from pymultimatic.systemmanager import SystemManager

        session = async_create_clientsession(hass)
        self._manager = SystemManager(
            username, password, session, DEFAULT_SMART_PHONE_ID, serial
        )
        self.system: System = None
        self.update_system = Throttle(DEFAULT_SCAN_INTERVAL)(self._update_system)
        self._hass = hass
async def _setup_micloud_entry(hass, config_entry):
    """Thanks to @AlexxIT """
    data: dict = config_entry.data.copy()
    server_location = data.get('server_location') or 'cn'

    session = aiohttp_client.async_create_clientsession(hass)
    cloud = MiCloud(session)
    cloud.svr = server_location
    hass.data[DOMAIN]['cloud_instance'] = cloud

    if 'service_token' in data:
        # load devices with saved MiCloud auth
        cloud.auth = data
        devices = await cloud.get_total_devices([server_location])
    else:
        devices = None

    if devices is None:
        _LOGGER.debug(f"Login to MiCloud for {config_entry.title}")
        if await cloud.login(data['username'], data['password']):
            # update MiCloud auth in .storage
            data.update(cloud.auth)
            hass.config_entries.async_update_entry(config_entry, data=data)

            devices = await cloud.get_total_devices([server_location])

            if devices is None:
                _LOGGER.error("Can't load devices from MiCloud")

        else:
            _LOGGER.error("Can't login to MiCloud")

    # load devices from or save to .storage
    filename = sanitize_filename(data['username'])
    store = Store(hass, 1, f"{DOMAIN}/{filename}.json")
    if devices is None:
        _LOGGER.debug("Loading a list of devices from the .storage")
        devices = await store.async_load()
    else:
        _LOGGER.debug(f"Loaded from MiCloud {len(devices)} devices")
        await store.async_save(devices)

    if devices is None:
        _LOGGER.debug("No devices in .storage")
        return False

    # TODO: Think about a bunch of devices
    if 'micloud_devices' not in hass.data[DOMAIN]:
        hass.data[DOMAIN]['micloud_devices'] = devices
    else:
        hass.data[DOMAIN]['micloud_devices'] += devices

    return True
Exemple #36
0
async def async_setup(hass, config):
    """Set up TP-Link LTE component."""
    if DATA_KEY not in hass.data:
        websession = async_create_clientsession(
            hass, cookie_jar=aiohttp.CookieJar(unsafe=True))
        hass.data[DATA_KEY] = LTEData(websession)

    domain_config = config.get(DOMAIN, [])

    tasks = [_setup_lte(hass, conf) for conf in domain_config]
    if tasks:
        await asyncio.wait(tasks)

    for conf in domain_config:
        for notify_conf in conf.get(CONF_NOTIFY, []):
            hass.async_create_task(discovery.async_load_platform(
                hass, 'notify', DOMAIN, notify_conf, config))

    return True
    def __init__(self, hass, config):
        """Initialize the scanner."""
        self.hass = hass
        self.host = config[CONF_HOST]
        self.password = config[CONF_PASSWORD]

        self.data = {}
        self.token = None

        self.headers = {
            'X-Requested-With': 'XMLHttpRequest',
            'Referer': "http://{}/index.html".format(self.host),
            'User-Agent': ("Mozilla/5.0 (Windows NT 10.0; WOW64) "
                           "AppleWebKit/537.36 (KHTML, like Gecko) "
                           "Chrome/47.0.2526.106 Safari/537.36")
        }

        self.websession = async_create_clientsession(
            hass, cookie_jar=aiohttp.CookieJar(unsafe=True, loop=hass.loop))
async def async_setup(hass, config):
    """Set up Netgear LTE component."""
    if DATA_KEY not in hass.data:
        websession = async_create_clientsession(
            hass, cookie_jar=aiohttp.CookieJar(unsafe=True))
        hass.data[DATA_KEY] = LTEData(websession)

        async def service_handler(service):
            """Apply a service."""
            host = service.data.get(ATTR_HOST)
            conf = {CONF_HOST: host}
            modem_data = hass.data[DATA_KEY].get_modem_data(conf)

            if not modem_data:
                _LOGGER.error(
                    "%s: host %s unavailable", service.service, host)
                return

            if service.service == SERVICE_DELETE_SMS:
                for sms_id in service.data[ATTR_SMS_ID]:
                    await modem_data.modem.delete_sms(sms_id)
            elif service.service == SERVICE_SET_OPTION:
                failover = service.data.get(ATTR_FAILOVER)
                if failover:
                    await modem_data.modem.set_failover_mode(failover)

                autoconnect = service.data.get(ATTR_AUTOCONNECT)
                if autoconnect:
                    await modem_data.modem.set_autoconnect_mode(autoconnect)
            elif service.service == SERVICE_CONNECT_LTE:
                await modem_data.modem.connect_lte()

        hass.services.async_register(
            DOMAIN, SERVICE_DELETE_SMS, service_handler,
            schema=DELETE_SMS_SCHEMA)

        hass.services.async_register(
            DOMAIN, SERVICE_SET_OPTION, service_handler,
            schema=SET_OPTION_SCHEMA)

        hass.services.async_register(
            DOMAIN, SERVICE_CONNECT_LTE, service_handler,
            schema=CONNECT_LTE_SCHEMA)

    netgear_lte_config = config[DOMAIN]

    # Set up each modem
    tasks = [_setup_lte(hass, lte_conf) for lte_conf in netgear_lte_config]
    await asyncio.wait(tasks)

    # Load platforms for each modem
    for lte_conf in netgear_lte_config:
        # Notify
        for notify_conf in lte_conf[NOTIFY_DOMAIN]:
            discovery_info = {
                CONF_HOST: lte_conf[CONF_HOST],
                CONF_NAME: notify_conf.get(CONF_NAME),
                NOTIFY_DOMAIN: notify_conf,
            }
            hass.async_create_task(discovery.async_load_platform(
                hass, NOTIFY_DOMAIN, DOMAIN, discovery_info, config))

        # Sensor
        sensor_conf = lte_conf.get(SENSOR_DOMAIN)
        discovery_info = {
            CONF_HOST: lte_conf[CONF_HOST],
            SENSOR_DOMAIN: sensor_conf,
        }
        hass.async_create_task(discovery.async_load_platform(
            hass, SENSOR_DOMAIN, DOMAIN, discovery_info, config))

        # Binary Sensor
        binary_sensor_conf = lte_conf.get(BINARY_SENSOR_DOMAIN)
        discovery_info = {
            CONF_HOST: lte_conf[CONF_HOST],
            BINARY_SENSOR_DOMAIN: binary_sensor_conf,
        }
        hass.async_create_task(discovery.async_load_platform(
            hass, BINARY_SENSOR_DOMAIN, DOMAIN, discovery_info, config))

    return True
 def _async_helper():
     return client.async_create_clientsession(
         self.hass,
         cookies={'bla': True}
     )
Exemple #40
0
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Setup a Synology IP Camera."""
    verify_ssl = config.get(CONF_VERIFY_SSL)
    timeout = config.get(CONF_TIMEOUT)
    websession_init = async_get_clientsession(hass, verify_ssl)

    # Determine API to use for authentication
    syno_api_url = SYNO_API_URL.format(
        config.get(CONF_URL), WEBAPI_PATH, QUERY_CGI)

    query_payload = {
        'api': QUERY_API,
        'method': 'Query',
        'version': '1',
        'query': 'SYNO.'
    }
    try:
        with async_timeout.timeout(timeout, loop=hass.loop):
            query_req = yield from websession_init.get(
                syno_api_url,
                params=query_payload
            )

        # Skip content type check because Synology doesn't return JSON with
        # right content type
        query_resp = yield from query_req.json(content_type=None)
        auth_path = query_resp['data'][AUTH_API]['path']
        camera_api = query_resp['data'][CAMERA_API]['path']
        camera_path = query_resp['data'][CAMERA_API]['path']
        streaming_path = query_resp['data'][STREAMING_API]['path']

    except (asyncio.TimeoutError, aiohttp.ClientError):
        _LOGGER.exception("Error on %s", syno_api_url)
        return False

    # Authticate to NAS to get a session id
    syno_auth_url = SYNO_API_URL.format(
        config.get(CONF_URL), WEBAPI_PATH, auth_path)

    session_id = yield from get_session_id(
        hass,
        websession_init,
        config.get(CONF_USERNAME),
        config.get(CONF_PASSWORD),
        syno_auth_url,
        timeout
    )

    # init websession
    websession = async_create_clientsession(
        hass, verify_ssl, cookies={'id': session_id})

    # Use SessionID to get cameras in system
    syno_camera_url = SYNO_API_URL.format(
        config.get(CONF_URL), WEBAPI_PATH, camera_api)

    camera_payload = {
        'api': CAMERA_API,
        'method': 'List',
        'version': '1'
    }
    try:
        with async_timeout.timeout(timeout, loop=hass.loop):
            camera_req = yield from websession.get(
                syno_camera_url,
                params=camera_payload
            )
    except (asyncio.TimeoutError, aiohttp.ClientError):
        _LOGGER.exception("Error on %s", syno_camera_url)
        return False

    camera_resp = yield from camera_req.json(content_type=None)
    cameras = camera_resp['data']['cameras']

    # add cameras
    devices = []
    for camera in cameras:
        if not config.get(CONF_WHITELIST):
            camera_id = camera['id']
            snapshot_path = camera['snapshot_path']

            device = SynologyCamera(
                hass,
                websession,
                config,
                camera_id,
                camera['name'],
                snapshot_path,
                streaming_path,
                camera_path,
                auth_path,
                timeout
            )
            devices.append(device)

    async_add_devices(devices)
Exemple #41
0
 def _async_helper():
     return client.async_create_clientsession(self.hass, False, cookies={"bla": True})