ha(ux): исправления по ревью — быстрый выход пробинга, prefill шаблона, ниты
- major: probe_template прекращает перебор на unreachable/no_slots/key_error (недоступный модуль: ~10 c вместо ~49 c), продолжает только при properties_missing (доступен, но чужой шаблон); +тест - m1: extra_state_attributes не падает до добавления в hass - m2: reconfigure берёт сохранённый шаблон как дефолт (не пересчитывает по модели); +тест - m3: device_capabilities/display_temperature переведены в необязательные зонды (trial не падает на молчащем caps; feature-модель трактует None как «не режем») - m4: async_sync_now(online_timeout) — честное имя/докстринг - ниты: удалены PRESET_CAP/as_dict/лишние плейсхолдеры, DIRECTION_KEYS упрощён, тавтология в тесте исправлена, en-тире - 59 components + 47 pyfglair/acceptance зелёные
This commit is contained in:
@@ -496,8 +496,6 @@ class FglairConfigFlow(ConfigFlow, domain=DOMAIN):
|
|||||||
default = str(data.get(CONF_TEMPLATE, default))
|
default = str(data.get(CONF_TEMPLATE, default))
|
||||||
placeholders = {
|
placeholders = {
|
||||||
"device_values": _device_values_text(self._trial_properties),
|
"device_values": _device_values_text(self._trial_properties),
|
||||||
"detected": default,
|
|
||||||
"model": str(data.get(CONF_MODEL) or "-"),
|
|
||||||
}
|
}
|
||||||
if self._probed:
|
if self._probed:
|
||||||
placeholders["probe_note"] = (
|
placeholders["probe_note"] = (
|
||||||
@@ -641,6 +639,12 @@ class FglairConfigFlow(ConfigFlow, domain=DOMAIN):
|
|||||||
# текущие конверсии, если путь их не задаёт.
|
# текущие конверсии, если путь их не задаёт.
|
||||||
for key, value in self._reconfigure_entry.data.items():
|
for key, value in self._reconfigure_entry.data.items():
|
||||||
data.setdefault(key, value)
|
data.setdefault(key, value)
|
||||||
|
# Сохранённый шаблон важнее пересчёта по модели: пользователь
|
||||||
|
# мог выбрать его вручную (страница подтвердит/изменит).
|
||||||
|
if self._reconfigure_entry.data.get(CONF_TEMPLATE):
|
||||||
|
data[CONF_TEMPLATE] = self._reconfigure_entry.data[
|
||||||
|
CONF_TEMPLATE
|
||||||
|
]
|
||||||
await self.async_set_unique_id(data[CONF_DSN], raise_on_progress=False)
|
await self.async_set_unique_id(data[CONF_DSN], raise_on_progress=False)
|
||||||
if self._reconfigure_entry is not None:
|
if self._reconfigure_entry is not None:
|
||||||
self._abort_if_unique_id_mismatch()
|
self._abort_if_unique_id_mismatch()
|
||||||
@@ -651,7 +655,11 @@ class FglairConfigFlow(ConfigFlow, domain=DOMAIN):
|
|||||||
)
|
)
|
||||||
if result.ok:
|
if result.ok:
|
||||||
self._pending_data = data
|
self._pending_data = data
|
||||||
self._pending_data[CONF_TEMPLATE] = template.name
|
if (
|
||||||
|
self._reconfigure_entry is None
|
||||||
|
or not self._reconfigure_entry.data.get(CONF_TEMPLATE)
|
||||||
|
):
|
||||||
|
self._pending_data[CONF_TEMPLATE] = template.name
|
||||||
self._trial_properties = result.properties
|
self._trial_properties = result.properties
|
||||||
self._trial_answered = result.answered
|
self._trial_answered = result.answered
|
||||||
self._resolved_template = template
|
self._resolved_template = template
|
||||||
|
|||||||
@@ -94,11 +94,6 @@ PRESET_PROP = {
|
|||||||
PRESET_ECO: Prop.ECONOMY_MODE,
|
PRESET_ECO: Prop.ECONOMY_MODE,
|
||||||
PRESET_BOOST: Prop.POWERFUL_MODE,
|
PRESET_BOOST: Prop.POWERFUL_MODE,
|
||||||
}
|
}
|
||||||
PRESET_CAP = {
|
|
||||||
PRESET_ECO: CAP_ECONOMY,
|
|
||||||
PRESET_BOOST: CAP_POWERFUL,
|
|
||||||
}
|
|
||||||
|
|
||||||
SWING_MODES = ["off", "on"]
|
SWING_MODES = ["off", "on"]
|
||||||
|
|
||||||
# switch-свойства: prop -> (translation_key, capability bit | None)
|
# switch-свойства: prop -> (translation_key, capability bit | None)
|
||||||
@@ -218,7 +213,7 @@ ENTITY_DESCRIPTIONS = {
|
|||||||
"en": {
|
"en": {
|
||||||
"climate": "Air conditioner control: mode, fan, setpoint, louvers, presets",
|
"climate": "Air conditioner control: mode, fan, setpoint, louvers, presets",
|
||||||
"room_temperature": "Room air temperature",
|
"room_temperature": "Room air temperature",
|
||||||
"error_code": "Air conditioner error code (0 — no errors)",
|
"error_code": "Air conditioner error code (0 = no errors)",
|
||||||
"connection_state": "Connection state with the AC module",
|
"connection_state": "Connection state with the AC module",
|
||||||
"connectivity": "Whether the module is reachable",
|
"connectivity": "Whether the module is reachable",
|
||||||
"defrost": "Outdoor unit defrost in progress",
|
"defrost": "Outdoor unit defrost in progress",
|
||||||
|
|||||||
@@ -123,13 +123,14 @@ class FglairCoordinator(DataUpdateCoordinator[FglairData]):
|
|||||||
# После разрыва при следующем ONLINE нужна повторная синхронизация.
|
# После разрыва при следующем ONLINE нужна повторная синхронизация.
|
||||||
self._synced = False
|
self._synced = False
|
||||||
|
|
||||||
async def async_sync_now(self, timeout: float = 2.0) -> None:
|
async def async_sync_now(self, online_timeout: float = 2.0) -> None:
|
||||||
"""Гарантирует первичный GET-батч и ожидание ключевых свойств.
|
"""Гарантирует первичный GET-батч и ожидание ключевых свойств.
|
||||||
|
|
||||||
Ждёт ONLINE (ограниченно), затем — завершения синхронизации, чтобы
|
Ждёт ONLINE не дольше ``online_timeout``, затем — завершения
|
||||||
сущности создавались с корректными feature-дефолтами.
|
синхронизации (сама синхронизация ограничена своим таймаутом),
|
||||||
|
чтобы сущности создавались с корректными feature-дефолтами.
|
||||||
"""
|
"""
|
||||||
deadline = self.hass.loop.time() + timeout
|
deadline = self.hass.loop.time() + online_timeout
|
||||||
while (
|
while (
|
||||||
self._sync_task is None
|
self._sync_task is None
|
||||||
and self.client.state != State.ONLINE
|
and self.client.state != State.ONLINE
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ class FglairEntity(CoordinatorEntity[FglairCoordinator]):
|
|||||||
def extra_state_attributes(self) -> Optional[dict]:
|
def extra_state_attributes(self) -> Optional[dict]:
|
||||||
"""HA не поддерживает тултипы сущностей: краткое описание видно в
|
"""HA не поддерживает тултипы сущностей: краткое описание видно в
|
||||||
атрибутах (More info → Атрибуты)."""
|
атрибутах (More info → Атрибуты)."""
|
||||||
if self._description_key is None:
|
if self._description_key is None or self.hass is None:
|
||||||
return None
|
return None
|
||||||
text = entity_description(self.hass.config.language, self._description_key)
|
text = entity_description(self.hass.config.language, self._description_key)
|
||||||
return {"description": text} if text else None
|
return {"description": text} if text else None
|
||||||
|
|||||||
@@ -13,11 +13,8 @@ from pyfglair import Prop, Value
|
|||||||
from .const import FEATURES
|
from .const import FEATURES
|
||||||
|
|
||||||
DIRECTION_KEYS = {
|
DIRECTION_KEYS = {
|
||||||
"af_vertical_direction": ("af_vertical_num_dir", Prop.AF_VERTICAL_NUM_DIR),
|
"af_vertical_direction": Prop.AF_VERTICAL_NUM_DIR,
|
||||||
"af_horizontal_direction": (
|
"af_horizontal_direction": Prop.AF_HORIZONTAL_NUM_DIR,
|
||||||
"af_horizontal_num_dir",
|
|
||||||
Prop.AF_HORIZONTAL_NUM_DIR,
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -44,7 +41,7 @@ def device_default(
|
|||||||
return True # возможностей не сообщили — не режем
|
return True # возможностей не сообщили — не режем
|
||||||
return bool(caps & (1 << bit))
|
return bool(caps & (1 << bit))
|
||||||
if key in DIRECTION_KEYS:
|
if key in DIRECTION_KEYS:
|
||||||
num = _int_value(values, DIRECTION_KEYS[key][1])
|
num = _int_value(values, DIRECTION_KEYS[key])
|
||||||
return bool(num and num > 1)
|
return bool(num and num > 1)
|
||||||
if prop is not None:
|
if prop is not None:
|
||||||
if answered is not None:
|
if answered is not None:
|
||||||
@@ -113,6 +110,3 @@ class FeatureSet:
|
|||||||
if key in self._explicit:
|
if key in self._explicit:
|
||||||
return self._explicit[key]
|
return self._explicit[key]
|
||||||
return device_default(key, self._values)
|
return device_default(key, self._values)
|
||||||
|
|
||||||
def as_dict(self) -> dict[str, bool]:
|
|
||||||
return dict(self._explicit)
|
|
||||||
|
|||||||
@@ -20,13 +20,13 @@ from pyfglair.templates import template_info
|
|||||||
REQUIRED_PROPS: tuple[Prop, ...] = (
|
REQUIRED_PROPS: tuple[Prop, ...] = (
|
||||||
Prop.OPERATION_MODE,
|
Prop.OPERATION_MODE,
|
||||||
Prop.FAN_SPEED,
|
Prop.FAN_SPEED,
|
||||||
Prop.DEVICE_CAPABILITIES,
|
|
||||||
Prop.DISPLAY_TEMPERATURE,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Зондируемые свойства (в пределах выбранного шаблона): наличие в ответе —
|
# Зондируемые свойства (в пределах выбранного шаблона): наличие в ответе —
|
||||||
# информация для дефолтов фич и распознавания шаблона.
|
# информация для дефолтов фич и распознавания шаблона.
|
||||||
OPTIONAL_PROPS: tuple[Prop, ...] = (
|
OPTIONAL_PROPS: tuple[Prop, ...] = (
|
||||||
|
Prop.DEVICE_CAPABILITIES,
|
||||||
|
Prop.DISPLAY_TEMPERATURE,
|
||||||
Prop.AF_VERTICAL_DIRECTION,
|
Prop.AF_VERTICAL_DIRECTION,
|
||||||
Prop.AF_HORIZONTAL_DIRECTION,
|
Prop.AF_HORIZONTAL_DIRECTION,
|
||||||
Prop.AF_VERTICAL_NUM_DIR,
|
Prop.AF_VERTICAL_NUM_DIR,
|
||||||
@@ -244,7 +244,11 @@ def probe_template(
|
|||||||
props_timeout=2.0,
|
props_timeout=2.0,
|
||||||
)
|
)
|
||||||
if not result.ok:
|
if not result.ok:
|
||||||
continue
|
if result.reason == "properties_missing":
|
||||||
|
# Модуль доступен, но свойств шаблона нет — пробуем дальше.
|
||||||
|
continue
|
||||||
|
# Недоступен/нет слотов/ключ — перебор шаблонов бессмыслен.
|
||||||
|
return None, properties
|
||||||
answered |= result.answered
|
answered |= result.answered
|
||||||
properties.update(result.properties)
|
properties.update(result.properties)
|
||||||
detected = classify_template(answered)
|
detected = classify_template(answered)
|
||||||
|
|||||||
@@ -600,3 +600,32 @@ async def test_run_trial_probes_unknown_model(hass: HomeAssistant):
|
|||||||
assert template is Template.B
|
assert template is Template.B
|
||||||
assert probed is True
|
assert probed is True
|
||||||
probe.assert_called_once()
|
probe.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_reconfigure_prefills_stored_template(
|
||||||
|
hass: HomeAssistant, mock_ac, socket_enabled
|
||||||
|
):
|
||||||
|
"""При reconfigure дефолт — сохранённый шаблон, а не пересчитанный."""
|
||||||
|
from test_entities import _setup_entry
|
||||||
|
|
||||||
|
proc = mock_ac(["--set", "operation_mode=6"])
|
||||||
|
entry = await _setup_entry(hass, proc.port)
|
||||||
|
hass.config_entries.async_update_entry(
|
||||||
|
entry, data={**entry.data, "template": "B"}
|
||||||
|
)
|
||||||
|
with patch(
|
||||||
|
"custom_components.fglair.config_flow._run_trial",
|
||||||
|
return_value=(TrialResult(ok=True), Template.A, False),
|
||||||
|
):
|
||||||
|
result = await hass.config_entries.flow.async_init(
|
||||||
|
DOMAIN,
|
||||||
|
context={"source": SOURCE_RECONFIGURE, "entry_id": entry.entry_id},
|
||||||
|
)
|
||||||
|
result = await _select(hass, result["flow_id"], "manual")
|
||||||
|
result = await _configure(
|
||||||
|
hass, result["flow_id"], {**MANUAL_INPUT, "host": "127.0.0.1",
|
||||||
|
"device_port": proc.port}
|
||||||
|
)
|
||||||
|
assert result["step_id"] == "template"
|
||||||
|
assert _suggested(result["data_schema"], "template") == "B"
|
||||||
|
await hass.config_entries.async_unload(entry.entry_id)
|
||||||
|
|||||||
@@ -60,9 +60,8 @@ def test_resolve_and_featureset_override():
|
|||||||
resolved = resolve_features(values, set(), {"swing_vertical": True})
|
resolved = resolve_features(values, set(), {"swing_vertical": True})
|
||||||
assert resolved["swing_vertical"] is True
|
assert resolved["swing_vertical"] is True
|
||||||
assert resolved["powerful_mode"] is False
|
assert resolved["powerful_mode"] is False
|
||||||
assert len(resolved) == len(
|
from custom_components.fglair.const import FEATURES
|
||||||
{key for key in resolved}
|
assert len(resolved) == len(FEATURES)
|
||||||
)
|
|
||||||
feature_set = FeatureSet({"swing_vertical": True}, values)
|
feature_set = FeatureSet({"swing_vertical": True}, values)
|
||||||
assert feature_set.enabled("swing_vertical") is True
|
assert feature_set.enabled("swing_vertical") is True
|
||||||
assert feature_set.enabled("powerful_mode") is False
|
assert feature_set.enabled("powerful_mode") is False
|
||||||
@@ -103,3 +102,20 @@ def test_resolved_features_for_ap_wc1e_without_sensor():
|
|||||||
assert resolved["mode_cool"] is True
|
assert resolved["mode_cool"] is True
|
||||||
assert resolved["economy_mode"] is True
|
assert resolved["economy_mode"] is True
|
||||||
assert resolved["powerful_mode"] is False
|
assert resolved["powerful_mode"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_probe_stops_on_unreachable(monkeypatch):
|
||||||
|
"""Недоступный модуль не перебираем трижды — выходим после первой сессии."""
|
||||||
|
from custom_components.fglair import trial as tr
|
||||||
|
|
||||||
|
calls: list = []
|
||||||
|
|
||||||
|
def fake_trial(*args, **kwargs):
|
||||||
|
calls.append(kwargs.get("template"))
|
||||||
|
return tr.TrialResult(ok=False, reason="unreachable")
|
||||||
|
|
||||||
|
monkeypatch.setattr(tr, "trial_connect", fake_trial)
|
||||||
|
template, props = tr.probe_template("host", "dsn", "key", 1)
|
||||||
|
assert template is None
|
||||||
|
assert props == {}
|
||||||
|
assert calls == [Template.A]
|
||||||
|
|||||||
Reference in New Issue
Block a user