2016-03-07 22:39:52 +00:00
|
|
|
"""Helper methods for components within Home Assistant."""
|
2021-03-17 17:34:19 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2021-04-20 15:40:41 +00:00
|
|
|
from collections.abc import Iterable, Sequence
|
2015-09-29 06:09:05 +00:00
|
|
|
import re
|
2021-04-20 15:40:41 +00:00
|
|
|
from typing import TYPE_CHECKING, Any
|
2016-07-28 03:33:49 +00:00
|
|
|
|
2016-01-24 07:00:46 +00:00
|
|
|
from homeassistant.const import CONF_PLATFORM
|
2015-01-19 08:02:25 +00:00
|
|
|
|
2020-07-06 22:58:53 +00:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
from .typing import ConfigType
|
2016-07-28 03:33:49 +00:00
|
|
|
|
2015-01-19 08:02:25 +00:00
|
|
|
|
2021-03-18 21:58:19 +00:00
|
|
|
def config_per_platform(config: ConfigType, domain: str) -> Iterable[tuple[Any, Any]]:
|
2017-05-02 16:18:47 +00:00
|
|
|
"""Break a component config into different platforms.
|
2016-03-07 22:39:52 +00:00
|
|
|
|
2014-12-07 07:57:02 +00:00
|
|
|
For example, will find 'switch', 'switch 2', 'switch 3', .. etc
|
2016-10-29 19:19:27 +00:00
|
|
|
Async friendly.
|
2014-12-07 07:57:02 +00:00
|
|
|
"""
|
2015-09-29 06:09:05 +00:00
|
|
|
for config_key in extract_domain_configs(config, domain):
|
2014-12-07 07:57:02 +00:00
|
|
|
platform_config = config[config_key]
|
2016-09-24 07:03:44 +00:00
|
|
|
|
|
|
|
if not platform_config:
|
|
|
|
continue
|
2019-09-24 20:53:03 +00:00
|
|
|
|
|
|
|
if not isinstance(platform_config, list):
|
2015-03-10 23:16:53 +00:00
|
|
|
platform_config = [platform_config]
|
2014-12-07 07:57:02 +00:00
|
|
|
|
2015-03-10 23:16:53 +00:00
|
|
|
for item in platform_config:
|
2016-06-11 05:53:31 +00:00
|
|
|
try:
|
|
|
|
platform = item.get(CONF_PLATFORM)
|
|
|
|
except AttributeError:
|
|
|
|
platform = None
|
|
|
|
|
2016-03-29 07:17:53 +00:00
|
|
|
yield platform, item
|
2015-09-29 06:09:05 +00:00
|
|
|
|
|
|
|
|
2021-03-18 21:58:19 +00:00
|
|
|
def extract_domain_configs(config: ConfigType, domain: str) -> Sequence[str]:
|
2016-10-29 19:19:27 +00:00
|
|
|
"""Extract keys from config for given domain name.
|
|
|
|
|
|
|
|
Async friendly.
|
|
|
|
"""
|
2020-01-03 13:47:06 +00:00
|
|
|
pattern = re.compile(fr"^{domain}(| .+)$")
|
2016-02-14 05:20:49 +00:00
|
|
|
return [key for key in config.keys() if pattern.match(key)]
|