Home Assistant Unofficial Reference 2024.12.1
scene.py
Go to the documentation of this file.
1 """Provide configuration end points for Scenes."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 import uuid
7 
9  DOMAIN as SCENE_DOMAIN,
10  PLATFORM_SCHEMA as SCENE_PLATFORM_SCHEMA,
11 )
12 from homeassistant.config import SCENE_CONFIG_PATH
13 from homeassistant.const import CONF_ID, SERVICE_RELOAD
14 from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant, callback
15 from homeassistant.helpers import config_validation as cv, entity_registry as er
16 
17 from .const import ACTION_DELETE
18 from .view import EditIdBasedConfigView
19 
20 PLATFORM_SCHEMA = SCENE_PLATFORM_SCHEMA
21 
22 
23 @callback
24 def async_setup(hass: HomeAssistant) -> bool:
25  """Set up the Scene config API."""
26 
27  async def hook(action: str, config_key: str) -> None:
28  """post_write_hook for Config View that reloads scenes."""
29  if action != ACTION_DELETE:
30  await hass.services.async_call(SCENE_DOMAIN, SERVICE_RELOAD)
31  return
32 
33  ent_reg = er.async_get(hass)
34 
35  entity_id = ent_reg.async_get_entity_id(
36  SCENE_DOMAIN, HOMEASSISTANT_DOMAIN, config_key
37  )
38 
39  if entity_id is None:
40  return
41 
42  ent_reg.async_remove(entity_id)
43 
44  hass.http.register_view(
46  SCENE_DOMAIN,
47  "config",
48  SCENE_CONFIG_PATH,
49  cv.string,
50  data_schema=PLATFORM_SCHEMA,
51  post_write_hook=hook,
52  )
53  )
54  return True
55 
56 
58  """Edit scene config."""
59 
61  self,
62  hass: HomeAssistant,
63  data: list[dict[str, Any]],
64  config_key: str,
65  new_value: dict[str, Any],
66  ) -> None:
67  """Set value."""
68  updated_value = {CONF_ID: config_key}
69  # Iterate through some keys that we want to have ordered in the output
70  for key in ("name", "entities"):
71  if key in new_value:
72  updated_value[key] = new_value[key]
73 
74  # We cover all current fields above, but just in case we start
75  # supporting more fields in the future.
76  updated_value.update(new_value)
77 
78  updated = False
79  for index, cur_value in enumerate(data):
80  # When people copy paste their scenes to the config file,
81  # they sometimes forget to add IDs. Fix it here.
82  if CONF_ID not in cur_value:
83  cur_value[CONF_ID] = uuid.uuid4().hex
84 
85  elif cur_value[CONF_ID] == config_key:
86  data[index] = updated_value
87  updated = True
88 
89  if not updated:
90  data.append(updated_value)
None _write_value(self, HomeAssistant hass, list[dict[str, Any]] data, str config_key, dict[str, Any] new_value)
Definition: scene.py:66
bool async_setup(HomeAssistant hass)
Definition: scene.py:24