Home Assistant Unofficial Reference 2024.12.1
util.py
Go to the documentation of this file.
1 """Define RainMachine utilities."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Iterable
6 from dataclasses import dataclass
7 from enum import StrEnum
8 from typing import Any
9 
10 from homeassistant.config_entries import ConfigEntry
11 from homeassistant.core import HomeAssistant, callback
12 from homeassistant.helpers import entity_registry as er
13 
14 from .const import LOGGER
15 
16 
17 class RunStates(StrEnum):
18  """Define an enum for program/zone run states."""
19 
20  NOT_RUNNING = "Not Running"
21  QUEUED = "Queued"
22  RUNNING = "Running"
23 
24 
25 RUN_STATE_MAP = {
26  0: RunStates.NOT_RUNNING,
27  1: RunStates.RUNNING,
28  2: RunStates.QUEUED,
29 }
30 
31 
32 @dataclass
34  """Define an entity replacement."""
35 
36  old_domain: str
37  old_unique_id: str
38  replacement_entity_id: str
39  breaks_in_ha_version: str
40  remove_old_entity: bool = True
41 
42 
43 @callback
45  hass: HomeAssistant,
46  entry: ConfigEntry,
47  entity_replacement_strategies: Iterable[EntityDomainReplacementStrategy],
48 ) -> None:
49  """Remove old entities and create a repairs issue with info on their replacement."""
50  ent_reg = er.async_get(hass)
51  for strategy in entity_replacement_strategies:
52  try:
53  [registry_entry] = [
54  registry_entry
55  for registry_entry in ent_reg.entities.get_entries_for_config_entry_id(
56  entry.entry_id
57  )
58  if registry_entry.domain == strategy.old_domain
59  and registry_entry.unique_id == strategy.old_unique_id
60  ]
61  except ValueError:
62  continue
63 
64  old_entity_id = registry_entry.entity_id
65  if strategy.remove_old_entity:
66  LOGGER.debug('Removing old entity: "%s"', old_entity_id)
67  ent_reg.async_remove(old_entity_id)
68 
69 
70 def key_exists(data: dict[str, Any], search_key: str) -> bool:
71  """Return whether a key exists in a nested dict."""
72  for key, value in data.items():
73  if key == search_key:
74  return True
75  if isinstance(value, dict):
76  return key_exists(value, search_key)
77  return False
bool key_exists(dict[str, Any] data, str search_key)
Definition: util.py:70
None async_finish_entity_domain_replacements(HomeAssistant hass, ConfigEntry entry, Iterable[EntityDomainReplacementStrategy] entity_replacement_strategies)
Definition: util.py:48