Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow to configure the LG Netcast TV integration."""
2 
3 from __future__ import annotations
4 
5 import contextlib
6 from datetime import datetime, timedelta
7 from typing import TYPE_CHECKING, Any
8 
9 from pylgnetcast import AccessTokenError, LgNetCastClient, SessionIdError
10 import voluptuous as vol
11 
12 from homeassistant import config_entries
13 from homeassistant.config_entries import ConfigFlowResult
14 from homeassistant.const import (
15  CONF_ACCESS_TOKEN,
16  CONF_HOST,
17  CONF_ID,
18  CONF_MODEL,
19  CONF_NAME,
20 )
21 from homeassistant.core import CALLBACK_TYPE, callback
22 from homeassistant.data_entry_flow import AbortFlow
23 from homeassistant.helpers.event import async_track_time_interval
24 from homeassistant.util.network import is_host_valid
25 
26 from .const import DEFAULT_NAME, DOMAIN
27 from .helpers import LGNetCastDetailDiscoveryError, async_discover_netcast_details
28 
29 DISPLAY_ACCESS_TOKEN_INTERVAL = timedelta(seconds=1)
30 
31 
32 class LGNetCast(config_entries.ConfigFlow, domain=DOMAIN):
33  """Handle a config flow for LG Netcast TV integration."""
34 
35  VERSION = 1
36 
37  def __init__(self) -> None:
38  """Initialize config flow."""
39  self.clientclient: LgNetCastClient | None = None
40  self.device_config: dict[str, Any] = {}
41  self._discovered_devices: dict[str, Any] = {}
42  self._track_interval_track_interval: CALLBACK_TYPE | None = None
43 
44  def create_client(self) -> None:
45  """Create LG Netcast client from config."""
46  host = self.device_config[CONF_HOST]
47  access_token = self.device_config.get(CONF_ACCESS_TOKEN)
48  self.clientclient = LgNetCastClient(host, access_token)
49 
50  async def async_step_user(
51  self, user_input: dict[str, Any] | None = None
52  ) -> ConfigFlowResult:
53  """Handle the initial step."""
54  errors: dict[str, str] = {}
55 
56  if user_input is not None:
57  host = user_input[CONF_HOST]
58  if is_host_valid(host):
59  self.device_config[CONF_HOST] = host
60  return await self.async_step_authorizeasync_step_authorize()
61 
62  errors[CONF_HOST] = "invalid_host"
63 
64  return self.async_show_formasync_show_formasync_show_form(
65  step_id="user",
66  data_schema=vol.Schema({vol.Required(CONF_HOST): str}),
67  errors=errors,
68  )
69 
70  async def async_discover_client(self):
71  """Handle Discovery step."""
72  self.create_clientcreate_client()
73 
74  if TYPE_CHECKING:
75  assert self.clientclient is not None
76 
77  if self.device_config.get(CONF_ID):
78  return
79 
80  try:
81  details = await async_discover_netcast_details(self.hass, self.clientclient)
82  except LGNetCastDetailDiscoveryError as err:
83  raise AbortFlow("cannot_connect") from err
84 
85  if (unique_id := details["uuid"]) is None:
86  raise AbortFlow("invalid_host")
87 
88  self.device_config[CONF_ID] = unique_id
89  self.device_config[CONF_MODEL] = details["model_name"]
90 
91  if CONF_NAME not in self.device_config:
92  self.device_config[CONF_NAME] = details["friendly_name"] or DEFAULT_NAME
93 
95  self, user_input: dict[str, Any] | None = None
96  ) -> ConfigFlowResult:
97  """Handle Authorize step."""
98  errors: dict[str, str] = {}
99  self.async_stop_display_access_tokenasync_stop_display_access_token()
100 
101  if user_input is not None and user_input.get(CONF_ACCESS_TOKEN) is not None:
102  self.device_config[CONF_ACCESS_TOKEN] = user_input[CONF_ACCESS_TOKEN]
103 
104  await self.async_discover_clientasync_discover_client()
105  assert self.clientclient is not None
106 
107  await self.async_set_unique_idasync_set_unique_id(self.device_config[CONF_ID])
108  self._abort_if_unique_id_configured_abort_if_unique_id_configured(
109  updates={CONF_HOST: self.device_config[CONF_HOST]}
110  )
111 
112  try:
113  await self.hass.async_add_executor_job(
114  self.clientclient._get_session_id # noqa: SLF001
115  )
116  except AccessTokenError:
117  if user_input is not None:
118  errors[CONF_ACCESS_TOKEN] = "invalid_access_token"
119  except SessionIdError:
120  errors["base"] = "cannot_connect"
121  else:
122  return await self.async_create_deviceasync_create_device()
123 
125  self.hass,
126  self.async_display_access_tokenasync_display_access_token,
127  DISPLAY_ACCESS_TOKEN_INTERVAL,
128  cancel_on_shutdown=True,
129  )
130 
131  return self.async_show_formasync_show_formasync_show_form(
132  step_id="authorize",
133  data_schema=vol.Schema(
134  {
135  vol.Optional(CONF_ACCESS_TOKEN): vol.All(str, vol.Length(max=6)),
136  }
137  ),
138  errors=errors,
139  )
140 
141  async def async_display_access_token(self, _: datetime | None = None):
142  """Display access token on screen."""
143  assert self.clientclient is not None
144  with contextlib.suppress(AccessTokenError, SessionIdError):
145  await self.hass.async_add_executor_job(
146  self.clientclient._get_session_id # noqa: SLF001
147  )
148 
149  @callback
150  def async_remove(self):
151  """Terminate Access token display if flow is removed."""
152  self.async_stop_display_access_tokenasync_stop_display_access_token()
153 
155  """Stop Access token request if running."""
156  if self._track_interval_track_interval is not None:
157  self._track_interval_track_interval()
158  self._track_interval_track_interval = None
159 
160  async def async_create_device(self) -> ConfigFlowResult:
161  """Create LG Netcast TV Device from config."""
162  assert self.clientclient
163 
164  return self.async_create_entryasync_create_entryasync_create_entry(
165  title=self.device_config[CONF_NAME], data=self.device_config
166  )
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:52
ConfigFlowResult async_step_authorize(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:96
def async_display_access_token(self, datetime|None _=None)
Definition: config_flow.py:141
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)
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
NetcastDetails async_discover_netcast_details(HomeAssistant hass, LgNetCastClient client)
Definition: helpers.py:30
CALLBACK_TYPE async_track_time_interval(HomeAssistant hass, Callable[[datetime], Coroutine[Any, Any, None]|None] action, timedelta interval, *str|None name=None, bool|None cancel_on_shutdown=None)
Definition: event.py:1679
bool is_host_valid(str host)
Definition: network.py:93