Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Philips TV integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import platform
7 from typing import Any
8 
9 from haphilipsjs import ConnectionFailure, PairingFailure, PhilipsTV
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import (
13  SOURCE_REAUTH,
14  ConfigEntry,
15  ConfigFlow,
16  ConfigFlowResult,
17 )
18 from homeassistant.const import (
19  CONF_API_VERSION,
20  CONF_HOST,
21  CONF_PASSWORD,
22  CONF_PIN,
23  CONF_USERNAME,
24 )
25 from homeassistant.core import HomeAssistant, callback
26 from homeassistant.helpers import selector
28  SchemaFlowFormStep,
29  SchemaOptionsFlowHandler,
30 )
31 
32 from . import LOGGER
33 from .const import CONF_ALLOW_NOTIFY, CONF_SYSTEM, CONST_APP_ID, CONST_APP_NAME, DOMAIN
34 
35 USER_SCHEMA = vol.Schema(
36  {
37  vol.Required(
38  CONF_HOST,
39  ): str,
40  vol.Required(
41  CONF_API_VERSION,
42  default=1,
43  ): vol.In([1, 5, 6]),
44  }
45 )
46 
47 OPTIONS_SCHEMA = vol.Schema(
48  {
49  vol.Optional(CONF_ALLOW_NOTIFY, default=False): selector.BooleanSelector(),
50  }
51 )
52 OPTIONS_FLOW = {
53  "init": SchemaFlowFormStep(OPTIONS_SCHEMA),
54 }
55 
56 
57 async def _validate_input(
58  hass: HomeAssistant, host: str, api_version: int
59 ) -> PhilipsTV:
60  """Validate the user input allows us to connect."""
61  hub = PhilipsTV(host, api_version)
62 
63  await hub.getSystem()
64  await hub.setTransport(hub.secured_transport)
65 
66  if not hub.system:
67  raise ConnectionFailure("System data is empty")
68 
69  return hub
70 
71 
72 class PhilipsJSConfigFlow(ConfigFlow, domain=DOMAIN):
73  """Handle a config flow for Philips TV."""
74 
75  VERSION = 1
76 
77  def __init__(self) -> None:
78  """Initialize flow."""
79  super().__init__()
80  self._current_current: dict[str, Any] = {}
81  self._hub_hub: PhilipsTV | None = None
82  self._pair_state_pair_state: Any = None
83 
84  async def _async_create_current(self) -> ConfigFlowResult:
85  system = self._current_current[CONF_SYSTEM]
86  if self.sourcesourcesourcesource == SOURCE_REAUTH:
87  return self.async_update_reload_and_abortasync_update_reload_and_abort(
88  self._get_reauth_entry_get_reauth_entry(), data_updates=self._current_current
89  )
90 
91  return self.async_create_entryasync_create_entryasync_create_entry(
92  title=f"{system['name']} ({system['serialnumber']})",
93  data=self._current_current,
94  )
95 
96  async def async_step_pair(
97  self, user_input: dict[str, Any] | None = None
98  ) -> ConfigFlowResult:
99  """Attempt to pair with device."""
100  assert self._hub_hub
101 
102  errors: dict[str, str] = {}
103  schema = vol.Schema(
104  {
105  vol.Required(CONF_PIN): str,
106  }
107  )
108 
109  if not user_input:
110  try:
111  self._pair_state_pair_state = await self._hub_hub.pairRequest(
112  CONST_APP_ID,
113  CONST_APP_NAME,
114  platform.node(),
115  platform.system(),
116  "native",
117  )
118  except PairingFailure as exc:
119  LOGGER.debug(exc)
120  return self.async_abortasync_abortasync_abort(
121  reason="pairing_failure",
122  description_placeholders={"error_id": exc.data.get("error_id")},
123  )
124  return self.async_show_formasync_show_formasync_show_form(
125  step_id="pair", data_schema=schema, errors=errors
126  )
127 
128  try:
129  username, password = await self._hub_hub.pairGrant(
130  self._pair_state_pair_state, user_input[CONF_PIN]
131  )
132  except PairingFailure as exc:
133  LOGGER.debug(exc)
134  if exc.data.get("error_id") == "INVALID_PIN":
135  errors[CONF_PIN] = "invalid_pin"
136  return self.async_show_formasync_show_formasync_show_form(
137  step_id="pair", data_schema=schema, errors=errors
138  )
139 
140  return self.async_abortasync_abortasync_abort(
141  reason="pairing_failure",
142  description_placeholders={"error_id": exc.data.get("error_id")},
143  )
144 
145  self._current_current[CONF_USERNAME] = username
146  self._current_current[CONF_PASSWORD] = password
147  return await self._async_create_current_async_create_current()
148 
149  async def async_step_reauth(
150  self, entry_data: Mapping[str, Any]
151  ) -> ConfigFlowResult:
152  """Handle configuration by re-auth."""
153  self._current_current[CONF_HOST] = entry_data[CONF_HOST]
154  self._current_current[CONF_API_VERSION] = entry_data[CONF_API_VERSION]
155  return await self.async_step_userasync_step_userasync_step_user()
156 
157  async def async_step_user(
158  self, user_input: dict[str, Any] | None = None
159  ) -> ConfigFlowResult:
160  """Handle the initial step."""
161  errors = {}
162  if user_input:
163  self._current_current = user_input
164  try:
165  hub = await _validate_input(
166  self.hass, user_input[CONF_HOST], user_input[CONF_API_VERSION]
167  )
168  except ConnectionFailure as exc:
169  LOGGER.error(exc)
170  errors["base"] = "cannot_connect"
171  except Exception: # noqa: BLE001
172  LOGGER.exception("Unexpected exception")
173  errors["base"] = "unknown"
174  else:
175  if serialnumber := hub.system.get("serialnumber"):
176  await self.async_set_unique_idasync_set_unique_id(serialnumber)
177  if self.sourcesourcesourcesource != SOURCE_REAUTH:
178  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
179 
180  self._current_current[CONF_SYSTEM] = hub.system
181  self._current_current[CONF_API_VERSION] = hub.api_version
182  self._hub_hub = hub
183 
184  if hub.pairing_type == "digest_auth_pairing":
185  return await self.async_step_pairasync_step_pair()
186  return await self._async_create_current_async_create_current()
187 
188  schema = self.add_suggested_values_to_schemaadd_suggested_values_to_schema(USER_SCHEMA, self._current_current)
189  return self.async_show_formasync_show_formasync_show_form(step_id="user", data_schema=schema, errors=errors)
190 
191  @staticmethod
192  @callback
194  config_entry: ConfigEntry,
195  ) -> SchemaOptionsFlowHandler:
196  """Get the options flow for this handler."""
197  return SchemaOptionsFlowHandler(config_entry, OPTIONS_FLOW)
SchemaOptionsFlowHandler async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:195
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:159
ConfigFlowResult async_step_pair(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:98
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:151
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_step_user(self, dict[str, Any]|None user_input=None)
ConfigFlowResult async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=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)
vol.Schema add_suggested_values_to_schema(self, vol.Schema data_schema, Mapping[str, Any]|None suggested_values)
_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)
PhilipsTV _validate_input(HomeAssistant hass, str host, int api_version)
Definition: config_flow.py:59