This commit is contained in:
Paulus Schoutsen committed 2019-07-31 12:25:30 -07:00
1 parent da05dfe708
commit 4de97abc3a
2676 files changed
+163166 -140084

No files matched your search

+130 -98
View File
@@ -4,8 +4,7 @@ import asyncio
from homeassistant.const import DEVICE_DEFAULT_NAME
from homeassistant.core import callback, valid_entity_id, split_entity_id
from homeassistant.exceptions import HomeAssistantError, PlatformNotReady
from homeassistant.util.async_ import (
run_callback_threadsafe, run_coroutine_threadsafe)
from homeassistant.util.async_ import run_callback_threadsafe, run_coroutine_threadsafe
from .event import async_track_time_interval, async_call_later
@@ -20,9 +19,18 @@ PLATFORM_NOT_READY_RETRIES = 10
class EntityPlatform:
"""Manage the entities for a single platform."""
def __init__(self, *, hass, logger, domain, platform_name, platform,
scan_interval, entity_namespace,
async_entities_added_callback):
def __init__(
self,
*,
hass,
logger,
domain,
platform_name,
platform,
scan_interval,
entity_namespace,
async_entities_added_callback,
):
"""Initialize the entity platform.
hass: HomeAssistant
@@ -57,7 +65,7 @@ class EntityPlatform:
self.parallel_updates_semaphore = None
return
self.parallel_updates = getattr(platform, 'PARALLEL_UPDATES', None)
self.parallel_updates = getattr(platform, "PARALLEL_UPDATES", None)
# semaphore will be created on demand
self.parallel_updates_semaphore = None
@@ -66,7 +74,7 @@ class EntityPlatform:
if self.parallel_updates_semaphore is None:
self.parallel_updates_semaphore = asyncio.Semaphore(
self.parallel_updates if self.parallel_updates else 1,
loop=self.hass.loop
loop=self.hass.loop,
)
return self.parallel_updates_semaphore
@@ -78,18 +86,25 @@ class EntityPlatform:
@callback
def async_create_setup_task():
"""Get task to set up platform."""
if getattr(platform, 'async_setup_platform', None):
if getattr(platform, "async_setup_platform", None):
return platform.async_setup_platform(
hass, platform_config,
self._async_schedule_add_entities, discovery_info
hass,
platform_config,
self._async_schedule_add_entities,
discovery_info,
)
# This should not be replaced with hass.async_add_job because
# we don't want to track this task in case it blocks startup.
return hass.loop.run_in_executor(
None, platform.setup_platform, hass, platform_config,
self._schedule_add_entities, discovery_info
None,
platform.setup_platform,
hass,
platform_config,
self._schedule_add_entities,
discovery_info,
)
await self._async_setup_platform(async_create_setup_task)
async def async_setup_entry(self, config_entry):
@@ -102,7 +117,8 @@ class EntityPlatform:
def async_create_setup_task():
"""Get task to set up platform."""
return platform.async_setup_entry(
self.hass, config_entry, self._async_schedule_add_entities)
self.hass, config_entry, self._async_schedule_add_entities
)
return await self._async_setup_platform(async_create_setup_task)
@@ -113,20 +129,21 @@ class EntityPlatform:
"""
logger = self.logger
hass = self.hass
full_name = '{}.{}'.format(self.domain, self.platform_name)
full_name = "{}.{}".format(self.domain, self.platform_name)
logger.info("Setting up %s", full_name)
warn_task = hass.loop.call_later(
SLOW_SETUP_WARNING, logger.warning,
SLOW_SETUP_WARNING,
logger.warning,
"Setup of platform %s is taking over %s seconds.",
self.platform_name, SLOW_SETUP_WARNING)
self.platform_name,
SLOW_SETUP_WARNING,
)
try:
task = async_create_setup_task()
await asyncio.wait_for(
asyncio.shield(task),
SLOW_SETUP_MAX_WAIT)
await asyncio.wait_for(asyncio.shield(task), SLOW_SETUP_MAX_WAIT)
# Block till all entities are done
if self._tasks:
@@ -134,8 +151,7 @@ class EntityPlatform:
self._tasks.clear()
if pending:
await asyncio.wait(
pending)
await asyncio.wait(pending)
hass.config.components.add(full_name)
return True
@@ -143,27 +159,30 @@ class EntityPlatform:
tries += 1
wait_time = min(tries, 6) * 30
logger.warning(
'Platform %s not ready yet. Retrying in %d seconds.',
self.platform_name, wait_time)
"Platform %s not ready yet. Retrying in %d seconds.",
self.platform_name,
wait_time,
)
async def setup_again(now):
"""Run setup again."""
self._async_cancel_retry_setup = None
await self._async_setup_platform(
async_create_setup_task, tries)
await self._async_setup_platform(async_create_setup_task, tries)
self._async_cancel_retry_setup = \
async_call_later(hass, wait_time, setup_again)
self._async_cancel_retry_setup = async_call_later(
hass, wait_time, setup_again
)
return False
except asyncio.TimeoutError:
logger.error(
"Setup of platform %s is taking longer than %s seconds."
" Startup will proceed without waiting any longer.",
self.platform_name, SLOW_SETUP_MAX_WAIT)
self.platform_name,
SLOW_SETUP_MAX_WAIT,
)
return False
except Exception: # pylint: disable=broad-except
logger.exception(
"Error while setting up platform %s", self.platform_name)
logger.exception("Error while setting up platform %s", self.platform_name)
return False
finally:
warn_task.cancel()
@@ -172,18 +191,21 @@ class EntityPlatform:
"""Schedule adding entities for a single platform, synchronously."""
run_callback_threadsafe(
self.hass.loop,
self._async_schedule_add_entities, list(new_entities),
update_before_add
self._async_schedule_add_entities,
list(new_entities),
update_before_add,
).result()
@callback
def _async_schedule_add_entities(self, new_entities,
update_before_add=False):
def _async_schedule_add_entities(self, new_entities, update_before_add=False):
"""Schedule adding entities for a single platform async."""
self._tasks.append(self.hass.async_add_job(
self.async_add_entities(
new_entities, update_before_add=update_before_add)
))
self._tasks.append(
self.hass.async_add_job(
self.async_add_entities(
new_entities, update_before_add=update_before_add
)
)
)
def add_entities(self, new_entities, update_before_add=False):
"""Add entities for a single platform."""
@@ -191,11 +213,13 @@ class EntityPlatform:
if update_before_add:
self.logger.warning(
"Call 'add_entities' with update_before_add=True "
"only inside tests or you can run into a deadlock!")
"only inside tests or you can run into a deadlock!"
)
run_coroutine_threadsafe(
self.async_add_entities(list(new_entities), update_before_add),
self.hass.loop).result()
self.hass.loop,
).result()
async def async_add_entities(self, new_entities, update_before_add=False):
"""Add entities for a single platform async.
@@ -208,14 +232,14 @@ class EntityPlatform:
hass = self.hass
device_registry = await \
hass.helpers.device_registry.async_get_registry()
entity_registry = await \
hass.helpers.entity_registry.async_get_registry()
device_registry = await hass.helpers.device_registry.async_get_registry()
entity_registry = await hass.helpers.entity_registry.async_get_registry()
tasks = [
self._async_add_entity(entity, update_before_add,
entity_registry, device_registry)
for entity in new_entities]
self._async_add_entity(
entity, update_before_add, entity_registry, device_registry
)
for entity in new_entities
]
# No entities for processing
if not tasks:
@@ -224,20 +248,21 @@ class EntityPlatform:
await asyncio.wait(tasks)
self.async_entities_added_callback()
if self._async_unsub_polling is not None or \
not any(entity.should_poll for entity
in self.entities.values()):
if self._async_unsub_polling is not None or not any(
entity.should_poll for entity in self.entities.values()
):
return
self._async_unsub_polling = async_track_time_interval(
self.hass, self._update_entity_states, self.scan_interval
)
async def _async_add_entity(self, entity, update_before_add,
entity_registry, device_registry):
async def _async_add_entity(
self, entity, update_before_add, entity_registry, device_registry
):
"""Add an entity to the platform."""
if entity is None:
raise ValueError('Entity cannot be None')
raise ValueError("Entity cannot be None")
entity.hass = self.hass
entity.platform = self
@@ -250,10 +275,9 @@ class EntityPlatform:
# PARALLEL_UPDATE == None: entity.parallel_updates = Semaphore(1)
# PARALLEL_UPDATE == 0: entity.parallel_updates = None
# PARALLEL_UPDATE > 0: entity.parallel_updates = Semaphore(p)
if hasattr(entity, 'async_update') and not self.parallel_updates:
if hasattr(entity, "async_update") and not self.parallel_updates:
entity.parallel_updates = None
elif (not hasattr(entity, 'async_update')
and self.parallel_updates == 0):
elif not hasattr(entity, "async_update") and self.parallel_updates == 0:
entity.parallel_updates = None
else:
entity.parallel_updates = self._get_parallel_updates_semaphore()
@@ -263,8 +287,7 @@ class EntityPlatform:
try:
await entity.async_device_update(warning=False)
except Exception: # pylint: disable=broad-except
self.logger.exception(
"%s: Error on device update!", self.platform_name)
self.logger.exception("%s: Error on device update!", self.platform_name)
return
suggested_object_id = None
@@ -277,8 +300,9 @@ class EntityPlatform:
suggested_object_id = entity.name
if self.entity_namespace is not None:
suggested_object_id = '{} {}'.format(
self.entity_namespace, suggested_object_id)
suggested_object_id = "{} {}".format(
self.entity_namespace, suggested_object_id
)
if self.config_entry is not None:
config_entry_id = self.config_entry.entry_id
@@ -289,38 +313,40 @@ class EntityPlatform:
device_id = None
if config_entry_id is not None and device_info is not None:
processed_dev_info = {
'config_entry_id': config_entry_id
}
processed_dev_info = {"config_entry_id": config_entry_id}
for key in (
'connections',
'identifiers',
'manufacturer',
'model',
'name',
'sw_version',
'via_device',
"connections",
"identifiers",
"manufacturer",
"model",
"name",
"sw_version",
"via_device",
):
if key in device_info:
processed_dev_info[key] = device_info[key]
device = device_registry.async_get_or_create(
**processed_dev_info)
device = device_registry.async_get_or_create(**processed_dev_info)
if device:
device_id = device.id
entry = entity_registry.async_get_or_create(
self.domain, self.platform_name, entity.unique_id,
self.domain,
self.platform_name,
entity.unique_id,
suggested_object_id=suggested_object_id,
config_entry_id=config_entry_id,
device_id=device_id,
known_object_ids=self.entities.keys())
known_object_ids=self.entities.keys(),
)
if entry.disabled:
self.logger.info(
"Not adding entity %s because it's disabled",
entry.name or entity.name or
'"{} {}"'.format(self.platform_name, entity.unique_id))
entry.name
or entity.name
or '"{} {}"'.format(self.platform_name, entity.unique_id),
)
return
entity.registry_entry = entry
@@ -328,34 +354,39 @@ class EntityPlatform:
# We won't generate an entity ID if the platform has already set one
# We will however make sure that platform cannot pick a registered ID
elif (entity.entity_id is not None and
entity_registry.async_is_registered(entity.entity_id)):
elif entity.entity_id is not None and entity_registry.async_is_registered(
entity.entity_id
):
# If entity already registered, convert entity id to suggestion
suggested_object_id = split_entity_id(entity.entity_id)[1]
entity.entity_id = None
# Generate entity ID
if entity.entity_id is None:
suggested_object_id = \
suggested_object_id = (
suggested_object_id or entity.name or DEVICE_DEFAULT_NAME
)
if self.entity_namespace is not None:
suggested_object_id = '{} {}'.format(self.entity_namespace,
suggested_object_id)
suggested_object_id = "{} {}".format(
self.entity_namespace, suggested_object_id
)
entity.entity_id = entity_registry.async_generate_entity_id(
self.domain, suggested_object_id, self.entities.keys())
self.domain, suggested_object_id, self.entities.keys()
)
# Make sure it is valid in case an entity set the value themselves
if not valid_entity_id(entity.entity_id):
raise HomeAssistantError(
'Invalid entity id: {}'.format(entity.entity_id))
if (entity.entity_id in self.entities or
entity.entity_id in self.hass.states.async_entity_ids(
self.domain)):
msg = 'Entity id already exists: {}'.format(entity.entity_id)
raise HomeAssistantError("Invalid entity id: {}".format(entity.entity_id))
if (
entity.entity_id in self.entities
or entity.entity_id in self.hass.states.async_entity_ids(self.domain)
):
msg = "Entity id already exists: {}".format(entity.entity_id)
if entity.unique_id is not None:
msg += '. Platform {} does not generate unique IDs'.format(
self.platform_name)
msg += ". Platform {} does not generate unique IDs".format(
self.platform_name
)
raise HomeAssistantError(msg)
entity_id = entity.entity_id
@@ -379,8 +410,7 @@ class EntityPlatform:
if not self.entities:
return
tasks = [self.async_remove_entity(entity_id)
for entity_id in self.entities]
tasks = [self.async_remove_entity(entity_id) for entity_id in self.entities]
await asyncio.wait(tasks)
@@ -393,9 +423,9 @@ class EntityPlatform:
await self.entities[entity_id].async_remove()
# Clean up polling job if no longer needed
if (self._async_unsub_polling is not None and
not any(entity.should_poll for entity
in self.entities.values())):
if self._async_unsub_polling is not None and not any(
entity.should_poll for entity in self.entities.values()
):
self._async_unsub_polling()
self._async_unsub_polling = None
@@ -411,9 +441,11 @@ class EntityPlatform:
self._process_updates = asyncio.Lock()
if self._process_updates.locked():
self.logger.warning(
"Updating %s %s took longer than the scheduled update "
"interval %s", self.platform_name, self.domain,
self.scan_interval)
"Updating %s %s took longer than the scheduled update " "interval %s",
self.platform_name,
self.domain,
self.scan_interval,
)
return
async with self._process_updates: