Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for the Cert Expiry platform."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import Any
8 
9 import voluptuous as vol
10 
11 from homeassistant.config_entries import SOURCE_IMPORT, ConfigFlow, ConfigFlowResult
12 from homeassistant.const import CONF_HOST, CONF_PORT
13 
14 from .const import DEFAULT_PORT, DOMAIN
15 from .errors import (
16  ConnectionRefused,
17  ConnectionTimeout,
18  ResolveFailed,
19  ValidationFailure,
20 )
21 from .helper import get_cert_expiry_timestamp
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 
26 class CertexpiryConfigFlow(ConfigFlow, domain=DOMAIN):
27  """Handle a config flow."""
28 
29  VERSION = 1
30 
31  def __init__(self) -> None:
32  """Initialize the config flow."""
33  self._errors_errors: dict[str, str] = {}
34 
35  async def _test_connection(
36  self,
37  user_input: Mapping[str, Any],
38  ) -> bool:
39  """Test connection to the server and try to get the certificate."""
40  try:
42  self.hass,
43  user_input[CONF_HOST],
44  user_input.get(CONF_PORT, DEFAULT_PORT),
45  )
46  except ResolveFailed:
47  self._errors_errors[CONF_HOST] = "resolve_failed"
48  except ConnectionTimeout:
49  self._errors_errors[CONF_HOST] = "connection_timeout"
50  except ConnectionRefused:
51  self._errors_errors[CONF_HOST] = "connection_refused"
52  except ValidationFailure:
53  return True
54  else:
55  return True
56  return False
57 
58  async def async_step_user(
59  self,
60  user_input: Mapping[str, Any] | None = None,
61  ) -> ConfigFlowResult:
62  """Step when user initializes a integration."""
63  self._errors_errors = {}
64  if user_input is not None:
65  host = user_input[CONF_HOST]
66  port = user_input.get(CONF_PORT, DEFAULT_PORT)
67  await self.async_set_unique_idasync_set_unique_id(f"{host}:{port}")
68  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
69 
70  if await self._test_connection_test_connection(user_input):
71  title_port = f":{port}" if port != DEFAULT_PORT else ""
72  title = f"{host}{title_port}"
73  return self.async_create_entryasync_create_entryasync_create_entry(
74  title=title,
75  data={CONF_HOST: host, CONF_PORT: port},
76  )
77  if self.context["source"] == SOURCE_IMPORT:
78  _LOGGER.error("Config import failed for %s", user_input[CONF_HOST])
79  return self.async_abortasync_abortasync_abort(reason="import_failed")
80  else:
81  user_input = {}
82  user_input[CONF_HOST] = ""
83  user_input[CONF_PORT] = DEFAULT_PORT
84 
85  return self.async_show_formasync_show_formasync_show_form(
86  step_id="user",
87  data_schema=vol.Schema(
88  {
89  vol.Required(CONF_HOST, default=user_input[CONF_HOST]): str,
90  vol.Required(
91  CONF_PORT, default=user_input.get(CONF_PORT, DEFAULT_PORT)
92  ): int,
93  }
94  ),
95  errors=self._errors_errors,
96  )
97 
98  async def async_step_import(self, import_data: dict[str, Any]) -> ConfigFlowResult:
99  """Import a config entry.
100 
101  Only host was required in the yaml file all other fields are optional
102  """
103  return await self.async_step_userasync_step_userasync_step_user(import_data)
ConfigFlowResult async_step_user(self, Mapping[str, Any]|None user_input=None)
Definition: config_flow.py:61
bool _test_connection(self, Mapping[str, Any] user_input)
Definition: config_flow.py:38
ConfigFlowResult async_step_import(self, dict[str, Any] import_data)
Definition: config_flow.py:98
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_step_user(self, dict[str, Any]|None user_input=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)
datetime.datetime get_cert_expiry_timestamp(HomeAssistant hass, str hostname, int port)
Definition: helper.py:47