Track entity sources (#37258)

Co-authored-by: David Mulcahey <david.mulcahey@me.com>
This commit is contained in:
Paulus SchoutsenandDavid Mulcahey authored and GitHub committed 2020-08-19 14:57:38 +02:00
1 parent 24a16ff8fe
commit 3dc79aa60a
15 files changed
+379 -154

No files matched your search

+75 -2
View File
@@ -25,15 +25,26 @@ from homeassistant.const import (
TEMP_FAHRENHEIT,
)
from homeassistant.core import CALLBACK_TYPE, Context, HomeAssistant, callback
from homeassistant.exceptions import NoEntitySpecifiedError
from homeassistant.exceptions import HomeAssistantError, NoEntitySpecifiedError
from homeassistant.helpers.entity_platform import EntityPlatform
from homeassistant.helpers.entity_registry import RegistryEntry
from homeassistant.helpers.event import Event, async_track_entity_registry_updated_event
from homeassistant.helpers.typing import StateType
from homeassistant.loader import bind_hass
from homeassistant.util import dt as dt_util, ensure_unique_string, slugify
_LOGGER = logging.getLogger(__name__)
SLOW_UPDATE_WARNING = 10
DATA_ENTITY_SOURCE = "entity_info"
SOURCE_CONFIG_ENTRY = "config_entry"
SOURCE_PLATFORM_CONFIG = "platform_config"
@callback
@bind_hass
def entity_sources(hass: HomeAssistant) -> Dict[str, Dict[str, str]]:
"""Get the entity sources."""
return hass.data.get(DATA_ENTITY_SOURCE, {})
def generate_entity_id(
@@ -109,6 +120,9 @@ class Entity(ABC):
_context: Optional[Context] = None
_context_set: Optional[datetime] = None
# If entity is added to an entity platform
_added = False
@property
def should_poll(self) -> bool:
"""Return True if entity has to be polled for state.
@@ -477,10 +491,49 @@ class Entity(ABC):
To be extended by integrations.
"""
@callback
def add_to_platform_start(
self,
hass: HomeAssistant,
platform: EntityPlatform,
parallel_updates: Optional[asyncio.Semaphore],
) -> None:
"""Start adding an entity to a platform."""
if self._added:
raise HomeAssistantError(
f"Entity {self.entity_id} cannot be added a second time to an entity platform"
)
self.hass = hass
self.platform = platform
self.parallel_updates = parallel_updates
self._added = True
@callback
def add_to_platform_abort(self) -> None:
"""Abort adding an entity to a platform."""
self.hass = None
self.platform = None
self.parallel_updates = None
self._added = False
async def add_to_platform_finish(self) -> None:
"""Finish adding an entity to a platform."""
await self.async_internal_added_to_hass()
await self.async_added_to_hass()
self.async_write_ha_state()
async def async_remove(self) -> None:
"""Remove entity from Home Assistant."""
assert self.hass is not None
if self.platform and not self._added:
raise HomeAssistantError(
f"Entity {self.entity_id} async_remove called twice"
)
self._added = False
if self._on_remove is not None:
while self._on_remove:
self._on_remove.pop()()
@@ -507,8 +560,25 @@ class Entity(ABC):
Not to be extended by integrations.
"""
assert self.hass is not None
if self.platform:
info = {"domain": self.platform.platform_name}
if self.platform.config_entry:
info["source"] = SOURCE_CONFIG_ENTRY
info["config_entry"] = self.platform.config_entry.entry_id
else:
info["source"] = SOURCE_PLATFORM_CONFIG
self.hass.data.setdefault(DATA_ENTITY_SOURCE, {})[self.entity_id] = info
if self.registry_entry is not None:
assert self.hass is not None
# This is an assert as it should never happen, but helps in tests
assert (
not self.registry_entry.disabled_by
), f"Entity {self.entity_id} is being added while it's disabled"
self.async_on_remove(
async_track_entity_registry_updated_event(
self.hass, self.entity_id, self._async_registry_updated
@@ -520,6 +590,9 @@ class Entity(ABC):
Not to be extended by integrations.
"""
if self.platform:
assert self.hass is not None
self.hass.data[DATA_ENTITY_SOURCE].pop(self.entity_id)
async def _async_registry_updated(self, event: Event) -> None:
"""Handle entity registry update."""
+12 -19
View File
@@ -6,7 +6,7 @@ from logging import Logger
from types import ModuleType
from typing import TYPE_CHECKING, Callable, Coroutine, Dict, Iterable, List, Optional
from homeassistant.config_entries import ConfigEntry
from homeassistant import config_entries
from homeassistant.const import DEVICE_DEFAULT_NAME
from homeassistant.core import (
CALLBACK_TYPE,
@@ -60,7 +60,7 @@ class EntityPlatform:
self.platform = platform
self.scan_interval = scan_interval
self.entity_namespace = entity_namespace
self.config_entry: Optional[ConfigEntry] = None
self.config_entry: Optional[config_entries.ConfigEntry] = None
self.entities: Dict[str, Entity] = {} # pylint: disable=used-before-assignment
self._tasks: List[asyncio.Future] = []
# Method to cancel the state change listener
@@ -149,7 +149,7 @@ class EntityPlatform:
await self._async_setup_platform(async_create_setup_task)
async def async_setup_entry(self, config_entry: ConfigEntry) -> bool:
async def async_setup_entry(self, config_entry: config_entries.ConfigEntry) -> bool:
"""Set up the platform from a config entry."""
# Store it so that we can save config entry ID in entity registry
self.config_entry = config_entry
@@ -332,10 +332,10 @@ class EntityPlatform:
if entity is None:
raise ValueError("Entity cannot be None")
entity.hass = self.hass
entity.platform = self
entity.parallel_updates = self._get_parallel_updates_semaphore(
hasattr(entity, "async_update")
entity.add_to_platform_start(
self.hass,
self,
self._get_parallel_updates_semaphore(hasattr(entity, "async_update")),
)
# Update properties before we generate the entity_id
@@ -344,8 +344,7 @@ class EntityPlatform:
await entity.async_device_update(warning=False)
except Exception: # pylint: disable=broad-except
self.logger.exception("%s: Error on device update!", self.platform_name)
entity.hass = None
entity.platform = None
entity.add_to_platform_abort()
return
requested_entity_id = None
@@ -423,8 +422,7 @@ class EntityPlatform:
or entity.name
or f'"{self.platform_name} {entity.unique_id}"',
)
entity.hass = None
entity.platform = None
entity.add_to_platform_abort()
return
# We won't generate an entity ID if the platform has already set one
@@ -450,8 +448,7 @@ class EntityPlatform:
# Make sure it is valid in case an entity set the value themselves
if not valid_entity_id(entity.entity_id):
entity.hass = None
entity.platform = None
entity.add_to_platform_abort()
raise HomeAssistantError(f"Invalid entity id: {entity.entity_id}")
already_exists = entity.entity_id in self.entities
@@ -472,18 +469,14 @@ class EntityPlatform:
else:
msg = f"Entity id already exists - ignoring: {entity.entity_id}"
self.logger.error(msg)
entity.hass = None
entity.platform = None
entity.add_to_platform_abort()
return
entity_id = entity.entity_id
self.entities[entity_id] = entity
entity.async_on_remove(lambda: self.entities.pop(entity_id))
await entity.async_internal_added_to_hass()
await entity.async_added_to_hass()
entity.async_write_ha_state()
await entity.add_to_platform_finish()
async def async_reset(self) -> None:
"""Remove all entities and reset data.