- config flow: template (A/B/F с пояснениями, значения с устройства, определение по oem_model; для неизвестных моделей — пробинг A/B/F тремя короткими сессиями) -> capabilities (23 тумблера с описаниями, дефолты из device_capabilities/num_dir/ответов) -> limits (диапазон/шаг, ручная конверсия); каждая страница с пометкой «значения определены автоматически, можно пропустить» - features.py: FeatureSet/LiveValues/device_default/resolve_features; entry.data["features"] хранит выбор пользователя; reconfigure предзаполняет; YAML-import получает дефолты - сущности создаются только для включённых фич: climate (режимы/скорости/ swing/пресеты), switch, select заслонок (caps+num_dir), датчик комнаты; исправлено появление select без ламелей - trial: caps/num_dir и presence-зонды (необязательные свойства), answered; координатор ждёт первые свойства перед созданием сущностей (feature- дефолты без гонки) - атрибут description у сущностей (HA не поддерживает тултипы) + описания фич в мастере (en/ru) - тесты: features, probing, обновлённые flow/entities/repairs; 57 components
122 lines
3.9 KiB
Python
122 lines
3.9 KiB
Python
"""FGLair (Fujitsu General) — локальное управление через LAN-протокол Ayla."""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
|
|
from homeassistant import config_entries
|
|
from homeassistant.config_entries import ConfigEntry
|
|
from homeassistant.const import Platform
|
|
from homeassistant.core import HomeAssistant
|
|
from homeassistant.helpers import issue_registry as ir
|
|
|
|
import pyfglair
|
|
|
|
from .const import CONF_DSN, CONF_FEATURES, DOMAIN
|
|
from .coordinator import FglairCoordinator, FglairRuntime, key_issue_id
|
|
from .features import FeatureSet, LiveValues
|
|
from .fglair_client import FglairClient
|
|
from .overrides import ConversionSet
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
PLATFORMS = [
|
|
Platform.CLIMATE,
|
|
Platform.SENSOR,
|
|
Platform.BINARY_SENSOR,
|
|
Platform.SWITCH,
|
|
Platform.SELECT,
|
|
]
|
|
|
|
_LOG_LEVELS = {
|
|
0: logging.DEBUG,
|
|
1: logging.INFO,
|
|
2: logging.WARNING,
|
|
3: logging.ERROR,
|
|
}
|
|
|
|
DATA_CLIENTS = f"{DOMAIN}_clients"
|
|
DATA_PENDING = f"{DOMAIN}_pending"
|
|
|
|
|
|
def _log_handler(level: int, message: str) -> None:
|
|
_LOGGER.log(_LOG_LEVELS.get(level, logging.DEBUG), "pyfglair: %s", message)
|
|
|
|
|
|
async def async_setup(hass: HomeAssistant, config: dict) -> bool:
|
|
if DOMAIN not in config:
|
|
return True
|
|
if not isinstance(config[DOMAIN], dict):
|
|
_LOGGER.warning(
|
|
"fglair: ожидался словарь параметров устройства, получено %s",
|
|
type(config[DOMAIN]).__name__,
|
|
)
|
|
return True
|
|
hass.async_create_task(
|
|
hass.config_entries.flow.async_init(
|
|
DOMAIN,
|
|
context={"source": config_entries.SOURCE_IMPORT},
|
|
data=config[DOMAIN],
|
|
)
|
|
)
|
|
return True
|
|
|
|
|
|
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|
clients: dict[str, FglairClient] = hass.data.setdefault(DATA_CLIENTS, {})
|
|
hass.data[DATA_PENDING] = hass.data.get(DATA_PENDING, 0) + 1
|
|
|
|
client = FglairClient(hass, entry.data)
|
|
conversions = ConversionSet.from_entry(entry.data)
|
|
# Координатор создаётся (и подписывается) до старта сессии, чтобы не
|
|
# пропустить первое ONLINE.
|
|
coordinator = FglairCoordinator(hass, client, conversions, entry.entry_id)
|
|
try:
|
|
await client.async_start()
|
|
await coordinator.async_config_entry_first_refresh()
|
|
await coordinator.async_sync_now()
|
|
except Exception:
|
|
await coordinator.async_shutdown()
|
|
await client.async_stop()
|
|
raise
|
|
finally:
|
|
hass.data[DATA_PENDING] -= 1
|
|
|
|
features = FeatureSet(
|
|
explicit=entry.data.get(CONF_FEATURES),
|
|
values=LiveValues(coordinator.client.cached),
|
|
)
|
|
coordinator.features = features
|
|
|
|
clients[entry.entry_id] = client
|
|
entry.runtime_data = FglairRuntime(client, coordinator, conversions, features)
|
|
if len(clients) == 1:
|
|
pyfglair.set_log_handler(_log_handler)
|
|
pyfglair.set_log_level(1)
|
|
|
|
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
|
return True
|
|
|
|
|
|
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|
runtime: FglairRuntime = entry.runtime_data
|
|
unloaded = await hass.config_entries.async_unload_platforms(
|
|
entry, PLATFORMS
|
|
)
|
|
if not unloaded:
|
|
return False
|
|
await runtime.coordinator.async_shutdown()
|
|
runtime.coordinator.async_remove_issue()
|
|
await runtime.client.async_stop()
|
|
|
|
clients: dict[str, FglairClient] = hass.data.get(DATA_CLIENTS, {})
|
|
clients.pop(entry.entry_id, None)
|
|
if not clients and not hass.data.get(DATA_PENDING, 0):
|
|
await hass.async_add_executor_job(pyfglair.set_log_handler, None)
|
|
return unloaded
|
|
|
|
|
|
async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
|
ir.async_delete_issue(
|
|
hass, DOMAIN, key_issue_id(str(entry.data.get(CONF_DSN, "")))
|
|
)
|