75 lines
2.1 KiB
Python
75 lines
2.1 KiB
Python
|
"""Config flow for Kumi Sensors integration."""
|
||
|
from __future__ import annotations
|
||
|
|
||
|
import logging
|
||
|
from typing import Any
|
||
|
|
||
|
import voluptuous as vol
|
||
|
|
||
|
from homeassistant import config_entries
|
||
|
from homeassistant.core import HomeAssistant
|
||
|
from homeassistant.data_entry_flow import FlowResult
|
||
|
from homeassistant.exceptions import HomeAssistantError
|
||
|
from homeassistant.const import CONF_NAME, CONF_HOST
|
||
|
|
||
|
from .const import DOMAIN
|
||
|
from .kumisensors import KumiSensors
|
||
|
|
||
|
from urllib.request import urlopen
|
||
|
|
||
|
_LOGGER = logging.getLogger(__name__)
|
||
|
|
||
|
STEP_USER_DATA_SCHEMA = vol.Schema({"host": str})
|
||
|
|
||
|
|
||
|
async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
|
||
|
"""Validate the user input allows us to connect.
|
||
|
|
||
|
Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
|
||
|
"""
|
||
|
|
||
|
hub = KumiSensors(data[CONF_HOST], hass)
|
||
|
|
||
|
if not await hub.connect():
|
||
|
raise CannotConnect
|
||
|
|
||
|
# Return info that you want to store in the config entry.
|
||
|
return {CONF_NAME: await hub.get_identifier()}
|
||
|
|
||
|
|
||
|
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||
|
"""Handle a config flow for Kumi Sensors."""
|
||
|
|
||
|
VERSION = 1
|
||
|
|
||
|
async def async_step_user(
|
||
|
self, user_input: dict[str, Any] | None = None
|
||
|
) -> FlowResult:
|
||
|
"""Handle the initial step."""
|
||
|
if user_input is None:
|
||
|
return self.async_show_form(
|
||
|
step_id="user", data_schema=STEP_USER_DATA_SCHEMA
|
||
|
)
|
||
|
|
||
|
errors = {}
|
||
|
|
||
|
try:
|
||
|
info = await validate_input(self.hass, user_input)
|
||
|
user_input[CONF_NAME] = info[CONF_NAME]
|
||
|
except CannotConnect:
|
||
|
errors["base"] = "cannot_connect"
|
||
|
except Exception: # pylint: disable=broad-except
|
||
|
_LOGGER.exception("Unexpected exception")
|
||
|
errors["base"] = "unknown"
|
||
|
else:
|
||
|
return self.async_create_entry(title=info[CONF_NAME], data=user_input)
|
||
|
|
||
|
return self.async_show_form(
|
||
|
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
|
||
|
)
|
||
|
|
||
|
|
||
|
class CannotConnect(HomeAssistantError):
|
||
|
"""Error to indicate we cannot connect."""
|
||
|
|