config_flow.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. """Config flow for Integration 101 Template integration."""
  2. from __future__ import annotations
  3. import logging
  4. from typing import Any
  5. import voluptuous as vol
  6. from homeassistant.config_entries import (
  7. ConfigEntry,
  8. ConfigFlow,
  9. ConfigFlowResult,
  10. OptionsFlow,
  11. )
  12. from homeassistant.const import (
  13. CONF_HOST,
  14. CONF_PASSWORD,
  15. CONF_SCAN_INTERVAL,
  16. CONF_USERNAME,
  17. )
  18. from homeassistant.core import HomeAssistant, callback
  19. from homeassistant.exceptions import HomeAssistantError
  20. from homeassistant.helpers.aiohttp_client import async_get_clientsession
  21. from .api import (RouterAPI,
  22. RouterAPIAuthError,
  23. RouterAPIConnectionError)
  24. from .const import (DEFAULT_SCAN_INTERVAL,
  25. DOMAIN,
  26. MIN_SCAN_INTERVAL,
  27. DEFAULT_IP,
  28. DEFAULT_USER)
  29. _LOGGER = logging.getLogger(__name__)
  30. # TODO adjust the data schema to the data that you need
  31. STEP_USER_DATA_SCHEMA = vol.Schema(
  32. {
  33. vol.Required(CONF_HOST, description={"suggested_value": DEFAULT_IP}): str,
  34. vol.Required(CONF_USERNAME, description={"suggested_value": DEFAULT_USER}): str,
  35. vol.Required(CONF_PASSWORD): str,
  36. }
  37. )
  38. async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
  39. """Validate the user input allows us to connect.
  40. Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
  41. """
  42. # TODO validate the data can be used to set up a connection.
  43. # If your PyPI package is not built with async, pass your methods
  44. # to the executor:
  45. # await hass.async_add_executor_job(
  46. # your_validate_func, data[CONF_USERNAME], data[CONF_PASSWORD]
  47. # )
  48. session = async_get_clientsession(
  49. hass=hass,
  50. verify_ssl=False
  51. )
  52. api = RouterAPI(host=data[CONF_HOST],
  53. user=data[CONF_USERNAME],
  54. pwd=data[CONF_PASSWORD],
  55. session=session)
  56. try:
  57. await api.async_login()
  58. except RouterAPIAuthError as err:
  59. raise InvalidAuth from err
  60. except RouterAPIConnectionError as err:
  61. raise CannotConnect from err
  62. return {"title": f"Odido Klik & Klaar router - {data[CONF_HOST]}"}
  63. class RouterConfigFlow(ConfigFlow, domain=DOMAIN):
  64. """Handle a config flow for Example Integration."""
  65. VERSION = 1
  66. _input_data: dict[str, Any]
  67. @staticmethod
  68. @callback
  69. def async_get_options_flow(config_entry):
  70. """Get the options flow for this handler."""
  71. # Remove this method and the ExampleOptionsFlowHandler class
  72. # if you do not want any options for your integration.
  73. return RouterOptionsFlowHandler(config_entry)
  74. async def async_step_user(
  75. self, user_input: dict[str, Any] | None = None
  76. ) -> ConfigFlowResult:
  77. """Handle the initial step."""
  78. # Called when you initiate adding an integration via the UI
  79. errors: dict[str, str] = {}
  80. if user_input is not None:
  81. # The form has been filled in and submitted, so process the data provided.
  82. try:
  83. # Validate that the setup data is valid and if not handle errors.
  84. # The errors["base"] values match the values in your strings.json and translation files.
  85. info = await validate_input(self.hass, user_input)
  86. except CannotConnect:
  87. errors["base"] = "cannot_connect"
  88. except InvalidAuth:
  89. errors["base"] = "invalid_auth"
  90. except Exception: # pylint: disable=broad-except
  91. _LOGGER.exception("Unexpected exception")
  92. errors["base"] = "unknown"
  93. if "base" not in errors:
  94. # Validation was successful, so create a unique id for this instance of your integration
  95. # and create the config entry.
  96. await self.async_set_unique_id(info.get("title"))
  97. self._abort_if_unique_id_configured()
  98. return self.async_create_entry(title=info["title"], data=user_input)
  99. # Show initial form.
  100. return self.async_show_form(
  101. step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
  102. )
  103. async def async_step_reconfigure(
  104. self, user_input: dict[str, Any] | None = None
  105. ) -> ConfigFlowResult:
  106. """Add reconfigure step to allow to reconfigure a config entry."""
  107. # This methid displays a reconfigure option in the integration and is
  108. # different to options.
  109. # It can be used to reconfigure any of the data submitted when first installed.
  110. # This is optional and can be removed if you do not want to allow reconfiguration.
  111. errors: dict[str, str] = {}
  112. config_entry = self.hass.config_entries.async_get_entry(
  113. self.context["entry_id"]
  114. )
  115. if user_input is not None:
  116. try:
  117. user_input[CONF_HOST] = config_entry.data[CONF_HOST]
  118. await validate_input(self.hass, user_input)
  119. except CannotConnect:
  120. errors["base"] = "cannot_connect"
  121. except InvalidAuth:
  122. errors["base"] = "invalid_auth"
  123. except Exception: # pylint: disable=broad-except
  124. _LOGGER.exception("Unexpected exception")
  125. errors["base"] = "unknown"
  126. else:
  127. return self.async_update_reload_and_abort(
  128. config_entry,
  129. unique_id=config_entry.unique_id,
  130. data={**config_entry.data, **user_input},
  131. reason="reconfigure_successful",
  132. )
  133. return self.async_show_form(
  134. step_id="reconfigure",
  135. data_schema=vol.Schema(
  136. {
  137. vol.Required(
  138. CONF_USERNAME, default=config_entry.data[CONF_USERNAME]
  139. ): str,
  140. vol.Required(CONF_PASSWORD): str,
  141. }
  142. ),
  143. errors=errors,
  144. )
  145. class RouterOptionsFlowHandler(OptionsFlow):
  146. """Handles the options flow."""
  147. def __init__(self, config_entry: ConfigEntry) -> None:
  148. """Initialize options flow."""
  149. self.config_entry = config_entry
  150. self.options = dict(config_entry.options)
  151. async def async_step_init(self, user_input=None):
  152. """Handle options flow."""
  153. if user_input is not None:
  154. options = self.config_entry.options | user_input
  155. return self.async_create_entry(title="", data=options)
  156. # It is recommended to prepopulate options fields with default values if available.
  157. # These will be the same default values you use on your coordinator for setting variable values
  158. # if the option has not been set.
  159. data_schema = vol.Schema(
  160. {
  161. vol.Required(
  162. CONF_SCAN_INTERVAL,
  163. default=self.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL),
  164. ): (vol.All(vol.Coerce(int), vol.Clamp(min=MIN_SCAN_INTERVAL))),
  165. }
  166. )
  167. return self.async_show_form(step_id="init", data_schema=data_schema)
  168. class CannotConnect(HomeAssistantError):
  169. """Error to indicate we cannot connect."""
  170. class InvalidAuth(HomeAssistantError):
  171. """Error to indicate there is invalid auth."""