Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Squeezebox integration."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 from http import HTTPStatus
7 import logging
8 from typing import TYPE_CHECKING, Any
9 
10 from pysqueezebox import Server, async_discover
11 import voluptuous as vol
12 
13 from homeassistant.components import dhcp
14 from homeassistant.components.media_player import DOMAIN as MP_DOMAIN
15 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
16 from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_USERNAME
17 from homeassistant.data_entry_flow import AbortFlow
18 from homeassistant.helpers import entity_registry as er
19 from homeassistant.helpers.aiohttp_client import async_get_clientsession
20 from homeassistant.helpers.device_registry import format_mac
21 
22 from .const import CONF_HTTPS, DEFAULT_PORT, DOMAIN
23 
24 _LOGGER = logging.getLogger(__name__)
25 
26 TIMEOUT = 5
27 
28 
30  discovery_info: dict[str, Any] | None = None,
31 ) -> vol.Schema:
32  """Generate base schema."""
33  base_schema: dict[Any, Any] = {}
34  if discovery_info and CONF_HOST in discovery_info:
35  base_schema.update(
36  {
37  vol.Required(
38  CONF_HOST,
39  description={"suggested_value": discovery_info[CONF_HOST]},
40  ): str,
41  }
42  )
43  else:
44  base_schema.update({vol.Required(CONF_HOST): str})
45 
46  if discovery_info and CONF_PORT in discovery_info:
47  base_schema.update(
48  {
49  vol.Required(
50  CONF_PORT,
51  default=DEFAULT_PORT,
52  description={"suggested_value": discovery_info[CONF_PORT]},
53  ): int,
54  }
55  )
56  else:
57  base_schema.update({vol.Required(CONF_PORT, default=DEFAULT_PORT): int})
58 
59  base_schema.update(
60  {
61  vol.Optional(CONF_USERNAME): str,
62  vol.Optional(CONF_PASSWORD): str,
63  vol.Optional(CONF_HTTPS, default=False): bool,
64  }
65  )
66 
67  return vol.Schema(base_schema)
68 
69 
70 class SqueezeboxConfigFlow(ConfigFlow, domain=DOMAIN):
71  """Handle a config flow for Squeezebox."""
72 
73  VERSION = 1
74 
75  def __init__(self) -> None:
76  """Initialize an instance of the squeezebox config flow."""
77  self.data_schemadata_schema = _base_schema()
78  self.discovery_infodiscovery_info: dict[str, Any] | None = None
79 
80  async def _discover(self, uuid: str | None = None) -> None:
81  """Discover an unconfigured LMS server."""
82  self.discovery_infodiscovery_info = None
83  discovery_event = asyncio.Event()
84 
85  def _discovery_callback(server: Server) -> None:
86  if server.uuid:
87  # ignore already configured uuids
88  for entry in self._async_current_entries_async_current_entries():
89  if entry.unique_id == server.uuid:
90  return
91  self.discovery_infodiscovery_info = {
92  CONF_HOST: server.host,
93  CONF_PORT: int(server.port),
94  "uuid": server.uuid,
95  }
96  _LOGGER.debug("Discovered server: %s", self.discovery_infodiscovery_info)
97  discovery_event.set()
98 
99  discovery_task = self.hass.async_create_task(
100  async_discover(_discovery_callback)
101  )
102 
103  await discovery_event.wait()
104  discovery_task.cancel() # stop searching as soon as we find server
105 
106  # update with suggested values from discovery
107  self.data_schemadata_schema = _base_schema(self.discovery_infodiscovery_info)
108 
109  async def _validate_input(self, data: dict[str, Any]) -> str | None:
110  """Validate the user input allows us to connect.
111 
112  Retrieve unique id and abort if already configured.
113  """
114  server = Server(
115  async_get_clientsession(self.hass),
116  data[CONF_HOST],
117  data[CONF_PORT],
118  data.get(CONF_USERNAME),
119  data.get(CONF_PASSWORD),
120  https=data[CONF_HTTPS],
121  )
122 
123  try:
124  status = await server.async_query("serverstatus")
125  if not status:
126  if server.http_status == HTTPStatus.UNAUTHORIZED:
127  return "invalid_auth"
128  return "cannot_connect"
129  except Exception: # noqa: BLE001
130  return "unknown"
131 
132  if "uuid" in status:
133  await self.async_set_unique_idasync_set_unique_id(status["uuid"])
134  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
135 
136  return None
137 
138  async def async_step_user(
139  self, user_input: dict[str, Any] | None = None
140  ) -> ConfigFlowResult:
141  """Handle a flow initialized by the user."""
142  errors = {}
143  if user_input and CONF_HOST in user_input:
144  # update with host provided by user
145  self.data_schemadata_schema = _base_schema(user_input)
146  return await self.async_step_editasync_step_edit()
147 
148  # no host specified, see if we can discover an unconfigured LMS server
149  try:
150  async with asyncio.timeout(TIMEOUT):
151  await self._discover_discover()
152  return await self.async_step_editasync_step_edit()
153  except TimeoutError:
154  errors["base"] = "no_server_found"
155 
156  # display the form
157  return self.async_show_formasync_show_formasync_show_form(
158  step_id="user",
159  data_schema=vol.Schema({vol.Optional(CONF_HOST): str}),
160  errors=errors,
161  )
162 
163  async def async_step_edit(
164  self, user_input: dict[str, Any] | None = None
165  ) -> ConfigFlowResult:
166  """Edit a discovered or manually inputted server."""
167  errors = {}
168  if user_input:
169  error = await self._validate_input_validate_input(user_input)
170  if not error:
171  return self.async_create_entryasync_create_entryasync_create_entry(
172  title=user_input[CONF_HOST], data=user_input
173  )
174  errors["base"] = error
175 
176  return self.async_show_formasync_show_formasync_show_form(
177  step_id="edit", data_schema=self.data_schemadata_schema, errors=errors
178  )
179 
181  self, discovery_info: dict[str, Any]
182  ) -> ConfigFlowResult:
183  """Handle discovery of a server."""
184  _LOGGER.debug("Reached server discovery flow with info: %s", discovery_info)
185  if "uuid" in discovery_info:
186  await self.async_set_unique_idasync_set_unique_id(discovery_info.pop("uuid"))
187  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
188  else:
189  # attempt to connect to server and determine uuid. will fail if
190  # password required
191  error = await self._validate_input_validate_input(discovery_info)
192  if error:
193  await self._async_handle_discovery_without_unique_id_async_handle_discovery_without_unique_id()
194 
195  # update schema with suggested values from discovery
196  self.data_schemadata_schema = _base_schema(discovery_info)
197 
198  self.context.update({"title_placeholders": {"host": discovery_info[CONF_HOST]}})
199 
200  return await self.async_step_editasync_step_edit()
201 
202  async def async_step_dhcp(
203  self, discovery_info: dhcp.DhcpServiceInfo
204  ) -> ConfigFlowResult:
205  """Handle dhcp discovery of a Squeezebox player."""
206  _LOGGER.debug(
207  "Reached dhcp discovery of a player with info: %s", discovery_info
208  )
209  await self.async_set_unique_idasync_set_unique_id(format_mac(discovery_info.macaddress))
210  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
211 
212  _LOGGER.debug("Configuring dhcp player with unique id: %s", self.unique_idunique_id)
213 
214  registry = er.async_get(self.hass)
215 
216  if TYPE_CHECKING:
217  assert self.unique_idunique_id
218  # if we have detected this player, do nothing. if not, there must be a server out there for us to configure, so start the normal user flow (which tries to autodetect server)
219  if registry.async_get_entity_id(MP_DOMAIN, DOMAIN, self.unique_idunique_id) is not None:
220  # this player is already known, so do nothing other than mark as configured
221  raise AbortFlow("already_configured")
222 
223  # if the player is unknown, then we likely need to configure its server
224  return await self.async_step_userasync_step_userasync_step_user()
ConfigFlowResult async_step_integration_discovery(self, dict[str, Any] discovery_info)
Definition: config_flow.py:182
ConfigFlowResult async_step_edit(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:165
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:140
ConfigFlowResult async_step_dhcp(self, dhcp.DhcpServiceInfo discovery_info)
Definition: config_flow.py:204
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)
list[ConfigEntry] _async_current_entries(self, bool|None include_ignore=None)
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=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)
IssData update(pyiss.ISS iss)
Definition: __init__.py:33
None async_discover(HomeAssistant hass)
Definition: config_flow.py:82
vol.Schema _base_schema(dict[str, Any]|None discovery_info=None)
Definition: config_flow.py:31
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)