From dee5819743b29f6f771b52370ab84446a428c2b6 Mon Sep 17 00:00:00 2001 From: Petr Polezhaev Date: Tue, 29 Sep 2026 13:54:55 +0300 Subject: [PATCH] =?UTF-8?q?ha(H3):=20=D0=BD=D0=B8=D1=82=D1=8B=20=D0=BF?= =?UTF-8?q?=D0=BE=D0=B2=D1=82=D0=BE=D1=80=D0=BD=D0=BE=D0=B3=D0=BE=20=D1=80?= =?UTF-8?q?=D0=B5=D0=B2=D1=8C=D1=8E=20=E2=80=94=20=D0=BF=D1=83=D1=81=D1=82?= =?UTF-8?q?=D0=BE=D0=B9=20=D0=B4=D0=B8=D0=B0=D0=BF=D0=B0=D0=B7=D0=BE=D0=BD?= =?UTF-8?q?,=20merge=20=D0=B7=D0=BD=D0=B0=D1=87=D0=B5=D0=BD=D0=B8=D0=B9,?= =?UTF-8?q?=20=D1=87=D0=B8=D1=81=D1=82=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - R1: config flow отклоняет пустое пересечение override и таблицы (достижимый диапазон), + тест - R2: async_sync_now перечитывает снимок без await (события не затираются) - R3: translation_key климата убран (FglairEntity принимает None) - R4: caps==0 «не сообщено» покрыт тестом - R5: SWING_HORIZONTAL_MODES удалён (общий SWING_MODES) --- custom_components/fglair/climate.py | 10 ++----- custom_components/fglair/config_flow.py | 32 ++++++++++++++++++--- custom_components/fglair/const.py | 1 - custom_components/fglair/coordinator.py | 12 ++------ custom_components/fglair/entity.py | 5 ++-- tests/components/fglair/test_config_flow.py | 24 ++++++++++++++++ tests/components/fglair/test_entities.py | 20 +++++++++++++ 7 files changed, 81 insertions(+), 23 deletions(-) diff --git a/custom_components/fglair/climate.py b/custom_components/fglair/climate.py index e4fb6d1..a066a88 100644 --- a/custom_components/fglair/climate.py +++ b/custom_components/fglair/climate.py @@ -30,7 +30,6 @@ from .const import ( PRESET_CAP, PRESET_ECO, PRESET_PROP, - SWING_HORIZONTAL_MODES, SWING_MODES, ) from .coordinator import FglairCoordinator, FglairRuntime @@ -47,7 +46,8 @@ class FglairClimate(FglairEntity, ClimateEntity): _attr_temperature_unit = UnitOfTemperature.CELSIUS def __init__(self, coordinator: FglairCoordinator) -> None: - super().__init__(coordinator, "climate", "climate") + # translation_key не нужен: имя = имя устройства (has_entity_name). + super().__init__(coordinator, "climate", None) self._last_hvac_mode: Optional[HVACMode] = None # -- свойства шаблона -------------------------------------------------- @@ -186,11 +186,7 @@ class FglairClimate(FglairEntity, ClimateEntity): @property def swing_horizontal_modes(self) -> Optional[list[str]]: - return ( - SWING_HORIZONTAL_MODES - if self._horizontal_swing_supported() - else None - ) + return SWING_MODES if self._horizontal_swing_supported() else None # -- команды ---------------------------------------------------------- async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: diff --git a/custom_components/fglair/config_flow.py b/custom_components/fglair/config_flow.py index e67ecfc..c25a6c4 100644 --- a/custom_components/fglair/config_flow.py +++ b/custom_components/fglair/config_flow.py @@ -51,6 +51,7 @@ from .const import ( TRIAL_ERRORS, TRIAL_TIMEOUT, ) +from .overrides import ConversionSet, LinearOverride from .trial import TrialResult, trial_connect _LOGGER = logging.getLogger(__name__) @@ -408,16 +409,39 @@ class FglairConfigFlow(ConfigFlow, domain=DOMAIN): temp_min = int(round(float(user_input[CONF_TEMP_MIN]) * 10)) temp_max = int(round(float(user_input[CONF_TEMP_MAX]) * 10)) step = int(round(float(user_input[CONF_TEMP_STEP]) * 10)) - if temp_min >= temp_max: + num = int(user_input[CONF_TEMP_NUM]) + den = int(user_input[CONF_TEMP_DEN]) + offset = int(user_input[CONF_TEMP_OFFSET]) + conversions = ConversionSet( + template, + { + Prop.ADJUST_TEMPERATURE: LinearOverride( + num=num, + den=den, + offset=offset, + min_value=temp_min, + max_value=temp_max, + ) + }, + step, + ) + bounds = conversions.range(Prop.ADJUST_TEMPERATURE) + if ( + temp_min >= temp_max + or bounds is None + or bounds[0] >= bounds[1] + ): + # Достижимый диапазон пуст: конверсия выводит таблицу + # шаблона за пределы, которые не пересекаются с min/max. errors["base"] = "invalid_range" else: data[CONF_TEMPLATE] = template.name data[CONF_TEMP_STEP] = step data[CONF_OVERRIDES] = { Prop.ADJUST_TEMPERATURE.name.lower(): { - "num": int(user_input[CONF_TEMP_NUM]), - "den": int(user_input[CONF_TEMP_DEN]), - "offset": int(user_input[CONF_TEMP_OFFSET]), + "num": num, + "den": den, + "offset": offset, "min": temp_min, "max": temp_max, } diff --git a/custom_components/fglair/const.py b/custom_components/fglair/const.py index b1beeff..9e58d5a 100644 --- a/custom_components/fglair/const.py +++ b/custom_components/fglair/const.py @@ -99,7 +99,6 @@ PRESET_CAP = { } SWING_MODES = ["off", "on"] -SWING_HORIZONTAL_MODES = ["off", "on"] # switch-свойства: prop -> (translation_key, capability bit | None) SWITCH_PROPS: dict[Prop, tuple[str, int | None]] = { diff --git a/custom_components/fglair/coordinator.py b/custom_components/fglair/coordinator.py index 6e95ed4..aa85710 100644 --- a/custom_components/fglair/coordinator.py +++ b/custom_components/fglair/coordinator.py @@ -112,15 +112,9 @@ class FglairCoordinator(DataUpdateCoordinator[FglairData]): self._async_initial_sync() ) await self._sync_task - # Снимок создавался до ONLINE: обновляем состояние/доступность из - # актуального состояния клиента (значения приходят событиями). - state = self.client.state - self.data = replace( - self.data, - state=state, - last_error=self.client.last_error, - available=state in AVAILABLE_STATES, - ) + # Снимок создавался до ONLINE: перечитываем его без await (события + # не могут вклиниться между чтением и присваиванием). + self.data = self._snapshot() self.async_set_updated_data(self.data) @callback diff --git a/custom_components/fglair/entity.py b/custom_components/fglair/entity.py index d102545..743c445 100644 --- a/custom_components/fglair/entity.py +++ b/custom_components/fglair/entity.py @@ -21,13 +21,14 @@ class FglairEntity(CoordinatorEntity[FglairCoordinator]): self, coordinator: FglairCoordinator, unique_suffix: str, - translation_key: str, + translation_key: Optional[str], ) -> None: super().__init__(coordinator) data = coordinator.client.data dsn = data[CONF_DSN] self._attr_unique_id = f"{dsn}_{unique_suffix}" - self._attr_translation_key = translation_key + if translation_key is not None: + self._attr_translation_key = translation_key self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, dsn)}, name=data.get(CONF_NAME) or dsn, diff --git a/tests/components/fglair/test_config_flow.py b/tests/components/fglair/test_config_flow.py index 4ba7732..26892ed 100644 --- a/tests/components/fglair/test_config_flow.py +++ b/tests/components/fglair/test_config_flow.py @@ -157,6 +157,30 @@ async def test_preview_invalid_range(hass: HomeAssistant): assert result["type"] == "create_entry" +async def test_preview_unreachable_range(hass: HomeAssistant): + """Конверсия выводит таблицу за min/max — пустой достижимый диапазон.""" + with patch( + "custom_components.fglair.config_flow._run_trial", + return_value=TRIAL_OK, + ): + result = await _menu(hass) + result = await _select(hass, result["flow_id"], "manual") + result = await _configure(hass, result["flow_id"], MANUAL_INPUT) + result = await _configure( + hass, + result["flow_id"], + { + **PREVIEW_INPUT, + "temp_min": 30.0, + "temp_max": 40.0, + "temp_num": 1, + "temp_den": 2, + }, + ) + assert result["type"] == "form" + assert result["errors"] == {"base": "invalid_range"} + + async def test_preview_contains_trial_values(hass: HomeAssistant): props = { Prop.DISPLAY_TEMPERATURE: Value(ValueKind.INT, 200), diff --git a/tests/components/fglair/test_entities.py b/tests/components/fglair/test_entities.py index 8cc4e6a..4a17e0c 100644 --- a/tests/components/fglair/test_entities.py +++ b/tests/components/fglair/test_entities.py @@ -296,3 +296,23 @@ async def test_manual_conversion_applied( ) assert proc.wait_line("CMD SET adjust_temperature=245", 10) assert await hass.config_entries.async_unload(entry.entry_id) + + +async def test_capabilities_zero_is_unknown( + hass: HomeAssistant, mock_ac, socket_enabled +): + """device_capabilities=0 трактуем как «не сообщено» — режимы не режем.""" + proc = mock_ac([ + "--set", "operation_mode=6", + "--set", "device_capabilities=0", + ]) + entry = await _setup_entry(hass, proc.port) + runtime = entry.runtime_data + await _wait_for(lambda: runtime.client.state == State.ONLINE) + climate_id = _entity_id(hass, "climate", f"{DSN}_climate") + await _wait_for( + lambda: climate_id and hass.states.get(climate_id) is not None + and hass.states.get(climate_id).state == "heat" + ) + assert "heat" in hass.states.get(climate_id).attributes["hvac_modes"] + assert await hass.config_entries.async_unload(entry.entry_id)