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