hass-sncf/config_flow.py

74 lines
2.2 KiB
Python
Raw Normal View History

2022-01-03 20:56:40 +01:00
"""Config flow for SNCF 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
2022-01-03 21:14:02 +01:00
from .sncf import SNCF
2022-01-03 20:56:40 +01:00
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required("token"): str,
vol.Required("source_stop_point"): str,
vol.Required("dest_stop_point"): str,
vol.Required("max_transfers"): int,
vol.Required("max_duration_secs"): int,
}
)
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.
"""
sncf = SNCF(data["token"])
token_is_valid = await hass.async_add_executor_job(sncf.test_api_key)
if not token_is_valid:
raise InvalidAuth
# Return info that you want to store in the config entry.
return {"title": "SNCF"}
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for SNCF."""
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)
except InvalidAuth:
errors["base"] = "invalid_auth"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
return self.async_create_entry(title=info["title"], data=user_input)
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
)
class InvalidAuth(HomeAssistantError):
"""Error to indicate there is invalid auth."""