Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for MusicCast."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 from urllib.parse import urlparse
8 
9 from aiohttp import ClientConnectorError
10 from aiomusiccast import MusicCastConnectionException, MusicCastDevice
11 import voluptuous as vol
12 
13 from homeassistant import data_entry_flow
14 from homeassistant.components import ssdp
15 from homeassistant.config_entries import ConfigFlow
16 from homeassistant.const import CONF_HOST
17 from homeassistant.helpers.aiohttp_client import async_get_clientsession
18 
19 from . import get_upnp_desc
20 from .const import CONF_SERIAL, CONF_UPNP_DESC, DOMAIN
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 
25 class MusicCastFlowHandler(ConfigFlow, domain=DOMAIN):
26  """Handle a MusicCast config flow."""
27 
28  VERSION = 1
29 
30  serial_number: str | None = None
31  host: str
32  upnp_description: str | None = None
33 
34  async def async_step_user(
35  self, user_input: dict[str, Any] | None = None
36  ) -> data_entry_flow.ConfigFlowResult:
37  """Handle a flow initiated by the user."""
38  # Request user input, unless we are preparing discovery flow
39  if user_input is None:
40  return self._show_setup_form()
41 
42  host = user_input[CONF_HOST]
43  serial_number = None
44 
45  errors = {}
46  # Check if device is a MusicCast device
47 
48  try:
49  info = await MusicCastDevice.get_device_info(
50  host, async_get_clientsession(self.hass)
51  )
52  except (MusicCastConnectionException, ClientConnectorError):
53  errors["base"] = "cannot_connect"
54  except Exception:
55  _LOGGER.exception("Unexpected exception")
56  errors["base"] = "unknown"
57  else:
58  if (serial_number := info.get("system_id")) is None:
59  errors["base"] = "no_musiccast_device"
60 
61  if not errors:
62  await self.async_set_unique_idasync_set_unique_id(serial_number, raise_on_progress=False)
63  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
64 
65  return self.async_create_entryasync_create_entryasync_create_entry(
66  title=host,
67  data={
68  CONF_HOST: host,
69  CONF_SERIAL: serial_number,
70  CONF_UPNP_DESC: await get_upnp_desc(self.hass, host),
71  },
72  )
73 
74  return self._show_setup_form(errors)
75 
76  def _show_setup_form(
77  self, errors: dict | None = None
78  ) -> data_entry_flow.ConfigFlowResult:
79  """Show the setup form to the user."""
80  return self.async_show_formasync_show_formasync_show_form(
81  step_id="user",
82  data_schema=vol.Schema({vol.Required(CONF_HOST): str}),
83  errors=errors or {},
84  )
85 
86  async def async_step_ssdp(
87  self, discovery_info: ssdp.SsdpServiceInfo
88  ) -> data_entry_flow.ConfigFlowResult:
89  """Handle ssdp discoveries."""
90  if not await MusicCastDevice.check_yamaha_ssdp(
91  discovery_info.ssdp_location, async_get_clientsession(self.hass)
92  ):
93  return self.async_abortasync_abortasync_abort(reason="yxc_control_url_missing")
94 
95  self.serial_numberserial_number = discovery_info.upnp[ssdp.ATTR_UPNP_SERIAL]
96  self.upnp_descriptionupnp_description = discovery_info.ssdp_location
97 
98  # ssdp_location and hostname have been checked in check_yamaha_ssdp so it is safe to ignore type assignment
99  self.hosthost = urlparse(discovery_info.ssdp_location).hostname # type: ignore[assignment]
100 
101  await self.async_set_unique_idasync_set_unique_id(self.serial_numberserial_number)
102  self._abort_if_unique_id_configured_abort_if_unique_id_configured(
103  {
104  CONF_HOST: self.hosthost,
105  CONF_UPNP_DESC: self.upnp_descriptionupnp_description,
106  }
107  )
108  self.context.update(
109  {
110  "title_placeholders": {
111  "name": discovery_info.upnp.get(
112  ssdp.ATTR_UPNP_FRIENDLY_NAME, self.hosthost
113  )
114  }
115  }
116  )
117 
118  return await self.async_step_confirm()
119 
120  async def async_step_confirm(
121  self, user_input=None
122  ) -> data_entry_flow.ConfigFlowResult:
123  """Allow the user to confirm adding the device."""
124  if user_input is not None:
125  return self.async_create_entryasync_create_entryasync_create_entry(
126  title=self.hosthost,
127  data={
128  CONF_HOST: self.hosthost,
129  CONF_SERIAL: self.serial_numberserial_number,
130  CONF_UPNP_DESC: self.upnp_descriptionupnp_description,
131  },
132  )
133 
134  return self.async_show_formasync_show_formasync_show_form(step_id="confirm")
data_entry_flow.ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:36
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_step_ssdp(self, SsdpServiceInfo discovery_info)
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_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)
_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)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
IssData update(pyiss.ISS iss)
Definition: __init__.py:33
def get_upnp_desc(HomeAssistant hass, str host)
Definition: __init__.py:23
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)
config_entries.ConfigFlowResult async_step_confirm(self, dict[str, Any]|None user_input=None)