Home Assistant Unofficial Reference 2024.12.1
helpers.py
Go to the documentation of this file.
1 """Helpers for template integration."""
2 
3 import logging
4 
5 from homeassistant.components import blueprint
6 from homeassistant.const import SERVICE_RELOAD
7 from homeassistant.core import HomeAssistant, callback
8 from homeassistant.helpers.entity_platform import async_get_platforms
9 from homeassistant.helpers.singleton import singleton
10 
11 from .const import DOMAIN, TEMPLATE_BLUEPRINT_SCHEMA
12 from .template_entity import TemplateEntity
13 
14 DATA_BLUEPRINTS = "template_blueprints"
15 
16 LOGGER = logging.getLogger(__name__)
17 
18 
19 @callback
20 def templates_with_blueprint(hass: HomeAssistant, blueprint_path: str) -> list[str]:
21  """Return all template entity ids that reference the blueprint."""
22  return [
23  entity_id
24  for platform in async_get_platforms(hass, DOMAIN)
25  for entity_id, template_entity in platform.entities.items()
26  if isinstance(template_entity, TemplateEntity)
27  and template_entity.referenced_blueprint == blueprint_path
28  ]
29 
30 
31 @callback
32 def blueprint_in_template(hass: HomeAssistant, entity_id: str) -> str | None:
33  """Return the blueprint the template entity is based on or None."""
34  for platform in async_get_platforms(hass, DOMAIN):
35  if isinstance(
36  (template_entity := platform.entities.get(entity_id)), TemplateEntity
37  ):
38  return template_entity.referenced_blueprint
39  return None
40 
41 
42 def _blueprint_in_use(hass: HomeAssistant, blueprint_path: str) -> bool:
43  """Return True if any template references the blueprint."""
44  return len(templates_with_blueprint(hass, blueprint_path)) > 0
45 
46 
47 async def _reload_blueprint_templates(hass: HomeAssistant, blueprint_path: str) -> None:
48  """Reload all templates that rely on a specific blueprint."""
49  await hass.services.async_call(DOMAIN, SERVICE_RELOAD)
50 
51 
52 @singleton(DATA_BLUEPRINTS)
53 @callback
55  """Get template blueprints."""
57  hass,
58  DOMAIN,
59  LOGGER,
60  _blueprint_in_use,
61  _reload_blueprint_templates,
62  TEMPLATE_BLUEPRINT_SCHEMA,
63  )
blueprint.DomainBlueprints async_get_blueprints(HomeAssistant hass)
Definition: helpers.py:54
None _reload_blueprint_templates(HomeAssistant hass, str blueprint_path)
Definition: helpers.py:47
list[str] templates_with_blueprint(HomeAssistant hass, str blueprint_path)
Definition: helpers.py:20
bool _blueprint_in_use(HomeAssistant hass, str blueprint_path)
Definition: helpers.py:42
str|None blueprint_in_template(HomeAssistant hass, str entity_id)
Definition: helpers.py:32
list[EntityPlatform] async_get_platforms(HomeAssistant hass, str integration_name)