Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Monoprice 6-Zone Amplifier integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from pymonoprice import get_monoprice
9 from serial import SerialException
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import (
13  ConfigEntry,
14  ConfigFlow,
15  ConfigFlowResult,
16  OptionsFlow,
17 )
18 from homeassistant.const import CONF_PORT
19 from homeassistant.core import HomeAssistant, callback
20 from homeassistant.exceptions import HomeAssistantError
21 from homeassistant.helpers.typing import VolDictType
22 
23 from .const import (
24  CONF_SOURCE_1,
25  CONF_SOURCE_2,
26  CONF_SOURCE_3,
27  CONF_SOURCE_4,
28  CONF_SOURCE_5,
29  CONF_SOURCE_6,
30  CONF_SOURCES,
31  DOMAIN,
32 )
33 
34 _LOGGER = logging.getLogger(__name__)
35 
36 SOURCES = [
37  CONF_SOURCE_1,
38  CONF_SOURCE_2,
39  CONF_SOURCE_3,
40  CONF_SOURCE_4,
41  CONF_SOURCE_5,
42  CONF_SOURCE_6,
43 ]
44 
45 OPTIONS_FOR_DATA: VolDictType = {vol.Optional(source): str for source in SOURCES}
46 
47 DATA_SCHEMA = vol.Schema({vol.Required(CONF_PORT): str, **OPTIONS_FOR_DATA})
48 
49 
50 @callback
52  sources_config = {
53  str(idx + 1): data.get(source) for idx, source in enumerate(SOURCES)
54  }
55 
56  return {
57  index: name.strip()
58  for index, name in sources_config.items()
59  if (name is not None and name.strip() != "")
60  }
61 
62 
63 async def validate_input(hass: HomeAssistant, data):
64  """Validate the user input allows us to connect.
65 
66  Data has the keys from DATA_SCHEMA with values provided by the user.
67  """
68  try:
69  await hass.async_add_executor_job(get_monoprice, data[CONF_PORT])
70  except SerialException as err:
71  _LOGGER.error("Error connecting to Monoprice controller")
72  raise CannotConnect from err
73 
74  sources = _sources_from_config(data)
75 
76  # Return info that you want to store in the config entry.
77  return {CONF_PORT: data[CONF_PORT], CONF_SOURCES: sources}
78 
79 
80 class MonoPriceConfigFlow(ConfigFlow, domain=DOMAIN):
81  """Handle a config flow for Monoprice 6-Zone Amplifier."""
82 
83  VERSION = 1
84 
85  async def async_step_user(
86  self, user_input: dict[str, Any] | None = None
87  ) -> ConfigFlowResult:
88  """Handle the initial step."""
89  errors = {}
90  if user_input is not None:
91  try:
92  info = await validate_input(self.hass, user_input)
93 
94  return self.async_create_entryasync_create_entryasync_create_entry(title=user_input[CONF_PORT], data=info)
95  except CannotConnect:
96  errors["base"] = "cannot_connect"
97  except Exception:
98  _LOGGER.exception("Unexpected exception")
99  errors["base"] = "unknown"
100 
101  return self.async_show_formasync_show_formasync_show_form(
102  step_id="user", data_schema=DATA_SCHEMA, errors=errors
103  )
104 
105  @staticmethod
106  @callback
108  config_entry: ConfigEntry,
109  ) -> MonopriceOptionsFlowHandler:
110  """Define the config flow to handle options."""
112 
113 
114 @callback
115 def _key_for_source(index, source, previous_sources):
116  if str(index) in previous_sources:
117  key = vol.Optional(
118  source, description={"suggested_value": previous_sources[str(index)]}
119  )
120  else:
121  key = vol.Optional(source)
122 
123  return key
124 
125 
127  """Handle a Monoprice options flow."""
128 
129  @callback
130  def _previous_sources(self):
131  if CONF_SOURCES in self.config_entryconfig_entryconfig_entry.options:
132  previous = self.config_entryconfig_entryconfig_entry.options[CONF_SOURCES]
133  else:
134  previous = self.config_entryconfig_entryconfig_entry.data[CONF_SOURCES]
135 
136  return previous
137 
138  async def async_step_init(
139  self, user_input: dict[str, Any] | None = None
140  ) -> ConfigFlowResult:
141  """Manage the options."""
142  if user_input is not None:
143  return self.async_create_entryasync_create_entry(
144  title="", data={CONF_SOURCES: _sources_from_config(user_input)}
145  )
146 
147  previous_sources = self._previous_sources_previous_sources()
148 
149  options = {
150  _key_for_source(idx + 1, source, previous_sources): str
151  for idx, source in enumerate(SOURCES)
152  }
153 
154  return self.async_show_formasync_show_form(
155  step_id="init",
156  data_schema=vol.Schema(options),
157  )
158 
159 
161  """Error to indicate we cannot connect."""
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:87
MonopriceOptionsFlowHandler async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:109
ConfigFlowResult async_step_init(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:140
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_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)
None config_entry(self, ConfigEntry value)
_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)
def _key_for_source(index, source, previous_sources)
Definition: config_flow.py:115
def validate_input(HomeAssistant hass, data)
Definition: config_flow.py:63