ha_gehome/sharkiq/config_flow.py

108 lines
3.5 KiB
Python
Raw Normal View History

2020-07-21 08:29:36 -06:00
"""Config flow for Shark IQ integration."""
import asyncio
2020-08-12 07:31:39 -06:00
from typing import Dict, Optional
import aiohttp
import async_timeout
from sharkiqpy import SharkIqAuthError, get_ayla_api
2020-07-21 08:29:36 -06:00
import voluptuous as vol
2020-08-12 07:31:39 -06:00
2020-07-21 08:29:36 -06:00
from homeassistant import config_entries, core, exceptions
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
2020-08-12 07:31:39 -06:00
from .const import DOMAIN, LOGGER # pylint:disable=unused-import
2020-07-21 08:29:36 -06:00
SHARKIQ_SCHEMA = vol.Schema(
{vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str}
)
async def validate_input(hass: core.HomeAssistant, data):
"""Validate the user input allows us to connect."""
ayla_api = get_ayla_api(
username=data[CONF_USERNAME],
password=data[CONF_PASSWORD],
2020-08-12 07:31:39 -06:00
websession=hass.helpers.aiohttp_client.async_get_clientsession(hass),
2020-07-21 08:29:36 -06:00
)
try:
with async_timeout.timeout(10):
2020-08-12 07:31:39 -06:00
LOGGER.debug("Initialize connection to Ayla networks API")
2020-07-21 08:29:36 -06:00
await ayla_api.async_sign_in()
2020-08-12 07:31:39 -06:00
except (asyncio.TimeoutError, aiohttp.ClientError):
2020-07-21 08:29:36 -06:00
raise CannotConnect
except SharkIqAuthError:
raise InvalidAuth
# Return info that you want to store in the config entry.
return {"title": f"Shark IQ ({data[CONF_USERNAME]:s})"}
2020-08-12 07:31:39 -06:00
class SharkIqConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
2020-07-21 08:29:36 -06:00
"""Handle a config flow for Shark IQ."""
VERSION = 1
2020-08-12 07:31:39 -06:00
CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL
2020-07-21 08:29:36 -06:00
2020-08-12 07:31:39 -06:00
async def _async_validate_input(self, user_input):
"""Validate form input."""
2020-07-21 08:29:36 -06:00
errors = {}
2020-08-12 07:31:39 -06:00
info = None
2020-07-21 08:29:36 -06:00
if user_input is not None:
# noinspection PyBroadException
try:
info = await validate_input(self.hass, user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
except InvalidAuth:
errors["base"] = "invalid_auth"
except Exception: # pylint: disable=broad-except
2020-08-12 07:31:39 -06:00
LOGGER.exception("Unexpected exception")
2020-07-21 08:29:36 -06:00
errors["base"] = "unknown"
2020-08-12 07:31:39 -06:00
return info, errors
async def async_step_user(self, user_input: Optional[Dict] = None):
"""Handle the initial step."""
errors = {}
if user_input is not None:
info, errors = await self._async_validate_input(user_input)
if info:
return self.async_create_entry(title=info["title"], data=user_input)
2020-07-21 08:29:36 -06:00
return self.async_show_form(
step_id="user", data_schema=SHARKIQ_SCHEMA, errors=errors
)
2020-08-12 07:31:39 -06:00
async def async_step_reauth(self, user_input: Optional[dict] = None):
"""Handle re-auth if login is invalid."""
errors = {}
if user_input is not None:
_, errors = await self._async_validate_input(user_input)
if not errors:
for entry in self._async_current_entries():
if entry.unique_id == self.unique_id:
self.hass.config_entries.async_update_entry(
entry, data=user_input
)
return self.async_abort(reason="reauth_successful")
if errors["base"] != "invalid_auth":
return self.async_abort(reason=errors["base"])
return self.async_show_form(
step_id="reauth", data_schema=SHARKIQ_SCHEMA, errors=errors,
)
2020-07-21 08:29:36 -06:00
class CannotConnect(exceptions.HomeAssistantError):
"""Error to indicate we cannot connect."""
class InvalidAuth(exceptions.HomeAssistantError):
"""Error to indicate there is invalid auth."""