diff --git a/custom_components/gree_custom/__init__.py b/custom_components/gree_custom/__init__.py index fe71e48e..021cffc7 100755 --- a/custom_components/gree_custom/__init__.py +++ b/custom_components/gree_custom/__init__.py @@ -26,6 +26,7 @@ from homeassistant.helpers import device_registry as dr, issue_registry as ir 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 @@ -49,6 +50,7 @@ CONF_MAX_ONLINE_ATTEMPTS, CONF_PREFER_CLOUD, CONF_RESTORE_STATES, + CONF_SETPOINT_MEMORY, CONF_UID, CONFENTRY_ID_LOCAL_ONLY, DEFAULT_CONNECTION_MAX_ATTEMPTS, @@ -60,6 +62,7 @@ DEFAULT_PREFER_CLOUD, DEFAULT_RESTORE_STATES, DEFAULT_SCAN_INTERVAL, + DEFAULT_SETPOINT_MEMORY, DOMAIN, ENCRYPTION_VERSION_AUTO, TO_REDACT, @@ -81,6 +84,7 @@ async_unload_legacy_entries, ) from .services import async_setup_services +from .setpoint_memory import SetpointMemory, offers_setpoint_memory ISSUE_DEVICE_CONNECTION_FAILED = "device_connection_failed" ISSUE_YAML_IMPORT_FAILED = "yaml_import_failed" @@ -292,6 +296,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: GreeConfigEntry) -> bool entry.runtime_data = {} entry.runtime_data = coordinators + _setup_setpoint_memory(coordinators) + # Move the 4.x registry rows before the entities are created moved = await async_migrate_legacy_registry(hass, entry) @@ -334,6 +340,31 @@ async def _async_refresh_entry_token( return new_cloud_conf +def _setup_setpoint_memory(coordinators: dict[str, GreeCoordinator]) -> None: + """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(): + 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 + + coordinator.setpoint_memory = SetpointMemory() + coordinator.zone_coordinators = [ + zone + for zone in coordinators.values() + if zone.device.device_type is DeviceType.ZONE + and zone.device.mac_address_controller == device.mac_address_controller + ] + for zone in coordinator.zone_coordinators: + zone.setpoint_memory = coordinator.setpoint_memory + + 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/climate.py b/custom_components/gree_custom/climate.py index 53c716da..858a9179 100755 --- a/custom_components/gree_custom/climate.py +++ b/custom_components/gree_custom/climate.py @@ -32,7 +32,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 ( @@ -40,10 +40,11 @@ FanSpeed, GreeProp, HorizontalSwingMode, + OperationMode, 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, @@ -67,6 +68,7 @@ ) from .coordinator import GreeConfigEntry, GreeCoordinator from .entity import GreeEntity, GreeEntityDescription +from .setpoint_memory import SetpointMemory, SetpointMemoryData _LOGGER = logging.getLogger(__name__) @@ -112,6 +114,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, @@ -287,6 +302,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() @@ -463,6 +483,17 @@ async def _restore_entity_state(self) -> None: # noqa: C901 self.native_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.""" @@ -700,6 +731,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: @@ -709,11 +750,22 @@ 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() else: - self.device.set_operation_mode(HVAC_MODES_HA_TO_GREE[hvac_mode]) + new_mode = HVAC_MODES_HA_TO_GREE[hvac_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 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 if self.coordinator.feature_auto_xfan: @@ -726,6 +778,9 @@ 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: + 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() @@ -738,6 +793,42 @@ async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: 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.""" + 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.""" if ( @@ -945,13 +1036,12 @@ async def async_set_temperature(self, **kwargs: Any) -> None: try: # TODO: Confirm that HA sends the values in this entity's native_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/config_schema.py b/custom_components/gree_custom/config_schema.py index 18c3d305..200c05a5 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, @@ -102,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) @@ -247,6 +250,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, } ) @@ -798,4 +804,15 @@ def setup_device_options_schema( # noqa: C901 } ) + # On the ducted unit of a zone controller it is for all of its zones + if offers_setpoint_memory(device): + 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 ef920e63..26b328d8 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 device 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 = True 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 79e480f2..60393515 100755 --- a/custom_components/gree_custom/coordinator.py +++ b/custom_components/gree_custom/coordinator.py @@ -15,6 +15,7 @@ from .aiogree.errors import GreeBindingError, GreeConnectionError from .const import DOMAIN from .helpers import try_find_new_ip +from .setpoint_memory import SetpointMemory _LOGGER = logging.getLogger(__name__) @@ -60,6 +61,11 @@ 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, 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] = [] async def _setup(self) -> None: """Bind to the device before the first coordinator refresh. @@ -130,6 +136,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 new file mode 100644 index 00000000..9539a137 --- /dev/null +++ b/custom_components/gree_custom/setpoint_memory.py @@ -0,0 +1,117 @@ +"""The target temperature of a device, remembered per mode. + +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 +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 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]]] + + +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 + self._last_mode: dict[str, OperationMode] = {} + + @property + def data(self) -> SetpointMemoryData: + """Return a copy of everything that is stored.""" + return _copy(self._data) + + 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. + + 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. + """ + mode = device.operation_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 + + 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. + + Returns: + True if the device got a new target temperature to send + + """ + 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 = 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)) + if unit is TemperatureUnits.F + else round(temperature * 2) / 2 + ) + if temperature == device.target_temperature: + return False + + device.set_target_temperature(temperature) + return True + + +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 40926e25..2259b42a 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. 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 4cbbbcdf..13807e73 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -27,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 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 ee1f9098..bd8bdc40 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 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 20743180..e59858fb 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 | 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 832b0757..5446fe72 100644 --- a/docs/entities.md +++ b/docs/entities.md @@ -31,6 +31,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') }}`. Since Home Assistant 2026.11 the climate entity also has a `temperature_unit` attribute, which Home Assistant itself adds. +### 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 on 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. @@ -59,6 +63,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. 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 Created when the unit has the sensor. Some are disabled by default: enable them on the device page. diff --git a/docs/protocol.md b/docs/protocol.md index 76f4d124..6c3b8d35 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -127,6 +127,17 @@ 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 `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, 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 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 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/manual-configuration.yaml b/manual-configuration.yaml index 9c953bd1..9bf26e1d 100644 --- a/manual-configuration.yaml +++ b/manual-configuration.yaml @@ -118,3 +118,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: 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/config_flow/test_setpoint_memory_climate.py b/tests/config_flow/test_setpoint_memory_climate.py new file mode 100644 index 00000000..532faf7f --- /dev/null +++ b/tests/config_flow/test_setpoint_memory_climate.py @@ -0,0 +1,180 @@ +"""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 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. +""" + +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 +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 + +COOL_24 = {"temperature": 24.0, "unit": "C"} +HEAT_20 = {"temperature": 20.0, "unit": "C"} + + +async def add_unit( + hass: HomeAssistant, gree: GreeEnv +) -> 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]) + return fake, entry, next(iter(entry.runtime_data.values())) + + +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(hass, coordinator) + await poll(hass, coordinator) + fake.values.update({"Mod": 1, "SetTem": 24}) + await poll(hass, coordinator) + await poll(hass, coordinator) + + +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_of(hass, entry), + ATTR_TEMPERATURE: 22, + "hvac_mode": "heat", + }, + blocking=True, + ) + + assert (fake.values["Mod"], fake.values["SetTem"]) == (4, 22) + 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) + + +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 new file mode 100644 index 00000000..861e0ecf --- /dev/null +++ b/tests/test_setpoint_memory.py @@ -0,0 +1,402 @@ +"""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 + +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, 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, + offers_setpoint_memory, +) + +from .fakes.device import FakeGreeDevice +from .fakes.zone import FakeZoneController + +HEAT = 2 + + +@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: a read, then learn().""" + for device in devices: + await device.fetch_device_status() + memory.learn(device) + + +def remembered( + memory: SetpointMemory, zones: list[GreeDevice], mode: OperationMode +) -> list[float | None]: + """Return what the memory has for each zone in one mode.""" + 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]: + """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.""" + memory = SetpointMemory() + + await poll(memory, zones) + assert memory.data == {} + + await poll(memory, zones) + assert remembered(memory, zones, OperationMode.fan) == [18, 18, 18, 18] + + +async def test_the_temperature_is_stored_with_its_unit( + controller: FakeZoneController, zones: list[GreeDevice] +) -> None: + """Keyed by device and mode.""" + memory = SetpointMemory() + await poll(memory, zones) + await poll(memory, zones) + + assert memory.data[controller.zone_macs[0]] == { + "fan": {"temperature": 18.0, "unit": "C"} + } + + +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.""" + 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() + memory.restore( + { + controller.zone_macs[0]: {"heat": {"temperature": 19.0, "unit": "C"}}, + controller.zone_macs[2]: {"heat": {"temperature": 17.0, "unit": "C"}}, + } + ) + await poll(memory, zones) + + changed = await recall(memory, 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 recall(memory, 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. 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]] + 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 recall(memory, zones, OperationMode.fan) + + assert (first["StTem"], first["StFahFlg"]) == (3, 1) + assert zones[0].target_temperature == 67 + + +async def test_a_value_from_celsius_comes_back_right_in_fahrenheit( + controller: FakeZoneController, zones: list[GreeDevice] +) -> None: + """A stored value is converted to the unit the device uses now. + + 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}) + 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 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_a_change_in_the_same_mode_is_stored_on_the_next_read( + controller: FakeZoneController, zones: list[GreeDevice] +) -> None: + """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 poll(memory, zones) + + assert remembered(memory, zones, OperationMode.fan) == [22, 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] + + +async def test_the_option_is_on_the_ducted_unit_for_all_zones( + controller: FakeZoneController, + transport: GreeUdpTransport, + zones: list[GreeDevice], +) -> None: + """As on the wall panel, the mode of the ducted unit sets every zone.""" + ac_unit = await bind(controller, transport, controller.ac_unit) + + assert offers_setpoint_memory(ac_unit) + assert not any(offers_setpoint_memory(zone) for zone in zones) + + +# +# 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_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": {"temperature": 24.0, "unit": "C"}, + "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) + 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_in_fahrenheit( + unit: tuple[FakeGreeDevice, GreeDevice], +) -> None: + """SetTem 24 with TemRec 1 is 76 F.""" + 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": {"temperature": 76.0, "unit": "F"}} + + +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) + + +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 poll(memory, [device]) + + assert memory.data == {}