Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Adds config flow for Time & Date integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from datetime import timedelta
7 import logging
8 from typing import Any
9 
10 import voluptuous as vol
11 
12 from homeassistant.components import websocket_api
13 from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
14 from homeassistant.core import HomeAssistant, callback
15 from homeassistant.helpers.entity_platform import EntityPlatform
17  SchemaCommonFlowHandler,
18  SchemaConfigFlowHandler,
19  SchemaFlowError,
20  SchemaFlowFormStep,
21 )
23  SelectSelector,
24  SelectSelectorConfig,
25  SelectSelectorMode,
26 )
27 from homeassistant.setup import async_prepare_setup_platform
28 
29 from .const import CONF_DISPLAY_OPTIONS, DOMAIN, OPTION_TYPES
30 from .sensor import TimeDateSensor
31 
32 _LOGGER = logging.getLogger(__name__)
33 
34 USER_SCHEMA = vol.Schema(
35  {
36  vol.Required(CONF_DISPLAY_OPTIONS): SelectSelector(
38  options=OPTION_TYPES,
39  mode=SelectSelectorMode.DROPDOWN,
40  translation_key="display_options",
41  )
42  ),
43  }
44 )
45 
46 
47 async def validate_input(
48  handler: SchemaCommonFlowHandler, user_input: dict[str, Any]
49 ) -> dict[str, Any]:
50  """Validate rest setup."""
51  hass = handler.parent_handler.hass
52  if hass.config.time_zone is None:
53  raise SchemaFlowError("timezone_not_exist")
54  return user_input
55 
56 
57 CONFIG_FLOW = {
58  "user": SchemaFlowFormStep(
59  schema=USER_SCHEMA,
60  preview=DOMAIN,
61  validate_user_input=validate_input,
62  )
63 }
64 
65 
67  """Handle a config flow for Time & Date."""
68 
69  config_flow = CONFIG_FLOW
70 
71  def async_config_entry_title(self, options: Mapping[str, Any]) -> str:
72  """Return config entry title."""
73  return f"Time & Date {options[CONF_DISPLAY_OPTIONS]}"
74 
75  def async_config_flow_finished(self, options: Mapping[str, Any]) -> None:
76  """Abort if instance already exist."""
77  self._async_abort_entries_match_async_abort_entries_match(dict(options))
78 
79  @staticmethod
80  async def async_setup_preview(hass: HomeAssistant) -> None:
81  """Set up preview WS API."""
82  websocket_api.async_register_command(hass, ws_start_preview)
83 
84 
85 @websocket_api.websocket_command( { vol.Required("type"): "time_date/start_preview",
86  vol.Required("flow_id"): str,
87  vol.Required("flow_type"): vol.Any("config_flow"),
88  vol.Required("user_input"): dict,
89  }
90 )
91 @websocket_api.async_response
92 async def ws_start_preview(
93  hass: HomeAssistant,
95  msg: dict[str, Any],
96 ) -> None:
97  """Generate a preview."""
98  validated = USER_SCHEMA(msg["user_input"])
99 
100  # Create an EntityPlatform, needed for name translations
101  platform = await async_prepare_setup_platform(hass, {}, SENSOR_DOMAIN, DOMAIN)
102  entity_platform = EntityPlatform(
103  hass=hass,
104  logger=_LOGGER,
105  domain=SENSOR_DOMAIN,
106  platform_name=DOMAIN,
107  platform=platform,
108  scan_interval=timedelta(seconds=3600),
109  entity_namespace=None,
110  )
111  await entity_platform.async_load_translations()
112 
113  @callback
114  def async_preview_updated(state: str, attributes: Mapping[str, Any]) -> None:
115  """Forward config entry state events to websocket."""
116  connection.send_message(
117  websocket_api.event_message(
118  msg["id"], {"attributes": attributes, "state": state}
119  )
120  )
121 
122  preview_entity = TimeDateSensor(validated[CONF_DISPLAY_OPTIONS])
123  preview_entity.hass = hass
124  preview_entity.platform = entity_platform
125 
126  connection.send_result(msg["id"])
127  connection.subscriptions[msg["id"]] = preview_entity.async_start_preview(
128  async_preview_updated
129  )
130 
None _async_abort_entries_match(self, dict[str, Any]|None match_dict=None)
None ws_start_preview(HomeAssistant hass, websocket_api.ActiveConnection connection, dict[str, Any] msg)
Definition: config_flow.py:98
dict[str, Any] validate_input(SchemaCommonFlowHandler handler, dict[str, Any] user_input)
Definition: config_flow.py:49
ModuleType|None async_prepare_setup_platform(core.HomeAssistant hass, ConfigType hass_config, str domain, str platform_name)
Definition: setup.py:487