From e8697751f2b9b4a0f4e6ee2b5b659f23b0639926 Mon Sep 17 00:00:00 2001 From: Twintop Date: Thu, 15 Oct 2026 00:03:29 +1100 Subject: [PATCH 1/9] Remember zone target temperatures per mode The wall panel of a zone controller remembers the target temperature of every zone for each mode, and sets them again when the mode is changed on the panel. A mode change over WiFi does not do that: the zones keep the values of the old mode (seen on a LE60-13/GH). So a mode change from Home Assistant left every zone at the wrong target temperature. SetpointMemory in aiogree/setpoint_memory.py keeps the same memory: - It learns from every poll. A device reports its mode and its target temperature in one reply, so the two belong together. A value is stored when the device reported the same mode on the poll before, so a poll in the middle of a mode change on the panel is not stored under the wrong mode. Changes made on the panel or in the Gree+ app are learned the same way. - Before the climate entity of the ducted unit changes the mode, it reads the zones again and stores them under the old mode. After the change it sends the stored values of the new mode. A mode with no stored values changes nothing. - It stores the raw columns that hold the target temperature, per device MAC and mode: {"": {"heat": {"StTem": 3, "StFahFlg": 0}}}. The raw columns are the same in Celsius and Fahrenheit, so a recalled value is right in either unit, and the bit brings back a half degree or a Fahrenheit value exactly. GreeDevice.target_temperature_props and set_target_temperature_props give the columns the device uses. The memory has no Home Assistant imports and is covered by tests against the fake controller. __init__.py keeps it in a Store per config entry (gree_custom..setpoints). --- custom_components/gree_custom/__init__.py | 51 ++++ .../gree_custom/aiogree/device.py | 28 ++ .../gree_custom/aiogree/setpoint_memory.py | 158 +++++++++++ custom_components/gree_custom/climate.py | 22 +- custom_components/gree_custom/coordinator.py | 5 + docs/architecture.md | 1 + docs/entities.md | 2 + docs/protocol.md | 9 + tests/test_setpoint_memory.py | 247 ++++++++++++++++++ 9 files changed, 522 insertions(+), 1 deletion(-) create mode 100644 custom_components/gree_custom/aiogree/setpoint_memory.py create mode 100644 tests/test_setpoint_memory.py diff --git a/custom_components/gree_custom/__init__.py b/custom_components/gree_custom/__init__.py index fe71e48e..0ea0865f 100755 --- a/custom_components/gree_custom/__init__.py +++ b/custom_components/gree_custom/__init__.py @@ -2,6 +2,7 @@ # Standard library imports from collections.abc import Mapping +from functools import partial import json import logging from typing import Any @@ -24,11 +25,14 @@ HomeAssistantError, ) from homeassistant.helpers import device_registry as dr, issue_registry as ir +from homeassistant.helpers.storage import Store from homeassistant.helpers.typing import ConfigType +from .aiogree.api import DeviceType from .aiogree.cipher import EncryptionVersion from .aiogree.device import GreeDevice from .aiogree.errors import GreeConnectionError +from .aiogree.setpoint_memory import SetpointMemory, SetpointMemoryData from .aiogree.transport_mqtt import GreeMqttTransport from .aiogree.transport_udp import GreeUdpTransport from .config_schema import CONFIG_SCHEMA as CONFIG_SCHEMA @@ -84,6 +88,8 @@ ISSUE_DEVICE_CONNECTION_FAILED = "device_connection_failed" ISSUE_YAML_IMPORT_FAILED = "yaml_import_failed" +SETPOINT_MEMORY_STORAGE_VERSION = 1 +SETPOINT_MEMORY_SAVE_DELAY = 10 PLATFORMS = [ Platform.BINARY_SENSOR, Platform.CLIMATE, @@ -292,6 +298,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: GreeConfigEntry) -> bool entry.runtime_data = {} entry.runtime_data = coordinators + await _async_setup_setpoint_memory(hass, entry, coordinators) + # Move the 4.x registry rows before the entities are created moved = await async_migrate_legacy_registry(hass, entry) @@ -334,6 +342,49 @@ async def _async_refresh_entry_token( return new_cloud_conf +async def _async_setup_setpoint_memory( + hass: HomeAssistant, + entry: GreeConfigEntry, + coordinators: dict[str, GreeCoordinator], +) -> None: + """Give the ducted unit of each zone controller the memory of its zones. + + The memory keeps the target temperature of every zone per mode, so a mode + change from Home Assistant sets them as the wall panel does. It learns from + every poll of a zone. See aiogree/setpoint_memory.py. + """ + zones = [ + c for c in coordinators.values() if c.device.device_type is DeviceType.ZONE + ] + if not zones: + return + + store: Store[SetpointMemoryData] = Store( + hass, SETPOINT_MEMORY_STORAGE_VERSION, f"{DOMAIN}.{entry.entry_id}.setpoints" + ) + memory = SetpointMemory( + await store.async_load(), + on_change=lambda: store.async_delay_save( + lambda: memory.data, SETPOINT_MEMORY_SAVE_DELAY + ), + ) + + for zone in zones: + entry.async_on_unload( + zone.async_add_listener(partial(memory.learn, zone.device)) + ) + + for coordinator in coordinators.values(): + if coordinator.device.device_type is DeviceType.ZONE_CONTROLLER: + coordinator.setpoint_memory = memory + coordinator.zone_coordinators = [ + zone + for zone in zones + if zone.device.mac_address_controller + == coordinator.device.mac_address_controller + ] + + async def async_unload_entry(hass: HomeAssistant, entry: GreeConfigEntry) -> bool: """Unload a config entry and close its connections. diff --git a/custom_components/gree_custom/aiogree/device.py b/custom_components/gree_custom/aiogree/device.py index 96d0af31..43e6f0fd 100755 --- a/custom_components/gree_custom/aiogree/device.py +++ b/custom_components/gree_custom/aiogree/device.py @@ -679,6 +679,34 @@ def device_type(self) -> DeviceType: """Return what kind of device this is. Known after the first bind.""" return self._device_type + @property + def target_temperature_props(self) -> dict[GreeProp, int] | None: + """Return the raw columns that hold the target temperature, to remember it. + + Used by `SetpointMemory`. Raw columns need no unit conversion. They + are the column the device uses, see _remove_unsupported_props. None + means there is nothing to remember. + """ + if self._target_temp_prop is None: + return None + raw = self._state.get(self._target_temp_prop) + if raw is None: + return None + props = {self._target_temp_prop: raw} + # With the bit, when the device has one: the half degree in Celsius, + # the table in Fahrenheit. A zone keeps an old bit when only StTem is + # sent, see set_target_temperature. + if self._target_temp_bit_prop is not None: + props[self._target_temp_bit_prop] = ( + self._state.get(self._target_temp_bit_prop) or 0 + ) + return props + + def set_target_temperature_props(self, props: Mapping[GreeProp, int]) -> None: + """Set the raw columns that hold the target temperature, as remembered.""" + for prop, value in props.items(): + self._state.set(prop, value) + @property def has_held_values(self) -> bool: """Return True if sent values still wait for the device to confirm them.""" diff --git a/custom_components/gree_custom/aiogree/setpoint_memory.py b/custom_components/gree_custom/aiogree/setpoint_memory.py new file mode 100644 index 00000000..5f8eaee9 --- /dev/null +++ b/custom_components/gree_custom/aiogree/setpoint_memory.py @@ -0,0 +1,158 @@ +"""The target temperature of a device, remembered per mode. + +The wall panel of a zone controller remembers the target temperature of every +zone for each mode, and sets them again when the mode is changed on the panel. +A mode change over WiFi does not do that: the zones keep the values of the old +mode (seen on a LE60-13/GH). This class keeps the same memory, so a mode change +from Home Assistant works like one on the panel. See docs/protocol.md. + +- A device reports its mode and its target temperature in one reply, so the + two belong together. A value is stored when the device reported the same + mode on the poll before. A poll in the middle of a mode change on the panel + is then not stored under the wrong mode. +- Before the mode is changed, `snapshot()` reads the devices again and stores + them under the old mode, so a change made on the panel since the last poll is + not lost. After the change, `recall()` sends the stored values of the new + mode. +- What is stored are the raw columns that hold the target temperature, as + `GreeDevice.target_temperature_props` gives them, per device MAC and mode. + Today only zones give any. + +The memory does not store itself. The owner loads `data` and saves it when +`on_change` is called. +""" + +from collections.abc import Callable, Iterable, Mapping +import logging + +from .api import PROP_KEY_TO_ENUM, GreeProp, OperationMode +from .device import GreeDevice +from .errors import GreeError + +_LOGGER = logging.getLogger(__name__) + +# {device MAC: {mode name: {column: raw value}}} +type SetpointMemoryData = dict[str, dict[str, dict[str, int]]] + + +class SetpointMemory: + """Remembers the target temperature of devices per mode.""" + + def __init__( + self, + data: SetpointMemoryData | None = None, + on_change: Callable[[], None] | None = None, + ) -> None: + """Start with stored data, if there is any. + + Args: + data: What `data` held before, for example after a restart. + on_change: Called after a stored value changed. + + """ + self._data: SetpointMemoryData = data or {} + self._on_change = on_change + # The mode each device reported on its last poll. + self._last_mode: dict[str, OperationMode] = {} + + @property + def data(self) -> SetpointMemoryData: + """Everything that is stored, to be saved by the owner.""" + return self._data + + def stored(self, device_mac: str, mode: OperationMode) -> dict[GreeProp, int]: + """Return the stored target temperature columns of a device for one mode.""" + columns = self._data.get(device_mac, {}).get(mode.name, {}) + return { + PROP_KEY_TO_ENUM[key]: value + for key, value in columns.items() + if key in PROP_KEY_TO_ENUM + } + + def learn(self, device: GreeDevice) -> None: + """Store what a device reported, once its mode is the same twice in a row. + + Call this after every poll of the device. + """ + props = device.target_temperature_props + if props is None: + return + + mode = device.operation_mode + previous = self._last_mode.get(device.mac_address) + self._last_mode[device.mac_address] = mode + + # Values that were just sent and are not confirmed yet are stored once + # the device reports them. + if previous is mode and not device.has_held_values: + self._remember(device, mode, props) + + async def snapshot( + self, devices: Iterable[GreeDevice], mode: OperationMode + ) -> None: + """Read the devices again and store their values under the mode that is about to end.""" + for device in devices: + try: + await device.fetch_device_status() + except GreeError: + _LOGGER.debug( + "[%s] Could not read the device before the mode change", + device.unique_id, + ) + continue + + props = device.target_temperature_props + if ( + props is not None + and device.operation_mode is mode + and not device.has_held_values + ): + self._remember(device, mode, props) + + async def recall( + self, devices: Iterable[GreeDevice], mode: OperationMode + ) -> list[GreeDevice]: + """Send the stored target temperatures of a mode to the devices. + + Returns: + The devices that got a new target temperature + + """ + changed: list[GreeDevice] = [] + for device in devices: + stored = self.stored(device.mac_address, mode) + if not stored or stored == device.target_temperature_props: + continue + + device.set_target_temperature_props(stored) + try: + await device.push_device_status() + except GreeError: + _LOGGER.warning( + "[%s] Could not set the stored target temperature for %s", + device.unique_id, + mode.name, + ) + continue + changed.append(device) + + return changed + + def _remember( + self, device: GreeDevice, mode: OperationMode, props: Mapping[GreeProp, int] + ) -> None: + """Store the target temperature columns a device has now for one mode.""" + columns = {prop.value: value for prop, value in props.items()} + modes = self._data.setdefault(device.mac_address, {}) + if modes.get(mode.name) == columns: + return + + modes[mode.name] = columns + _LOGGER.debug( + "[%s] Stored target temperature %s for %s", + device.unique_id, + columns, + mode.name, + ) + if self._on_change is not None: + self._on_change() diff --git a/custom_components/gree_custom/climate.py b/custom_components/gree_custom/climate.py index 01539594..719838c8 100755 --- a/custom_components/gree_custom/climate.py +++ b/custom_components/gree_custom/climate.py @@ -658,7 +658,20 @@ async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: # This will be called in the turn on # await self._device.update_device_status() else: - self.device.set_operation_mode(HVAC_MODES_HA_TO_GREE[hvac_mode]) + new_mode = HVAC_MODES_HA_TO_GREE[hvac_mode] + old_mode = self.device.operation_mode + # A zone controller keeps the zone target temperatures of the old + # mode on a change over WiFi. Do what its wall panel does. + memory = ( + self.coordinator.setpoint_memory + if new_mode is not old_mode + else None + ) + zones = [z.device for z in self.coordinator.zone_coordinators] + if memory is not None: + await memory.snapshot(zones, old_mode) + + self.device.set_operation_mode(new_mode) # The Auto X-FAN enables that feature if the device is set to a hvac mode that supports X-FAN if self.coordinator.feature_auto_xfan: @@ -671,6 +684,13 @@ async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: # This will be called in the turn on: # await self._device.update_device_status() + if memory is not None: + changed = await memory.recall(zones, new_mode) + for zone in self.coordinator.zone_coordinators: + if zone.device in changed: + zone.async_update_listeners() + await zone.async_request_refresh() + # notify coordinator listeners of state change so that dependent entities are updated immediately self.coordinator.async_update_listeners() diff --git a/custom_components/gree_custom/coordinator.py b/custom_components/gree_custom/coordinator.py index 79e480f2..76d65d57 100755 --- a/custom_components/gree_custom/coordinator.py +++ b/custom_components/gree_custom/coordinator.py @@ -13,6 +13,7 @@ from .aiogree.api import OperationMode from .aiogree.device import GreeDevice from .aiogree.errors import GreeBindingError, GreeConnectionError +from .aiogree.setpoint_memory import SetpointMemory from .const import DOMAIN from .helpers import try_find_new_ip @@ -60,6 +61,10 @@ def __init__( self._feature_auto_light: bool = False self._unsub_follow_up_refresh: CALLBACK_TYPE | None = None self._is_shut_down: bool = False + # Set on the ducted unit of a zone controller: the memory of the zone + # target temperatures per mode, and the zones of the same controller. + self.setpoint_memory: SetpointMemory | None = None + self.zone_coordinators: list[GreeCoordinator] = [] async def _setup(self) -> None: """Bind to the device before the first coordinator refresh. diff --git a/docs/architecture.md b/docs/architecture.md index 1d9f8fc3..a56303ca 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -20,6 +20,7 @@ No Home Assistant imports here. | `helpers.py` | Encrypt and decrypt packs, temperature math, `TempOffsetResolver`, `redact_str`, `chunked`. | | `const.py` | Protocol constants: `MAX_PACK_SIZE`, `MIN_PACK_PROPS`, `STATUS_CANARY_PROP`, `PROBE_TIMEOUT`, `STATUS_CANARY_PROP_MAX_REQUESTS`, temperature and humidity ranges. | | `errors.py` | Exceptions. `GreeConnectionError` means no answer. `GreeProtocolError` means a bad answer. `GreeBindingError` means the key exchange failed. | +| `setpoint_memory.py` | `SetpointMemory`. The target temperature of a device per mode, stored as raw columns per device MAC. Used for the zones of a zone controller, so a mode change works like one on the wall panel. See [protocol.md](protocol.md#target-temperatures-per-mode). | ## Home Assistant layer diff --git a/docs/entities.md b/docs/entities.md index 550fcd2e..9e9aa514 100644 --- a/docs/entities.md +++ b/docs/entities.md @@ -53,6 +53,8 @@ A zone controller is controlled locally. Add it with local discovery, or with bo | Switch with the name of the zone | Opens and closes the zone. It is the **Zone Switch** feature, so you can leave it out. Do that for a zone that must always stay open: turning such a zone off is refused by the controller or turns the whole system off. | | Target Temperature | The target temperature of the zone, in the unit of the controller: 16 to 30 °C in half degrees, or 61 to 86 °F in whole degrees. Home Assistant shows it in your own unit. The wall panel shows only whole degrees in °C, so it shows 18 for 18.5. | +The wall panel remembers the target temperature of every zone for each mode, and sets them again when you change the mode on the panel. A mode change from Home Assistant does the same: the integration learns the values of each mode from what the zones report, and sends them when you change the mode of the AC unit. A mode the integration has not seen yet keeps the values the zones have. + ## Sensors Created when the unit has the sensor. Nothing to enable. diff --git a/docs/protocol.md b/docs/protocol.md index 73f72007..0dd61069 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -104,6 +104,15 @@ A zone controller (seen: LE60-13/GH with a ME31-00/C13 WiFi module, firmware `36 - The full list of columns is a table in the WiFi module firmware. There is no column for the room temperature of a zone, in any released firmware, so it cannot be shown. - The status column limit measured by `probe_device_limits()` is 29. Requests far above the limit (about 40 columns and more) made the module reboot. +### Target temperatures per mode + +The wall panel remembers the target temperature of every zone per mode. When the mode is changed on the panel, it sets them again. A `Mod` change over WiFi does not: the zones keep the values of the old mode. `SetpointMemory` in `aiogree/setpoint_memory.py` keeps the same memory: + +- It learns from every poll of a zone. A zone reports its mode and its target temperature in one reply, so the two belong together. A value is stored when the zone reported the same mode on its poll before, so a poll in the middle of a mode change on the panel is not stored under the wrong mode. +- Before the climate entity of the ducted unit changes the mode, `snapshot()` reads the zones again and stores them under the old mode. After the change, `recall()` sends the stored values of the new mode. A mode with no stored values changes nothing. +- It stores the raw columns that hold the target temperature, as `GreeDevice.target_temperature_props` gives them, keyed by device MAC and mode: `{"": {"heat": {"StTem": 3, "StFahFlg": 0}}}`. Raw columns need no unit conversion. The bit is stored too, so a half degree or a °F value comes back exactly. Every device with a target temperature gives them, in the columns it uses, so the format also fits the `SetTem` and `TemRec` of a normal unit. Only zones are remembered today. +- `__init__.py` keeps the memory in a `Store` per config entry (`gree_custom..setpoints`). + ## MAC addresses MACs are written in lower case with no separators. Talking to a device needs two MACs: the device MAC (the unit to control) and the controller MAC (the unit that manages it). diff --git a/tests/test_setpoint_memory.py b/tests/test_setpoint_memory.py new file mode 100644 index 00000000..a0dabb4f --- /dev/null +++ b/tests/test_setpoint_memory.py @@ -0,0 +1,247 @@ +"""Tests for the target temperature remembered per mode. + +The wall panel of a zone controller recalls the target temperature of every +zone per mode when the mode is changed on the panel. A mode change over WiFi +does not, so `SetpointMemory` does it. See docs/protocol.md. +""" + +# pylint: disable=redefined-outer-name +# A test takes a fixture as an argument with the same name. That is the +# pytest pattern, not shadowing. + +from collections.abc import AsyncIterator + +from aiogree.api import GreeProp, OperationMode +from aiogree.device import GreeDevice +from aiogree.setpoint_memory import SetpointMemory +from aiogree.transport_udp import GreeUdpTransport +import pytest + +from .fakes.zone import FakeZoneController + +HEAT = 2 +COOL = 1 + + +@pytest.fixture +async def controller() -> AsyncIterator[FakeZoneController]: + """Start a fake zone controller with four zones.""" + fake = FakeZoneController() + await fake.start() + try: + yield fake + finally: + fake.close() + + +@pytest.fixture +async def transport( + controller: FakeZoneController, +) -> AsyncIterator[GreeUdpTransport]: + """One transport for all units of the controller, as Home Assistant does.""" + shared = GreeUdpTransport( + controller.host, controller.port, max_retries=1, timeout=0.3 + ) + try: + yield shared + finally: + await shared.disconnect() + + +async def bind( + controller: FakeZoneController, transport: GreeUdpTransport, mac: str +) -> GreeDevice: + """Bind one sub-unit of the controller.""" + device = GreeDevice(name=mac[-2:], mac_addr=mac) + await device.bind_with_transport( + local_controller_mac=controller.mac, local_transport=transport + ) + return device + + +@pytest.fixture +async def zones( + controller: FakeZoneController, transport: GreeUdpTransport +) -> list[GreeDevice]: + """Bind the four zones.""" + return [await bind(controller, transport, mac) for mac in controller.zone_macs] + + +def panel_mode( + controller: FakeZoneController, mode: int, temperatures: list[int] +) -> None: + """Change the mode on the wall panel. The panel sets its stored temperatures.""" + for unit in controller.units.values(): + unit["Mod"] = mode + for zone_mac, temperature in zip(controller.zone_macs, temperatures, strict=True): + controller.units[zone_mac]["StTem"] = temperature - 16 + + +def set_on_panel(controller: FakeZoneController, temperatures: list[int]) -> None: + """Change the target temperatures on the wall panel, in the current mode.""" + for zone_mac, temperature in zip(controller.zone_macs, temperatures, strict=True): + controller.units[zone_mac]["StTem"] = temperature - 16 + + +async def poll(memory: SetpointMemory, devices: list[GreeDevice]) -> None: + """One poll of every device, as the coordinators do.""" + for device in devices: + await device.fetch_device_status() + memory.learn(device) + + +def remembered( + memory: SetpointMemory, zones: list[GreeDevice], mode: OperationMode +) -> list[int | None]: + """Return what the memory has for each zone in one mode, in degrees Celsius.""" + out: list[int | None] = [] + for zone in zones: + raw = memory.stored(zone.mac_address, mode).get(GreeProp.TARGET_TEMPERATURE_2) + out.append(None if raw is None else raw + 16) + return out + + +def temperatures(controller: FakeZoneController) -> list[int]: + """Return the target temperatures the controller has now.""" + return [controller.units[z]["StTem"] + 16 for z in controller.zone_macs] + + +async def test_a_value_is_stored_once_the_mode_is_seen_twice( + zones: list[GreeDevice], +) -> None: + """The first poll after start only notes the mode.""" + changes: list[int] = [] + memory = SetpointMemory(on_change=lambda: changes.append(1)) + + await poll(memory, zones) + assert memory.data == {} + + await poll(memory, zones) + assert remembered(memory, zones, OperationMode.fan) == [18, 18, 18, 18] + assert changes + + +async def test_the_raw_columns_are_stored_per_device( + controller: FakeZoneController, zones: list[GreeDevice] +) -> None: + """Keyed by device and mode, with the raw column, so no unit conversion is needed.""" + memory = SetpointMemory() + await poll(memory, zones) + await poll(memory, zones) + + assert memory.data[controller.zone_macs[0]] == {"fan": {"StTem": 2, "StFahFlg": 0}} + + +async def test_a_unit_without_target_temperature_columns_is_ignored( + controller: FakeZoneController, transport: GreeUdpTransport +) -> None: + """The ducted unit has no target temperature, so there is nothing to remember.""" + ac_unit = await bind(controller, transport, controller.ac_unit) + memory = SetpointMemory() + + await poll(memory, [ac_unit]) + await poll(memory, [ac_unit]) + + assert memory.data == {} + + +async def test_a_mode_change_on_the_panel_is_stored_under_the_new_mode( + controller: FakeZoneController, zones: list[GreeDevice] +) -> None: + """The poll that first sees the new mode stores nothing, the next one does.""" + memory = SetpointMemory() + set_on_panel(controller, [19, 20, 18, 20]) + await poll(memory, zones) + await poll(memory, zones) + + panel_mode(controller, HEAT, [19, 18, 17, 20]) + await poll(memory, zones) + + assert remembered(memory, zones, OperationMode.heat) == [None] * 4 + + await poll(memory, zones) + + assert remembered(memory, zones, OperationMode.heat) == [19, 18, 17, 20] + assert remembered(memory, zones, OperationMode.fan) == [19, 20, 18, 20] + + +async def test_recall_sends_the_stored_values_of_the_new_mode( + controller: FakeZoneController, zones: list[GreeDevice] +) -> None: + """A mode change over WiFi keeps the old values. Recall puts the stored ones back.""" + memory = SetpointMemory( + { + controller.zone_macs[0]: {"heat": {"StTem": 3, "StFahFlg": 0}}, + controller.zone_macs[2]: {"heat": {"StTem": 1, "StFahFlg": 0}}, + } + ) + await poll(memory, zones) + + changed = await memory.recall(zones, OperationMode.heat) + + assert temperatures(controller) == [19, 18, 17, 18] + assert [zone.mac_address for zone in changed] == [ + controller.zone_macs[0], + controller.zone_macs[2], + ] + + +async def test_recall_of_a_mode_without_values_changes_nothing( + controller: FakeZoneController, zones: list[GreeDevice] +) -> None: + """Nothing is known about Dry yet, so the zones keep what they have.""" + memory = SetpointMemory() + await poll(memory, zones) + controller.reset_record() + + changed = await memory.recall(zones, OperationMode.dry) + + assert changed == [] + assert not any(pack.get("t") == "cmd" for pack in controller.packs) + + +async def test_a_fahrenheit_target_comes_back_with_its_bit( + controller: FakeZoneController, zones: list[GreeDevice] +) -> None: + """67 F is StTem 3 with StFahFlg 1. Without the bit, recall would give 66 F.""" + for values in controller.units.values(): + values["TemUnit"] = 1 + first = controller.units[controller.zone_macs[0]] + first.update({"StTem": 3, "StFahFlg": 1}) + memory = SetpointMemory() + await poll(memory, zones) + await poll(memory, zones) + + panel_mode(controller, HEAT, [19, 18, 18, 18]) + first["StFahFlg"] = 0 + await poll(memory, zones) + await memory.recall(zones, OperationMode.fan) + + assert (first["StTem"], first["StFahFlg"]) == (3, 1) + assert zones[0].target_temperature == 67 + + +async def test_snapshot_keeps_a_panel_change_made_since_the_last_poll( + controller: FakeZoneController, zones: list[GreeDevice] +) -> None: + """The value changed on the panel just before the switch is not lost.""" + memory = SetpointMemory() + await poll(memory, zones) + await poll(memory, zones) + + set_on_panel(controller, [22, 18, 18, 18]) + await memory.snapshot(zones, OperationMode.fan) + + assert remembered(memory, zones, OperationMode.fan) == [22, 18, 18, 18] + + +async def test_snapshot_does_not_store_values_of_another_mode( + controller: FakeZoneController, zones: list[GreeDevice] +) -> None: + """If the mode already changed on the panel, the values are not the old mode's.""" + memory = SetpointMemory() + panel_mode(controller, COOL, [24, 24, 24, 24]) + + await memory.snapshot(zones, OperationMode.fan) + + assert remembered(memory, zones, OperationMode.fan) == [None] * 4 From a7fee8fb17bbc9ad1c3260469f2b135f2da9c223 Mon Sep 17 00:00:00 2001 From: Twintop Date: Thu, 15 Oct 2026 00:03:29 +1100 Subject: [PATCH 2/9] Remember the target temperature per mode on every device that has one The zones of a zone controller remember their target temperature per mode, as the wall panel does. Standalone and VRF units can now do the same, as an opt-in device option, "Remember Target Temperature per Mode" (setpoint_memory, off by default). Suggested by @p-monteiro in #549. - GreeDevice.target_temperature_props already gives SetTem and TemRec for a standalone or VRF unit, because it uses the columns the unit answers. Raw columns are stored, so a unit set to Fahrenheit needs no conversion. - The unit learns from its own polls: mode and target come in one reply. - On a mode change from Home Assistant, SetpointMemory.apply() sets the stored target of the new mode without sending it, so it goes out in the same command as the mode. Nothing is recalled into Auto, where the unit ignores the target temperature. - The option is in the device options form for units with a target temperature, and in the YAML schema. Tested against fakes. This project has no standalone or VRF unit to try it on. --- custom_components/gree_custom/__init__.py | 31 ++++-- .../gree_custom/aiogree/setpoint_memory.py | 24 ++++- custom_components/gree_custom/climate.py | 18 +++- .../gree_custom/config_schema.py | 20 ++++ custom_components/gree_custom/const.py | 3 + custom_components/gree_custom/coordinator.py | 5 +- .../gree_custom/translations/en.json | 4 +- docs/architecture.md | 2 +- docs/config-entry.md | 1 + docs/configuration.md | 1 + docs/entities.md | 4 + docs/protocol.md | 3 +- manual-configuration.yaml | 1 + tests/test_setpoint_memory.py | 95 ++++++++++++++++++- 14 files changed, 192 insertions(+), 20 deletions(-) diff --git a/custom_components/gree_custom/__init__.py b/custom_components/gree_custom/__init__.py index 0ea0865f..9703bcee 100755 --- a/custom_components/gree_custom/__init__.py +++ b/custom_components/gree_custom/__init__.py @@ -28,7 +28,7 @@ from homeassistant.helpers.storage import Store from homeassistant.helpers.typing import ConfigType -from .aiogree.api import DeviceType +from .aiogree.api import DeviceType, GreeProp from .aiogree.cipher import EncryptionVersion from .aiogree.device import GreeDevice from .aiogree.errors import GreeConnectionError @@ -53,6 +53,7 @@ CONF_MAX_ONLINE_ATTEMPTS, CONF_PREFER_CLOUD, CONF_RESTORE_STATES, + CONF_SETPOINT_MEMORY, CONF_UID, CONFENTRY_ID_LOCAL_ONLY, DEFAULT_CONNECTION_MAX_ATTEMPTS, @@ -64,6 +65,7 @@ DEFAULT_PREFER_CLOUD, DEFAULT_RESTORE_STATES, DEFAULT_SCAN_INTERVAL, + DEFAULT_SETPOINT_MEMORY, DOMAIN, ENCRYPTION_VERSION_AUTO, TO_REDACT, @@ -347,16 +349,26 @@ async def _async_setup_setpoint_memory( entry: GreeConfigEntry, coordinators: dict[str, GreeCoordinator], ) -> None: - """Give the ducted unit of each zone controller the memory of its zones. + """Give the devices that remember their target temperature per mode the memory. - The memory keeps the target temperature of every zone per mode, so a mode - change from Home Assistant sets them as the wall panel does. It learns from - every poll of a zone. See aiogree/setpoint_memory.py. + The ducted unit of a zone controller gets it for its zones, so a mode + change from Home Assistant sets them as the wall panel does. A standalone + or VRF unit gets it for itself when its options ask for it. The memory + learns from every poll of those devices. See aiogree/setpoint_memory.py. """ zones = [ c for c in coordinators.values() if c.device.device_type is DeviceType.ZONE ] - if not zones: + units = [ + c + for c in coordinators.values() + if c.device.device_type in (DeviceType.AC_UNIT, DeviceType.VRF_UNIT) + and c.device.supports_property(GreeProp.TARGET_TEMPERATURE_1) + and c.device_config.get(CONF_DEVICE_OPTIONS, {}).get( + CONF_SETPOINT_MEMORY, DEFAULT_SETPOINT_MEMORY + ) + ] + if not zones and not units: return store: Store[SetpointMemoryData] = Store( @@ -369,11 +381,14 @@ async def _async_setup_setpoint_memory( ), ) - for zone in zones: + for learner in (*zones, *units): entry.async_on_unload( - zone.async_add_listener(partial(memory.learn, zone.device)) + learner.async_add_listener(partial(memory.learn, learner.device)) ) + for unit in units: + unit.setpoint_memory = memory + for coordinator in coordinators.values(): if coordinator.device.device_type is DeviceType.ZONE_CONTROLLER: coordinator.setpoint_memory = memory diff --git a/custom_components/gree_custom/aiogree/setpoint_memory.py b/custom_components/gree_custom/aiogree/setpoint_memory.py index 5f8eaee9..070c6d0a 100644 --- a/custom_components/gree_custom/aiogree/setpoint_memory.py +++ b/custom_components/gree_custom/aiogree/setpoint_memory.py @@ -15,8 +15,10 @@ not lost. After the change, `recall()` sends the stored values of the new mode. - What is stored are the raw columns that hold the target temperature, as - `GreeDevice.target_temperature_props` gives them, per device MAC and mode. - Today only zones give any. + `GreeDevice.target_temperature_props` gives them, per device MAC and mode: + `StTem` for a zone, `SetTem` and `TemRec` for a standalone or VRF unit. +- For a unit that remembers its own target, `apply()` sets the stored value + without sending it, so it can go out in the same command as the new mode. The memory does not store itself. The owner loads `data` and saves it when `on_change` is called. @@ -120,11 +122,9 @@ async def recall( """ changed: list[GreeDevice] = [] for device in devices: - stored = self.stored(device.mac_address, mode) - if not stored or stored == device.target_temperature_props: + if not self.apply(device, mode): continue - device.set_target_temperature_props(stored) try: await device.push_device_status() except GreeError: @@ -138,6 +138,20 @@ async def recall( return changed + def apply(self, device: GreeDevice, mode: OperationMode) -> bool: + """Set the stored target temperature of a mode on a device, without sending it. + + Returns: + True if the device got a new target temperature to send + + """ + stored = self.stored(device.mac_address, mode) + if not stored or stored == device.target_temperature_props: + return False + + device.set_target_temperature_props(stored) + return True + def _remember( self, device: GreeDevice, mode: OperationMode, props: Mapping[GreeProp, int] ) -> None: diff --git a/custom_components/gree_custom/climate.py b/custom_components/gree_custom/climate.py index 719838c8..870b594d 100755 --- a/custom_components/gree_custom/climate.py +++ b/custom_components/gree_custom/climate.py @@ -39,6 +39,7 @@ FanSpeed, GreeProp, HorizontalSwingMode, + OperationMode, VerticalSwingMode, ) from .aiogree.const import MAX_TEMP_C, MAX_TEMP_F, MIN_TEMP_C, MIN_TEMP_F @@ -668,10 +669,25 @@ async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: else None ) zones = [z.device for z in self.coordinator.zone_coordinators] + # A standalone or VRF unit with the option remembers its own + # target. In Auto it ignores the target, so nothing goes there. + for_itself = self.device.device_type in ( + DeviceType.AC_UNIT, + DeviceType.VRF_UNIT, + ) if memory is not None: - await memory.snapshot(zones, old_mode) + await memory.snapshot( + [*zones, self.device] if for_itself else zones, old_mode + ) self.device.set_operation_mode(new_mode) + if ( + memory is not None + and for_itself + and new_mode is not OperationMode.auto + ): + # Goes out in the same command as the mode, below. + memory.apply(self.device, new_mode) # The Auto X-FAN enables that feature if the device is set to a hvac mode that supports X-FAN if self.coordinator.feature_auto_xfan: diff --git a/custom_components/gree_custom/config_schema.py b/custom_components/gree_custom/config_schema.py index fccd014a..aa5e5ec0 100644 --- a/custom_components/gree_custom/config_schema.py +++ b/custom_components/gree_custom/config_schema.py @@ -74,6 +74,7 @@ CONF_MAX_ONLINE_ATTEMPTS, CONF_PREFER_CLOUD, CONF_RESTORE_STATES, + CONF_SETPOINT_MEMORY, CONF_SWING_HORIZONTAL_MODES, CONF_SWING_MODES, CONF_TEMPERATURE_STEP, @@ -90,6 +91,7 @@ DEFAULT_PREFER_CLOUD, DEFAULT_RESTORE_STATES, DEFAULT_SCAN_INTERVAL, + DEFAULT_SETPOINT_MEMORY, DEFAULT_SWING_HORIZONTAL_MODES, DEFAULT_SWING_MODES, DEFAULT_TARGET_TEMP_STEP, @@ -246,6 +248,9 @@ def _target_temp_step(value: Any) -> float: probatio.Optional( CONF_RESTORE_STATES, default=DEFAULT_RESTORE_STATES ): cv.boolean, + probatio.Optional( + CONF_SETPOINT_MEMORY, default=DEFAULT_SETPOINT_MEMORY + ): cv.boolean, } ) @@ -793,4 +798,19 @@ def setup_device_options_schema( # noqa: C901 } ) + # Zones remember their target per mode anyway, like the wall panel. Other + # units with a target temperature can opt in. + if device.device_type in ( + DeviceType.AC_UNIT, + DeviceType.VRF_UNIT, + ) and device.supports_property(GreeProp.TARGET_TEMPERATURE_1): + schema.update( + { + probatio.Required( + CONF_SETPOINT_MEMORY, + default=defaults.get(CONF_SETPOINT_MEMORY, DEFAULT_SETPOINT_MEMORY), + ): cv.boolean, + } + ) + return probatio.Schema(schema) diff --git a/custom_components/gree_custom/const.py b/custom_components/gree_custom/const.py index 55e09559..7d2be7db 100755 --- a/custom_components/gree_custom/const.py +++ b/custom_components/gree_custom/const.py @@ -52,6 +52,8 @@ CONF_DISABLE_AVAILABLE_CHECK = "disable_available_check" CONF_MAX_ONLINE_ATTEMPTS = "max_online_attempts" CONF_RESTORE_STATES = "restore_states" +# Remember the target temperature per mode, for a unit that has one +CONF_SETPOINT_MEMORY = "setpoint_memory" CONF_DEVICES = "devices" CONF_HVAC_MODES = "hvac_modes" CONF_FAN_MODES = "fan_modes" @@ -67,6 +69,7 @@ DEFAULT_ENCRYPTION_KEY = "" DEFAULT_DISABLE_AVAILABLE_CHECK = False DEFAULT_RESTORE_STATES = True +DEFAULT_SETPOINT_MEMORY = False MIN_SCAN_INTERVAL = 5 DEFAULT_SCAN_INTERVAL = 60 DEFAULT_PREFER_CLOUD = False diff --git a/custom_components/gree_custom/coordinator.py b/custom_components/gree_custom/coordinator.py index 76d65d57..97c83936 100755 --- a/custom_components/gree_custom/coordinator.py +++ b/custom_components/gree_custom/coordinator.py @@ -61,8 +61,9 @@ def __init__( self._feature_auto_light: bool = False self._unsub_follow_up_refresh: CALLBACK_TYPE | None = None self._is_shut_down: bool = False - # Set on the ducted unit of a zone controller: the memory of the zone - # target temperatures per mode, and the zones of the same controller. + # The memory of the target temperatures per mode. Set on the ducted + # unit of a zone controller, with the zones of the same controller, and + # on a standalone or VRF unit that remembers its own target. self.setpoint_memory: SetpointMemory | None = None self.zone_coordinators: list[GreeCoordinator] = [] diff --git a/custom_components/gree_custom/translations/en.json b/custom_components/gree_custom/translations/en.json index 572a3fb5..454d118c 100644 --- a/custom_components/gree_custom/translations/en.json +++ b/custom_components/gree_custom/translations/en.json @@ -116,13 +116,15 @@ "target_temp_step": "Temperature Step", "external_temperature_sensor": "External Temperature Sensor", "external_humidity_sensor": "External Humidity Sensor", - "restore_states": "Restore Entities" + "restore_states": "Restore Entities", + "setpoint_memory": "Remember Target Temperature per Mode" }, "data_description": { "features": "On a zone of a zone controller, leave out Zone Switch if the zone must always stay open.", "external_temperature_sensor": "If set will replace the built-in HVAC temperature sensor for the Climate entity data", "external_humidity_sensor": "If set will replace the built-in HVAC humidity sensor for the Climate entity data", "restore_states": "If checked, when the integration is started the device will be overridden by previous states of the integration instead of using the current device state.", + "setpoint_memory": "If checked, the target temperature of each mode is remembered and set again when the mode is changed from Home Assistant. Not for Auto, where the unit uses its own setting.", "target_temp_step": "Sets the increment step for adjusting the target temperature. Fahrenheit degrees are clamped to the nearest integer." } }, diff --git a/docs/architecture.md b/docs/architecture.md index a56303ca..452deb2b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -20,7 +20,7 @@ No Home Assistant imports here. | `helpers.py` | Encrypt and decrypt packs, temperature math, `TempOffsetResolver`, `redact_str`, `chunked`. | | `const.py` | Protocol constants: `MAX_PACK_SIZE`, `MIN_PACK_PROPS`, `STATUS_CANARY_PROP`, `PROBE_TIMEOUT`, `STATUS_CANARY_PROP_MAX_REQUESTS`, temperature and humidity ranges. | | `errors.py` | Exceptions. `GreeConnectionError` means no answer. `GreeProtocolError` means a bad answer. `GreeBindingError` means the key exchange failed. | -| `setpoint_memory.py` | `SetpointMemory`. The target temperature of a device per mode, stored as raw columns per device MAC. Used for the zones of a zone controller, so a mode change works like one on the wall panel. See [protocol.md](protocol.md#target-temperatures-per-mode). | +| `setpoint_memory.py` | `SetpointMemory`. The target temperature of a device per mode, stored as raw columns per device MAC. Used for the zones of a zone controller, so a mode change works like one on the wall panel, and for a standalone or VRF unit with the `setpoint_memory` option. See [protocol.md](protocol.md#target-temperatures-per-mode). | ## Home Assistant layer diff --git a/docs/config-entry.md b/docs/config-entry.md index 6c10df85..47145cb6 100644 --- a/docs/config-entry.md +++ b/docs/config-entry.md @@ -53,6 +53,7 @@ For a cloud entry, `cloud` holds the account email, region, user id and token. T | `options.name` | Device name in Home Assistant. Defaults to the name the unit reports, which is usually the tail of its MAC. | | `options.features` | Which optional switches to create. Only features the unit reported as supported are offered. | | `options.restore_states` | Restore the last known entity states after a restart. | +| `options.setpoint_memory` | Remember the target temperature per mode for a standalone or VRF unit. Off by default. | ## YAML import diff --git a/docs/configuration.md b/docs/configuration.md index f2f19bc5..9e30d017 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -98,6 +98,7 @@ One page per device. Gree devices do not report reliably which features they hav | External Temperature Sensor | none | A Home Assistant sensor that replaces the unit's own room temperature in the climate entity. | | External Humidity Sensor | none | A Home Assistant sensor that replaces the unit's own humidity in the climate entity. | | Restore Entities | on | After a restart, send the last known Home Assistant state to the device instead of taking over the device state. See [Restoring state](entities.md#restoring-state-after-a-restart). | +| Remember Target Temperature per Mode | off | Remember the target temperature of each mode, and set it again when you change the mode from Home Assistant. Not for Auto, where the unit uses its own setting. Only shown for a unit with a target temperature. The zones of a zone controller always do this. | The external sensors only change what the climate entity shows. The unit keeps using its own sensor to regulate. diff --git a/docs/entities.md b/docs/entities.md index 9e9aa514..041ee526 100644 --- a/docs/entities.md +++ b/docs/entities.md @@ -26,6 +26,10 @@ The main entity. Its name is the device name. Extra attribute: `current_outside_temperature`, the outdoor sensor value in the unit's temperature scale, when the unit has an outdoor sensor. Read it with `{{ state_attr('climate.your_ac', 'current_outside_temperature') }}`. +### Target temperature per mode + +With the option **Remember Target Temperature per Mode** on, the climate entity remembers the target temperature of each mode. When you change the mode from Home Assistant, it sets the remembered target of the new mode in the same command. It learns from what the unit reports, so a change made with the remote is remembered too. A mode it has not seen yet keeps the current target. Auto is left out, because the unit uses its own setting there. The option is off by default. + ### Turbo and Quiet Turbo and Quiet are not fan speeds on the unit but separate features. The integration shows them as fan modes because that is how the remote presents them. diff --git a/docs/protocol.md b/docs/protocol.md index 0dd61069..98a5dfec 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -110,7 +110,8 @@ The wall panel remembers the target temperature of every zone per mode. When the - It learns from every poll of a zone. A zone reports its mode and its target temperature in one reply, so the two belong together. A value is stored when the zone reported the same mode on its poll before, so a poll in the middle of a mode change on the panel is not stored under the wrong mode. - Before the climate entity of the ducted unit changes the mode, `snapshot()` reads the zones again and stores them under the old mode. After the change, `recall()` sends the stored values of the new mode. A mode with no stored values changes nothing. -- It stores the raw columns that hold the target temperature, as `GreeDevice.target_temperature_props` gives them, keyed by device MAC and mode: `{"": {"heat": {"StTem": 3, "StFahFlg": 0}}}`. Raw columns need no unit conversion. The bit is stored too, so a half degree or a °F value comes back exactly. Every device with a target temperature gives them, in the columns it uses, so the format also fits the `SetTem` and `TemRec` of a normal unit. Only zones are remembered today. +- It stores the raw columns that hold the target temperature, as `GreeDevice.target_temperature_props` gives them, keyed by device MAC and mode: `{"": {"heat": {"StTem": 3, "StFahFlg": 0}}}`. Raw columns need no unit conversion. They are the columns the device uses: a zone stores `StTem` and its bit `StFahFlg`, so a half degree or a °F value comes back exactly. A standalone or VRF unit stores `SetTem` and `TemRec`. +- A standalone or VRF unit can use the same memory for itself, with the device option `setpoint_memory`. It stores `SetTem` and `TemRec`, so a unit set to Fahrenheit needs no conversion. On a mode change from Home Assistant, `apply()` sets the stored target without sending it, and it goes out in the same command as the new mode. Nothing is recalled into Auto, where the unit ignores the target temperature. - `__init__.py` keeps the memory in a `Store` per config entry (`gree_custom..setpoints`). ## MAC addresses diff --git a/manual-configuration.yaml b/manual-configuration.yaml index 0755d237..c934dd36 100644 --- a/manual-configuration.yaml +++ b/manual-configuration.yaml @@ -117,3 +117,4 @@ gree_custom: external_temperature_sensor: "sensor.living_room_temperature" # Sets a given temperature sensor as the sensor for the AC | str (Entity ID) | omit the key to not use one external_humidity_sensor: "sensor.living_room_humidity" # Sets a given humidity sensor as the sensor for the AC | str (Entity ID) | omit the key to not use one restore_states: true # Wether to restore the last HA state to device when HA starts | bool | default = true + setpoint_memory: false # Remember the target temperature per mode and set it again on a mode change from Home Assistant, not for Auto | bool | default = false diff --git a/tests/test_setpoint_memory.py b/tests/test_setpoint_memory.py index a0dabb4f..31d8b16c 100644 --- a/tests/test_setpoint_memory.py +++ b/tests/test_setpoint_memory.py @@ -11,12 +11,13 @@ from collections.abc import AsyncIterator -from aiogree.api import GreeProp, OperationMode +from aiogree.api import DeviceType, GreeProp, OperationMode from aiogree.device import GreeDevice from aiogree.setpoint_memory import SetpointMemory from aiogree.transport_udp import GreeUdpTransport import pytest +from .fakes.device import FakeGreeDevice from .fakes.zone import FakeZoneController HEAT = 2 @@ -245,3 +246,95 @@ async def test_snapshot_does_not_store_values_of_another_mode( await memory.snapshot(zones, OperationMode.fan) assert remembered(memory, zones, OperationMode.fan) == [None] * 4 + + +# +# A standalone unit that remembers its own target +# + + +@pytest.fixture +async def unit() -> AsyncIterator[tuple[FakeGreeDevice, GreeDevice]]: + """Bind a standalone unit that is in Cool at 24 degrees.""" + fake = FakeGreeDevice() + fake.values.update({"Pow": 1, "Mod": 1, "SetTem": 24, "TemRec": 0, "TemUn": 0}) + await fake.start() + transport = GreeUdpTransport(fake.host, fake.port, max_retries=1, timeout=0.3) + device = GreeDevice(name="Zolderkamer", mac_addr=fake.mac) + await device.bind_with_transport( + local_controller_mac=fake.mac, local_transport=transport + ) + try: + yield fake, device + finally: + await transport.disconnect() + fake.close() + + +async def test_a_standalone_unit_gives_set_tem_and_tem_rec( + unit: tuple[FakeGreeDevice, GreeDevice], +) -> None: + """SetTem holds the degrees and TemRec the half degree.""" + _, device = unit + + assert device.device_type is DeviceType.AC_UNIT + assert device.target_temperature_props == { + GreeProp.TARGET_TEMPERATURE_1: 24, + GreeProp.TARGET_TEMPERATURE_BIT_1: 0, + } + + +async def test_a_unit_learns_its_target_and_sends_it_with_the_mode( + unit: tuple[FakeGreeDevice, GreeDevice], +) -> None: + """The stored target of the new mode goes out in the same command as the mode.""" + fake, device = unit + memory = SetpointMemory() + await poll(memory, [device]) + await poll(memory, [device]) + fake.values.update({"Mod": 4, "SetTem": 20}) + await poll(memory, [device]) + await poll(memory, [device]) + + assert memory.data[fake.mac] == { + "cool": {"SetTem": 24, "TemRec": 0}, + "heat": {"SetTem": 20, "TemRec": 0}, + } + + device.set_operation_mode(OperationMode.cool) + assert memory.apply(device, OperationMode.cool) + fake.reset_record() + await device.push_device_status() + + commands = [pack for pack in fake.packs if pack.get("t") == "cmd"] + assert len(commands) == 1 + assert {"Mod", "SetTem"} <= set(commands[0]["opt"]) + assert (fake.values["Mod"], fake.values["SetTem"]) == (1, 24) + + +async def test_a_fahrenheit_target_is_stored_raw( + unit: tuple[FakeGreeDevice, GreeDevice], +) -> None: + """The raw columns already hold the Fahrenheit value, so nothing is converted.""" + fake, device = unit + fake.values.update({"TemUn": 1, "SetTem": 24, "TemRec": 1}) + memory = SetpointMemory() + + await poll(memory, [device]) + await poll(memory, [device]) + + assert memory.data[fake.mac] == {"cool": {"SetTem": 24, "TemRec": 1}} + + +async def test_apply_without_a_stored_target_changes_nothing( + unit: tuple[FakeGreeDevice, GreeDevice], +) -> None: + """Nothing is known about Heat, so the unit keeps its target.""" + fake, device = unit + memory = SetpointMemory() + + assert not memory.apply(device, OperationMode.heat) + fake.reset_record() + await device.push_device_status() + + assert not any(pack.get("t") == "cmd" for pack in fake.packs) From f759b41713e500b70ab703fd0f7047e77649f663 Mon Sep 17 00:00:00 2001 From: Twintop Date: Thu, 15 Oct 2026 00:07:59 +1100 Subject: [PATCH 3/9] Setpoint memory: an option for every device, on by default Asked in review: one PR for the memory of every device, and the memory as a device option that is on by default. - setpoint_memory is offered for every device with a target temperature, zones included, and is on by default. The ducted unit of a zone controller has no target of its own, so it gets no option; it recalls the zones that have it on. GreeDevice.has_target_temperature says which devices have one. - Zones always had the memory before. A zone with the option off is now left out of the learning, and of the recall on a mode change. - As asked as well, and already so: the raw columns are stored, so a value comes back right also when the unit was switched between the modes (a new test has 18.5 C come back as 65 F), and a mode without a stored value keeps the current target. The docs, the option text and the YAML example say it is on by default. --- custom_components/gree_custom/__init__.py | 44 ++++++++++--------- .../gree_custom/aiogree/device.py | 8 ++++ .../gree_custom/config_schema.py | 9 ++-- custom_components/gree_custom/const.py | 4 +- .../gree_custom/translations/en.json | 2 +- docs/architecture.md | 2 +- docs/config-entry.md | 2 +- docs/configuration.md | 2 +- docs/entities.md | 4 +- docs/protocol.md | 2 +- manual-configuration.yaml | 2 +- tests/test_setpoint_memory.py | 27 ++++++++++++ 12 files changed, 72 insertions(+), 36 deletions(-) diff --git a/custom_components/gree_custom/__init__.py b/custom_components/gree_custom/__init__.py index 9703bcee..dd6ba9e7 100755 --- a/custom_components/gree_custom/__init__.py +++ b/custom_components/gree_custom/__init__.py @@ -28,7 +28,7 @@ from homeassistant.helpers.storage import Store from homeassistant.helpers.typing import ConfigType -from .aiogree.api import DeviceType, GreeProp +from .aiogree.api import DeviceType from .aiogree.cipher import EncryptionVersion from .aiogree.device import GreeDevice from .aiogree.errors import GreeConnectionError @@ -351,26 +351,27 @@ async def _async_setup_setpoint_memory( ) -> None: """Give the devices that remember their target temperature per mode the memory. - The ducted unit of a zone controller gets it for its zones, so a mode - change from Home Assistant sets them as the wall panel does. A standalone - or VRF unit gets it for itself when its options ask for it. The memory - learns from every poll of those devices. See aiogree/setpoint_memory.py. + Every device with a target temperature does, unless its setpoint_memory + option is off. A standalone or VRF unit gets the memory for itself. The + zones of a zone controller follow the mode of their ducted unit, so the + ducted unit gets it for them, and a mode change from Home Assistant sets + them as the wall panel does. The memory learns from every poll of those + devices. See aiogree/setpoint_memory.py. """ - zones = [ - c for c in coordinators.values() if c.device.device_type is DeviceType.ZONE - ] - units = [ + learners = [ c for c in coordinators.values() - if c.device.device_type in (DeviceType.AC_UNIT, DeviceType.VRF_UNIT) - and c.device.supports_property(GreeProp.TARGET_TEMPERATURE_1) + if c.device.has_target_temperature and c.device_config.get(CONF_DEVICE_OPTIONS, {}).get( CONF_SETPOINT_MEMORY, DEFAULT_SETPOINT_MEMORY ) ] - if not zones and not units: + if not learners: return + zones = [c for c in learners if c.device.device_type is DeviceType.ZONE] + units = [c for c in learners if c.device.device_type is not DeviceType.ZONE] + store: Store[SetpointMemoryData] = Store( hass, SETPOINT_MEMORY_STORAGE_VERSION, f"{DOMAIN}.{entry.entry_id}.setpoints" ) @@ -381,7 +382,7 @@ async def _async_setup_setpoint_memory( ), ) - for learner in (*zones, *units): + for learner in learners: entry.async_on_unload( learner.async_add_listener(partial(memory.learn, learner.device)) ) @@ -390,14 +391,17 @@ async def _async_setup_setpoint_memory( unit.setpoint_memory = memory for coordinator in coordinators.values(): - if coordinator.device.device_type is DeviceType.ZONE_CONTROLLER: + if coordinator.device.device_type is not DeviceType.ZONE_CONTROLLER: + continue + own_zones = [ + zone + for zone in zones + if zone.device.mac_address_controller + == coordinator.device.mac_address_controller + ] + if own_zones: coordinator.setpoint_memory = memory - coordinator.zone_coordinators = [ - zone - for zone in zones - if zone.device.mac_address_controller - == coordinator.device.mac_address_controller - ] + coordinator.zone_coordinators = own_zones async def async_unload_entry(hass: HomeAssistant, entry: GreeConfigEntry) -> bool: diff --git a/custom_components/gree_custom/aiogree/device.py b/custom_components/gree_custom/aiogree/device.py index 43e6f0fd..184aeb04 100755 --- a/custom_components/gree_custom/aiogree/device.py +++ b/custom_components/gree_custom/aiogree/device.py @@ -899,6 +899,14 @@ def set_target_temperature_unit(self, units: TemperatureUnits) -> None: return self._state.set(self._temp_unit_prop, units) + @property + def has_target_temperature(self) -> bool: + """Return True if the device answers a target temperature column. + + The ducted unit of a zone controller has none, its zones have one each. + """ + return self._target_temp_prop is not None + @property def has_target_temperature_bit(self) -> bool: """Return True if the device answers a bit for the target temperature. diff --git a/custom_components/gree_custom/config_schema.py b/custom_components/gree_custom/config_schema.py index aa5e5ec0..6ca3fbe5 100644 --- a/custom_components/gree_custom/config_schema.py +++ b/custom_components/gree_custom/config_schema.py @@ -798,12 +798,9 @@ def setup_device_options_schema( # noqa: C901 } ) - # Zones remember their target per mode anyway, like the wall panel. Other - # units with a target temperature can opt in. - if device.device_type in ( - DeviceType.AC_UNIT, - DeviceType.VRF_UNIT, - ) and device.supports_property(GreeProp.TARGET_TEMPERATURE_1): + # Every device with a target temperature can remember it per mode. A zone + # follows the mode of its ducted unit, which has no target of its own. + if device.has_target_temperature: schema.update( { probatio.Required( diff --git a/custom_components/gree_custom/const.py b/custom_components/gree_custom/const.py index 7d2be7db..6c1a73c0 100755 --- a/custom_components/gree_custom/const.py +++ b/custom_components/gree_custom/const.py @@ -52,7 +52,7 @@ CONF_DISABLE_AVAILABLE_CHECK = "disable_available_check" CONF_MAX_ONLINE_ATTEMPTS = "max_online_attempts" CONF_RESTORE_STATES = "restore_states" -# Remember the target temperature per mode, for a unit that has one +# Remember the target temperature per mode, for a device that has one CONF_SETPOINT_MEMORY = "setpoint_memory" CONF_DEVICES = "devices" CONF_HVAC_MODES = "hvac_modes" @@ -69,7 +69,7 @@ DEFAULT_ENCRYPTION_KEY = "" DEFAULT_DISABLE_AVAILABLE_CHECK = False DEFAULT_RESTORE_STATES = True -DEFAULT_SETPOINT_MEMORY = False +DEFAULT_SETPOINT_MEMORY = True MIN_SCAN_INTERVAL = 5 DEFAULT_SCAN_INTERVAL = 60 DEFAULT_PREFER_CLOUD = False diff --git a/custom_components/gree_custom/translations/en.json b/custom_components/gree_custom/translations/en.json index 454d118c..03bfdd45 100644 --- a/custom_components/gree_custom/translations/en.json +++ b/custom_components/gree_custom/translations/en.json @@ -124,7 +124,7 @@ "external_temperature_sensor": "If set will replace the built-in HVAC temperature sensor for the Climate entity data", "external_humidity_sensor": "If set will replace the built-in HVAC humidity sensor for the Climate entity data", "restore_states": "If checked, when the integration is started the device will be overridden by previous states of the integration instead of using the current device state.", - "setpoint_memory": "If checked, the target temperature of each mode is remembered and set again when the mode is changed from Home Assistant. Not for Auto, where the unit uses its own setting.", + "setpoint_memory": "If checked, the target temperature of each mode is remembered and set again when the mode is changed from Home Assistant. A zone follows the mode of its AC unit. A unit keeps its own setting in Auto.", "target_temp_step": "Sets the increment step for adjusting the target temperature. Fahrenheit degrees are clamped to the nearest integer." } }, diff --git a/docs/architecture.md b/docs/architecture.md index 452deb2b..64ae8e85 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -20,7 +20,7 @@ No Home Assistant imports here. | `helpers.py` | Encrypt and decrypt packs, temperature math, `TempOffsetResolver`, `redact_str`, `chunked`. | | `const.py` | Protocol constants: `MAX_PACK_SIZE`, `MIN_PACK_PROPS`, `STATUS_CANARY_PROP`, `PROBE_TIMEOUT`, `STATUS_CANARY_PROP_MAX_REQUESTS`, temperature and humidity ranges. | | `errors.py` | Exceptions. `GreeConnectionError` means no answer. `GreeProtocolError` means a bad answer. `GreeBindingError` means the key exchange failed. | -| `setpoint_memory.py` | `SetpointMemory`. The target temperature of a device per mode, stored as raw columns per device MAC. Used for the zones of a zone controller, so a mode change works like one on the wall panel, and for a standalone or VRF unit with the `setpoint_memory` option. See [protocol.md](protocol.md#target-temperatures-per-mode). | +| `setpoint_memory.py` | `SetpointMemory`. The target temperature of a device per mode, stored as raw columns per device MAC. Used for every device with a target temperature, unless its `setpoint_memory` option is off: for the zones of a zone controller, so a mode change works like one on the wall panel, and for a standalone or VRF unit itself. See [protocol.md](protocol.md#target-temperatures-per-mode). | ## Home Assistant layer diff --git a/docs/config-entry.md b/docs/config-entry.md index 47145cb6..0d97af42 100644 --- a/docs/config-entry.md +++ b/docs/config-entry.md @@ -53,7 +53,7 @@ For a cloud entry, `cloud` holds the account email, region, user id and token. T | `options.name` | Device name in Home Assistant. Defaults to the name the unit reports, which is usually the tail of its MAC. | | `options.features` | Which optional switches to create. Only features the unit reported as supported are offered. | | `options.restore_states` | Restore the last known entity states after a restart. | -| `options.setpoint_memory` | Remember the target temperature per mode for a standalone or VRF unit. Off by default. | +| `options.setpoint_memory` | Remember the target temperature per mode, for a device with a target temperature. On by default. | ## YAML import diff --git a/docs/configuration.md b/docs/configuration.md index 9e30d017..805ebb7c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -98,7 +98,7 @@ One page per device. Gree devices do not report reliably which features they hav | External Temperature Sensor | none | A Home Assistant sensor that replaces the unit's own room temperature in the climate entity. | | External Humidity Sensor | none | A Home Assistant sensor that replaces the unit's own humidity in the climate entity. | | Restore Entities | on | After a restart, send the last known Home Assistant state to the device instead of taking over the device state. See [Restoring state](entities.md#restoring-state-after-a-restart). | -| Remember Target Temperature per Mode | off | Remember the target temperature of each mode, and set it again when you change the mode from Home Assistant. Not for Auto, where the unit uses its own setting. Only shown for a unit with a target temperature. The zones of a zone controller always do this. | +| Remember Target Temperature per Mode | on | Remember the target temperature of each mode, and set it again when you change the mode from Home Assistant. A zone follows the mode of its AC unit. A unit is left alone in Auto, where it uses its own setting. Only shown for a device with a target temperature. | The external sensors only change what the climate entity shows. The unit keeps using its own sensor to regulate. diff --git a/docs/entities.md b/docs/entities.md index 041ee526..d418e78c 100644 --- a/docs/entities.md +++ b/docs/entities.md @@ -28,7 +28,7 @@ Extra attribute: `current_outside_temperature`, the outdoor sensor value in the ### Target temperature per mode -With the option **Remember Target Temperature per Mode** on, the climate entity remembers the target temperature of each mode. When you change the mode from Home Assistant, it sets the remembered target of the new mode in the same command. It learns from what the unit reports, so a change made with the remote is remembered too. A mode it has not seen yet keeps the current target. Auto is left out, because the unit uses its own setting there. The option is off by default. +With the option **Remember Target Temperature per Mode** on, the climate entity remembers the target temperature of each mode. When you change the mode from Home Assistant, it sets the remembered target of the new mode in the same command. It learns from what the unit reports, so a change made with the remote is remembered too. A mode it has not seen yet keeps the current target. Auto is left out, because the unit uses its own setting there. The option is on by default. ### Turbo and Quiet @@ -57,7 +57,7 @@ A zone controller is controlled locally. Add it with local discovery, or with bo | Switch with the name of the zone | Opens and closes the zone. It is the **Zone Switch** feature, so you can leave it out. Do that for a zone that must always stay open: turning such a zone off is refused by the controller or turns the whole system off. | | Target Temperature | The target temperature of the zone, in the unit of the controller: 16 to 30 °C in half degrees, or 61 to 86 °F in whole degrees. Home Assistant shows it in your own unit. The wall panel shows only whole degrees in °C, so it shows 18 for 18.5. | -The wall panel remembers the target temperature of every zone for each mode, and sets them again when you change the mode on the panel. A mode change from Home Assistant does the same: the integration learns the values of each mode from what the zones report, and sends them when you change the mode of the AC unit. A mode the integration has not seen yet keeps the values the zones have. +The wall panel remembers the target temperature of every zone for each mode, and sets them again when you change the mode on the panel. A mode change from Home Assistant does the same: the integration learns the values of each mode from what the zones report, and sends them when you change the mode of the AC unit. A mode the integration has not seen yet keeps the values the zones have. To leave a zone out, turn off **Remember Target Temperature per Mode** in the options of that zone. ## Sensors diff --git a/docs/protocol.md b/docs/protocol.md index 98a5dfec..06006081 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -111,7 +111,7 @@ The wall panel remembers the target temperature of every zone per mode. When the - It learns from every poll of a zone. A zone reports its mode and its target temperature in one reply, so the two belong together. A value is stored when the zone reported the same mode on its poll before, so a poll in the middle of a mode change on the panel is not stored under the wrong mode. - Before the climate entity of the ducted unit changes the mode, `snapshot()` reads the zones again and stores them under the old mode. After the change, `recall()` sends the stored values of the new mode. A mode with no stored values changes nothing. - It stores the raw columns that hold the target temperature, as `GreeDevice.target_temperature_props` gives them, keyed by device MAC and mode: `{"": {"heat": {"StTem": 3, "StFahFlg": 0}}}`. Raw columns need no unit conversion. They are the columns the device uses: a zone stores `StTem` and its bit `StFahFlg`, so a half degree or a °F value comes back exactly. A standalone or VRF unit stores `SetTem` and `TemRec`. -- A standalone or VRF unit can use the same memory for itself, with the device option `setpoint_memory`. It stores `SetTem` and `TemRec`, so a unit set to Fahrenheit needs no conversion. On a mode change from Home Assistant, `apply()` sets the stored target without sending it, and it goes out in the same command as the new mode. Nothing is recalled into Auto, where the unit ignores the target temperature. +- A standalone or VRF unit uses the same memory for itself. The device option `setpoint_memory`, on by default, turns the memory off for one device, a zone included. It stores `SetTem` and `TemRec`, so a unit set to Fahrenheit needs no conversion. On a mode change from Home Assistant, `apply()` sets the stored target without sending it, and it goes out in the same command as the new mode. Nothing is recalled into Auto, where the unit ignores the target temperature. - `__init__.py` keeps the memory in a `Store` per config entry (`gree_custom..setpoints`). ## MAC addresses diff --git a/manual-configuration.yaml b/manual-configuration.yaml index c934dd36..b2fd6f8b 100644 --- a/manual-configuration.yaml +++ b/manual-configuration.yaml @@ -117,4 +117,4 @@ gree_custom: external_temperature_sensor: "sensor.living_room_temperature" # Sets a given temperature sensor as the sensor for the AC | str (Entity ID) | omit the key to not use one external_humidity_sensor: "sensor.living_room_humidity" # Sets a given humidity sensor as the sensor for the AC | str (Entity ID) | omit the key to not use one restore_states: true # Wether to restore the last HA state to device when HA starts | bool | default = true - setpoint_memory: false # Remember the target temperature per mode and set it again on a mode change from Home Assistant, not for Auto | bool | default = false + setpoint_memory: true # Remember the target temperature per mode and set it again on a mode change from Home Assistant, not for Auto | bool | default = true diff --git a/tests/test_setpoint_memory.py b/tests/test_setpoint_memory.py index 31d8b16c..d4f5c491 100644 --- a/tests/test_setpoint_memory.py +++ b/tests/test_setpoint_memory.py @@ -222,6 +222,33 @@ async def test_a_fahrenheit_target_comes_back_with_its_bit( assert zones[0].target_temperature == 67 +async def test_a_value_from_celsius_comes_back_right_in_fahrenheit( + controller: FakeZoneController, zones: list[GreeDevice] +) -> None: + """The raw columns are the same in both units. + + 18.5 C is remembered as StTem 2 with the bit. After the unit is switched + to Fahrenheit between the modes, the same columns read as 65 F. + """ + first = controller.units[controller.zone_macs[0]] + first.update({"StTem": 2, "StFahFlg": 1}) + memory = SetpointMemory() + await poll(memory, zones) + await poll(memory, zones) + assert zones[0].target_temperature == 18.5 + + panel_mode(controller, HEAT, [21, 18, 18, 18]) + first["StFahFlg"] = 0 + for values in controller.units.values(): + values["TemUnit"] = 1 + await poll(memory, zones) + await memory.recall(zones, OperationMode.fan) + + assert (first["StTem"], first["StFahFlg"]) == (2, 1) + await zones[0].fetch_device_status() + assert zones[0].target_temperature == 65 + + async def test_snapshot_keeps_a_panel_change_made_since_the_last_poll( controller: FakeZoneController, zones: list[GreeDevice] ) -> None: From 4edcfaac03b51a5175db7ba6b6ace7bac0220d08 Mon Sep 17 00:00:00 2001 From: Twintop Date: Sat, 31 Oct 2026 16:32:07 +1100 Subject: [PATCH 4/9] Remove the setpoint memory with its config entry The memory of a removed config entry stayed in .storage. It is now removed in async_remove_entry. The memory is also saved when the entry unloads: a delayed save still pending at that point would write the file again after the removal. The module docstring now says a zone stores StFahFlg as well as StTem. --- custom_components/gree_custom/__init__.py | 25 ++++++++++++++++--- .../gree_custom/aiogree/setpoint_memory.py | 3 ++- docs/protocol.md | 2 +- 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/custom_components/gree_custom/__init__.py b/custom_components/gree_custom/__init__.py index dd6ba9e7..74a02a25 100755 --- a/custom_components/gree_custom/__init__.py +++ b/custom_components/gree_custom/__init__.py @@ -372,15 +372,16 @@ async def _async_setup_setpoint_memory( zones = [c for c in learners if c.device.device_type is DeviceType.ZONE] units = [c for c in learners if c.device.device_type is not DeviceType.ZONE] - store: Store[SetpointMemoryData] = Store( - hass, SETPOINT_MEMORY_STORAGE_VERSION, f"{DOMAIN}.{entry.entry_id}.setpoints" - ) + store = _setpoint_memory_store(hass, entry.entry_id) memory = SetpointMemory( await store.async_load(), on_change=lambda: store.async_delay_save( lambda: memory.data, SETPOINT_MEMORY_SAVE_DELAY ), ) + # Save on unload rather than after the delay. A delayed save would still + # run after the entry is removed, and write the file again. + entry.async_on_unload(lambda: store.async_save(memory.data)) for learner in learners: entry.async_on_unload( @@ -404,6 +405,15 @@ async def _async_setup_setpoint_memory( coordinator.zone_coordinators = own_zones +def _setpoint_memory_store( + hass: HomeAssistant, entry_id: str +) -> Store[SetpointMemoryData]: + """Return the store that keeps the setpoint memory of a config entry.""" + return Store( + hass, SETPOINT_MEMORY_STORAGE_VERSION, f"{DOMAIN}.{entry_id}.setpoints" + ) + + async def async_unload_entry(hass: HomeAssistant, entry: GreeConfigEntry) -> bool: """Unload a config entry and close its connections. @@ -430,6 +440,15 @@ async def async_unload_entry(hass: HomeAssistant, entry: GreeConfigEntry) -> boo return True +async def async_remove_entry(hass: HomeAssistant, entry: GreeConfigEntry) -> None: + """Remove the setpoint memory of a removed config entry. + + Home Assistant unloads the entry first, and the unload saves the memory, so + nothing writes the file again after this. + """ + await _setpoint_memory_store(hass, entry.entry_id).async_remove() + + async def async_remove_config_entry_device( hass: HomeAssistant, config_entry: GreeConfigEntry, device_entry: dr.DeviceEntry ) -> bool: diff --git a/custom_components/gree_custom/aiogree/setpoint_memory.py b/custom_components/gree_custom/aiogree/setpoint_memory.py index 070c6d0a..b64f8bb2 100644 --- a/custom_components/gree_custom/aiogree/setpoint_memory.py +++ b/custom_components/gree_custom/aiogree/setpoint_memory.py @@ -16,7 +16,8 @@ mode. - What is stored are the raw columns that hold the target temperature, as `GreeDevice.target_temperature_props` gives them, per device MAC and mode: - `StTem` for a zone, `SetTem` and `TemRec` for a standalone or VRF unit. + `StTem` and `StFahFlg` for a zone, `SetTem` and `TemRec` for a standalone or + VRF unit. - For a unit that remembers its own target, `apply()` sets the stored value without sending it, so it can go out in the same command as the new mode. diff --git a/docs/protocol.md b/docs/protocol.md index 06006081..135c4cf6 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -112,7 +112,7 @@ The wall panel remembers the target temperature of every zone per mode. When the - Before the climate entity of the ducted unit changes the mode, `snapshot()` reads the zones again and stores them under the old mode. After the change, `recall()` sends the stored values of the new mode. A mode with no stored values changes nothing. - It stores the raw columns that hold the target temperature, as `GreeDevice.target_temperature_props` gives them, keyed by device MAC and mode: `{"": {"heat": {"StTem": 3, "StFahFlg": 0}}}`. Raw columns need no unit conversion. They are the columns the device uses: a zone stores `StTem` and its bit `StFahFlg`, so a half degree or a °F value comes back exactly. A standalone or VRF unit stores `SetTem` and `TemRec`. - A standalone or VRF unit uses the same memory for itself. The device option `setpoint_memory`, on by default, turns the memory off for one device, a zone included. It stores `SetTem` and `TemRec`, so a unit set to Fahrenheit needs no conversion. On a mode change from Home Assistant, `apply()` sets the stored target without sending it, and it goes out in the same command as the new mode. Nothing is recalled into Auto, where the unit ignores the target temperature. -- `__init__.py` keeps the memory in a `Store` per config entry (`gree_custom..setpoints`). +- `__init__.py` keeps the memory in a `Store` per config entry (`gree_custom..setpoints`). It is saved when the entry unloads, and removed with the entry. ## MAC addresses From a82257a791d99644c32308f5c85ac7ca72f3c636 Mon Sep 17 00:00:00 2001 From: Twintop Date: Thu, 12 Nov 2026 12:01:24 +1100 Subject: [PATCH 5/9] Move the setpoint memory to the Home Assistant layer The memory is Home Assistant behaviour, turned on by a device option, so it now lives next to the coordinator instead of in aiogree. It still imports nothing from Home Assistant. Its tests import the protocol layer through the package path, so the devices and the memory share one copy of the enums. GreeDevice.set_target_temperature_props() is now set_state_props(), a generic setter for raw columns in the device state. Its docstring says the typed setters are the right choice otherwise. --- custom_components/gree_custom/__init__.py | 4 ++-- custom_components/gree_custom/aiogree/device.py | 13 +++++++++++-- custom_components/gree_custom/coordinator.py | 2 +- .../{aiogree => }/setpoint_memory.py | 14 ++++++++++---- docs/architecture.md | 2 +- docs/protocol.md | 4 ++-- tests/test_setpoint_memory.py | 17 +++++++++++++---- 7 files changed, 40 insertions(+), 16 deletions(-) rename custom_components/gree_custom/{aiogree => }/setpoint_memory.py (92%) diff --git a/custom_components/gree_custom/__init__.py b/custom_components/gree_custom/__init__.py index 74a02a25..d4bb262d 100755 --- a/custom_components/gree_custom/__init__.py +++ b/custom_components/gree_custom/__init__.py @@ -32,7 +32,6 @@ from .aiogree.cipher import EncryptionVersion from .aiogree.device import GreeDevice from .aiogree.errors import GreeConnectionError -from .aiogree.setpoint_memory import SetpointMemory, SetpointMemoryData from .aiogree.transport_mqtt import GreeMqttTransport from .aiogree.transport_udp import GreeUdpTransport from .config_schema import CONFIG_SCHEMA as CONFIG_SCHEMA @@ -87,6 +86,7 @@ async_unload_legacy_entries, ) from .services import async_setup_services +from .setpoint_memory import SetpointMemory, SetpointMemoryData ISSUE_DEVICE_CONNECTION_FAILED = "device_connection_failed" ISSUE_YAML_IMPORT_FAILED = "yaml_import_failed" @@ -356,7 +356,7 @@ async def _async_setup_setpoint_memory( zones of a zone controller follow the mode of their ducted unit, so the ducted unit gets it for them, and a mode change from Home Assistant sets them as the wall panel does. The memory learns from every poll of those - devices. See aiogree/setpoint_memory.py. + devices. See setpoint_memory.py. """ learners = [ c diff --git a/custom_components/gree_custom/aiogree/device.py b/custom_components/gree_custom/aiogree/device.py index 184aeb04..9b005c71 100755 --- a/custom_components/gree_custom/aiogree/device.py +++ b/custom_components/gree_custom/aiogree/device.py @@ -702,8 +702,17 @@ def target_temperature_props(self) -> dict[GreeProp, int] | None: ) return props - def set_target_temperature_props(self, props: Mapping[GreeProp, int]) -> None: - """Set the raw columns that hold the target temperature, as remembered.""" + def set_state_props(self, props: Mapping[GreeProp, int]) -> None: + """Set raw column values in the device state, without sending them. + + They go out with the next push_device_status(), the same way as the + values of the typed setters. set_props() instead sends them at once + and skips the state. A column the device does not answer is refused. + + Only for exceptions, such as raw values remembered from the device + itself. Use the typed setters otherwise (set_target_temperature() and + the others): they convert units and check ranges, this does not. + """ for prop, value in props.items(): self._state.set(prop, value) diff --git a/custom_components/gree_custom/coordinator.py b/custom_components/gree_custom/coordinator.py index 97c83936..3f86cc9f 100755 --- a/custom_components/gree_custom/coordinator.py +++ b/custom_components/gree_custom/coordinator.py @@ -13,9 +13,9 @@ from .aiogree.api import OperationMode from .aiogree.device import GreeDevice from .aiogree.errors import GreeBindingError, GreeConnectionError -from .aiogree.setpoint_memory import SetpointMemory from .const import DOMAIN from .helpers import try_find_new_ip +from .setpoint_memory import SetpointMemory _LOGGER = logging.getLogger(__name__) diff --git a/custom_components/gree_custom/aiogree/setpoint_memory.py b/custom_components/gree_custom/setpoint_memory.py similarity index 92% rename from custom_components/gree_custom/aiogree/setpoint_memory.py rename to custom_components/gree_custom/setpoint_memory.py index b64f8bb2..4dfbedb5 100644 --- a/custom_components/gree_custom/aiogree/setpoint_memory.py +++ b/custom_components/gree_custom/setpoint_memory.py @@ -6,6 +6,10 @@ mode (seen on a LE60-13/GH). This class keeps the same memory, so a mode change from Home Assistant works like one on the panel. See docs/protocol.md. +It is Home Assistant behaviour, turned on per device by the setpoint_memory +option, so it lives here and not in aiogree. It still imports nothing from +Home Assistant, so the tests need no Home Assistant instance. + - A device reports its mode and its target temperature in one reply, so the two belong together. A value is stored when the device reported the same mode on the poll before. A poll in the middle of a mode change on the panel @@ -20,6 +24,8 @@ VRF unit. - For a unit that remembers its own target, `apply()` sets the stored value without sending it, so it can go out in the same command as the new mode. + It uses `GreeDevice.set_state_props()`, since the raw columns need no + conversion. The memory does not store itself. The owner loads `data` and saves it when `on_change` is called. @@ -28,9 +34,9 @@ from collections.abc import Callable, Iterable, Mapping import logging -from .api import PROP_KEY_TO_ENUM, GreeProp, OperationMode -from .device import GreeDevice -from .errors import GreeError +from .aiogree.api import PROP_KEY_TO_ENUM, GreeProp, OperationMode +from .aiogree.device import GreeDevice +from .aiogree.errors import GreeError _LOGGER = logging.getLogger(__name__) @@ -150,7 +156,7 @@ def apply(self, device: GreeDevice, mode: OperationMode) -> bool: if not stored or stored == device.target_temperature_props: return False - device.set_target_temperature_props(stored) + device.set_state_props(stored) return True def _remember( diff --git a/docs/architecture.md b/docs/architecture.md index 64ae8e85..751793f1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -20,7 +20,6 @@ No Home Assistant imports here. | `helpers.py` | Encrypt and decrypt packs, temperature math, `TempOffsetResolver`, `redact_str`, `chunked`. | | `const.py` | Protocol constants: `MAX_PACK_SIZE`, `MIN_PACK_PROPS`, `STATUS_CANARY_PROP`, `PROBE_TIMEOUT`, `STATUS_CANARY_PROP_MAX_REQUESTS`, temperature and humidity ranges. | | `errors.py` | Exceptions. `GreeConnectionError` means no answer. `GreeProtocolError` means a bad answer. `GreeBindingError` means the key exchange failed. | -| `setpoint_memory.py` | `SetpointMemory`. The target temperature of a device per mode, stored as raw columns per device MAC. Used for every device with a target temperature, unless its `setpoint_memory` option is off: for the zones of a zone controller, so a mode change works like one on the wall panel, and for a standalone or VRF unit itself. See [protocol.md](protocol.md#target-temperatures-per-mode). | ## Home Assistant layer @@ -28,6 +27,7 @@ No Home Assistant imports here. |---|---| | `__init__.py` | Entry setup. Builds transports and devices, binds them, starts one `GreeCoordinator` per device. Creates and links the VRF controller devices, see [VRF controller device](#vrf-controller-device). | | `coordinator.py` | `GreeCoordinator`. Polls on `scan_interval` and listens for status pushed by the device. Polls again every 2 s after a command while the device has not confirmed it, until the hold ends. | +| `setpoint_memory.py` | `SetpointMemory`. The target temperature of a device per mode, stored as raw columns per device MAC. Used for every device with a target temperature, unless its `setpoint_memory` option is off: for the zones of a zone controller, so a mode change works like one on the wall panel, and for a standalone or VRF unit itself. It imports nothing from Home Assistant; `__init__.py` keeps it in a `Store`. See [protocol.md](protocol.md#target-temperatures-per-mode). | | `config_flow.py` | Setup, reconfigure, reauth and YAML import flows. Local discovery, cloud login, device picker, per device options. Reconfigure is a menu over the same steps, see [config-entry.md](config-entry.md#reconfigure). `async_step_import` turns one validated YAML item into a config entry. | | `config_schema.py` | `CONFIG_SCHEMA` for the `gree_custom:` block in `configuration.yaml`. Validates the YAML, normalizes the MAC addresses and fills the defaults. It also holds the form schemas that the config flow shows. | | `migration.py` | Moves a 4.x setup (domain `gree`) to this integration: config entries, the `gree:` YAML block, and the device and entity registry rows. See [config-entry.md](config-entry.md#migration-from-4x). | diff --git a/docs/protocol.md b/docs/protocol.md index 135c4cf6..74bd5f10 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -106,12 +106,12 @@ A zone controller (seen: LE60-13/GH with a ME31-00/C13 WiFi module, firmware `36 ### Target temperatures per mode -The wall panel remembers the target temperature of every zone per mode. When the mode is changed on the panel, it sets them again. A `Mod` change over WiFi does not: the zones keep the values of the old mode. `SetpointMemory` in `aiogree/setpoint_memory.py` keeps the same memory: +The wall panel remembers the target temperature of every zone per mode. When the mode is changed on the panel, it sets them again. A `Mod` change over WiFi does not: the zones keep the values of the old mode. `SetpointMemory` in `setpoint_memory.py`, in the Home Assistant layer, keeps the same memory: - It learns from every poll of a zone. A zone reports its mode and its target temperature in one reply, so the two belong together. A value is stored when the zone reported the same mode on its poll before, so a poll in the middle of a mode change on the panel is not stored under the wrong mode. - Before the climate entity of the ducted unit changes the mode, `snapshot()` reads the zones again and stores them under the old mode. After the change, `recall()` sends the stored values of the new mode. A mode with no stored values changes nothing. - It stores the raw columns that hold the target temperature, as `GreeDevice.target_temperature_props` gives them, keyed by device MAC and mode: `{"": {"heat": {"StTem": 3, "StFahFlg": 0}}}`. Raw columns need no unit conversion. They are the columns the device uses: a zone stores `StTem` and its bit `StFahFlg`, so a half degree or a °F value comes back exactly. A standalone or VRF unit stores `SetTem` and `TemRec`. -- A standalone or VRF unit uses the same memory for itself. The device option `setpoint_memory`, on by default, turns the memory off for one device, a zone included. It stores `SetTem` and `TemRec`, so a unit set to Fahrenheit needs no conversion. On a mode change from Home Assistant, `apply()` sets the stored target without sending it, and it goes out in the same command as the new mode. Nothing is recalled into Auto, where the unit ignores the target temperature. +- A standalone or VRF unit uses the same memory for itself. The device option `setpoint_memory`, on by default, turns the memory off for one device, a zone included. It stores `SetTem` and `TemRec`, so a unit set to Fahrenheit needs no conversion. On a mode change from Home Assistant, `apply()` sets the stored target with `GreeDevice.set_state_props()`, without sending it, and it goes out in the same command as the new mode. Nothing is recalled into Auto, where the unit ignores the target temperature. - `__init__.py` keeps the memory in a `Store` per config entry (`gree_custom..setpoints`). It is saved when the entry unloads, and removed with the entry. ## MAC addresses diff --git a/tests/test_setpoint_memory.py b/tests/test_setpoint_memory.py index d4f5c491..90e8b7e0 100644 --- a/tests/test_setpoint_memory.py +++ b/tests/test_setpoint_memory.py @@ -11,12 +11,21 @@ from collections.abc import AsyncIterator -from aiogree.api import DeviceType, GreeProp, OperationMode -from aiogree.device import GreeDevice -from aiogree.setpoint_memory import SetpointMemory -from aiogree.transport_udp import GreeUdpTransport import pytest +# SetpointMemory is on the Home Assistant side, so it imports the protocol +# layer as custom_components.gree_custom.aiogree. The devices must come from +# the same import, not the top level "aiogree" the protocol tests use: two +# imports are two copies, and their enums would not compare equal. +from custom_components.gree_custom.aiogree.api import ( + DeviceType, + GreeProp, + OperationMode, +) +from custom_components.gree_custom.aiogree.device import GreeDevice +from custom_components.gree_custom.aiogree.transport_udp import GreeUdpTransport +from custom_components.gree_custom.setpoint_memory import SetpointMemory + from .fakes.device import FakeGreeDevice from .fakes.zone import FakeZoneController From f5abaa9309dc75c92357c4fdbedb00766ab416e6 Mon Sep 17 00:00:00 2001 From: Twintop Date: Sun, 15 Nov 2026 14:36:24 +1100 Subject: [PATCH 6/9] Setpoint memory: keep a target given with the mode, learn from real reads A temperature given to climate.set_temperature together with a mode was stored under the old mode, and then replaced by the remembered one. The memory now stores only what a device reported, and apply() leaves alone a target that is already set for the command. learn() counted listener calls, so one mode change from Home Assistant could count as two reads. GreeDevice.status_reads now tells a new read from another look at the same one. A standalone or VRF unit no longer learns while it is off. A zone still does, because its Pow is its damper. --- custom_components/gree_custom/__init__.py | 2 +- .../gree_custom/aiogree/device.py | 38 +++++++++-- .../gree_custom/setpoint_memory.py | 64 +++++++++++++---- docs/protocol.md | 4 +- .../test_setpoint_memory_climate.py | 66 ++++++++++++++++++ tests/test_setpoint_memory.py | 68 +++++++++++++++++++ 6 files changed, 219 insertions(+), 23 deletions(-) create mode 100644 tests/config_flow/test_setpoint_memory_climate.py diff --git a/custom_components/gree_custom/__init__.py b/custom_components/gree_custom/__init__.py index d4bb262d..04ceb05c 100755 --- a/custom_components/gree_custom/__init__.py +++ b/custom_components/gree_custom/__init__.py @@ -355,7 +355,7 @@ async def _async_setup_setpoint_memory( option is off. A standalone or VRF unit gets the memory for itself. The zones of a zone controller follow the mode of their ducted unit, so the ducted unit gets it for them, and a mode change from Home Assistant sets - them as the wall panel does. The memory learns from every poll of those + them as the wall panel does. The memory learns from every read of those devices. See setpoint_memory.py. """ learners = [ diff --git a/custom_components/gree_custom/aiogree/device.py b/custom_components/gree_custom/aiogree/device.py index 9b005c71..546e82dd 100755 --- a/custom_components/gree_custom/aiogree/device.py +++ b/custom_components/gree_custom/aiogree/device.py @@ -106,6 +106,9 @@ def __init__( self._device_type: DeviceType = DeviceType.AC_UNIT + # Successful status reads, see status_reads. + self._status_reads = 0 + # The column of each group that the device answers, see # _remove_unsupported_props. None until the first bind, or when the # device answers none of them. @@ -320,6 +323,7 @@ async def fetch_device_status(self, first_fetch: bool = False) -> None: ) self._state.process_new_state(result.prop_values) + self._status_reads += 1 except GreeConnectionError, GreeProtocolError: _LOGGER.exception( @@ -679,29 +683,49 @@ def device_type(self) -> DeviceType: """Return what kind of device this is. Known after the first bind.""" return self._device_type + @property + def status_reads(self) -> int: + """Return how many times the status was read from the device. + + Tells a new reading from another look at the same one. + """ + return self._status_reads + @property def target_temperature_props(self) -> dict[GreeProp, int] | None: - """Return the raw columns that hold the target temperature, to remember it. + """Return the raw columns that hold the target temperature, as reported. Used by `SetpointMemory`. Raw columns need no unit conversion. They - are the column the device uses, see _remove_unsupported_props. None - means there is nothing to remember. + are the column the device uses, see _remove_unsupported_props. These + are the values the device last reported: a value that is set and not + sent yet is left out, see has_pending_target_temperature. None means + there is nothing to remember. """ if self._target_temp_prop is None: return None - raw = self._state.get(self._target_temp_prop) - if raw is None: + reported = self._state.raw + value = reported.get(self._target_temp_prop) + if value is None: return None - props = {self._target_temp_prop: raw} + props = {self._target_temp_prop: value} # With the bit, when the device has one: the half degree in Celsius, # the table in Fahrenheit. A zone keeps an old bit when only StTem is # sent, see set_target_temperature. if self._target_temp_bit_prop is not None: props[self._target_temp_bit_prop] = ( - self._state.get(self._target_temp_bit_prop) or 0 + reported.get(self._target_temp_bit_prop) or 0 ) return props + @property + def has_pending_target_temperature(self) -> bool: + """Return True if a target temperature is set and not sent yet.""" + pending = self._state.pending + return any( + prop is not None and prop in pending + for prop in (self._target_temp_prop, self._target_temp_bit_prop) + ) + def set_state_props(self, props: Mapping[GreeProp, int]) -> None: """Set raw column values in the device state, without sending them. diff --git a/custom_components/gree_custom/setpoint_memory.py b/custom_components/gree_custom/setpoint_memory.py index 4dfbedb5..f5c762df 100644 --- a/custom_components/gree_custom/setpoint_memory.py +++ b/custom_components/gree_custom/setpoint_memory.py @@ -12,8 +12,13 @@ - A device reports its mode and its target temperature in one reply, so the two belong together. A value is stored when the device reported the same - mode on the poll before. A poll in the middle of a mode change on the panel - is then not stored under the wrong mode. + mode on the read before. A read in the middle of a mode change on the panel + is then not stored under the wrong mode. Another look at the same read does + not count, see `GreeDevice.status_reads`. +- Only what a device reported is stored, never a value that is set and not + sent yet. A standalone or VRF unit learns only while it is on. A zone also + learns while it is closed: its `Pow` is its damper, not the power of the + unit. - Before the mode is changed, `snapshot()` reads the devices again and stores them under the old mode, so a change made on the panel since the last poll is not lost. After the change, `recall()` sends the stored values of the new @@ -25,7 +30,8 @@ - For a unit that remembers its own target, `apply()` sets the stored value without sending it, so it can go out in the same command as the new mode. It uses `GreeDevice.set_state_props()`, since the raw columns need no - conversion. + conversion. A target set for the same command, for example by + `climate.set_temperature` with a mode, wins over the stored one. The memory does not store itself. The owner loads `data` and saves it when `on_change` is called. @@ -34,7 +40,7 @@ from collections.abc import Callable, Iterable, Mapping import logging -from .aiogree.api import PROP_KEY_TO_ENUM, GreeProp, OperationMode +from .aiogree.api import PROP_KEY_TO_ENUM, DeviceType, GreeProp, OperationMode from .aiogree.device import GreeDevice from .aiogree.errors import GreeError @@ -61,8 +67,9 @@ def __init__( """ self._data: SetpointMemoryData = data or {} self._on_change = on_change - # The mode each device reported on its last poll. - self._last_mode: dict[str, OperationMode] = {} + # The read and the mode each device reported on it, as last seen by + # learn(). + self._last_read: dict[str, tuple[int, OperationMode]] = {} @property def data(self) -> SetpointMemoryData: @@ -79,27 +86,40 @@ def stored(self, device_mac: str, mode: OperationMode) -> dict[GreeProp, int]: } def learn(self, device: GreeDevice) -> None: - """Store what a device reported, once its mode is the same twice in a row. + """Store what a device reported, once it reports the same mode twice in a row. - Call this after every poll of the device. + Call this whenever the device may have been read, for example from a + coordinator listener. A call without a new read changes nothing. """ props = device.target_temperature_props if props is None: return + read = device.status_reads + last = self._last_read.get(device.mac_address) + if last is not None and last[0] == read: + return mode = device.operation_mode - previous = self._last_mode.get(device.mac_address) - self._last_mode[device.mac_address] = mode + self._last_read[device.mac_address] = (read, mode) # Values that were just sent and are not confirmed yet are stored once # the device reports them. - if previous is mode and not device.has_held_values: + if ( + last is not None + and last[1] is mode + and not device.has_held_values + and _is_running(device) + ): self._remember(device, mode, props) async def snapshot( self, devices: Iterable[GreeDevice], mode: OperationMode ) -> None: - """Read the devices again and store their values under the mode that is about to end.""" + """Read the devices again and store their values under the mode that is about to end. + + What the devices report is stored, not a target that is set and not + sent yet. + """ for device in devices: try: await device.fetch_device_status() @@ -115,6 +135,7 @@ async def snapshot( props is not None and device.operation_mode is mode and not device.has_held_values + and _is_running(device) ): self._remember(device, mode, props) @@ -148,12 +169,19 @@ async def recall( def apply(self, device: GreeDevice, mode: OperationMode) -> bool: """Set the stored target temperature of a mode on a device, without sending it. + A target that is already set for the same command wins, for example + one given to climate.set_temperature with the mode. + Returns: True if the device got a new target temperature to send """ stored = self.stored(device.mac_address, mode) - if not stored or stored == device.target_temperature_props: + if ( + not stored + or device.has_pending_target_temperature + or stored == device.target_temperature_props + ): return False device.set_state_props(stored) @@ -177,3 +205,13 @@ def _remember( ) if self._on_change is not None: self._on_change() + + +def _is_running(device: GreeDevice) -> bool: + """Return True if the target of the device belongs to the mode it reports. + + A standalone or VRF unit that is off keeps a mode and a target, but they + are not in use. A zone's Pow is its damper, not the power of the unit, so + a closed zone counts as running. + """ + return device.device_type is DeviceType.ZONE or device.power_mode diff --git a/docs/protocol.md b/docs/protocol.md index 74bd5f10..84a5e57c 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -108,10 +108,10 @@ A zone controller (seen: LE60-13/GH with a ME31-00/C13 WiFi module, firmware `36 The wall panel remembers the target temperature of every zone per mode. When the mode is changed on the panel, it sets them again. A `Mod` change over WiFi does not: the zones keep the values of the old mode. `SetpointMemory` in `setpoint_memory.py`, in the Home Assistant layer, keeps the same memory: -- It learns from every poll of a zone. A zone reports its mode and its target temperature in one reply, so the two belong together. A value is stored when the zone reported the same mode on its poll before, so a poll in the middle of a mode change on the panel is not stored under the wrong mode. +- It learns from every read of a zone. A zone reports its mode and its target temperature in one reply, so the two belong together. A value is stored when the zone reported the same mode on the read before, so a read in the middle of a mode change on the panel is not stored under the wrong mode. A read counts once, however often the entities are updated from it (`GreeDevice.status_reads`). Only reported values are stored, never a target that is set and not sent yet. A closed zone learns too: a zone's `Pow` is its damper, not the power of the unit. - Before the climate entity of the ducted unit changes the mode, `snapshot()` reads the zones again and stores them under the old mode. After the change, `recall()` sends the stored values of the new mode. A mode with no stored values changes nothing. - It stores the raw columns that hold the target temperature, as `GreeDevice.target_temperature_props` gives them, keyed by device MAC and mode: `{"": {"heat": {"StTem": 3, "StFahFlg": 0}}}`. Raw columns need no unit conversion. They are the columns the device uses: a zone stores `StTem` and its bit `StFahFlg`, so a half degree or a °F value comes back exactly. A standalone or VRF unit stores `SetTem` and `TemRec`. -- A standalone or VRF unit uses the same memory for itself. The device option `setpoint_memory`, on by default, turns the memory off for one device, a zone included. It stores `SetTem` and `TemRec`, so a unit set to Fahrenheit needs no conversion. On a mode change from Home Assistant, `apply()` sets the stored target with `GreeDevice.set_state_props()`, without sending it, and it goes out in the same command as the new mode. Nothing is recalled into Auto, where the unit ignores the target temperature. +- A standalone or VRF unit uses the same memory for itself. The device option `setpoint_memory`, on by default, turns the memory off for one device, a zone included. It stores `SetTem` and `TemRec`, so a unit set to Fahrenheit needs no conversion. It learns only while the unit is on: an off unit keeps a mode and a target that are not in use. On a mode change from Home Assistant, `snapshot()` reads the unit once more, so a change made with the remote since the last poll is kept. Then `apply()` sets the stored target with `GreeDevice.set_state_props()`, without sending it, and it goes out in the same command as the new mode. A target given with the mode, as `climate.set_temperature` does with `hvac_mode`, wins over the stored one. Nothing is recalled into Auto, where the unit ignores the target temperature. - `__init__.py` keeps the memory in a `Store` per config entry (`gree_custom..setpoints`). It is saved when the entry unloads, and removed with the entry. ## MAC addresses diff --git a/tests/config_flow/test_setpoint_memory_climate.py b/tests/config_flow/test_setpoint_memory_climate.py new file mode 100644 index 00000000..bac7c8b5 --- /dev/null +++ b/tests/config_flow/test_setpoint_memory_climate.py @@ -0,0 +1,66 @@ +"""The target temperature per mode, through the climate entity of a real Home Assistant. + +The memory itself is tested in tests/test_setpoint_memory.py. This checks what a +service call does with it. +""" + +import pytest + +from homeassistant.components.climate import DOMAIN as CLIMATE_DOMAIN +from homeassistant.const import ( + ATTR_ENTITY_ID, + ATTR_TEMPERATURE, + MAJOR_VERSION, + MINOR_VERSION, +) +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er +from tests.config_flow.conftest import MAC_A, GreeEnv, add_entry + +# The climate entity uses the native temperature API of Home Assistant 2026.11 +# (#570). The test plugin is still pinned to 2026.10, where the entity cannot +# be created, so this runs once the pin moves to 2026.11. +pytestmark = pytest.mark.skipif( + (MAJOR_VERSION, MINOR_VERSION) < (2026, 11), + reason="the climate entity needs Home Assistant 2026.11", +) + + +async def test_set_temperature_with_a_mode_keeps_the_given_temperature( + hass: HomeAssistant, gree: GreeEnv +) -> None: + """A temperature given with the mode wins over the remembered one.""" + fake = gree.devices[MAC_A] + fake.values.update({"Pow": 1, "Mod": 1, "SetTem": 24, "TemRec": 0, "TemUn": 0}) + host = await gree.start_udp(fake) + entry = await add_entry(hass, ["local"], [MAC_A], [host]) + coordinator = next(iter(entry.runtime_data.values())) + memory = coordinator.setpoint_memory + assert memory is not None + + async def poll() -> None: + await coordinator.async_refresh() + await hass.async_block_till_done() + + # Heat 20 and Cool 24, as set with the remote + fake.values.update({"Mod": 4, "SetTem": 20}) + await poll() + await poll() + fake.values.update({"Mod": 1, "SetTem": 24}) + await poll() + await poll() + + climate = next( + e.entity_id + for e in er.async_entries_for_config_entry(er.async_get(hass), entry.entry_id) + if e.domain == CLIMATE_DOMAIN + ) + await hass.services.async_call( + CLIMATE_DOMAIN, + "set_temperature", + {ATTR_ENTITY_ID: climate, ATTR_TEMPERATURE: 22, "hvac_mode": "heat"}, + blocking=True, + ) + + assert (fake.values["Mod"], fake.values["SetTem"]) == (4, 22) + assert memory.data[MAC_A]["cool"]["SetTem"] == 24 diff --git a/tests/test_setpoint_memory.py b/tests/test_setpoint_memory.py index 90e8b7e0..7e5c2522 100644 --- a/tests/test_setpoint_memory.py +++ b/tests/test_setpoint_memory.py @@ -284,6 +284,33 @@ async def test_snapshot_does_not_store_values_of_another_mode( assert remembered(memory, zones, OperationMode.fan) == [None] * 4 +async def test_another_look_at_the_same_read_does_not_count( + zones: list[GreeDevice], +) -> None: + """A listener can run more than once per read. Only a new read counts.""" + memory = SetpointMemory() + await poll(memory, zones) + for zone in zones: + memory.learn(zone) + assert memory.data == {} + + await poll(memory, zones) + assert remembered(memory, zones, OperationMode.fan) == [18, 18, 18, 18] + + +async def test_a_closed_zone_still_learns( + controller: FakeZoneController, zones: list[GreeDevice] +) -> None: + """A zone's Pow is its damper. Its target still belongs to the mode.""" + controller.units[controller.zone_macs[1]]["Pow"] = 0 + memory = SetpointMemory() + + await poll(memory, zones) + await poll(memory, zones) + + assert remembered(memory, zones, OperationMode.fan) == [18, 18, 18, 18] + + # # A standalone unit that remembers its own target # @@ -374,3 +401,44 @@ async def test_apply_without_a_stored_target_changes_nothing( await device.push_device_status() assert not any(pack.get("t") == "cmd" for pack in fake.packs) + + +async def test_a_target_given_with_the_mode_wins( + unit: tuple[FakeGreeDevice, GreeDevice], +) -> None: + """As climate.set_temperature does with a temperature and a mode.""" + fake, device = unit + memory = SetpointMemory() + await poll(memory, [device]) + await poll(memory, [device]) + fake.values.update({"Mod": 4, "SetTem": 20}) + await poll(memory, [device]) + await poll(memory, [device]) + + # In Heat at 20, asked for 22 in Cool + device.set_target_temperature(22) + await memory.snapshot([device], OperationMode.heat) + device.set_operation_mode(OperationMode.cool) + assert not memory.apply(device, OperationMode.cool) + await device.push_device_status() + + assert (fake.values["Mod"], fake.values["SetTem"]) == (1, 22) + assert memory.data[fake.mac] == { + "cool": {"SetTem": 24, "TemRec": 0}, + "heat": {"SetTem": 20, "TemRec": 0}, + } + + +async def test_a_unit_that_is_off_learns_nothing( + unit: tuple[FakeGreeDevice, GreeDevice], +) -> None: + """An off unit keeps a mode and a target, but they are not in use.""" + fake, device = unit + fake.values["Pow"] = 0 + memory = SetpointMemory() + + await poll(memory, [device]) + await poll(memory, [device]) + await memory.snapshot([device], OperationMode.cool) + + assert memory.data == {} From c960a03b323886aa5fa32fde7133053d6dceae92 Mon Sep 17 00:00:00 2001 From: Twintop Date: Mon, 16 Nov 2026 00:20:24 +1100 Subject: [PATCH 7/9] Setpoint memory: build it on the existing device interface The memory now stores GreeDevice.target_temperature with its unit, and sets it back with set_target_temperature(). Every target in range comes back as the same temperature, and a value stored in the other unit is converted. This removes target_temperature_props, set_state_props, status_reads and has_pending_target_temperature from GreeDevice. Only has_target_temperature stays. GreeCoordinator._update_data() calls learn() after each read, so every call is one new read, without a counter. A temperature given to climate.set_temperature with a mode is now set by the mode change itself, after the read of the old mode, and goes out in the same command. The stored target is only applied when no temperature is given. The climate entity keeps the memory in its restore state, the entity of the ducted unit for its zones. This replaces the Store, its delayed save, the save on unload and async_remove_entry. New tests through Home Assistant: a change on the device is learned from the polls, and the memory is kept over a reload and a restart. They skip below Home Assistant 2026.11, as the set_temperature test does. --- custom_components/gree_custom/__init__.py | 72 ++---- .../gree_custom/aiogree/device.py | 61 ----- custom_components/gree_custom/climate.py | 75 +++++- custom_components/gree_custom/coordinator.py | 11 +- .../gree_custom/setpoint_memory.py | 227 +++++++----------- docs/architecture.md | 2 +- docs/protocol.md | 8 +- .../test_setpoint_memory_climate.py | 131 ++++++++-- tests/test_setpoint_memory.py | 134 ++++------- 9 files changed, 344 insertions(+), 377 deletions(-) diff --git a/custom_components/gree_custom/__init__.py b/custom_components/gree_custom/__init__.py index 04ceb05c..1581bafa 100755 --- a/custom_components/gree_custom/__init__.py +++ b/custom_components/gree_custom/__init__.py @@ -2,7 +2,6 @@ # Standard library imports from collections.abc import Mapping -from functools import partial import json import logging from typing import Any @@ -25,7 +24,6 @@ HomeAssistantError, ) from homeassistant.helpers import device_registry as dr, issue_registry as ir -from homeassistant.helpers.storage import Store from homeassistant.helpers.typing import ConfigType from .aiogree.api import DeviceType @@ -86,12 +84,10 @@ async_unload_legacy_entries, ) from .services import async_setup_services -from .setpoint_memory import SetpointMemory, SetpointMemoryData +from .setpoint_memory import SetpointMemory ISSUE_DEVICE_CONNECTION_FAILED = "device_connection_failed" ISSUE_YAML_IMPORT_FAILED = "yaml_import_failed" -SETPOINT_MEMORY_STORAGE_VERSION = 1 -SETPOINT_MEMORY_SAVE_DELAY = 10 PLATFORMS = [ Platform.BINARY_SENSOR, Platform.CLIMATE, @@ -300,7 +296,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: GreeConfigEntry) -> bool entry.runtime_data = {} entry.runtime_data = coordinators - await _async_setup_setpoint_memory(hass, entry, coordinators) + _setup_setpoint_memory(coordinators) # Move the 4.x registry rows before the entities are created moved = await async_migrate_legacy_registry(hass, entry) @@ -344,19 +340,15 @@ async def _async_refresh_entry_token( return new_cloud_conf -async def _async_setup_setpoint_memory( - hass: HomeAssistant, - entry: GreeConfigEntry, - coordinators: dict[str, GreeCoordinator], -) -> None: - """Give the devices that remember their target temperature per mode the memory. +def _setup_setpoint_memory(coordinators: dict[str, GreeCoordinator]) -> None: + """Give the devices that remember their target temperature per mode a memory. Every device with a target temperature does, unless its setpoint_memory - option is off. A standalone or VRF unit gets the memory for itself. The - zones of a zone controller follow the mode of their ducted unit, so the - ducted unit gets it for them, and a mode change from Home Assistant sets - them as the wall panel does. The memory learns from every read of those - devices. See setpoint_memory.py. + option is off. A standalone or VRF unit gets a memory for itself. The + zones of a zone controller follow the mode of their ducted unit, so they + share one memory with it: the zones learn, and a mode change of the ducted + unit sets them as the wall panel does. The climate entity keeps the memory + in its restore state. See setpoint_memory.py. """ learners = [ c @@ -366,30 +358,11 @@ async def _async_setup_setpoint_memory( CONF_SETPOINT_MEMORY, DEFAULT_SETPOINT_MEMORY ) ] - if not learners: - return - zones = [c for c in learners if c.device.device_type is DeviceType.ZONE] - units = [c for c in learners if c.device.device_type is not DeviceType.ZONE] - - store = _setpoint_memory_store(hass, entry.entry_id) - memory = SetpointMemory( - await store.async_load(), - on_change=lambda: store.async_delay_save( - lambda: memory.data, SETPOINT_MEMORY_SAVE_DELAY - ), - ) - # Save on unload rather than after the delay. A delayed save would still - # run after the entry is removed, and write the file again. - entry.async_on_unload(lambda: store.async_save(memory.data)) - - for learner in learners: - entry.async_on_unload( - learner.async_add_listener(partial(memory.learn, learner.device)) - ) - for unit in units: - unit.setpoint_memory = memory + for unit in learners: + if unit.device.device_type is not DeviceType.ZONE: + unit.setpoint_memory = SetpointMemory() for coordinator in coordinators.values(): if coordinator.device.device_type is not DeviceType.ZONE_CONTROLLER: @@ -401,17 +374,11 @@ async def _async_setup_setpoint_memory( == coordinator.device.mac_address_controller ] if own_zones: + memory = SetpointMemory() coordinator.setpoint_memory = memory coordinator.zone_coordinators = own_zones - - -def _setpoint_memory_store( - hass: HomeAssistant, entry_id: str -) -> Store[SetpointMemoryData]: - """Return the store that keeps the setpoint memory of a config entry.""" - return Store( - hass, SETPOINT_MEMORY_STORAGE_VERSION, f"{DOMAIN}.{entry_id}.setpoints" - ) + for zone in own_zones: + zone.setpoint_memory = memory async def async_unload_entry(hass: HomeAssistant, entry: GreeConfigEntry) -> bool: @@ -440,15 +407,6 @@ async def async_unload_entry(hass: HomeAssistant, entry: GreeConfigEntry) -> boo return True -async def async_remove_entry(hass: HomeAssistant, entry: GreeConfigEntry) -> None: - """Remove the setpoint memory of a removed config entry. - - Home Assistant unloads the entry first, and the unload saves the memory, so - nothing writes the file again after this. - """ - await _setpoint_memory_store(hass, entry.entry_id).async_remove() - - async def async_remove_config_entry_device( hass: HomeAssistant, config_entry: GreeConfigEntry, device_entry: dr.DeviceEntry ) -> bool: diff --git a/custom_components/gree_custom/aiogree/device.py b/custom_components/gree_custom/aiogree/device.py index 546e82dd..23774bd1 100755 --- a/custom_components/gree_custom/aiogree/device.py +++ b/custom_components/gree_custom/aiogree/device.py @@ -106,9 +106,6 @@ def __init__( self._device_type: DeviceType = DeviceType.AC_UNIT - # Successful status reads, see status_reads. - self._status_reads = 0 - # The column of each group that the device answers, see # _remove_unsupported_props. None until the first bind, or when the # device answers none of them. @@ -323,7 +320,6 @@ async def fetch_device_status(self, first_fetch: bool = False) -> None: ) self._state.process_new_state(result.prop_values) - self._status_reads += 1 except GreeConnectionError, GreeProtocolError: _LOGGER.exception( @@ -683,63 +679,6 @@ def device_type(self) -> DeviceType: """Return what kind of device this is. Known after the first bind.""" return self._device_type - @property - def status_reads(self) -> int: - """Return how many times the status was read from the device. - - Tells a new reading from another look at the same one. - """ - return self._status_reads - - @property - def target_temperature_props(self) -> dict[GreeProp, int] | None: - """Return the raw columns that hold the target temperature, as reported. - - Used by `SetpointMemory`. Raw columns need no unit conversion. They - are the column the device uses, see _remove_unsupported_props. These - are the values the device last reported: a value that is set and not - sent yet is left out, see has_pending_target_temperature. None means - there is nothing to remember. - """ - if self._target_temp_prop is None: - return None - reported = self._state.raw - value = reported.get(self._target_temp_prop) - if value is None: - return None - props = {self._target_temp_prop: value} - # With the bit, when the device has one: the half degree in Celsius, - # the table in Fahrenheit. A zone keeps an old bit when only StTem is - # sent, see set_target_temperature. - if self._target_temp_bit_prop is not None: - props[self._target_temp_bit_prop] = ( - reported.get(self._target_temp_bit_prop) or 0 - ) - return props - - @property - def has_pending_target_temperature(self) -> bool: - """Return True if a target temperature is set and not sent yet.""" - pending = self._state.pending - return any( - prop is not None and prop in pending - for prop in (self._target_temp_prop, self._target_temp_bit_prop) - ) - - def set_state_props(self, props: Mapping[GreeProp, int]) -> None: - """Set raw column values in the device state, without sending them. - - They go out with the next push_device_status(), the same way as the - values of the typed setters. set_props() instead sends them at once - and skips the state. A column the device does not answer is refused. - - Only for exceptions, such as raw values remembered from the device - itself. Use the typed setters otherwise (set_target_temperature() and - the others): they convert units and check ranges, this does not. - """ - for prop, value in props.items(): - self._state.set(prop, value) - @property def has_held_values(self) -> bool: """Return True if sent values still wait for the device to confirm them.""" diff --git a/custom_components/gree_custom/climate.py b/custom_components/gree_custom/climate.py index 870b594d..7f2b55a7 100755 --- a/custom_components/gree_custom/climate.py +++ b/custom_components/gree_custom/climate.py @@ -31,7 +31,7 @@ from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.event import async_track_state_change_event -from homeassistant.helpers.restore_state import RestoreEntity +from homeassistant.helpers.restore_state import ExtraStoredData, RestoreEntity from homeassistant.util.unit_conversion import TemperatureConverter from .aiogree.api import ( @@ -67,6 +67,7 @@ ) from .coordinator import GreeConfigEntry, GreeCoordinator from .entity import GreeEntity, GreeEntityDescription +from .setpoint_memory import SetpointMemory, SetpointMemoryData _LOGGER = logging.getLogger(__name__) @@ -79,6 +80,19 @@ class GreeClimateDescription( """Description of a Gree Climate entity.""" +class GreeClimateExtraData(ExtraStoredData): + """What the climate entity keeps over a restart, next to its state.""" + + def __init__(self, setpoint_memory: SetpointMemoryData) -> None: + """Keep the target temperatures per mode, see setpoint_memory.py.""" + self.setpoint_memory = setpoint_memory + + @override + def as_dict(self) -> dict[str, Any]: + """Return the data to store.""" + return {"setpoint_memory": self.setpoint_memory} + + async def async_setup_entry( hass: HomeAssistant, entry: GreeConfigEntry, @@ -252,6 +266,11 @@ async def async_added_to_hass(self) -> None: self._update_attributes() + # Before the state, whose mode change uses it. Not tied to restore_state. + memory = self.coordinator.setpoint_memory + if memory is not None and (extra := await self.async_get_last_extra_data()): + memory.restore(extra.as_dict().get("setpoint_memory") or {}) + # Restore last HA state to device if applicable if self.restore_state: await self._restore_entity_state() @@ -428,6 +447,17 @@ async def _restore_entity_state(self) -> None: # noqa: C901 self.temperature_unit, ) + @property + @override + def extra_restore_state_data(self) -> GreeClimateExtraData | None: + """Keep the target temperatures per mode over a restart. + + For a zone controller these are the ones of its zones, which have no + climate entity of their own. + """ + memory = self.coordinator.setpoint_memory + return None if memory is None else GreeClimateExtraData(memory.data) + @override def _handle_coordinator_update(self) -> None: """Handle updated data from the coordinator.""" @@ -646,6 +676,16 @@ def get_hvac_mode(self) -> HVACMode: @override async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Set the HVAC Mode.""" + await self._async_set_hvac_mode(hvac_mode) + + async def _async_set_hvac_mode( + self, hvac_mode: HVACMode, temperature: float | None = None + ) -> None: + """Set the HVAC Mode, and the target temperature if one is given. + + Both go out in one command. A given temperature wins over the one the + setpoint memory has for the new mode. + """ _LOGGER.debug("set_hvac_mode(%s, %s)", self.device.unique_id, hvac_mode) if not self.available: @@ -655,6 +695,8 @@ async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: try: if hvac_mode == HVACMode.OFF: + if temperature is not None: + self.device.set_target_temperature(temperature) await self.async_turn_off() # This will be called in the turn on # await self._device.update_device_status() @@ -675,13 +717,16 @@ async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: DeviceType.AC_UNIT, DeviceType.VRF_UNIT, ) + # Before anything is set, so it stores what the devices report if memory is not None: await memory.snapshot( [*zones, self.device] if for_itself else zones, old_mode ) self.device.set_operation_mode(new_mode) - if ( + if temperature is not None: + self.device.set_target_temperature(temperature) + elif ( memory is not None and for_itself and new_mode is not OperationMode.auto @@ -701,11 +746,7 @@ async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: # await self._device.update_device_status() if memory is not None: - changed = await memory.recall(zones, new_mode) - for zone in self.coordinator.zone_coordinators: - if zone.device in changed: - zone.async_update_listeners() - await zone.async_request_refresh() + await self._async_recall_zones(memory, new_mode) # notify coordinator listeners of state change so that dependent entities are updated immediately self.coordinator.async_update_listeners() @@ -719,6 +760,17 @@ async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: self.async_write_ha_state() + async def _async_recall_zones( + self, memory: SetpointMemory, mode: OperationMode + ) -> None: + """Send the stored target temperatures of a mode to the zones, if any.""" + zones = self.coordinator.zone_coordinators + changed = await memory.recall([zone.device for zone in zones], mode) + for zone in zones: + if zone.device in changed: + zone.async_update_listeners() + await zone.async_request_refresh() + def get_fan_mode(self) -> str: """Convert Gree Fan Modes to HA. Accounts for the 2 special modes.""" if ( @@ -926,13 +978,12 @@ async def async_set_temperature(self, **kwargs: Any) -> None: try: # TODO: Confirm that HA sends the values in this entity's temperature_unit which matches the device unit - if temperature is not None: - self.device.set_target_temperature(temperature) - if hvac_mode and hvac_mode in self._attr_hvac_modes: - # This will call the set_hvac_mode which internally will send to device - await self.async_set_hvac_mode(hvac_mode) + # Sets the temperature too, and sends both in one command + await self._async_set_hvac_mode(hvac_mode, temperature) else: + if temperature is not None: + self.device.set_target_temperature(temperature) await self.coordinator.push_device_status() # notify coordinator listeners of state change so that dependent entities are updated immediately diff --git a/custom_components/gree_custom/coordinator.py b/custom_components/gree_custom/coordinator.py index 3f86cc9f..7982881c 100755 --- a/custom_components/gree_custom/coordinator.py +++ b/custom_components/gree_custom/coordinator.py @@ -61,9 +61,10 @@ def __init__( self._feature_auto_light: bool = False self._unsub_follow_up_refresh: CALLBACK_TYPE | None = None self._is_shut_down: bool = False - # The memory of the target temperatures per mode. Set on the ducted - # unit of a zone controller, with the zones of the same controller, and - # on a standalone or VRF unit that remembers its own target. + # The memory of the target temperatures per mode. Set on every device + # it learns from: a standalone or VRF unit that remembers its own + # target, and the zones of a zone controller. Also set on the ducted + # unit, with its zones, because its mode change sets them. self.setpoint_memory: SetpointMemory | None = None self.zone_coordinators: list[GreeCoordinator] = [] @@ -136,6 +137,10 @@ async def _update_data(self) -> None: _LOGGER.exception("Error getting state from device") raise UpdateFailed("Error getting state from device") from err + # Here and only here: each call is then one new read of the device. + if self.setpoint_memory is not None: + self.setpoint_memory.learn(self.device) + async def push_device_status(self) -> None: """Push the current transient state to the device. diff --git a/custom_components/gree_custom/setpoint_memory.py b/custom_components/gree_custom/setpoint_memory.py index f5c762df..ae6aab47 100644 --- a/custom_components/gree_custom/setpoint_memory.py +++ b/custom_components/gree_custom/setpoint_memory.py @@ -1,124 +1,87 @@ """The target temperature of a device, remembered per mode. -The wall panel of a zone controller remembers the target temperature of every -zone for each mode, and sets them again when the mode is changed on the panel. -A mode change over WiFi does not do that: the zones keep the values of the old -mode (seen on a LE60-13/GH). This class keeps the same memory, so a mode change -from Home Assistant works like one on the panel. See docs/protocol.md. - -It is Home Assistant behaviour, turned on per device by the setpoint_memory -option, so it lives here and not in aiogree. It still imports nothing from -Home Assistant, so the tests need no Home Assistant instance. - -- A device reports its mode and its target temperature in one reply, so the - two belong together. A value is stored when the device reported the same - mode on the read before. A read in the middle of a mode change on the panel - is then not stored under the wrong mode. Another look at the same read does - not count, see `GreeDevice.status_reads`. -- Only what a device reported is stored, never a value that is set and not - sent yet. A standalone or VRF unit learns only while it is on. A zone also - learns while it is closed: its `Pow` is its damper, not the power of the - unit. -- Before the mode is changed, `snapshot()` reads the devices again and stores - them under the old mode, so a change made on the panel since the last poll is - not lost. After the change, `recall()` sends the stored values of the new - mode. -- What is stored are the raw columns that hold the target temperature, as - `GreeDevice.target_temperature_props` gives them, per device MAC and mode: - `StTem` and `StFahFlg` for a zone, `SetTem` and `TemRec` for a standalone or - VRF unit. -- For a unit that remembers its own target, `apply()` sets the stored value - without sending it, so it can go out in the same command as the new mode. - It uses `GreeDevice.set_state_props()`, since the raw columns need no - conversion. A target set for the same command, for example by - `climate.set_temperature` with a mode, wins over the stored one. - -The memory does not store itself. The owner loads `data` and saves it when -`on_change` is called. +When the mode is changed on the wall panel of a zone controller, the panel sets +the target temperatures the zones had in that mode. A mode change over WiFi +does not. This class remembers the targets per device and mode, from what the +devices report, so a mode change from Home Assistant can set them. A standalone +or VRF unit uses it for its own target. It is Home Assistant behaviour, turned +on per device by the setpoint_memory option, but imports nothing from Home +Assistant. See docs/protocol.md. """ -from collections.abc import Callable, Iterable, Mapping +from collections.abc import Iterable, Mapping import logging +from typing import Any -from .aiogree.api import PROP_KEY_TO_ENUM, DeviceType, GreeProp, OperationMode +from .aiogree.api import DeviceType, OperationMode, TemperatureUnits from .aiogree.device import GreeDevice from .aiogree.errors import GreeError _LOGGER = logging.getLogger(__name__) -# {device MAC: {mode name: {column: raw value}}} -type SetpointMemoryData = dict[str, dict[str, dict[str, int]]] +# {device MAC: {mode name: {"temperature": 20.5, "unit": "C"}}} +type SetpointMemoryData = dict[str, dict[str, dict[str, Any]]] class SetpointMemory: """Remembers the target temperature of devices per mode.""" - def __init__( - self, - data: SetpointMemoryData | None = None, - on_change: Callable[[], None] | None = None, - ) -> None: - """Start with stored data, if there is any. - - Args: - data: What `data` held before, for example after a restart. - on_change: Called after a stored value changed. - - """ - self._data: SetpointMemoryData = data or {} - self._on_change = on_change - # The read and the mode each device reported on it, as last seen by - # learn(). - self._last_read: dict[str, tuple[int, OperationMode]] = {} + def __init__(self) -> None: + """Start empty. The climate entity restores what was stored.""" + self._data: SetpointMemoryData = {} + # The mode each device reported on its last read, see learn(). + self._last_mode: dict[str, OperationMode] = {} @property def data(self) -> SetpointMemoryData: - """Everything that is stored, to be saved by the owner.""" - return self._data - - def stored(self, device_mac: str, mode: OperationMode) -> dict[GreeProp, int]: - """Return the stored target temperature columns of a device for one mode.""" - columns = self._data.get(device_mac, {}).get(mode.name, {}) + """Return a copy of everything that is stored.""" return { - PROP_KEY_TO_ENUM[key]: value - for key, value in columns.items() - if key in PROP_KEY_TO_ENUM + mac: {mode: dict(value) for mode, value in modes.items()} + for mac, modes in self._data.items() } + def restore(self, data: Mapping[str, Any]) -> None: + """Take back what `data` gave before a restart. Values learned since win.""" + for mac, modes in data.items(): + if not isinstance(modes, Mapping): + continue + for mode, value in modes.items(): + if mode in OperationMode.__members__ and _is_stored_value(value): + self._data.setdefault(mac, {}).setdefault(mode, dict(value)) + + def stored(self, device: GreeDevice, mode: OperationMode) -> float | None: + """Return the stored target of a device for a mode, in the unit it uses now.""" + value = self._data.get(device.mac_address, {}).get(mode.name) + if value is None: + return None + + temperature = float(value["temperature"]) + unit = device.target_temperature_unit + if value["unit"] == unit.name: + return temperature + if unit is TemperatureUnits.F: + return float(round(temperature * 9 / 5 + 32)) + return round((temperature - 32) * 5 / 9 * 2) / 2 + def learn(self, device: GreeDevice) -> None: """Store what a device reported, once it reports the same mode twice in a row. - Call this whenever the device may have been read, for example from a - coordinator listener. A call without a new read changes nothing. + The coordinator calls this after every read. A device reports its mode + and its target in one reply, so a read in the middle of a mode change on + the panel is not stored under the wrong mode. """ - props = device.target_temperature_props - if props is None: - return - - read = device.status_reads - last = self._last_read.get(device.mac_address) - if last is not None and last[0] == read: - return mode = device.operation_mode - self._last_read[device.mac_address] = (read, mode) - - # Values that were just sent and are not confirmed yet are stored once - # the device reports them. - if ( - last is not None - and last[1] is mode - and not device.has_held_values - and _is_running(device) - ): - self._remember(device, mode, props) + if self._last_mode.get(device.mac_address) is mode: + self._store(device, mode) + self._last_mode[device.mac_address] = mode async def snapshot( self, devices: Iterable[GreeDevice], mode: OperationMode ) -> None: - """Read the devices again and store their values under the mode that is about to end. + """Read the devices again and store their targets under the mode that ends. - What the devices report is stored, not a target that is set and not - sent yet. + Call it before the new mode or a new target is set, so a change made on + the panel or with the remote since the last poll is kept. """ for device in devices: try: @@ -129,20 +92,12 @@ async def snapshot( device.unique_id, ) continue - - props = device.target_temperature_props - if ( - props is not None - and device.operation_mode is mode - and not device.has_held_values - and _is_running(device) - ): - self._remember(device, mode, props) + self._store(device, mode) async def recall( self, devices: Iterable[GreeDevice], mode: OperationMode ) -> list[GreeDevice]: - """Send the stored target temperatures of a mode to the devices. + """Send the stored targets of a mode to the devices. Returns: The devices that got a new target temperature @@ -167,51 +122,51 @@ async def recall( return changed def apply(self, device: GreeDevice, mode: OperationMode) -> bool: - """Set the stored target temperature of a mode on a device, without sending it. - - A target that is already set for the same command wins, for example - one given to climate.set_temperature with the mode. + """Set the stored target of a mode on a device, without sending it. Returns: True if the device got a new target temperature to send """ - stored = self.stored(device.mac_address, mode) - if ( - not stored - or device.has_pending_target_temperature - or stored == device.target_temperature_props - ): + temperature = self.stored(device, mode) + if temperature is None or temperature == device.target_temperature: return False - device.set_state_props(stored) + device.set_target_temperature(temperature) return True - def _remember( - self, device: GreeDevice, mode: OperationMode, props: Mapping[GreeProp, int] - ) -> None: - """Store the target temperature columns a device has now for one mode.""" - columns = {prop.value: value for prop, value in props.items()} - modes = self._data.setdefault(device.mac_address, {}) - if modes.get(mode.name) == columns: + def _store(self, device: GreeDevice, mode: OperationMode) -> None: + """Store the target of a device under a mode, if it belongs to that mode.""" + temperature = device.target_temperature + if ( + temperature is None + or device.operation_mode is not mode + # Sent and not confirmed yet: stored once the device reports it + or device.has_held_values + # An off unit keeps a mode and a target that are not in use. A + # zone's Pow is its damper, so a closed zone still counts. + or (device.device_type is not DeviceType.ZONE and not device.power_mode) + ): return - modes[mode.name] = columns - _LOGGER.debug( - "[%s] Stored target temperature %s for %s", - device.unique_id, - columns, - mode.name, - ) - if self._on_change is not None: - self._on_change() - - -def _is_running(device: GreeDevice) -> bool: - """Return True if the target of the device belongs to the mode it reports. - - A standalone or VRF unit that is off keeps a mode and a target, but they - are not in use. A zone's Pow is its damper, not the power of the unit, so - a closed zone counts as running. - """ - return device.device_type is DeviceType.ZONE or device.power_mode + unit = device.target_temperature_unit.name + value = {"temperature": float(temperature), "unit": unit} + modes = self._data.setdefault(device.mac_address, {}) + if modes.get(mode.name) != value: + modes[mode.name] = value + _LOGGER.debug( + "[%s] Stored %s %s for %s", + device.unique_id, + temperature, + unit, + mode.name, + ) + + +def _is_stored_value(value: Any) -> bool: + """Return True if `value` is a target as _store() stores it.""" + return ( + isinstance(value, Mapping) + and isinstance(value.get("temperature"), int | float) + and value.get("unit") in TemperatureUnits.__members__ + ) diff --git a/docs/architecture.md b/docs/architecture.md index 751793f1..19cdeee3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -27,7 +27,7 @@ No Home Assistant imports here. |---|---| | `__init__.py` | Entry setup. Builds transports and devices, binds them, starts one `GreeCoordinator` per device. Creates and links the VRF controller devices, see [VRF controller device](#vrf-controller-device). | | `coordinator.py` | `GreeCoordinator`. Polls on `scan_interval` and listens for status pushed by the device. Polls again every 2 s after a command while the device has not confirmed it, until the hold ends. | -| `setpoint_memory.py` | `SetpointMemory`. The target temperature of a device per mode, stored as raw columns per device MAC. Used for every device with a target temperature, unless its `setpoint_memory` option is off: for the zones of a zone controller, so a mode change works like one on the wall panel, and for a standalone or VRF unit itself. It imports nothing from Home Assistant; `__init__.py` keeps it in a `Store`. See [protocol.md](protocol.md#target-temperatures-per-mode). | +| `setpoint_memory.py` | `SetpointMemory`. The target temperature of a device per mode, stored with its unit per device MAC. Used for every device with a target temperature, unless its `setpoint_memory` option is off: for the zones of a zone controller, so a mode change works like one on the wall panel, and for a standalone or VRF unit itself. The coordinator feeds it after every read, and the climate entity keeps it in its restore state. It imports nothing from Home Assistant. See [protocol.md](protocol.md#target-temperatures-per-mode). | | `config_flow.py` | Setup, reconfigure, reauth and YAML import flows. Local discovery, cloud login, device picker, per device options. Reconfigure is a menu over the same steps, see [config-entry.md](config-entry.md#reconfigure). `async_step_import` turns one validated YAML item into a config entry. | | `config_schema.py` | `CONFIG_SCHEMA` for the `gree_custom:` block in `configuration.yaml`. Validates the YAML, normalizes the MAC addresses and fills the defaults. It also holds the form schemas that the config flow shows. | | `migration.py` | Moves a 4.x setup (domain `gree`) to this integration: config entries, the `gree:` YAML block, and the device and entity registry rows. See [config-entry.md](config-entry.md#migration-from-4x). | diff --git a/docs/protocol.md b/docs/protocol.md index 84a5e57c..3255f9a7 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -108,11 +108,11 @@ A zone controller (seen: LE60-13/GH with a ME31-00/C13 WiFi module, firmware `36 The wall panel remembers the target temperature of every zone per mode. When the mode is changed on the panel, it sets them again. A `Mod` change over WiFi does not: the zones keep the values of the old mode. `SetpointMemory` in `setpoint_memory.py`, in the Home Assistant layer, keeps the same memory: -- It learns from every read of a zone. A zone reports its mode and its target temperature in one reply, so the two belong together. A value is stored when the zone reported the same mode on the read before, so a read in the middle of a mode change on the panel is not stored under the wrong mode. A read counts once, however often the entities are updated from it (`GreeDevice.status_reads`). Only reported values are stored, never a target that is set and not sent yet. A closed zone learns too: a zone's `Pow` is its damper, not the power of the unit. +- It learns from every read of a zone: `GreeCoordinator._update_data()` calls `learn()` after each read, and nothing else does. A zone reports its mode and its target temperature in one reply, so the two belong together. A value is stored when the zone reported the same mode on the read before, so a read in the middle of a mode change on the panel is not stored under the wrong mode. A closed zone learns too: a zone's `Pow` is its damper, not the power of the unit. - Before the climate entity of the ducted unit changes the mode, `snapshot()` reads the zones again and stores them under the old mode. After the change, `recall()` sends the stored values of the new mode. A mode with no stored values changes nothing. -- It stores the raw columns that hold the target temperature, as `GreeDevice.target_temperature_props` gives them, keyed by device MAC and mode: `{"": {"heat": {"StTem": 3, "StFahFlg": 0}}}`. Raw columns need no unit conversion. They are the columns the device uses: a zone stores `StTem` and its bit `StFahFlg`, so a half degree or a °F value comes back exactly. A standalone or VRF unit stores `SetTem` and `TemRec`. -- A standalone or VRF unit uses the same memory for itself. The device option `setpoint_memory`, on by default, turns the memory off for one device, a zone included. It stores `SetTem` and `TemRec`, so a unit set to Fahrenheit needs no conversion. It learns only while the unit is on: an off unit keeps a mode and a target that are not in use. On a mode change from Home Assistant, `snapshot()` reads the unit once more, so a change made with the remote since the last poll is kept. Then `apply()` sets the stored target with `GreeDevice.set_state_props()`, without sending it, and it goes out in the same command as the new mode. A target given with the mode, as `climate.set_temperature` does with `hvac_mode`, wins over the stored one. Nothing is recalled into Auto, where the unit ignores the target temperature. -- `__init__.py` keeps the memory in a `Store` per config entry (`gree_custom..setpoints`). It is saved when the entry unloads, and removed with the entry. +- It stores `GreeDevice.target_temperature` with its unit, keyed by device MAC and mode: `{"": {"heat": {"temperature": 19.5, "unit": "C"}}}`. Through `set_target_temperature()`, every target in range comes back as the same temperature, with its bit: `StFahFlg` next to `StTem` for a zone. In °C these are also the same columns. In °F, three values come back with the other encoding of the same °F. A value stored in the other unit is converted. +- A standalone or VRF unit uses the same memory for itself. The device option `setpoint_memory`, on by default, turns the memory off for one device, a zone included. A unit learns only while it is on: an off unit keeps a mode and a target that are not in use. On a mode change from Home Assistant, `snapshot()` reads the unit once more, so a change made with the remote since the last poll is kept. Then `apply()` sets the stored target without sending it, and it goes out in the same command as the new mode. A target given with the mode, as `climate.set_temperature` does with `hvac_mode`, is set instead of the stored one, in the same command. Nothing is recalled into Auto, where the unit ignores the target temperature. +- The climate entity keeps the memory in its restore state, the climate entity of the ducted unit for its zones. Home Assistant saves it every 15 minutes, on a stop, and when the entity is removed, for example on a reload. It is restored whether or not `restore_states` is on. ## MAC addresses diff --git a/tests/config_flow/test_setpoint_memory_climate.py b/tests/config_flow/test_setpoint_memory_climate.py index bac7c8b5..5ec7ed84 100644 --- a/tests/config_flow/test_setpoint_memory_climate.py +++ b/tests/config_flow/test_setpoint_memory_climate.py @@ -1,12 +1,16 @@ """The target temperature per mode, through the climate entity of a real Home Assistant. -The memory itself is tested in tests/test_setpoint_memory.py. This checks what a -service call does with it. +The memory itself is tested in tests/test_setpoint_memory.py. This checks that +the coordinator feeds it from its reads, what a service call does with it, and +that the climate entity keeps it over a reload and a restart. """ import pytest +from custom_components.gree_custom.coordinator import GreeCoordinator +from custom_components.gree_custom.setpoint_memory import SetpointMemory from homeassistant.components.climate import DOMAIN as CLIMATE_DOMAIN +from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_TEMPERATURE, @@ -14,8 +18,9 @@ MINOR_VERSION, ) from homeassistant.core import HomeAssistant -from homeassistant.helpers import entity_registry as er +from homeassistant.helpers import entity_registry as er, restore_state from tests.config_flow.conftest import MAC_A, GreeEnv, add_entry +from tests.fakes.device import FakeGreeDevice # The climate entity uses the native temperature API of Home Assistant 2026.11 # (#570). The test plugin is still pinned to 2026.10, where the entity cannot @@ -25,42 +30,128 @@ reason="the climate entity needs Home Assistant 2026.11", ) +COOL_24 = {"temperature": 24.0, "unit": "C"} +HEAT_20 = {"temperature": 20.0, "unit": "C"} -async def test_set_temperature_with_a_mode_keeps_the_given_temperature( + +async def add_unit( hass: HomeAssistant, gree: GreeEnv -) -> None: - """A temperature given with the mode wins over the remembered one.""" +) -> tuple[FakeGreeDevice, ConfigEntry, GreeCoordinator]: + """Add a standalone unit that is in Cool at 24 degrees.""" fake = gree.devices[MAC_A] fake.values.update({"Pow": 1, "Mod": 1, "SetTem": 24, "TemRec": 0, "TemUn": 0}) host = await gree.start_udp(fake) entry = await add_entry(hass, ["local"], [MAC_A], [host]) - coordinator = next(iter(entry.runtime_data.values())) - memory = coordinator.setpoint_memory - assert memory is not None + return fake, entry, next(iter(entry.runtime_data.values())) - async def poll() -> None: - await coordinator.async_refresh() - await hass.async_block_till_done() - # Heat 20 and Cool 24, as set with the remote +async def poll(hass: HomeAssistant, coordinator: GreeCoordinator) -> None: + """One poll, as the update interval does.""" + await coordinator.async_refresh() + await hass.async_block_till_done() + + +async def learn_heat_and_cool( + hass: HomeAssistant, fake: FakeGreeDevice, coordinator: GreeCoordinator +) -> None: + """Heat 20 and then Cool 24, as set with the remote, each seen on two polls.""" fake.values.update({"Mod": 4, "SetTem": 20}) - await poll() - await poll() + await poll(hass, coordinator) + await poll(hass, coordinator) fake.values.update({"Mod": 1, "SetTem": 24}) - await poll() - await poll() + await poll(hass, coordinator) + await poll(hass, coordinator) - climate = next( + +def memory_of(entry: ConfigEntry) -> SetpointMemory: + """Return the setpoint memory of the unit of the entry.""" + memory = next(iter(entry.runtime_data.values())).setpoint_memory + assert memory is not None + return memory + + +def climate_of(hass: HomeAssistant, entry: ConfigEntry) -> str: + """Return the entity id of the climate entity of the entry.""" + return next( e.entity_id for e in er.async_entries_for_config_entry(er.async_get(hass), entry.entry_id) if e.domain == CLIMATE_DOMAIN ) + + +async def test_a_change_on_the_device_is_learned_from_the_polls( + hass: HomeAssistant, gree: GreeEnv +) -> None: + """A mode set with the remote is stored on the second poll that sees it.""" + fake, _, coordinator = await add_unit(hass, gree) + memory = coordinator.setpoint_memory + assert memory is not None + + fake.values.update({"Mod": 4, "SetTem": 20}) + await poll(hass, coordinator) + # Updates of the entities are not reads + coordinator.async_update_listeners() + coordinator.async_update_listeners() + assert "heat" not in memory.data.get(MAC_A, {}) + + await poll(hass, coordinator) + assert memory.data[MAC_A]["heat"] == HEAT_20 + + # Changed with the remote, in the same mode + fake.values["SetTem"] = 21 + await poll(hass, coordinator) + assert memory.data[MAC_A]["heat"] == {"temperature": 21.0, "unit": "C"} + + +async def test_set_temperature_with_a_mode_keeps_the_given_temperature( + hass: HomeAssistant, gree: GreeEnv +) -> None: + """A temperature given with the mode wins over the remembered one.""" + fake, entry, coordinator = await add_unit(hass, gree) + await learn_heat_and_cool(hass, fake, coordinator) + await hass.services.async_call( CLIMATE_DOMAIN, "set_temperature", - {ATTR_ENTITY_ID: climate, ATTR_TEMPERATURE: 22, "hvac_mode": "heat"}, + { + ATTR_ENTITY_ID: climate_of(hass, entry), + ATTR_TEMPERATURE: 22, + "hvac_mode": "heat", + }, blocking=True, ) assert (fake.values["Mod"], fake.values["SetTem"]) == (4, 22) - assert memory.data[MAC_A]["cool"]["SetTem"] == 24 + assert memory_of(entry).data[MAC_A]["cool"] == COOL_24 + + +async def test_the_memory_is_kept_over_a_reload_and_a_restart( + hass: HomeAssistant, gree: GreeEnv +) -> None: + """The climate entity keeps it in its restore state.""" + fake, entry, coordinator = await add_unit(hass, gree) + await learn_heat_and_cool(hass, fake, coordinator) + learned = {MAC_A: {"cool": COOL_24, "heat": HEAT_20}} + assert memory_of(entry).data == learned + + # The entity that is removed hands its data to the new one + assert await hass.config_entries.async_reload(entry.entry_id) + await hass.async_block_till_done() + assert memory_of(entry).data == learned + + # Saved to storage on a stop, and loaded from it on the next start + restored = restore_state.async_get(hass) + await restored.async_dump_states() + assert await hass.config_entries.async_unload(entry.entry_id) + await restored.async_load() + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + assert memory_of(entry).data == learned + + await hass.services.async_call( + CLIMATE_DOMAIN, + "set_hvac_mode", + {ATTR_ENTITY_ID: climate_of(hass, entry), "hvac_mode": "heat"}, + blocking=True, + ) + assert (fake.values["Mod"], fake.values["SetTem"]) == (4, 20) diff --git a/tests/test_setpoint_memory.py b/tests/test_setpoint_memory.py index 7e5c2522..9f487fc8 100644 --- a/tests/test_setpoint_memory.py +++ b/tests/test_setpoint_memory.py @@ -17,11 +17,7 @@ # layer as custom_components.gree_custom.aiogree. The devices must come from # the same import, not the top level "aiogree" the protocol tests use: two # imports are two copies, and their enums would not compare equal. -from custom_components.gree_custom.aiogree.api import ( - DeviceType, - GreeProp, - OperationMode, -) +from custom_components.gree_custom.aiogree.api import DeviceType, OperationMode from custom_components.gree_custom.aiogree.device import GreeDevice from custom_components.gree_custom.aiogree.transport_udp import GreeUdpTransport from custom_components.gree_custom.setpoint_memory import SetpointMemory @@ -94,7 +90,7 @@ def set_on_panel(controller: FakeZoneController, temperatures: list[int]) -> Non async def poll(memory: SetpointMemory, devices: list[GreeDevice]) -> None: - """One poll of every device, as the coordinators do.""" + """One poll of every device, as the coordinators do: a read, then learn().""" for device in devices: await device.fetch_device_status() memory.learn(device) @@ -102,13 +98,9 @@ async def poll(memory: SetpointMemory, devices: list[GreeDevice]) -> None: def remembered( memory: SetpointMemory, zones: list[GreeDevice], mode: OperationMode -) -> list[int | None]: - """Return what the memory has for each zone in one mode, in degrees Celsius.""" - out: list[int | None] = [] - for zone in zones: - raw = memory.stored(zone.mac_address, mode).get(GreeProp.TARGET_TEMPERATURE_2) - out.append(None if raw is None else raw + 16) - return out +) -> list[float | None]: + """Return what the memory has for each zone in one mode.""" + return [memory.stored(zone, mode) for zone in zones] def temperatures(controller: FakeZoneController) -> list[int]: @@ -120,29 +112,29 @@ async def test_a_value_is_stored_once_the_mode_is_seen_twice( zones: list[GreeDevice], ) -> None: """The first poll after start only notes the mode.""" - changes: list[int] = [] - memory = SetpointMemory(on_change=lambda: changes.append(1)) + memory = SetpointMemory() await poll(memory, zones) assert memory.data == {} await poll(memory, zones) assert remembered(memory, zones, OperationMode.fan) == [18, 18, 18, 18] - assert changes -async def test_the_raw_columns_are_stored_per_device( +async def test_the_temperature_is_stored_with_its_unit( controller: FakeZoneController, zones: list[GreeDevice] ) -> None: - """Keyed by device and mode, with the raw column, so no unit conversion is needed.""" + """Keyed by device and mode.""" memory = SetpointMemory() await poll(memory, zones) await poll(memory, zones) - assert memory.data[controller.zone_macs[0]] == {"fan": {"StTem": 2, "StFahFlg": 0}} + assert memory.data[controller.zone_macs[0]] == { + "fan": {"temperature": 18.0, "unit": "C"} + } -async def test_a_unit_without_target_temperature_columns_is_ignored( +async def test_a_unit_without_a_target_temperature_is_ignored( controller: FakeZoneController, transport: GreeUdpTransport ) -> None: """The ducted unit has no target temperature, so there is nothing to remember.""" @@ -179,10 +171,11 @@ async def test_recall_sends_the_stored_values_of_the_new_mode( controller: FakeZoneController, zones: list[GreeDevice] ) -> None: """A mode change over WiFi keeps the old values. Recall puts the stored ones back.""" - memory = SetpointMemory( + memory = SetpointMemory() + memory.restore( { - controller.zone_macs[0]: {"heat": {"StTem": 3, "StFahFlg": 0}}, - controller.zone_macs[2]: {"heat": {"StTem": 1, "StFahFlg": 0}}, + controller.zone_macs[0]: {"heat": {"temperature": 19.0, "unit": "C"}}, + controller.zone_macs[2]: {"heat": {"temperature": 17.0, "unit": "C"}}, } ) await poll(memory, zones) @@ -213,7 +206,7 @@ async def test_recall_of_a_mode_without_values_changes_nothing( async def test_a_fahrenheit_target_comes_back_with_its_bit( controller: FakeZoneController, zones: list[GreeDevice] ) -> None: - """67 F is StTem 3 with StFahFlg 1. Without the bit, recall would give 66 F.""" + """67 F is StTem 3 with StFahFlg 1. It is stored as 67 F and set as 67 F.""" for values in controller.units.values(): values["TemUnit"] = 1 first = controller.units[controller.zone_macs[0]] @@ -234,10 +227,10 @@ async def test_a_fahrenheit_target_comes_back_with_its_bit( async def test_a_value_from_celsius_comes_back_right_in_fahrenheit( controller: FakeZoneController, zones: list[GreeDevice] ) -> None: - """The raw columns are the same in both units. + """A stored value is converted to the unit the device uses now. - 18.5 C is remembered as StTem 2 with the bit. After the unit is switched - to Fahrenheit between the modes, the same columns read as 65 F. + 18.5 C is StTem 2 with the bit. After the unit is switched to Fahrenheit + between the modes, it is set as 65 F, which is the same columns. """ first = controller.units[controller.zone_macs[0]] first.update({"StTem": 2, "StFahFlg": 1}) @@ -284,31 +277,44 @@ async def test_snapshot_does_not_store_values_of_another_mode( assert remembered(memory, zones, OperationMode.fan) == [None] * 4 -async def test_another_look_at_the_same_read_does_not_count( - zones: list[GreeDevice], +async def test_a_closed_zone_still_learns( + controller: FakeZoneController, zones: list[GreeDevice] ) -> None: - """A listener can run more than once per read. Only a new read counts.""" + """A zone's Pow is its damper. Its target still belongs to the mode.""" + controller.units[controller.zone_macs[1]]["Pow"] = 0 memory = SetpointMemory() - await poll(memory, zones) - for zone in zones: - memory.learn(zone) - assert memory.data == {} await poll(memory, zones) + await poll(memory, zones) + assert remembered(memory, zones, OperationMode.fan) == [18, 18, 18, 18] -async def test_a_closed_zone_still_learns( +async def test_restore_keeps_what_was_learned_since( controller: FakeZoneController, zones: list[GreeDevice] ) -> None: - """A zone's Pow is its damper. Its target still belongs to the mode.""" - controller.units[controller.zone_macs[1]]["Pow"] = 0 + """A value learned before the entity restored its data is newer.""" memory = SetpointMemory() - await poll(memory, zones) await poll(memory, zones) + first = controller.zone_macs[0] - assert remembered(memory, zones, OperationMode.fan) == [18, 18, 18, 18] + memory.restore( + { + first: { + "fan": {"temperature": 22.0, "unit": "C"}, + "heat": {"temperature": 20.0, "unit": "C"}, + "warm": {"temperature": 21.0, "unit": "C"}, + "cool": {"temperature": "24", "unit": "C"}, + }, + controller.zone_macs[1]: "not a mode", + } + ) + + assert memory.data[first] == { + "fan": {"temperature": 18.0, "unit": "C"}, + "heat": {"temperature": 20.0, "unit": "C"}, + } # @@ -334,19 +340,6 @@ async def unit() -> AsyncIterator[tuple[FakeGreeDevice, GreeDevice]]: fake.close() -async def test_a_standalone_unit_gives_set_tem_and_tem_rec( - unit: tuple[FakeGreeDevice, GreeDevice], -) -> None: - """SetTem holds the degrees and TemRec the half degree.""" - _, device = unit - - assert device.device_type is DeviceType.AC_UNIT - assert device.target_temperature_props == { - GreeProp.TARGET_TEMPERATURE_1: 24, - GreeProp.TARGET_TEMPERATURE_BIT_1: 0, - } - - async def test_a_unit_learns_its_target_and_sends_it_with_the_mode( unit: tuple[FakeGreeDevice, GreeDevice], ) -> None: @@ -360,9 +353,10 @@ async def test_a_unit_learns_its_target_and_sends_it_with_the_mode( await poll(memory, [device]) assert memory.data[fake.mac] == { - "cool": {"SetTem": 24, "TemRec": 0}, - "heat": {"SetTem": 20, "TemRec": 0}, + "cool": {"temperature": 24.0, "unit": "C"}, + "heat": {"temperature": 20.0, "unit": "C"}, } + assert device.device_type is DeviceType.AC_UNIT device.set_operation_mode(OperationMode.cool) assert memory.apply(device, OperationMode.cool) @@ -375,10 +369,10 @@ async def test_a_unit_learns_its_target_and_sends_it_with_the_mode( assert (fake.values["Mod"], fake.values["SetTem"]) == (1, 24) -async def test_a_fahrenheit_target_is_stored_raw( +async def test_a_fahrenheit_target_is_stored_in_fahrenheit( unit: tuple[FakeGreeDevice, GreeDevice], ) -> None: - """The raw columns already hold the Fahrenheit value, so nothing is converted.""" + """SetTem 24 with TemRec 1 is 76 F.""" fake, device = unit fake.values.update({"TemUn": 1, "SetTem": 24, "TemRec": 1}) memory = SetpointMemory() @@ -386,7 +380,7 @@ async def test_a_fahrenheit_target_is_stored_raw( await poll(memory, [device]) await poll(memory, [device]) - assert memory.data[fake.mac] == {"cool": {"SetTem": 24, "TemRec": 1}} + assert memory.data[fake.mac] == {"cool": {"temperature": 76.0, "unit": "F"}} async def test_apply_without_a_stored_target_changes_nothing( @@ -403,32 +397,6 @@ async def test_apply_without_a_stored_target_changes_nothing( assert not any(pack.get("t") == "cmd" for pack in fake.packs) -async def test_a_target_given_with_the_mode_wins( - unit: tuple[FakeGreeDevice, GreeDevice], -) -> None: - """As climate.set_temperature does with a temperature and a mode.""" - fake, device = unit - memory = SetpointMemory() - await poll(memory, [device]) - await poll(memory, [device]) - fake.values.update({"Mod": 4, "SetTem": 20}) - await poll(memory, [device]) - await poll(memory, [device]) - - # In Heat at 20, asked for 22 in Cool - device.set_target_temperature(22) - await memory.snapshot([device], OperationMode.heat) - device.set_operation_mode(OperationMode.cool) - assert not memory.apply(device, OperationMode.cool) - await device.push_device_status() - - assert (fake.values["Mod"], fake.values["SetTem"]) == (1, 22) - assert memory.data[fake.mac] == { - "cool": {"SetTem": 24, "TemRec": 0}, - "heat": {"SetTem": 20, "TemRec": 0}, - } - - async def test_a_unit_that_is_off_learns_nothing( unit: tuple[FakeGreeDevice, GreeDevice], ) -> None: From ad7f5c494446fff03b1ea96f9c8104fe2d221790 Mon Sep 17 00:00:00 2001 From: Twintop Date: Mon, 16 Nov 2026 00:44:10 +1100 Subject: [PATCH 8/9] Setpoint memory: let the coordinators do the I/O, option on the AC unit The read before a mode change is now a refresh of the coordinators, whose learn() stores the old mode. The zones get their stored targets through their own coordinator, with its IP recovery and follow-up refresh, like any other command. The memory itself does no I/O, so snapshot() and recall() are gone. The option is now on the device whose mode changes: a unit with a target temperature, or the ducted unit of a zone controller for all of its zones, as the wall panel does. GreeDevice is unchanged from 5.0-dev. restore() is a plain copy. It runs while the climate entity is added, before the memory has seen the two reads it needs to store anything. New test through Home Assistant: the zones of a zone controller learn from the polls, and a mode change of the ducted unit sets them. --- custom_components/gree_custom/__init__.py | 52 ++---- .../gree_custom/aiogree/device.py | 8 - custom_components/gree_custom/climate.py | 69 +++---- .../gree_custom/config_schema.py | 6 +- custom_components/gree_custom/coordinator.py | 7 +- .../gree_custom/setpoint_memory.py | 176 ++++++------------ .../gree_custom/translations/en.json | 2 +- docs/architecture.md | 2 +- docs/config-entry.md | 2 +- docs/configuration.md | 2 +- docs/entities.md | 2 +- docs/protocol.md | 5 +- .../test_setpoint_memory_climate.py | 42 ++++- tests/test_setpoint_memory.py | 82 ++++---- 14 files changed, 200 insertions(+), 257 deletions(-) diff --git a/custom_components/gree_custom/__init__.py b/custom_components/gree_custom/__init__.py index 1581bafa..021cffc7 100755 --- a/custom_components/gree_custom/__init__.py +++ b/custom_components/gree_custom/__init__.py @@ -84,7 +84,7 @@ async_unload_legacy_entries, ) from .services import async_setup_services -from .setpoint_memory import SetpointMemory +from .setpoint_memory import SetpointMemory, offers_setpoint_memory ISSUE_DEVICE_CONNECTION_FAILED = "device_connection_failed" ISSUE_YAML_IMPORT_FAILED = "yaml_import_failed" @@ -341,44 +341,28 @@ async def _async_refresh_entry_token( def _setup_setpoint_memory(coordinators: dict[str, GreeCoordinator]) -> None: - """Give the devices that remember their target temperature per mode a memory. - - Every device with a target temperature does, unless its setpoint_memory - option is off. A standalone or VRF unit gets a memory for itself. The - zones of a zone controller follow the mode of their ducted unit, so they - share one memory with it: the zones learn, and a mode change of the ducted - unit sets them as the wall panel does. The climate entity keeps the memory - in its restore state. See setpoint_memory.py. - """ - learners = [ - c - for c in coordinators.values() - if c.device.has_target_temperature - and c.device_config.get(CONF_DEVICE_OPTIONS, {}).get( - CONF_SETPOINT_MEMORY, DEFAULT_SETPOINT_MEMORY - ) - ] - zones = [c for c in learners if c.device.device_type is DeviceType.ZONE] - - for unit in learners: - if unit.device.device_type is not DeviceType.ZONE: - unit.setpoint_memory = SetpointMemory() + """Give the units with the setpoint_memory option a memory. + The ducted unit of a zone controller shares it with its zones, as the wall + panel does: they learn into it, and its mode change sets them. See + setpoint_memory.py. + """ for coordinator in coordinators.values(): - if coordinator.device.device_type is not DeviceType.ZONE_CONTROLLER: + device = coordinator.device + if not offers_setpoint_memory(device) or not coordinator.device_config.get( + CONF_DEVICE_OPTIONS, {} + ).get(CONF_SETPOINT_MEMORY, DEFAULT_SETPOINT_MEMORY): continue - own_zones = [ + + coordinator.setpoint_memory = SetpointMemory() + coordinator.zone_coordinators = [ zone - for zone in zones - if zone.device.mac_address_controller - == coordinator.device.mac_address_controller + for zone in coordinators.values() + if zone.device.device_type is DeviceType.ZONE + and zone.device.mac_address_controller == device.mac_address_controller ] - if own_zones: - memory = SetpointMemory() - coordinator.setpoint_memory = memory - coordinator.zone_coordinators = own_zones - for zone in own_zones: - zone.setpoint_memory = memory + for zone in coordinator.zone_coordinators: + zone.setpoint_memory = coordinator.setpoint_memory async def async_unload_entry(hass: HomeAssistant, entry: GreeConfigEntry) -> bool: diff --git a/custom_components/gree_custom/aiogree/device.py b/custom_components/gree_custom/aiogree/device.py index 5abdb26e..4ffe9889 100755 --- a/custom_components/gree_custom/aiogree/device.py +++ b/custom_components/gree_custom/aiogree/device.py @@ -970,14 +970,6 @@ def set_target_temperature_unit(self, units: TemperatureUnits) -> None: return self._state.set(self._temp_unit_prop, units) - @property - def has_target_temperature(self) -> bool: - """Return True if the device answers a target temperature column. - - The ducted unit of a zone controller has none, its zones have one each. - """ - return self._target_temp_prop is not None - @property def has_target_temperature_bit(self) -> bool: """Return True if the device answers a bit for the target temperature. diff --git a/custom_components/gree_custom/climate.py b/custom_components/gree_custom/climate.py index 51141e2e..858a9179 100755 --- a/custom_components/gree_custom/climate.py +++ b/custom_components/gree_custom/climate.py @@ -44,7 +44,7 @@ VerticalSwingMode, ) from .aiogree.const import MAX_TEMP_C, MAX_TEMP_F, MIN_TEMP_C, MIN_TEMP_F -from .aiogree.errors import GreeTurboUnavailable +from .aiogree.errors import GreeError, GreeTurboUnavailable from .const import ( ATTR_EXTERNAL_HUMIDITY_SENSOR, ATTR_EXTERNAL_TEMPERATURE_SENSOR, @@ -757,36 +757,14 @@ async def _async_set_hvac_mode( # await self._device.update_device_status() else: new_mode = HVAC_MODES_HA_TO_GREE[hvac_mode] - old_mode = self.device.operation_mode - # A zone controller keeps the zone target temperatures of the old - # mode on a change over WiFi. Do what its wall panel does. - memory = ( - self.coordinator.setpoint_memory - if new_mode is not old_mode - else None - ) - zones = [z.device for z in self.coordinator.zone_coordinators] - # A standalone or VRF unit with the option remembers its own - # target. In Auto it ignores the target, so nothing goes there. - for_itself = self.device.device_type in ( - DeviceType.AC_UNIT, - DeviceType.VRF_UNIT, - ) - # Before anything is set, so it stores what the devices report - if memory is not None: - await memory.snapshot( - [*zones, self.device] if for_itself else zones, old_mode - ) + memory = await self._async_setpoint_memory_for(new_mode) self.device.set_operation_mode(new_mode) if temperature is not None: self.device.set_target_temperature(temperature) - elif ( - memory is not None - and for_itself - and new_mode is not OperationMode.auto - ): - # Goes out in the same command as the mode, below. + elif memory is not None and new_mode is not OperationMode.auto: + # A unit ignores its target in Auto. This goes out in the + # same command as the mode, below. memory.apply(self.device, new_mode) # The Auto X-FAN enables that feature if the device is set to a hvac mode that supports X-FAN @@ -815,16 +793,41 @@ async def _async_set_hvac_mode( self.async_write_ha_state() + async def _async_setpoint_memory_for( + self, new_mode: OperationMode + ) -> SetpointMemory | None: + """Return the setpoint memory if it is used for this mode change. + + The wall panel of a zone controller sets the zone targets of the new + mode, a mode change over WiFi does not, so the memory does it. A unit + with the memory gets its own target. One more read first, before + anything is set, so the old mode keeps a target changed since the last + poll. + """ + memory = self.coordinator.setpoint_memory + if memory is None or new_mode is self.device.operation_mode: + return None + + for coordinator in self.coordinator.zone_coordinators or [self.coordinator]: + await coordinator.async_refresh() + return memory + async def _async_recall_zones( self, memory: SetpointMemory, mode: OperationMode ) -> None: """Send the stored target temperatures of a mode to the zones, if any.""" - zones = self.coordinator.zone_coordinators - changed = await memory.recall([zone.device for zone in zones], mode) - for zone in zones: - if zone.device in changed: - zone.async_update_listeners() - await zone.async_request_refresh() + for zone in self.coordinator.zone_coordinators: + if not memory.apply(zone.device, mode): + continue + try: + await zone.push_device_status() + except GreeError: + _LOGGER.warning( + "[%s] Could not set the stored target temperature for %s", + zone.device.unique_id, + mode.name, + ) + zone.async_update_listeners() def get_fan_mode(self) -> str: """Convert Gree Fan Modes to HA. Accounts for the 2 special modes.""" diff --git a/custom_components/gree_custom/config_schema.py b/custom_components/gree_custom/config_schema.py index 18048ac9..200c05a5 100644 --- a/custom_components/gree_custom/config_schema.py +++ b/custom_components/gree_custom/config_schema.py @@ -104,6 +104,7 @@ ZONE_ONLY_FEATURES, ) from .helpers import get_entity_ids_from_unique_ids +from .setpoint_memory import offers_setpoint_memory HEX_CHARACTERS = "0123456789abcdef" VALID_MAC_LENGTHS = (12, 14) @@ -803,9 +804,8 @@ def setup_device_options_schema( # noqa: C901 } ) - # Every device with a target temperature can remember it per mode. A zone - # follows the mode of its ducted unit, which has no target of its own. - if device.has_target_temperature: + # On the ducted unit of a zone controller it is for all of its zones + if offers_setpoint_memory(device): schema.update( { probatio.Required( diff --git a/custom_components/gree_custom/coordinator.py b/custom_components/gree_custom/coordinator.py index 7982881c..60393515 100755 --- a/custom_components/gree_custom/coordinator.py +++ b/custom_components/gree_custom/coordinator.py @@ -61,10 +61,9 @@ def __init__( self._feature_auto_light: bool = False self._unsub_follow_up_refresh: CALLBACK_TYPE | None = None self._is_shut_down: bool = False - # The memory of the target temperatures per mode. Set on every device - # it learns from: a standalone or VRF unit that remembers its own - # target, and the zones of a zone controller. Also set on the ducted - # unit, with its zones, because its mode change sets them. + # The memory of the target temperatures per mode, on a unit with the + # setpoint_memory option. The ducted unit of a zone controller shares + # its memory with its zones, which learn into it. self.setpoint_memory: SetpointMemory | None = None self.zone_coordinators: list[GreeCoordinator] = [] diff --git a/custom_components/gree_custom/setpoint_memory.py b/custom_components/gree_custom/setpoint_memory.py index ae6aab47..ef60b6e9 100644 --- a/custom_components/gree_custom/setpoint_memory.py +++ b/custom_components/gree_custom/setpoint_memory.py @@ -3,65 +3,50 @@ When the mode is changed on the wall panel of a zone controller, the panel sets the target temperatures the zones had in that mode. A mode change over WiFi does not. This class remembers the targets per device and mode, from what the -devices report, so a mode change from Home Assistant can set them. A standalone -or VRF unit uses it for its own target. It is Home Assistant behaviour, turned -on per device by the setpoint_memory option, but imports nothing from Home -Assistant. See docs/protocol.md. +coordinators read, so a mode change from Home Assistant can set them as the +panel does. A standalone or VRF unit uses it for its own target. The memory +does no I/O of its own. See docs/protocol.md. """ -from collections.abc import Iterable, Mapping -import logging from typing import Any -from .aiogree.api import DeviceType, OperationMode, TemperatureUnits +from .aiogree.api import DeviceType, GreeProp, OperationMode, TemperatureUnits from .aiogree.device import GreeDevice -from .aiogree.errors import GreeError - -_LOGGER = logging.getLogger(__name__) # {device MAC: {mode name: {"temperature": 20.5, "unit": "C"}}} type SetpointMemoryData = dict[str, dict[str, dict[str, Any]]] +def offers_setpoint_memory(device: GreeDevice) -> bool: + """Return True if the setpoint_memory option is for this device. + + A unit with a target temperature of its own has it, and so has the ducted + unit of a zone controller, for all of its zones. + """ + if device.device_type is DeviceType.ZONE_CONTROLLER: + return True + return device.device_type is not DeviceType.ZONE and device.supports_property( + GreeProp.TARGET_TEMPERATURE_1 + ) + + class SetpointMemory: """Remembers the target temperature of devices per mode.""" def __init__(self) -> None: """Start empty. The climate entity restores what was stored.""" self._data: SetpointMemoryData = {} - # The mode each device reported on its last read, see learn(). + # The mode each device reported on its last read self._last_mode: dict[str, OperationMode] = {} @property def data(self) -> SetpointMemoryData: """Return a copy of everything that is stored.""" - return { - mac: {mode: dict(value) for mode, value in modes.items()} - for mac, modes in self._data.items() - } + return _copy(self._data) - def restore(self, data: Mapping[str, Any]) -> None: - """Take back what `data` gave before a restart. Values learned since win.""" - for mac, modes in data.items(): - if not isinstance(modes, Mapping): - continue - for mode, value in modes.items(): - if mode in OperationMode.__members__ and _is_stored_value(value): - self._data.setdefault(mac, {}).setdefault(mode, dict(value)) - - def stored(self, device: GreeDevice, mode: OperationMode) -> float | None: - """Return the stored target of a device for a mode, in the unit it uses now.""" - value = self._data.get(device.mac_address, {}).get(mode.name) - if value is None: - return None - - temperature = float(value["temperature"]) - unit = device.target_temperature_unit - if value["unit"] == unit.name: - return temperature - if unit is TemperatureUnits.F: - return float(round(temperature * 9 / 5 + 32)) - return round((temperature - 32) * 5 / 9 * 2) / 2 + def restore(self, data: SetpointMemoryData) -> None: + """Take back what `data` gave before a restart.""" + self._data = _copy(data) def learn(self, device: GreeDevice) -> None: """Store what a device reported, once it reports the same mode twice in a row. @@ -71,55 +56,24 @@ def learn(self, device: GreeDevice) -> None: the panel is not stored under the wrong mode. """ mode = device.operation_mode - if self._last_mode.get(device.mac_address) is mode: - self._store(device, mode) + last_mode = self._last_mode.get(device.mac_address) self._last_mode[device.mac_address] = mode + temperature = device.target_temperature + if ( + mode is not last_mode + or temperature is None + # Sent and not confirmed yet: stored once the device reports it + or device.has_held_values + # An off unit keeps a mode and a target that are not in use. A + # zone's Pow is its damper, so a closed zone still counts. + or (device.device_type is not DeviceType.ZONE and not device.power_mode) + ): + return - async def snapshot( - self, devices: Iterable[GreeDevice], mode: OperationMode - ) -> None: - """Read the devices again and store their targets under the mode that ends. - - Call it before the new mode or a new target is set, so a change made on - the panel or with the remote since the last poll is kept. - """ - for device in devices: - try: - await device.fetch_device_status() - except GreeError: - _LOGGER.debug( - "[%s] Could not read the device before the mode change", - device.unique_id, - ) - continue - self._store(device, mode) - - async def recall( - self, devices: Iterable[GreeDevice], mode: OperationMode - ) -> list[GreeDevice]: - """Send the stored targets of a mode to the devices. - - Returns: - The devices that got a new target temperature - - """ - changed: list[GreeDevice] = [] - for device in devices: - if not self.apply(device, mode): - continue - - try: - await device.push_device_status() - except GreeError: - _LOGGER.warning( - "[%s] Could not set the stored target temperature for %s", - device.unique_id, - mode.name, - ) - continue - changed.append(device) - - return changed + self._data.setdefault(device.mac_address, {})[mode.name] = { + "temperature": float(temperature), + "unit": device.target_temperature_unit.name, + } def apply(self, device: GreeDevice, mode: OperationMode) -> bool: """Set the stored target of a mode on a device, without sending it. @@ -128,45 +82,27 @@ def apply(self, device: GreeDevice, mode: OperationMode) -> bool: True if the device got a new target temperature to send """ - temperature = self.stored(device, mode) - if temperature is None or temperature == device.target_temperature: + stored = self._data.get(device.mac_address, {}).get(mode.name) + if stored is None: + return False + + temperature = stored["temperature"] + unit = device.target_temperature_unit + if stored["unit"] != unit.name: + temperature = ( + float(round(temperature * 9 / 5 + 32)) + if unit is TemperatureUnits.F + else round((temperature - 32) * 5 / 9 * 2) / 2 + ) + if temperature == device.target_temperature: return False device.set_target_temperature(temperature) return True - def _store(self, device: GreeDevice, mode: OperationMode) -> None: - """Store the target of a device under a mode, if it belongs to that mode.""" - temperature = device.target_temperature - if ( - temperature is None - or device.operation_mode is not mode - # Sent and not confirmed yet: stored once the device reports it - or device.has_held_values - # An off unit keeps a mode and a target that are not in use. A - # zone's Pow is its damper, so a closed zone still counts. - or (device.device_type is not DeviceType.ZONE and not device.power_mode) - ): - return - - unit = device.target_temperature_unit.name - value = {"temperature": float(temperature), "unit": unit} - modes = self._data.setdefault(device.mac_address, {}) - if modes.get(mode.name) != value: - modes[mode.name] = value - _LOGGER.debug( - "[%s] Stored %s %s for %s", - device.unique_id, - temperature, - unit, - mode.name, - ) - -def _is_stored_value(value: Any) -> bool: - """Return True if `value` is a target as _store() stores it.""" - return ( - isinstance(value, Mapping) - and isinstance(value.get("temperature"), int | float) - and value.get("unit") in TemperatureUnits.__members__ - ) +def _copy(data: SetpointMemoryData) -> SetpointMemoryData: + return { + mac: {mode: dict(value) for mode, value in modes.items()} + for mac, modes in data.items() + } diff --git a/custom_components/gree_custom/translations/en.json b/custom_components/gree_custom/translations/en.json index 42d96db4..2259b42a 100644 --- a/custom_components/gree_custom/translations/en.json +++ b/custom_components/gree_custom/translations/en.json @@ -124,7 +124,7 @@ "external_temperature_sensor": "If set will replace the built-in HVAC temperature sensor for the Climate entity data", "external_humidity_sensor": "If set will replace the built-in HVAC humidity sensor for the Climate entity data", "restore_states": "If checked, when the integration is started the device will be overridden by previous states of the integration instead of using the current device state.", - "setpoint_memory": "If checked, the target temperature of each mode is remembered and set again when the mode is changed from Home Assistant. A zone follows the mode of its AC unit. A unit keeps its own setting in Auto.", + "setpoint_memory": "If checked, the target temperature of each mode is remembered and set again when the mode is changed from Home Assistant. On the AC unit of a zone controller it covers every zone, as the wall panel does. A unit keeps its own setting in Auto.", "target_temp_step": "Sets the increment step for adjusting the target temperature. Fahrenheit degrees are clamped to the nearest integer." } }, diff --git a/docs/architecture.md b/docs/architecture.md index d8977d5d..13807e73 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -27,7 +27,7 @@ No Home Assistant imports here. |---|---| | `__init__.py` | Entry setup. Builds transports and devices, binds them, starts one `GreeCoordinator` per device. Creates and links the VRF controller devices, see [VRF controller device](#vrf-controller-device). | | `coordinator.py` | `GreeCoordinator`. Polls on `scan_interval` and listens for status pushed by the device. Polls again every 2 s after a command while the device has not confirmed it, until the hold ends. | -| `setpoint_memory.py` | `SetpointMemory`. The target temperature of a device per mode, stored with its unit per device MAC. Used for every device with a target temperature, unless its `setpoint_memory` option is off: for the zones of a zone controller, so a mode change works like one on the wall panel, and for a standalone or VRF unit itself. The coordinator feeds it after every read, and the climate entity keeps it in its restore state. It imports nothing from Home Assistant. See [protocol.md](protocol.md#target-temperatures-per-mode). | +| `setpoint_memory.py` | `SetpointMemory`. The target temperature of a device per mode, stored with its unit per device MAC. Used unless the `setpoint_memory` option is off: by the ducted unit of a zone controller for its zones, so a mode change works like one on the wall panel, and by a standalone or VRF unit for itself. The coordinators feed it after every read and send what it sets, and the climate entity keeps it in its restore state. It does no I/O and imports nothing from Home Assistant. See [protocol.md](protocol.md#target-temperatures-per-mode). | | `config_flow.py` | Setup, reconfigure, reauth and YAML import flows. Local discovery, cloud login, device picker, per device options. Reconfigure is a menu over the same steps, see [config-entry.md](config-entry.md#reconfigure). `async_step_import` turns one validated YAML item into a config entry. | | `config_schema.py` | `CONFIG_SCHEMA` for the `gree_custom:` block in `configuration.yaml`. Validates the YAML, normalizes the MAC addresses and fills the defaults. It also holds the form schemas that the config flow shows. | | `migration.py` | Moves a 4.x setup (domain `gree`) to this integration: config entries, the `gree:` YAML block, and the device and entity registry rows. See [config-entry.md](config-entry.md#migration-from-4x). | diff --git a/docs/config-entry.md b/docs/config-entry.md index 3982b572..bd8bdc40 100644 --- a/docs/config-entry.md +++ b/docs/config-entry.md @@ -53,7 +53,7 @@ For a cloud entry, `cloud` holds the account email, region, user id and token. T | `options.name` | Device name in Home Assistant. Defaults to the name the unit reports, which is usually the tail of its MAC. | | `options.features` | Which optional switches to create. Only features the unit reported as supported are offered. | | `options.restore_states` | Restore the last known entity states after a restart. | -| `options.setpoint_memory` | Remember the target temperature per mode, for a device with a target temperature. On by default. | +| `options.setpoint_memory` | Remember the target temperature per mode, for a unit with a target temperature, or on the AC unit of a zone controller for all its zones. On by default. | ## YAML import diff --git a/docs/configuration.md b/docs/configuration.md index 4b481c09..e59858fb 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -98,7 +98,7 @@ One page per device. Gree devices do not report reliably which features they hav | External Temperature Sensor | none | A Home Assistant sensor that replaces the unit's own room temperature in the climate entity. | | External Humidity Sensor | none | A Home Assistant sensor that replaces the unit's own humidity in the climate entity. | | Restore Entities | on | After a restart, send the last known Home Assistant state to the device instead of taking over the device state. See [Restoring state](entities.md#restoring-state-after-a-restart). | -| Remember Target Temperature per Mode | on | Remember the target temperature of each mode, and set it again when you change the mode from Home Assistant. A zone follows the mode of its AC unit. A unit is left alone in Auto, where it uses its own setting. Only shown for a device with a target temperature. | +| Remember Target Temperature per Mode | on | Remember the target temperature of each mode, and set it again when you change the mode from Home Assistant. On the AC unit of a zone controller it covers every zone, as the wall panel does. A unit is left alone in Auto, where it uses its own setting. Shown for a unit with a target temperature and for the AC unit of a zone controller. | The external sensors only change what the climate entity shows. The unit keeps using its own sensor to regulate. diff --git a/docs/entities.md b/docs/entities.md index 829cb750..5446fe72 100644 --- a/docs/entities.md +++ b/docs/entities.md @@ -63,7 +63,7 @@ A zone controller is controlled locally. Add it with local discovery, or with bo | Switch with the name of the zone | Opens and closes the zone. It is the **Zone Switch** feature, so you can leave it out. Do that for a zone that must always stay open: turning such a zone off is refused by the controller or turns the whole system off. | | Target Temperature | The target temperature of the zone, in the unit of the controller: 16 to 30 °C in half degrees, or 61 to 86 °F in whole degrees. Home Assistant shows it in your own unit. The wall panel shows only whole degrees in °C, so it shows 18 for 18.5. | -The wall panel remembers the target temperature of every zone for each mode, and sets them again when you change the mode on the panel. A mode change from Home Assistant does the same: the integration learns the values of each mode from what the zones report, and sends them when you change the mode of the AC unit. A mode the integration has not seen yet keeps the values the zones have. To leave a zone out, turn off **Remember Target Temperature per Mode** in the options of that zone. +The wall panel remembers the target temperature of every zone for each mode, and sets them again when you change the mode on the panel. A mode change from Home Assistant does the same: the integration learns the values of each mode from what the zones report, and sends them when you change the mode of the AC unit. A mode the integration has not seen yet keeps the values the zones have. It covers every zone, as the panel does. To turn it off, turn off **Remember Target Temperature per Mode** in the options of the AC unit. ## Sensors diff --git a/docs/protocol.md b/docs/protocol.md index 20609091..6c3b8d35 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -131,10 +131,11 @@ A zone controller (seen: LE60-13/GH with a ME31-00/C13 WiFi module, firmware `36 The wall panel remembers the target temperature of every zone per mode. When the mode is changed on the panel, it sets them again. A `Mod` change over WiFi does not: the zones keep the values of the old mode. `SetpointMemory` in `setpoint_memory.py`, in the Home Assistant layer, keeps the same memory: +- The ducted unit has the memory, and shares it with its zones, as the wall panel sets every zone. The device option `setpoint_memory` of the ducted unit, on by default, turns it off. - It learns from every read of a zone: `GreeCoordinator._update_data()` calls `learn()` after each read, and nothing else does. A zone reports its mode and its target temperature in one reply, so the two belong together. A value is stored when the zone reported the same mode on the read before, so a read in the middle of a mode change on the panel is not stored under the wrong mode. A closed zone learns too: a zone's `Pow` is its damper, not the power of the unit. -- Before the climate entity of the ducted unit changes the mode, `snapshot()` reads the zones again and stores them under the old mode. After the change, `recall()` sends the stored values of the new mode. A mode with no stored values changes nothing. +- Before the climate entity of the ducted unit changes the mode, it refreshes the coordinators of the zones, so the old mode keeps a value changed on the panel since the last poll. After the change, `apply()` sets the stored value of the new mode on each zone, and the zone's coordinator sends it. A mode with no stored values changes nothing. The memory itself does no I/O. - It stores `GreeDevice.target_temperature` with its unit, keyed by device MAC and mode: `{"": {"heat": {"temperature": 19.5, "unit": "C"}}}`. Through `set_target_temperature()`, every target in range comes back as the same temperature, with its bit: `StFahFlg` next to `StTem` for a zone. In °C these are also the same columns. In °F, three values come back with the other encoding of the same °F. A value stored in the other unit is converted. -- A standalone or VRF unit uses the same memory for itself. The device option `setpoint_memory`, on by default, turns the memory off for one device, a zone included. A unit learns only while it is on: an off unit keeps a mode and a target that are not in use. On a mode change from Home Assistant, `snapshot()` reads the unit once more, so a change made with the remote since the last poll is kept. Then `apply()` sets the stored target without sending it, and it goes out in the same command as the new mode. A target given with the mode, as `climate.set_temperature` does with `hvac_mode`, is set instead of the stored one, in the same command. Nothing is recalled into Auto, where the unit ignores the target temperature. +- A standalone or VRF unit with a target temperature uses a memory for itself, with the same option. A unit learns only while it is on: an off unit keeps a mode and a target that are not in use. On a mode change from Home Assistant, its coordinator reads the unit once more, so a change made with the remote since the last poll is kept. Then `apply()` sets the stored target without sending it, and it goes out in the same command as the new mode. A target given with the mode, as `climate.set_temperature` does with `hvac_mode`, is set instead of the stored one, in the same command. Nothing is recalled into Auto, where the unit ignores the target temperature. - The climate entity keeps the memory in its restore state, the climate entity of the ducted unit for its zones. Home Assistant saves it every 15 minutes, on a stop, and when the entity is removed, for example on a reload. It is restored whether or not `restore_states` is on. ## MAC addresses diff --git a/tests/config_flow/test_setpoint_memory_climate.py b/tests/config_flow/test_setpoint_memory_climate.py index 5ec7ed84..82b7906f 100644 --- a/tests/config_flow/test_setpoint_memory_climate.py +++ b/tests/config_flow/test_setpoint_memory_climate.py @@ -1,8 +1,9 @@ """The target temperature per mode, through the climate entity of a real Home Assistant. The memory itself is tested in tests/test_setpoint_memory.py. This checks that -the coordinator feeds it from its reads, what a service call does with it, and -that the climate entity keeps it over a reload and a restart. +the coordinators feed it from their reads, what a mode change does with it, for +a standalone unit and for the zones of a zone controller, and that the climate +entity keeps it over a reload and a restart. """ import pytest @@ -21,6 +22,7 @@ from homeassistant.helpers import entity_registry as er, restore_state from tests.config_flow.conftest import MAC_A, GreeEnv, add_entry from tests.fakes.device import FakeGreeDevice +from tests.fakes.zone import FakeZoneController # The climate entity uses the native temperature API of Home Assistant 2026.11 # (#570). The test plugin is still pinned to 2026.10, where the entity cannot @@ -155,3 +157,39 @@ async def test_the_memory_is_kept_over_a_reload_and_a_restart( blocking=True, ) assert (fake.values["Mod"], fake.values["SetTem"]) == (4, 20) + + +async def test_a_mode_change_sets_the_zones_as_the_wall_panel_does( + hass: HomeAssistant, gree: GreeEnv +) -> None: + """The zones learn into the memory of the ducted unit, whose mode change sets them.""" + controller = FakeZoneController() + gree.devices["zone_controller"] = controller + host = await gree.start_udp(controller) + entry = await add_entry( + hass, ["local"], [controller.ac_unit, *controller.zone_macs], [host] + ) + coordinators = list(entry.runtime_data.values()) + first = controller.units[controller.zone_macs[0]] + + async def poll_all() -> None: + for coordinator in coordinators: + await poll(hass, coordinator) + + # Fan with every zone at 18, then Heat with the first zone at 21, on the panel + await poll_all() + await poll_all() + for unit in controller.units.values(): + unit["Mod"] = 2 + first["StTem"] = 21 - 16 + await poll_all() + await poll_all() + + for hvac_mode, expected in (("fan_only", 18), ("heat", 21)): + await hass.services.async_call( + CLIMATE_DOMAIN, + "set_hvac_mode", + {ATTR_ENTITY_ID: climate_of(hass, entry), "hvac_mode": hvac_mode}, + blocking=True, + ) + assert first["StTem"] + 16 == expected, hvac_mode diff --git a/tests/test_setpoint_memory.py b/tests/test_setpoint_memory.py index 9f487fc8..861e0ecf 100644 --- a/tests/test_setpoint_memory.py +++ b/tests/test_setpoint_memory.py @@ -20,13 +20,15 @@ from custom_components.gree_custom.aiogree.api import DeviceType, OperationMode from custom_components.gree_custom.aiogree.device import GreeDevice from custom_components.gree_custom.aiogree.transport_udp import GreeUdpTransport -from custom_components.gree_custom.setpoint_memory import SetpointMemory +from custom_components.gree_custom.setpoint_memory import ( + SetpointMemory, + offers_setpoint_memory, +) from .fakes.device import FakeGreeDevice from .fakes.zone import FakeZoneController HEAT = 2 -COOL = 1 @pytest.fixture @@ -100,7 +102,21 @@ def remembered( memory: SetpointMemory, zones: list[GreeDevice], mode: OperationMode ) -> list[float | None]: """Return what the memory has for each zone in one mode.""" - return [memory.stored(zone, mode) for zone in zones] + data = memory.data + return [ + data.get(zone.mac_address, {}).get(mode.name, {}).get("temperature") + for zone in zones + ] + + +async def recall( + memory: SetpointMemory, zones: list[GreeDevice], mode: OperationMode +) -> list[GreeDevice]: + """Set and send the stored targets of a mode, as the climate entity does.""" + changed = [zone for zone in zones if memory.apply(zone, mode)] + for zone in changed: + await zone.push_device_status() + return changed def temperatures(controller: FakeZoneController) -> list[int]: @@ -180,7 +196,7 @@ async def test_recall_sends_the_stored_values_of_the_new_mode( ) await poll(memory, zones) - changed = await memory.recall(zones, OperationMode.heat) + changed = await recall(memory, zones, OperationMode.heat) assert temperatures(controller) == [19, 18, 17, 18] assert [zone.mac_address for zone in changed] == [ @@ -197,7 +213,7 @@ async def test_recall_of_a_mode_without_values_changes_nothing( await poll(memory, zones) controller.reset_record() - changed = await memory.recall(zones, OperationMode.dry) + changed = await recall(memory, zones, OperationMode.dry) assert changed == [] assert not any(pack.get("t") == "cmd" for pack in controller.packs) @@ -218,7 +234,7 @@ async def test_a_fahrenheit_target_comes_back_with_its_bit( panel_mode(controller, HEAT, [19, 18, 18, 18]) first["StFahFlg"] = 0 await poll(memory, zones) - await memory.recall(zones, OperationMode.fan) + await recall(memory, zones, OperationMode.fan) assert (first["StTem"], first["StFahFlg"]) == (3, 1) assert zones[0].target_temperature == 67 @@ -244,39 +260,27 @@ async def test_a_value_from_celsius_comes_back_right_in_fahrenheit( for values in controller.units.values(): values["TemUnit"] = 1 await poll(memory, zones) - await memory.recall(zones, OperationMode.fan) + await recall(memory, zones, OperationMode.fan) assert (first["StTem"], first["StFahFlg"]) == (2, 1) await zones[0].fetch_device_status() assert zones[0].target_temperature == 65 -async def test_snapshot_keeps_a_panel_change_made_since_the_last_poll( +async def test_a_change_in_the_same_mode_is_stored_on_the_next_read( controller: FakeZoneController, zones: list[GreeDevice] ) -> None: - """The value changed on the panel just before the switch is not lost.""" + """The climate entity reads once more before a mode change, so this keeps it.""" memory = SetpointMemory() await poll(memory, zones) await poll(memory, zones) set_on_panel(controller, [22, 18, 18, 18]) - await memory.snapshot(zones, OperationMode.fan) + await poll(memory, zones) assert remembered(memory, zones, OperationMode.fan) == [22, 18, 18, 18] -async def test_snapshot_does_not_store_values_of_another_mode( - controller: FakeZoneController, zones: list[GreeDevice] -) -> None: - """If the mode already changed on the panel, the values are not the old mode's.""" - memory = SetpointMemory() - panel_mode(controller, COOL, [24, 24, 24, 24]) - - await memory.snapshot(zones, OperationMode.fan) - - assert remembered(memory, zones, OperationMode.fan) == [None] * 4 - - async def test_a_closed_zone_still_learns( controller: FakeZoneController, zones: list[GreeDevice] ) -> None: @@ -290,31 +294,16 @@ async def test_a_closed_zone_still_learns( assert remembered(memory, zones, OperationMode.fan) == [18, 18, 18, 18] -async def test_restore_keeps_what_was_learned_since( - controller: FakeZoneController, zones: list[GreeDevice] +async def test_the_option_is_on_the_ducted_unit_for_all_zones( + controller: FakeZoneController, + transport: GreeUdpTransport, + zones: list[GreeDevice], ) -> None: - """A value learned before the entity restored its data is newer.""" - memory = SetpointMemory() - await poll(memory, zones) - await poll(memory, zones) - first = controller.zone_macs[0] - - memory.restore( - { - first: { - "fan": {"temperature": 22.0, "unit": "C"}, - "heat": {"temperature": 20.0, "unit": "C"}, - "warm": {"temperature": 21.0, "unit": "C"}, - "cool": {"temperature": "24", "unit": "C"}, - }, - controller.zone_macs[1]: "not a mode", - } - ) + """As on the wall panel, the mode of the ducted unit sets every zone.""" + ac_unit = await bind(controller, transport, controller.ac_unit) - assert memory.data[first] == { - "fan": {"temperature": 18.0, "unit": "C"}, - "heat": {"temperature": 20.0, "unit": "C"}, - } + assert offers_setpoint_memory(ac_unit) + assert not any(offers_setpoint_memory(zone) for zone in zones) # @@ -357,6 +346,7 @@ async def test_a_unit_learns_its_target_and_sends_it_with_the_mode( "heat": {"temperature": 20.0, "unit": "C"}, } assert device.device_type is DeviceType.AC_UNIT + assert offers_setpoint_memory(device) device.set_operation_mode(OperationMode.cool) assert memory.apply(device, OperationMode.cool) @@ -407,6 +397,6 @@ async def test_a_unit_that_is_off_learns_nothing( await poll(memory, [device]) await poll(memory, [device]) - await memory.snapshot([device], OperationMode.cool) + await poll(memory, [device]) assert memory.data == {} From 3ff1437335de18532ae78cf3791c6c8aaff83d45 Mon Sep 17 00:00:00 2001 From: Twintop Date: Mon, 16 Nov 2026 09:12:33 +1100 Subject: [PATCH 9/9] Setpoint memory: use TemperatureConverter, run the climate tests A target that was stored in the other unit is converted with TemperatureConverter and UNITS_GREE_TO_HA, as in climate.py and number.py, and then rounded to the steps of the device. Every target in range gives the same result as before, in both directions. 5.0-dev tests on Home Assistant 2026.11 since #578, so the climate tests of the memory no longer skip. --- .../gree_custom/setpoint_memory.py | 13 +++++++++++-- .../config_flow/test_setpoint_memory_climate.py | 17 +---------------- 2 files changed, 12 insertions(+), 18 deletions(-) diff --git a/custom_components/gree_custom/setpoint_memory.py b/custom_components/gree_custom/setpoint_memory.py index ef60b6e9..9539a137 100644 --- a/custom_components/gree_custom/setpoint_memory.py +++ b/custom_components/gree_custom/setpoint_memory.py @@ -10,8 +10,11 @@ from typing import Any +from homeassistant.util.unit_conversion import TemperatureConverter + from .aiogree.api import DeviceType, GreeProp, OperationMode, TemperatureUnits from .aiogree.device import GreeDevice +from .const import UNITS_GREE_TO_HA # {device MAC: {mode name: {"temperature": 20.5, "unit": "C"}}} type SetpointMemoryData = dict[str, dict[str, dict[str, Any]]] @@ -89,10 +92,16 @@ def apply(self, device: GreeDevice, mode: OperationMode) -> bool: temperature = stored["temperature"] unit = device.target_temperature_unit if stored["unit"] != unit.name: + temperature = TemperatureConverter.convert( + temperature, + UNITS_GREE_TO_HA[TemperatureUnits[stored["unit"]]], + UNITS_GREE_TO_HA[unit], + ) + # The steps of the device: whole degrees in °F, half degrees in °C temperature = ( - float(round(temperature * 9 / 5 + 32)) + float(round(temperature)) if unit is TemperatureUnits.F - else round((temperature - 32) * 5 / 9 * 2) / 2 + else round(temperature * 2) / 2 ) if temperature == device.target_temperature: return False diff --git a/tests/config_flow/test_setpoint_memory_climate.py b/tests/config_flow/test_setpoint_memory_climate.py index 82b7906f..532faf7f 100644 --- a/tests/config_flow/test_setpoint_memory_climate.py +++ b/tests/config_flow/test_setpoint_memory_climate.py @@ -6,32 +6,17 @@ entity keeps it over a reload and a restart. """ -import pytest - from custom_components.gree_custom.coordinator import GreeCoordinator from custom_components.gree_custom.setpoint_memory import SetpointMemory from homeassistant.components.climate import DOMAIN as CLIMATE_DOMAIN from homeassistant.config_entries import ConfigEntry -from homeassistant.const import ( - ATTR_ENTITY_ID, - ATTR_TEMPERATURE, - MAJOR_VERSION, - MINOR_VERSION, -) +from homeassistant.const import ATTR_ENTITY_ID, ATTR_TEMPERATURE from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er, restore_state from tests.config_flow.conftest import MAC_A, GreeEnv, add_entry from tests.fakes.device import FakeGreeDevice from tests.fakes.zone import FakeZoneController -# The climate entity uses the native temperature API of Home Assistant 2026.11 -# (#570). The test plugin is still pinned to 2026.10, where the entity cannot -# be created, so this runs once the pin moves to 2026.11. -pytestmark = pytest.mark.skipif( - (MAJOR_VERSION, MINOR_VERSION) < (2026, 11), - reason="the climate entity needs Home Assistant 2026.11", -) - COOL_24 = {"temperature": 24.0, "unit": "C"} HEAT_20 = {"temperature": 20.0, "unit": "C"}