Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow to configure the Bravia TV integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from typing import Any, cast
7 from urllib.parse import urlparse
8 
9 from aiohttp import CookieJar
10 from pybravia import BraviaAuthError, BraviaClient, BraviaError, BraviaNotSupported
11 import voluptuous as vol
12 
13 from homeassistant.components import ssdp
14 from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult
15 from homeassistant.const import CONF_CLIENT_ID, CONF_HOST, CONF_MAC, CONF_NAME, CONF_PIN
16 from homeassistant.helpers import instance_id
17 from homeassistant.helpers.aiohttp_client import async_create_clientsession
18 from homeassistant.util.network import is_host_valid
19 
20 from .const import (
21  ATTR_CID,
22  ATTR_MAC,
23  ATTR_MODEL,
24  CONF_NICKNAME,
25  CONF_USE_PSK,
26  DOMAIN,
27  NICKNAME_PREFIX,
28 )
29 
30 
31 class BraviaTVConfigFlow(ConfigFlow, domain=DOMAIN):
32  """Handle a config flow for Bravia TV integration."""
33 
34  VERSION = 1
35 
36  def __init__(self) -> None:
37  """Initialize config flow."""
38  self.clientclient: BraviaClient | None = None
39  self.device_configdevice_config: dict[str, Any] = {}
40 
41  def create_client(self) -> None:
42  """Create Bravia TV client from config."""
43  host = self.device_configdevice_config[CONF_HOST]
45  self.hass,
46  cookie_jar=CookieJar(unsafe=True, quote_cookie=False),
47  )
48  self.clientclient = BraviaClient(host=host, session=session)
49 
50  async def gen_instance_ids(self) -> tuple[str, str]:
51  """Generate client_id and nickname."""
52  uuid = await instance_id.async_get(self.hass)
53  return uuid, f"{NICKNAME_PREFIX} {uuid[:6]}"
54 
55  async def async_connect_device(self) -> None:
56  """Connect to Bravia TV device from config."""
57  assert self.clientclient
58 
59  pin = self.device_configdevice_config[CONF_PIN]
60  use_psk = self.device_configdevice_config[CONF_USE_PSK]
61 
62  if use_psk:
63  await self.clientclient.connect(psk=pin)
64  else:
65  client_id = self.device_configdevice_config[CONF_CLIENT_ID]
66  nickname = self.device_configdevice_config[CONF_NICKNAME]
67  await self.clientclient.connect(pin=pin, clientid=client_id, nickname=nickname)
68  await self.clientclient.set_wol_mode(True)
69 
70  async def async_create_device(self) -> ConfigFlowResult:
71  """Create Bravia TV device from config."""
72  assert self.clientclient
73  await self.async_connect_deviceasync_connect_device()
74 
75  system_info = await self.clientclient.get_system_info()
76  cid = system_info[ATTR_CID].lower()
77  title = system_info[ATTR_MODEL]
78 
79  self.device_configdevice_config[CONF_MAC] = system_info[ATTR_MAC]
80 
81  await self.async_set_unique_idasync_set_unique_id(cid)
82  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
83 
84  return self.async_create_entryasync_create_entryasync_create_entry(title=title, data=self.device_configdevice_config)
85 
86  async def async_reauth_device(self) -> ConfigFlowResult:
87  """Reauthorize Bravia TV device from config."""
88  assert self.clientclient
89  await self.async_connect_deviceasync_connect_device()
90 
91  return self.async_update_reload_and_abortasync_update_reload_and_abort(
92  self._get_reauth_entry_get_reauth_entry(), data=self.device_configdevice_config
93  )
94 
95  async def async_step_user(
96  self, user_input: dict[str, Any] | None = None
97  ) -> ConfigFlowResult:
98  """Handle the initial step."""
99  errors: dict[str, str] = {}
100 
101  if user_input is not None:
102  host = user_input[CONF_HOST]
103  if is_host_valid(host):
104  self.device_configdevice_config[CONF_HOST] = host
105  return await self.async_step_authorizeasync_step_authorize()
106 
107  errors[CONF_HOST] = "invalid_host"
108 
109  return self.async_show_formasync_show_formasync_show_form(
110  step_id="user",
111  data_schema=vol.Schema({vol.Required(CONF_HOST): str}),
112  errors=errors,
113  )
114 
116  self, user_input: dict[str, Any] | None = None
117  ) -> ConfigFlowResult:
118  """Handle authorize step."""
119  self.create_clientcreate_client()
120 
121  if user_input is not None:
122  self.device_configdevice_config[CONF_USE_PSK] = user_input[CONF_USE_PSK]
123  if user_input[CONF_USE_PSK]:
124  return await self.async_step_pskasync_step_psk()
125  return await self.async_step_pinasync_step_pin()
126 
127  return self.async_show_formasync_show_formasync_show_form(
128  step_id="authorize",
129  data_schema=vol.Schema(
130  {
131  vol.Required(CONF_USE_PSK, default=False): bool,
132  }
133  ),
134  )
135 
136  async def async_step_pin(
137  self, user_input: dict[str, Any] | None = None
138  ) -> ConfigFlowResult:
139  """Handle PIN authorize step."""
140  errors: dict[str, str] = {}
141  client_id, nickname = await self.gen_instance_idsgen_instance_ids()
142 
143  if user_input is not None:
144  self.device_configdevice_config[CONF_PIN] = user_input[CONF_PIN]
145  self.device_configdevice_config[CONF_CLIENT_ID] = client_id
146  self.device_configdevice_config[CONF_NICKNAME] = nickname
147  try:
148  if self.sourcesourcesourcesource == SOURCE_REAUTH:
149  return await self.async_reauth_deviceasync_reauth_device()
150  return await self.async_create_deviceasync_create_device()
151  except BraviaAuthError:
152  errors["base"] = "invalid_auth"
153  except BraviaNotSupported:
154  errors["base"] = "unsupported_model"
155  except BraviaError:
156  errors["base"] = "cannot_connect"
157 
158  assert self.clientclient
159 
160  try:
161  await self.clientclient.pair(client_id, nickname)
162  except BraviaError:
163  return self.async_abortasync_abortasync_abort(reason="no_ip_control")
164 
165  return self.async_show_formasync_show_formasync_show_form(
166  step_id="pin",
167  data_schema=vol.Schema(
168  {
169  vol.Required(CONF_PIN): str,
170  }
171  ),
172  errors=errors,
173  )
174 
175  async def async_step_psk(
176  self, user_input: dict[str, Any] | None = None
177  ) -> ConfigFlowResult:
178  """Handle PSK authorize step."""
179  errors: dict[str, str] = {}
180 
181  if user_input is not None:
182  self.device_configdevice_config[CONF_PIN] = user_input[CONF_PIN]
183  try:
184  if self.sourcesourcesourcesource == SOURCE_REAUTH:
185  return await self.async_reauth_deviceasync_reauth_device()
186  return await self.async_create_deviceasync_create_device()
187  except BraviaAuthError:
188  errors["base"] = "invalid_auth"
189  except BraviaNotSupported:
190  errors["base"] = "unsupported_model"
191  except BraviaError:
192  errors["base"] = "cannot_connect"
193 
194  return self.async_show_formasync_show_formasync_show_form(
195  step_id="psk",
196  data_schema=vol.Schema(
197  {
198  vol.Required(CONF_PIN): str,
199  }
200  ),
201  errors=errors,
202  )
203 
204  async def async_step_ssdp(
205  self, discovery_info: ssdp.SsdpServiceInfo
206  ) -> ConfigFlowResult:
207  """Handle a discovered device."""
208  # We can cast the hostname to str because the ssdp_location is not bytes and
209  # not a relative url
210  host = cast(str, urlparse(discovery_info.ssdp_location).hostname)
211 
212  await self.async_set_unique_idasync_set_unique_id(discovery_info.upnp[ssdp.ATTR_UPNP_UDN])
213  self._abort_if_unique_id_configured_abort_if_unique_id_configured(updates={CONF_HOST: host})
214  self._async_abort_entries_match_async_abort_entries_match({CONF_HOST: host})
215 
216  scalarweb_info = discovery_info.upnp["X_ScalarWebAPI_DeviceInfo"]
217  service_types = scalarweb_info["X_ScalarWebAPI_ServiceList"][
218  "X_ScalarWebAPI_ServiceType"
219  ]
220 
221  if "videoScreen" not in service_types:
222  return self.async_abortasync_abortasync_abort(reason="not_bravia_device")
223 
224  model_name = discovery_info.upnp[ssdp.ATTR_UPNP_MODEL_NAME]
225  friendly_name = discovery_info.upnp[ssdp.ATTR_UPNP_FRIENDLY_NAME]
226 
227  self.context["title_placeholders"] = {
228  CONF_NAME: f"{model_name} ({friendly_name})",
229  CONF_HOST: host,
230  }
231 
232  self.device_configdevice_config[CONF_HOST] = host
233  return await self.async_step_confirmasync_step_confirm()
234 
236  self, user_input: dict[str, Any] | None = None
237  ) -> ConfigFlowResult:
238  """Allow the user to confirm adding the device."""
239  if user_input is not None:
240  return await self.async_step_authorizeasync_step_authorize()
241 
242  return self.async_show_formasync_show_formasync_show_form(step_id="confirm")
243 
244  async def async_step_reauth(
245  self, entry_data: Mapping[str, Any]
246  ) -> ConfigFlowResult:
247  """Handle configuration by re-auth."""
248  self.device_configdevice_config = {**entry_data}
249  return await self.async_step_authorizeasync_step_authorize()
ConfigFlowResult async_step_ssdp(self, ssdp.SsdpServiceInfo discovery_info)
Definition: config_flow.py:206
ConfigFlowResult async_step_psk(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:177
ConfigFlowResult async_step_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:237
ConfigFlowResult async_step_pin(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:138
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:97
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:246
ConfigFlowResult async_step_authorize(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:117
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_update_reload_and_abort(self, ConfigEntry entry, *str|None|UndefinedType unique_id=UNDEFINED, str|UndefinedType title=UNDEFINED, Mapping[str, Any]|UndefinedType data=UNDEFINED, Mapping[str, Any]|UndefinedType data_updates=UNDEFINED, Mapping[str, Any]|UndefinedType options=UNDEFINED, str|UndefinedType reason=UNDEFINED, bool reload_even_if_entry_is_unchanged=True)
ConfigFlowResult async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
None _async_abort_entries_match(self, dict[str, Any]|None match_dict=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)
str|None source(self)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
aiohttp.ClientSession async_create_clientsession()
Definition: coordinator.py:51
bool is_host_valid(str host)
Definition: network.py:93