Import homeassistant trigger platforms in the executor (#113124)
This commit is contained in:
parent
3f72fae60b
commit
52b2522be2
1 changed files with 21 additions and 4 deletions
|
@ -11,16 +11,33 @@ from homeassistant.helpers.trigger import (
|
|||
)
|
||||
from homeassistant.helpers.typing import ConfigType
|
||||
|
||||
DATA_TRIGGER_PLATFORMS = "homeassistant_trigger_platforms"
|
||||
|
||||
def _get_trigger_platform(config: ConfigType) -> TriggerProtocol:
|
||||
return importlib.import_module(f"..triggers.{config[CONF_PLATFORM]}", __name__)
|
||||
|
||||
def _get_trigger_platform(platform_name: str) -> TriggerProtocol:
|
||||
"""Get trigger platform."""
|
||||
return importlib.import_module(f"..triggers.{platform_name}", __name__)
|
||||
|
||||
|
||||
async def _async_get_trigger_platform(
|
||||
hass: HomeAssistant, platform_name: str
|
||||
) -> TriggerProtocol:
|
||||
"""Get trigger platform from cache or import it."""
|
||||
cache: dict[str, TriggerProtocol] = hass.data.setdefault(DATA_TRIGGER_PLATFORMS, {})
|
||||
if platform := cache.get(platform_name):
|
||||
return platform
|
||||
platform = await hass.async_add_import_executor_job(
|
||||
_get_trigger_platform, platform_name
|
||||
)
|
||||
cache[platform_name] = platform
|
||||
return platform
|
||||
|
||||
|
||||
async def async_validate_trigger_config(
|
||||
hass: HomeAssistant, config: ConfigType
|
||||
) -> ConfigType:
|
||||
"""Validate config."""
|
||||
platform = _get_trigger_platform(config)
|
||||
platform = await _async_get_trigger_platform(hass, config[CONF_PLATFORM])
|
||||
if hasattr(platform, "async_validate_trigger_config"):
|
||||
return await platform.async_validate_trigger_config(hass, config)
|
||||
|
||||
|
@ -34,5 +51,5 @@ async def async_attach_trigger(
|
|||
trigger_info: TriggerInfo,
|
||||
) -> CALLBACK_TYPE:
|
||||
"""Attach trigger of specified platform."""
|
||||
platform = _get_trigger_platform(config)
|
||||
platform = await _async_get_trigger_platform(hass, config[CONF_PLATFORM])
|
||||
return await platform.async_attach_trigger(hass, config, action, trigger_info)
|
||||
|
|
Loading…
Add table
Reference in a new issue