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