Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions custom_components/gree_custom/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -60,6 +62,7 @@
DEFAULT_PREFER_CLOUD,
DEFAULT_RESTORE_STATES,
DEFAULT_SCAN_INTERVAL,
DEFAULT_SETPOINT_MEMORY,
DOMAIN,
ENCRYPTION_VERSION_AUTO,
TO_REDACT,
Expand All @@ -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"
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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.

Expand Down
106 changes: 98 additions & 8 deletions custom_components/gree_custom/climate.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,19 @@
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 (
DeviceType,
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,
Expand All @@ -67,6 +68,7 @@
)
from .coordinator import GreeConfigEntry, GreeCoordinator
from .entity import GreeEntity, GreeEntityDescription
from .setpoint_memory import SetpointMemory, SetpointMemoryData

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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()

Expand All @@ -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 (
Expand Down Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions custom_components/gree_custom/config_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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)
Expand Down Expand Up @@ -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,
}
)

Expand Down Expand Up @@ -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)
3 changes: 3 additions & 0 deletions custom_components/gree_custom/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand Down
10 changes: 10 additions & 0 deletions custom_components/gree_custom/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.

Expand Down
Loading
Loading