Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Volumio integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from pyvolumio import CannotConnectError, Volumio
9 import voluptuous as vol
10 
11 from homeassistant.components import zeroconf
12 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
13 from homeassistant.const import CONF_HOST, CONF_ID, CONF_NAME, CONF_PORT
14 from homeassistant.core import HomeAssistant, callback
15 from homeassistant.exceptions import HomeAssistantError
16 from homeassistant.helpers.aiohttp_client import async_get_clientsession
17 
18 from .const import DOMAIN
19 
20 _LOGGER = logging.getLogger(__name__)
21 
22 
23 DATA_SCHEMA = vol.Schema(
24  {vol.Required(CONF_HOST): str, vol.Required(CONF_PORT, default=3000): int}
25 )
26 
27 
28 async def validate_input(hass: HomeAssistant, host: str, port: int) -> dict[str, Any]:
29  """Validate the user input allows us to connect."""
30  volumio = Volumio(host, port, async_get_clientsession(hass))
31 
32  try:
33  return await volumio.get_system_info()
34  except CannotConnectError as error:
35  raise CannotConnect from error
36 
37 
38 class VolumioConfigFlow(ConfigFlow, domain=DOMAIN):
39  """Handle a config flow for Volumio."""
40 
41  VERSION = 1
42 
43  _host: str
44  _port: int
45  _name: str
46  _uuid: str | None
47 
48  @callback
49  def _async_get_entry(self) -> ConfigFlowResult:
50  return self.async_create_entryasync_create_entryasync_create_entry(
51  title=self._name_name,
52  data={
53  CONF_NAME: self._name_name,
54  CONF_HOST: self._host_host,
55  CONF_PORT: self._port_port,
56  CONF_ID: self._uuid_uuid,
57  },
58  )
59 
60  async def _set_uid_and_abort(self):
61  await self.async_set_unique_idasync_set_unique_id(self._uuid_uuid)
62  self._abort_if_unique_id_configured_abort_if_unique_id_configured(
63  updates={
64  CONF_HOST: self._host_host,
65  CONF_PORT: self._port_port,
66  CONF_NAME: self._name_name,
67  }
68  )
69 
70  async def async_step_user(
71  self, user_input: dict[str, Any] | None = None
72  ) -> ConfigFlowResult:
73  """Handle the initial step."""
74  errors = {}
75  if user_input is not None:
76  info = None
77  self._host_host = user_input[CONF_HOST]
78  self._port_port = user_input[CONF_PORT]
79  try:
80  info = await validate_input(self.hass, self._host_host, self._port_port)
81  except CannotConnect:
82  errors["base"] = "cannot_connect"
83  except Exception:
84  _LOGGER.exception("Unexpected exception")
85  errors["base"] = "unknown"
86 
87  if info is not None:
88  self._name_name = info.get("name", self._host_host)
89  self._uuid_uuid = info.get("id")
90  if self._uuid_uuid is not None:
91  await self._set_uid_and_abort_set_uid_and_abort()
92 
93  return self._async_get_entry_async_get_entry()
94 
95  return self.async_show_formasync_show_formasync_show_form(
96  step_id="user", data_schema=DATA_SCHEMA, errors=errors
97  )
98 
100  self, discovery_info: zeroconf.ZeroconfServiceInfo
101  ) -> ConfigFlowResult:
102  """Handle zeroconf discovery."""
103  self._host_host = discovery_info.host
104  self._port_port = discovery_info.port or 3000
105  self._name_name = discovery_info.properties["volumioName"]
106  self._uuid_uuid = discovery_info.properties["UUID"]
107 
108  await self._set_uid_and_abort_set_uid_and_abort()
109 
110  return await self.async_step_discovery_confirmasync_step_discovery_confirm()
111 
113  self, user_input: dict[str, Any] | None = None
114  ) -> ConfigFlowResult:
115  """Handle user-confirmation of discovered node."""
116  if user_input is not None:
117  try:
118  await validate_input(self.hass, self._host_host, self._port_port)
119  return self._async_get_entry_async_get_entry()
120  except CannotConnect:
121  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
122 
123  return self.async_show_formasync_show_formasync_show_form(
124  step_id="discovery_confirm", description_placeholders={"name": self._name_name}
125  )
126 
127 
129  """Error to indicate we cannot connect."""
ConfigFlowResult async_step_zeroconf(self, zeroconf.ZeroconfServiceInfo discovery_info)
Definition: config_flow.py:101
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:72
ConfigFlowResult async_step_discovery_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:114
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_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)
dict[str, Any] validate_input(HomeAssistant hass, str host, int port)
Definition: config_flow.py:28
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)