Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for the integration."""
2 
3 import asyncio
4 import logging
5 from typing import Any
6 
7 import aiohttp
8 from madvr.madvr import HeartBeatError, Madvr
9 import voluptuous as vol
10 
11 from homeassistant.config_entries import (
12  SOURCE_RECONFIGURE,
13  ConfigFlow,
14  ConfigFlowResult,
15 )
16 from homeassistant.const import CONF_HOST, CONF_PORT
17 from homeassistant.core import HomeAssistant
18 
19 from .const import DEFAULT_NAME, DEFAULT_PORT, DOMAIN
20 from .errors import CannotConnect
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 STEP_USER_DATA_SCHEMA = vol.Schema(
25  {
26  vol.Required(CONF_HOST): str,
27  vol.Required(CONF_PORT, default=DEFAULT_PORT): int,
28  }
29 )
30 
31 RETRY_INTERVAL = 1
32 
33 
34 class MadVRConfigFlow(ConfigFlow, domain=DOMAIN):
35  """Handle a config flow for the integration."""
36 
37  VERSION = 1
38 
39  async def async_step_user(
40  self, user_input: dict[str, Any] | None = None
41  ) -> ConfigFlowResult:
42  """Handle the initial step."""
43  return await self._handle_config_step_handle_config_step(user_input)
44 
46  self, user_input: dict[str, Any] | None = None
47  ) -> ConfigFlowResult:
48  """Handle a reconfiguration flow initialized by the user."""
49  return await self._handle_config_step_handle_config_step(user_input, step_id="reconfigure")
50 
52  self, user_input: dict[str, Any] | None = None, step_id: str = "user"
53  ) -> ConfigFlowResult:
54  """Handle the configuration step for both initial setup and reconfiguration."""
55  errors: dict[str, str] = {}
56 
57  if user_input is not None:
58  _LOGGER.debug("User input: %s", user_input)
59  host = user_input[CONF_HOST]
60  port = user_input[CONF_PORT]
61 
62  try:
63  mac = await test_connection(self.hass, host, port)
64  except CannotConnect:
65  _LOGGER.error("CannotConnect error caught")
66  errors["base"] = "cannot_connect"
67  else:
68  if not mac:
69  errors["base"] = "no_mac"
70  else:
71  _LOGGER.debug("MAC address found: %s", mac)
72  # abort if the detected mac differs from the one in the entry
73  await self.async_set_unique_idasync_set_unique_id(mac)
74  if self.sourcesourcesourcesource == SOURCE_RECONFIGURE:
75  self._abort_if_unique_id_mismatch_abort_if_unique_id_mismatch(reason="set_up_new_device")
76 
77  _LOGGER.debug("Reconfiguration done")
78  return self.async_update_reload_and_abortasync_update_reload_and_abort(
79  entry=self._get_reconfigure_entry_get_reconfigure_entry(),
80  data={**user_input, CONF_HOST: host, CONF_PORT: port},
81  )
82  # abort if already configured with same mac
83  self._abort_if_unique_id_configured_abort_if_unique_id_configured(updates={CONF_HOST: host})
84 
85  _LOGGER.debug("Configuration successful")
86  return self.async_create_entryasync_create_entryasync_create_entry(
87  title=DEFAULT_NAME,
88  data=user_input,
89  )
90  _LOGGER.debug("Showing form with errors: %s", errors)
91  return self.async_show_formasync_show_formasync_show_form(
92  step_id=step_id,
93  data_schema=self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
94  STEP_USER_DATA_SCHEMA, user_input
95  ),
96  errors=errors,
97  )
98 
99 
100 async def test_connection(hass: HomeAssistant, host: str, port: int) -> str:
101  """Test if we can connect to the device and grab the mac."""
102  madvr_client = Madvr(host=host, port=port, loop=hass.loop)
103  _LOGGER.debug("Testing connection to madVR at %s:%s", host, port)
104  # try to connect
105  try:
106  await asyncio.wait_for(madvr_client.open_connection(), timeout=15)
107  # connection can raise HeartBeatError if the device is not available or connection does not work
108  except (TimeoutError, aiohttp.ClientError, OSError, HeartBeatError) as err:
109  _LOGGER.error("Error connecting to madVR: %s", err)
110  raise CannotConnect from err
111 
112  # check if we are connected
113  if not madvr_client.connected:
114  raise CannotConnect("Connection failed")
115 
116  # background tasks needed to capture realtime info
117  await madvr_client.async_add_tasks()
118 
119  # wait for client to capture device info
120  retry_time = 15
121  while not madvr_client.mac_address and retry_time > 0:
122  await asyncio.sleep(RETRY_INTERVAL)
123  retry_time -= 1
124 
125  mac_address = madvr_client.mac_address
126  if mac_address:
127  _LOGGER.debug("Connected to madVR with MAC: %s", mac_address)
128  # close this connection because this client object will not be reused
129  await close_test_connection(madvr_client)
130  _LOGGER.debug("Connection test successful")
131  return mac_address
132 
133 
134 async def close_test_connection(madvr_client: Madvr) -> None:
135  """Close the test connection."""
136  _LOGGER.debug("Closing test connection")
137  madvr_client.stop()
138  await madvr_client.async_cancel_tasks()
139  await madvr_client.close_connection()
ConfigFlowResult async_step_reconfigure(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:47
ConfigFlowResult _handle_config_step(self, dict[str, Any]|None user_input=None, str step_id="user")
Definition: config_flow.py:53
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:41
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)
None _abort_if_unique_id_mismatch(self, *str reason="unique_id_mismatch", 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)
None close_test_connection(Madvr madvr_client)
Definition: config_flow.py:134
str test_connection(HomeAssistant hass, str host, int port)
Definition: config_flow.py:100