Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for La Marzocco integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import Any
8 
9 from httpx import AsyncClient
10 from pylamarzocco.client_cloud import LaMarzoccoCloudClient
11 from pylamarzocco.client_local import LaMarzoccoLocalClient
12 from pylamarzocco.exceptions import AuthFail, RequestNotSuccessful
13 from pylamarzocco.models import LaMarzoccoDeviceInfo
14 import voluptuous as vol
15 
17  BluetoothServiceInfo,
18  async_discovered_service_info,
19 )
20 from homeassistant.components.dhcp import DhcpServiceInfo
21 from homeassistant.config_entries import (
22  SOURCE_REAUTH,
23  SOURCE_RECONFIGURE,
24  ConfigEntry,
25  ConfigFlow,
26  ConfigFlowResult,
27  OptionsFlow,
28 )
29 from homeassistant.const import (
30  CONF_ADDRESS,
31  CONF_HOST,
32  CONF_MAC,
33  CONF_MODEL,
34  CONF_NAME,
35  CONF_PASSWORD,
36  CONF_TOKEN,
37  CONF_USERNAME,
38 )
39 from homeassistant.core import callback
40 from homeassistant.helpers import config_validation as cv
41 from homeassistant.helpers.httpx_client import create_async_httpx_client
43  SelectOptionDict,
44  SelectSelector,
45  SelectSelectorConfig,
46  SelectSelectorMode,
47 )
48 
49 from .const import CONF_USE_BLUETOOTH, DOMAIN
50 
51 CONF_MACHINE = "machine"
52 
53 _LOGGER = logging.getLogger(__name__)
54 
55 
56 class LmConfigFlow(ConfigFlow, domain=DOMAIN):
57  """Handle a config flow for La Marzocco."""
58 
59  VERSION = 2
60 
61  _client: AsyncClient
62 
63  def __init__(self) -> None:
64  """Initialize the config flow."""
65  self._config_config: dict[str, Any] = {}
66  self._fleet_fleet: dict[str, LaMarzoccoDeviceInfo] = {}
67  self._discovered: dict[str, str] = {}
68 
69  async def async_step_user(
70  self, user_input: dict[str, Any] | None = None
71  ) -> ConfigFlowResult:
72  """Handle the initial step."""
73 
74  errors = {}
75 
76  if user_input:
77  data: dict[str, Any] = {}
78  if self.sourcesourcesourcesource == SOURCE_REAUTH:
79  data = dict(self._get_reauth_entry_get_reauth_entry().data)
80  data = {
81  **data,
82  **user_input,
83  **self._discovered,
84  }
85  self._client_client = create_async_httpx_client(self.hass)
86 
87  cloud_client = LaMarzoccoCloudClient(
88  username=data[CONF_USERNAME],
89  password=data[CONF_PASSWORD],
90  client=self._client_client,
91  )
92  try:
93  self._fleet_fleet = await cloud_client.get_customer_fleet()
94  except AuthFail:
95  _LOGGER.debug("Server rejected login credentials")
96  errors["base"] = "invalid_auth"
97  except RequestNotSuccessful as exc:
98  _LOGGER.error("Error connecting to server: %s", exc)
99  errors["base"] = "cannot_connect"
100  else:
101  if not self._fleet_fleet:
102  errors["base"] = "no_machines"
103 
104  if not errors:
105  if self.sourcesourcesourcesource == SOURCE_REAUTH:
106  return self.async_update_reload_and_abortasync_update_reload_and_abort(
107  self._get_reauth_entry_get_reauth_entry(), data=data
108  )
109  if self._discovered:
110  if self._discovered[CONF_MACHINE] not in self._fleet_fleet:
111  errors["base"] = "machine_not_found"
112  else:
113  self._config_config = data
114  # if DHCP discovery was used, auto fill machine selection
115  if CONF_HOST in self._discovered:
116  return await self.async_step_machine_selectionasync_step_machine_selection(
117  user_input={
118  CONF_HOST: self._discovered[CONF_HOST],
119  CONF_MACHINE: self._discovered[CONF_MACHINE],
120  }
121  )
122  # if Bluetooth discovery was used, only select host
123  return self.async_show_formasync_show_formasync_show_form(
124  step_id="machine_selection",
125  data_schema=vol.Schema(
126  {vol.Optional(CONF_HOST): cv.string}
127  ),
128  )
129 
130  if not errors:
131  self._config_config = data
132  return await self.async_step_machine_selectionasync_step_machine_selection()
133 
134  placeholders: dict[str, str] | None = None
135  if self._discovered:
136  self.context["title_placeholders"] = placeholders = {
137  CONF_NAME: self._discovered[CONF_MACHINE]
138  }
139 
140  return self.async_show_formasync_show_formasync_show_form(
141  step_id="user",
142  data_schema=vol.Schema(
143  {
144  vol.Required(CONF_USERNAME): str,
145  vol.Required(CONF_PASSWORD): str,
146  }
147  ),
148  errors=errors,
149  description_placeholders=placeholders,
150  )
151 
153  self, user_input: dict[str, Any] | None = None
154  ) -> ConfigFlowResult:
155  """Let user select machine to connect to."""
156  errors: dict[str, str] = {}
157  if user_input:
158  if not self._discovered:
159  serial_number = user_input[CONF_MACHINE]
160  if self.sourcesourcesourcesource != SOURCE_RECONFIGURE:
161  await self.async_set_unique_idasync_set_unique_id(serial_number)
162  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
163  else:
164  serial_number = self._discovered[CONF_MACHINE]
165 
166  selected_device = self._fleet_fleet[serial_number]
167 
168  # validate local connection if host is provided
169  if user_input.get(CONF_HOST):
170  if not await LaMarzoccoLocalClient.validate_connection(
171  client=self._client_client,
172  host=user_input[CONF_HOST],
173  token=selected_device.communication_key,
174  ):
175  errors[CONF_HOST] = "cannot_connect"
176  else:
177  self._config_config[CONF_HOST] = user_input[CONF_HOST]
178 
179  if not errors:
180  if self.sourcesourcesourcesource == SOURCE_RECONFIGURE:
181  for service_info in async_discovered_service_info(self.hass):
182  self._discovered[service_info.name] = service_info.address
183 
184  if self._discovered:
185  return await self.async_step_bluetooth_selectionasync_step_bluetooth_selection()
186 
187  return self.async_create_entryasync_create_entryasync_create_entry(
188  title=selected_device.name,
189  data={
190  **self._config_config,
191  CONF_NAME: selected_device.name,
192  CONF_MODEL: selected_device.model,
193  CONF_TOKEN: selected_device.communication_key,
194  },
195  )
196 
197  machine_options = [
199  value=device.serial_number,
200  label=f"{device.model} ({device.serial_number})",
201  )
202  for device in self._fleet_fleet.values()
203  ]
204 
205  machine_selection_schema = vol.Schema(
206  {
207  vol.Required(
208  CONF_MACHINE, default=machine_options[0]["value"]
209  ): SelectSelector(
211  options=machine_options,
212  mode=SelectSelectorMode.DROPDOWN,
213  )
214  ),
215  vol.Optional(CONF_HOST): cv.string,
216  }
217  )
218 
219  return self.async_show_formasync_show_formasync_show_form(
220  step_id="machine_selection",
221  data_schema=machine_selection_schema,
222  errors=errors,
223  )
224 
226  self, user_input: dict[str, Any] | None = None
227  ) -> ConfigFlowResult:
228  """Handle Bluetooth device selection."""
229 
230  if user_input is not None:
231  return self.async_update_reload_and_abortasync_update_reload_and_abort(
232  self._get_reconfigure_entry_get_reconfigure_entry(),
233  data={
234  **self._config_config,
235  CONF_MAC: user_input[CONF_MAC],
236  },
237  )
238 
239  bt_options = [
241  value=device_mac,
242  label=f"{device_name} ({device_mac})",
243  )
244  for device_name, device_mac in self._discovered.items()
245  ]
246 
247  return self.async_show_formasync_show_formasync_show_form(
248  step_id="bluetooth_selection",
249  data_schema=vol.Schema(
250  {
251  vol.Required(CONF_MAC): SelectSelector(
253  options=bt_options,
254  mode=SelectSelectorMode.DROPDOWN,
255  )
256  ),
257  },
258  ),
259  )
260 
262  self, discovery_info: BluetoothServiceInfo
263  ) -> ConfigFlowResult:
264  """Handle a flow initialized by discovery over Bluetooth."""
265  address = discovery_info.address
266  name = discovery_info.name
267 
268  _LOGGER.debug(
269  "Discovered La Marzocco machine %s through Bluetooth at address %s",
270  name,
271  address,
272  )
273 
274  self._discovered[CONF_NAME] = name
275  self._discovered[CONF_MAC] = address
276 
277  serial = name.split("_")[1]
278  self._discovered[CONF_MACHINE] = serial
279 
280  await self.async_set_unique_idasync_set_unique_id(serial)
281  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
282 
283  return await self.async_step_userasync_step_userasync_step_user()
284 
285  async def async_step_dhcp(
286  self, discovery_info: DhcpServiceInfo
287  ) -> ConfigFlowResult:
288  """Handle discovery via dhcp."""
289 
290  serial = discovery_info.hostname.upper()
291 
292  await self.async_set_unique_idasync_set_unique_id(serial)
293  self._abort_if_unique_id_configured_abort_if_unique_id_configured(
294  updates={
295  CONF_HOST: discovery_info.ip,
296  CONF_ADDRESS: discovery_info.macaddress,
297  }
298  )
299  self._async_abort_entries_match_async_abort_entries_match({CONF_ADDRESS: discovery_info.macaddress})
300 
301  _LOGGER.debug(
302  "Discovered La Marzocco machine %s through DHCP at address %s",
303  discovery_info.hostname,
304  discovery_info.ip,
305  )
306 
307  self._discovered[CONF_MACHINE] = serial
308  self._discovered[CONF_HOST] = discovery_info.ip
309  self._discovered[CONF_ADDRESS] = discovery_info.macaddress
310 
311  return await self.async_step_userasync_step_userasync_step_user()
312 
313  async def async_step_reauth(
314  self, entry_data: Mapping[str, Any]
315  ) -> ConfigFlowResult:
316  """Perform reauth upon an API authentication error."""
317  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
318 
320  self, user_input: dict[str, Any] | None = None
321  ) -> ConfigFlowResult:
322  """Dialog that informs the user that reauth is required."""
323  if not user_input:
324  return self.async_show_formasync_show_formasync_show_form(
325  step_id="reauth_confirm",
326  data_schema=vol.Schema(
327  {
328  vol.Required(CONF_PASSWORD): str,
329  }
330  ),
331  )
332 
333  return await self.async_step_userasync_step_userasync_step_user(user_input)
334 
336  self, user_input: dict[str, Any] | None = None
337  ) -> ConfigFlowResult:
338  """Perform reconfiguration of the config entry."""
339  if not user_input:
340  reconfigure_entry = self._get_reconfigure_entry_get_reconfigure_entry()
341  return self.async_show_formasync_show_formasync_show_form(
342  step_id="reconfigure",
343  data_schema=vol.Schema(
344  {
345  vol.Required(
346  CONF_USERNAME,
347  default=reconfigure_entry.data[CONF_USERNAME],
348  ): str,
349  vol.Required(
350  CONF_PASSWORD,
351  default=reconfigure_entry.data[CONF_PASSWORD],
352  ): str,
353  }
354  ),
355  )
356 
357  return await self.async_step_userasync_step_userasync_step_user(user_input)
358 
359  @staticmethod
360  @callback
362  config_entry: ConfigEntry,
363  ) -> LmOptionsFlowHandler:
364  """Create the options flow."""
365  return LmOptionsFlowHandler()
366 
367 
369  """Handles options flow for the component."""
370 
371  async def async_step_init(
372  self, user_input: dict[str, Any] | None = None
373  ) -> ConfigFlowResult:
374  """Manage the options for the custom component."""
375  if user_input:
376  return self.async_create_entryasync_create_entry(title="", data=user_input)
377 
378  options_schema = vol.Schema(
379  {
380  vol.Optional(
381  CONF_USE_BLUETOOTH,
382  default=self.config_entryconfig_entryconfig_entry.options.get(CONF_USE_BLUETOOTH, True),
383  ): cv.boolean,
384  }
385  )
386 
387  return self.async_show_formasync_show_form(
388  step_id="init",
389  data_schema=options_schema,
390  )
ConfigFlowResult async_step_dhcp(self, DhcpServiceInfo discovery_info)
Definition: config_flow.py:287
LmOptionsFlowHandler async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:363
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:315
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:321
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:71
ConfigFlowResult async_step_machine_selection(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:154
ConfigFlowResult async_step_bluetooth_selection(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:227
ConfigFlowResult async_step_bluetooth(self, BluetoothServiceInfo discovery_info)
Definition: config_flow.py:263
ConfigFlowResult async_step_reconfigure(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:337
ConfigFlowResult async_step_init(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:373
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_step_user(self, dict[str, Any]|None user_input=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)
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)
str|None source(self)
Iterable[BluetoothServiceInfoBleak] async_discovered_service_info(HomeAssistant hass, bool connectable=True)
Definition: api.py:72
httpx.AsyncClient create_async_httpx_client(HomeAssistant hass, bool verify_ssl=True, bool auto_cleanup=True, SSLCipherList ssl_cipher_list=SSLCipherList.PYTHON_DEFAULT, **Any kwargs)
Definition: httpx_client.py:72