Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for SMS integration."""
2 
3 import logging
4 from typing import Any
5 
6 import gammu
7 import voluptuous as vol
8 
9 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
10 from homeassistant.const import CONF_DEVICE
11 from homeassistant.core import HomeAssistant
12 from homeassistant.exceptions import HomeAssistantError
13 from homeassistant.helpers import selector
14 
15 from .const import CONF_BAUD_SPEED, DEFAULT_BAUD_SPEED, DEFAULT_BAUD_SPEEDS, DOMAIN
16 from .gateway import create_sms_gateway
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 DATA_SCHEMA = vol.Schema(
21  {
22  vol.Required(CONF_DEVICE): str,
23  vol.Optional(CONF_BAUD_SPEED, default=DEFAULT_BAUD_SPEED): selector.selector(
24  {"select": {"options": DEFAULT_BAUD_SPEEDS}}
25  ),
26  }
27 )
28 
29 
30 async def get_imei_from_config(hass: HomeAssistant, data: dict[str, Any]) -> str:
31  """Validate the user input allows us to connect.
32 
33  Data has the keys from DATA_SCHEMA with values provided by the user.
34  """
35  device = data[CONF_DEVICE]
36  connection_mode = "at"
37  baud_speed = data.get(CONF_BAUD_SPEED, DEFAULT_BAUD_SPEED)
38  if baud_speed != DEFAULT_BAUD_SPEED:
39  connection_mode += baud_speed
40  config = {"Device": device, "Connection": connection_mode}
41  gateway = await create_sms_gateway(config, hass)
42  if not gateway:
43  raise CannotConnect
44  try:
45  imei = await gateway.get_imei_async()
46  except gammu.GSMError as err:
47  raise CannotConnect from err
48  finally:
49  await gateway.terminate_async()
50 
51  # Return info that you want to store in the config entry.
52  return imei
53 
54 
55 class SMSFlowHandler(ConfigFlow, domain=DOMAIN):
56  """Handle a config flow for SMS integration."""
57 
58  VERSION = 1
59 
60  async def async_step_user(
61  self, user_input: dict[str, Any] | None = None
62  ) -> ConfigFlowResult:
63  """Handle the initial step."""
64  if self._async_current_entries_async_current_entries():
65  return self.async_abortasync_abortasync_abort(reason="single_instance_allowed")
66  errors = {}
67  if user_input is not None:
68  try:
69  imei = await get_imei_from_config(self.hass, user_input)
70  except CannotConnect:
71  errors["base"] = "cannot_connect"
72  except Exception:
73  _LOGGER.exception("Unexpected exception")
74  errors["base"] = "unknown"
75 
76  if not errors:
77  await self.async_set_unique_idasync_set_unique_id(imei)
78  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
79  return self.async_create_entryasync_create_entryasync_create_entry(title=imei, 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 
85 
87  """Error to indicate we cannot connect."""
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:62
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)
list[ConfigEntry] _async_current_entries(self, bool|None include_ignore=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)
str get_imei_from_config(HomeAssistant hass, dict[str, Any] data)
Definition: config_flow.py:30
def create_sms_gateway(config, hass)
Definition: gateway.py:198