Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Adds config flow for Brother Printer."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from brother import Brother, SnmpError, UnsupportedModelError
8 import voluptuous as vol
9 
10 from homeassistant.components import zeroconf
11 from homeassistant.components.snmp import async_get_snmp_engine
12 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
13 from homeassistant.const import CONF_HOST, CONF_TYPE
14 from homeassistant.core import HomeAssistant
15 from homeassistant.exceptions import HomeAssistantError
16 from homeassistant.util.network import is_host_valid
17 
18 from .const import DOMAIN, PRINTER_TYPES
19 
20 DATA_SCHEMA = vol.Schema(
21  {
22  vol.Required(CONF_HOST): str,
23  vol.Optional(CONF_TYPE, default="laser"): vol.In(PRINTER_TYPES),
24  }
25 )
26 RECONFIGURE_SCHEMA = vol.Schema({vol.Required(CONF_HOST): str})
27 
28 
29 async def validate_input(
30  hass: HomeAssistant, user_input: dict[str, Any], expected_mac: str | None = None
31 ) -> tuple[str, str]:
32  """Validate the user input."""
33  if not is_host_valid(user_input[CONF_HOST]):
34  raise InvalidHost
35 
36  snmp_engine = await async_get_snmp_engine(hass)
37 
38  brother = await Brother.create(user_input[CONF_HOST], snmp_engine=snmp_engine)
39  await brother.async_update()
40 
41  if expected_mac is not None and brother.serial.lower() != expected_mac:
42  raise AnotherDevice
43 
44  return (brother.model, brother.serial)
45 
46 
47 class BrotherConfigFlow(ConfigFlow, domain=DOMAIN):
48  """Handle a config flow for Brother Printer."""
49 
50  VERSION = 1
51 
52  def __init__(self) -> None:
53  """Initialize."""
54  self.brotherbrother: Brother
55  self.hosthost: str | None = None
56 
57  async def async_step_user(
58  self, user_input: dict[str, Any] | None = None
59  ) -> ConfigFlowResult:
60  """Handle the initial step."""
61  errors = {}
62 
63  if user_input is not None:
64  try:
65  model, serial = await validate_input(self.hass, user_input)
66  except InvalidHost:
67  errors[CONF_HOST] = "wrong_host"
68  except (ConnectionError, TimeoutError):
69  errors["base"] = "cannot_connect"
70  except SnmpError:
71  errors["base"] = "snmp_error"
72  except UnsupportedModelError:
73  return self.async_abortasync_abortasync_abort(reason="unsupported_model")
74  else:
75  await self.async_set_unique_idasync_set_unique_id(serial.lower())
76  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
77 
78  title = f"{model} {serial}"
79  return self.async_create_entryasync_create_entryasync_create_entry(title=title, data=user_input)
80 
81  return self.async_show_formasync_show_formasync_show_form(
82  step_id="user", data_schema=DATA_SCHEMA, errors=errors
83  )
84 
86  self, discovery_info: zeroconf.ZeroconfServiceInfo
87  ) -> ConfigFlowResult:
88  """Handle zeroconf discovery."""
89  self.hosthost = discovery_info.host
90 
91  # Do not probe the device if the host is already configured
92  self._async_abort_entries_match_async_abort_entries_match({CONF_HOST: self.hosthost})
93 
94  snmp_engine = await async_get_snmp_engine(self.hass)
95  model = discovery_info.properties.get("product")
96 
97  try:
98  self.brotherbrother = await Brother.create(
99  self.hosthost, snmp_engine=snmp_engine, model=model
100  )
101  await self.brotherbrother.async_update()
102  except UnsupportedModelError:
103  return self.async_abortasync_abortasync_abort(reason="unsupported_model")
104  except (ConnectionError, SnmpError, TimeoutError):
105  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
106 
107  # Check if already configured
108  await self.async_set_unique_idasync_set_unique_id(self.brotherbrother.serial.lower())
109  self._abort_if_unique_id_configured_abort_if_unique_id_configured({CONF_HOST: self.hosthost})
110 
111  self.context.update(
112  {
113  "title_placeholders": {
114  "serial_number": self.brotherbrother.serial,
115  "model": self.brotherbrother.model,
116  }
117  }
118  )
119  return await self.async_step_zeroconf_confirmasync_step_zeroconf_confirm()
120 
122  self, user_input: dict[str, Any] | None = None
123  ) -> ConfigFlowResult:
124  """Handle a flow initiated by zeroconf."""
125  if user_input is not None:
126  title = f"{self.brother.model} {self.brother.serial}"
127  return self.async_create_entryasync_create_entryasync_create_entry(
128  title=title,
129  data={CONF_HOST: self.hosthost, CONF_TYPE: user_input[CONF_TYPE]},
130  )
131  return self.async_show_formasync_show_formasync_show_form(
132  step_id="zeroconf_confirm",
133  data_schema=vol.Schema(
134  {vol.Optional(CONF_TYPE, default="laser"): vol.In(PRINTER_TYPES)}
135  ),
136  description_placeholders={
137  "serial_number": self.brotherbrother.serial,
138  "model": self.brotherbrother.model,
139  },
140  )
141 
143  self, user_input: dict[str, Any] | None = None
144  ) -> ConfigFlowResult:
145  """Handle a reconfiguration flow initialized by the user."""
146  entry = self._get_reconfigure_entry_get_reconfigure_entry()
147  errors = {}
148 
149  if user_input is not None:
150  try:
151  await validate_input(self.hass, user_input, entry.unique_id)
152  except InvalidHost:
153  errors[CONF_HOST] = "wrong_host"
154  except (ConnectionError, TimeoutError):
155  errors["base"] = "cannot_connect"
156  except SnmpError:
157  errors["base"] = "snmp_error"
158  except AnotherDevice:
159  errors["base"] = "another_device"
160  else:
161  return self.async_update_reload_and_abortasync_update_reload_and_abort(
162  entry,
163  data_updates={CONF_HOST: user_input[CONF_HOST]},
164  )
165 
166  return self.async_show_formasync_show_formasync_show_form(
167  step_id="reconfigure",
168  data_schema=self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
169  data_schema=RECONFIGURE_SCHEMA,
170  suggested_values=entry.data | (user_input or {}),
171  ),
172  description_placeholders={"printer_name": entry.title},
173  errors=errors,
174  )
175 
176 
178  """Error to indicate that hostname/IP address is invalid."""
179 
180 
181 class AnotherDevice(HomeAssistantError):
182  """Error to indicate that hostname/IP address belongs to another device."""
ConfigFlowResult async_step_zeroconf_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:123
ConfigFlowResult async_step_zeroconf(self, zeroconf.ZeroconfServiceInfo discovery_info)
Definition: config_flow.py:87
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:59
ConfigFlowResult async_step_reconfigure(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:144
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)
ConfigFlowResult async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
None _async_abort_entries_match(self, dict[str, Any]|None match_dict=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)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
tuple[str, str] validate_input(HomeAssistant hass, dict[str, Any] user_input, str|None expected_mac=None)
Definition: config_flow.py:31
IssData update(pyiss.ISS iss)
Definition: __init__.py:33
SnmpEngine async_get_snmp_engine(HomeAssistant hass)
Definition: util.py:76
bool is_host_valid(str host)
Definition: network.py:93