Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for LG ThinQ."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 import uuid
8 
9 from thinqconnect import ThinQApi, ThinQAPIErrorCodes, ThinQAPIException
10 from thinqconnect.country import Country
11 import voluptuous as vol
12 
13 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
14 from homeassistant.const import CONF_ACCESS_TOKEN, CONF_COUNTRY
15 from homeassistant.helpers import config_validation as cv
16 from homeassistant.helpers.aiohttp_client import async_get_clientsession
17 from homeassistant.helpers.selector import CountrySelector, CountrySelectorConfig
18 
19 from .const import (
20  CLIENT_PREFIX,
21  CONF_CONNECT_CLIENT_ID,
22  DEFAULT_COUNTRY,
23  DOMAIN,
24  THINQ_DEFAULT_NAME,
25  THINQ_PAT_URL,
26 )
27 
28 SUPPORTED_COUNTRIES = [country.value for country in Country]
29 THINQ_ERRORS = {
30  ThinQAPIErrorCodes.INVALID_TOKEN: "invalid_token",
31  ThinQAPIErrorCodes.NOT_ACCEPTABLE_TERMS: "not_acceptable_terms",
32  ThinQAPIErrorCodes.NOT_ALLOWED_API_AGAIN: "not_allowed_api_again",
33  ThinQAPIErrorCodes.NOT_SUPPORTED_COUNTRY: "not_supported_country",
34  ThinQAPIErrorCodes.EXCEEDED_API_CALLS: "exceeded_api_calls",
35 }
36 
37 _LOGGER = logging.getLogger(__name__)
38 
39 
40 class ThinQFlowHandler(ConfigFlow, domain=DOMAIN):
41  """Handle a config flow."""
42 
43  VERSION = 1
44 
45  def _get_default_country_code(self) -> str:
46  """Get the default country code based on config."""
47  country = self.hass.config.country
48  if country is not None and country in SUPPORTED_COUNTRIES:
49  return country
50 
51  return DEFAULT_COUNTRY
52 
54  self, access_token: str, country_code: str
55  ) -> ConfigFlowResult:
56  """Create an entry for the flow."""
57  connect_client_id = f"{CLIENT_PREFIX}-{uuid.uuid4()!s}"
58 
59  # To verify PAT, create an api to retrieve the device list.
60  await ThinQApi(
61  session=async_get_clientsession(self.hass),
62  access_token=access_token,
63  country_code=country_code,
64  client_id=connect_client_id,
65  ).async_get_device_list()
66 
67  # If verification is success, create entry.
68  return self.async_create_entryasync_create_entryasync_create_entry(
69  title=THINQ_DEFAULT_NAME,
70  data={
71  CONF_ACCESS_TOKEN: access_token,
72  CONF_CONNECT_CLIENT_ID: connect_client_id,
73  CONF_COUNTRY: country_code,
74  },
75  )
76 
77  async def async_step_user(
78  self, user_input: dict[str, Any] | None = None
79  ) -> ConfigFlowResult:
80  """Handle a flow initiated by the user."""
81  errors: dict[str, str] = {}
82 
83  if user_input is not None:
84  access_token = user_input[CONF_ACCESS_TOKEN]
85  country_code = user_input[CONF_COUNTRY]
86 
87  # Check if PAT is already configured.
88  await self.async_set_unique_idasync_set_unique_id(access_token)
89  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
90 
91  try:
92  return await self._validate_and_create_entry_validate_and_create_entry(access_token, country_code)
93  except ThinQAPIException as exc:
94  errors["base"] = THINQ_ERRORS.get(exc.code, "token_unauthorized")
95  _LOGGER.error("Failed to validate access_token %s", exc)
96 
97  return self.async_show_formasync_show_formasync_show_form(
98  step_id="user",
99  data_schema=vol.Schema(
100  {
101  vol.Required(CONF_ACCESS_TOKEN): cv.string,
102  vol.Required(
103  CONF_COUNTRY, default=self._get_default_country_code_get_default_country_code()
104  ): CountrySelector(
105  CountrySelectorConfig(countries=SUPPORTED_COUNTRIES)
106  ),
107  }
108  ),
109  description_placeholders={"pat_url": THINQ_PAT_URL},
110  errors=errors,
111  )
ConfigFlowResult _validate_and_create_entry(self, str access_token, str country_code)
Definition: config_flow.py:55
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:79
None _abort_if_unique_id_configured(self, dict[str, Any]|None updates=None, bool reload_on_update=True, *str error="already_configured")
ConfigEntry|None async_set_unique_id(self, str|None unique_id=None, *bool raise_on_progress=True)
ConfigFlowResult async_create_entry(self, *str title, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None, Mapping[str, Any]|None options=None)
ConfigFlowResult async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_create_entry(self, *str|None title=None, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None)
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)