diff --git a/custom_components/gree_custom/__init__.py b/custom_components/gree_custom/__init__.py index fe71e48e..b616a26a 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 +import copy import json import logging from typing import Any @@ -31,7 +32,10 @@ from .aiogree.errors import GreeConnectionError from .aiogree.transport_mqtt import GreeMqttTransport from .aiogree.transport_udp import GreeUdpTransport -from .config_schema import CONFIG_SCHEMA as CONFIG_SCHEMA +from .config_schema import ( + CONFIG_SCHEMA as CONFIG_SCHEMA, + options_without_temperature_step, +) # Local imports from .const import ( @@ -44,6 +48,7 @@ CONF_DISABLE_AVAILABLE_CHECK, CONF_ENCRYPTION_KEY, CONF_ENCRYPTION_VERSION, + CONF_HALF_DEGREES, CONF_MAC_CONTROLLER_CLOUD, CONF_MAC_CONTROLLER_LOCAL, CONF_MAX_ONLINE_ATTEMPTS, @@ -51,6 +56,8 @@ CONF_RESTORE_STATES, CONF_UID, CONFENTRY_ID_LOCAL_ONLY, + CURRENT_CONF_MINOR_VERSION, + CURRENT_CONF_VERSION, DEFAULT_CONNECTION_MAX_ATTEMPTS, DEFAULT_CONNECTION_TIMEOUT, DEFAULT_DEVICE_PORT, @@ -214,6 +221,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: GreeConfigEntry) -> bool preferred_encryption_key=preferred_encryption_key, user_id=uid, ) + half_degrees = options.get(CONF_HALF_DEGREES) + device.set_half_degrees(None if half_degrees is None else bool(half_degrees)) local_transport = ( None if prefer_cloud else local_transports.get(mac_controller_local) @@ -307,6 +316,41 @@ async def async_setup_entry(hass: HomeAssistant, entry: GreeConfigEntry) -> bool return True +async def async_migrate_entry(hass: HomeAssistant, entry: GreeConfigEntry) -> bool: + """Bring an entry of an older minor version up to date. + + Minor version 2 replaced the device option target_temp_step with + half_degrees. An entry of another major version is refused, as Home + Assistant did before this function existed. + """ + if entry.version != CURRENT_CONF_VERSION: + _LOGGER.error( + "Entry '%s' has version %s, this release only reads version %s", + entry.title, + entry.version, + CURRENT_CONF_VERSION, + ) + return False + + if entry.minor_version < 2: + data = copy.deepcopy(dict(entry.data)) + for dev_config in data.get(CONF_DEVICES, {}).values(): + options = dev_config.get(CONF_DEVICE_OPTIONS) + if options is not None: + dev_config[CONF_DEVICE_OPTIONS] = options_without_temperature_step( + options + ) + hass.config_entries.async_update_entry( + entry, data=data, minor_version=CURRENT_CONF_MINOR_VERSION + ) + _LOGGER.info( + "Entry '%s': the temperature step option is now Use half-degrees °C", + entry.title, + ) + + return True + + async def _async_refresh_entry_token( hass: HomeAssistant, entry: GreeConfigEntry, cloud_conf: Mapping[str, Any] ) -> dict[str, Any]: diff --git a/custom_components/gree_custom/aiogree/api.py b/custom_components/gree_custom/aiogree/api.py index d4d54daf..ccc82c74 100755 --- a/custom_components/gree_custom/aiogree/api.py +++ b/custom_components/gree_custom/aiogree/api.py @@ -44,6 +44,11 @@ class GreeProp(StrEnum): # used to distinguish between Fahrenheit values, and the half degree in Celsius TARGET_TEMPERATURE_BIT_1 = "TemRec" TARGET_TEMPERATURE_BIT_2 = "StFahFlg" + # Other columns that some units use for the half degree in Celsius, see + # GreeDevice.set_target_temperature. Add0.5 is 0 or 1, Add0.1 is a tenths + # digit that the unit rounds to the nearest half degree. + TARGET_TEMPERATURE_HALF_C = "Add0.5" + TARGET_TEMPERATURE_TENTHS_C = "Add0.1" # defines the unit of temperature for the target temperature TARGET_TEMPERATURE_UNIT_1 = "TemUn" TARGET_TEMPERATURE_UNIT_2 = "TemUnit" # zone controller and all its sub-units @@ -144,8 +149,6 @@ class OtherProps(StrEnum): UNKN_ACStupPos = "ACStupPos" UNKN_ActiveTime = "ActiveTime" - UNKN_Add0_1 = "Add0.1" - UNKN_Add0_5 = "Add0.5" UNKN_AirQ = "AirQ" UNKN_AllErr = "AllErr" UNKN_Antifreeze = "Antifreeze" diff --git a/custom_components/gree_custom/aiogree/device.py b/custom_components/gree_custom/aiogree/device.py index 4ffe9889..5dfb2cc0 100755 --- a/custom_components/gree_custom/aiogree/device.py +++ b/custom_components/gree_custom/aiogree/device.py @@ -2,6 +2,7 @@ from collections.abc import Mapping import logging +import math from typing import Any from aiomqtt import MqttError @@ -141,6 +142,10 @@ def __init__( self._target_temp_bit_prop: GreeProp | None = None self._temp_unit_prop: GreeProp | None = None + # The user option "Use half-degrees °C". None when the user made no + # choice: see default_half_degrees. + self._half_degrees: bool | None = None + self._state = DeviceState( device_id=self.unique_id, capabilities=self._capabilities ) @@ -955,9 +960,30 @@ def set_horizontal_swing_mode(self, swing_mode: HorizontalSwingMode) -> None: self._state.set(GreeProp.SWING_HORIZONTAL, swing_mode) @property - def target_temperature_unit(self) -> TemperatureUnits: - """Return the units of the target temperature.""" + def supports_temperature_unit_change(self) -> bool: + """Return True if the unit can be switched between Celsius and Fahrenheit. + + The target temperature column is always Celsius. Only the bit column + tells the Fahrenheit degrees apart, so a unit without a bit is Celsius + only. The ducted unit of a zone controller is the exception: it has no + target temperature and no bit of its own, but its unit column sets the + unit of the whole system, and the zones do have the bit. + """ if self._temp_unit_prop is None: + return False + return ( + self._target_temp_bit_prop is not None + or self._device_type is DeviceType.ZONE_CONTROLLER + ) + + @property + def target_temperature_unit(self) -> TemperatureUnits: + """Return the units of the target temperature. + + Celsius when the unit cannot change units, see + supports_temperature_unit_change. + """ + if self._temp_unit_prop is None or not self.supports_temperature_unit_change: return TemperatureUnits.C return TemperatureUnits( self._state.get(self._temp_unit_prop) or TemperatureUnits.C.value @@ -965,8 +991,10 @@ def target_temperature_unit(self) -> TemperatureUnits: def set_target_temperature_unit(self, units: TemperatureUnits) -> None: """Set the units of the target temperature.""" - if self._temp_unit_prop is None: - _LOGGER.warning("[%s] The device has no temperature unit", self.unique_id) + if self._temp_unit_prop is None or not self.supports_temperature_unit_change: + _LOGGER.warning( + "[%s] The device cannot change its temperature unit", self.unique_id + ) return self._state.set(self._temp_unit_prop, units) @@ -974,18 +1002,78 @@ def set_target_temperature_unit(self, units: TemperatureUnits) -> None: def has_target_temperature_bit(self) -> bool: """Return True if the device answers a bit for the target temperature. - Only then can it hold half degrees in Celsius, and every whole degree - in Fahrenheit. Without it, Fahrenheit goes in steps of about 2. + Only then can it hold every whole degree in Fahrenheit. """ return self._target_temp_bit_prop is not None + def _half_degree_props(self) -> list[GreeProp]: + """Return the half degree columns the device answers. + + These are the bit column (TemRec or StFahFlg), Add0.5 and Add0.1. + Answering a column is no proof that the unit uses it: some units + answer all three with 0. So all of them are written together, and + the unit takes the one it knows. + """ + props = [ + prop + for prop in ( + GreeProp.TARGET_TEMPERATURE_HALF_C, + GreeProp.TARGET_TEMPERATURE_TENTHS_C, + ) + if self._state.supports(prop) + ] + if self._target_temp_bit_prop is not None: + props.insert(0, self._target_temp_bit_prop) + return props + + @property + def supports_half_degrees(self) -> bool: + """Return True if the unit answers a column for half degrees Celsius.""" + return self._target_temp_prop is not None and bool(self._half_degree_props()) + + @property + def half_degrees(self) -> bool: + """Return True if half degrees Celsius are used. + + This needs the user option and a unit that answers a half degree + column. Fahrenheit is always in whole degrees. + """ + choice = self._half_degrees + if choice is None: + choice = self.default_half_degrees + return choice and self.supports_half_degrees + + @property + def default_half_degrees(self) -> bool: + """Return the option "Use half-degrees °C" when the user made no choice. + + On for a zone of a zone controller: its only half degree column is + StFahFlg, which the zones take, and before the option existed zones + always used half degrees. Off for every other unit, because some + answer a half degree column and still take only whole degrees. + """ + return self.device_type is DeviceType.ZONE + + def set_half_degrees(self, value: bool | None) -> None: + """Set the user option "Use half-degrees °C". None means no choice.""" + self._half_degrees = value + + @property + def target_temperature_step(self) -> float: + """Return the step of the target temperature, in its unit.""" + if self.target_temperature_unit is TemperatureUnits.C and self.half_degrees: + return 0.5 + return 1.0 + @property def target_temperature(self) -> float | None: """Return the target temperature in target_temperature_unit. - The bit is the half degree in Celsius, and picks the value from the - table in Fahrenheit. Without a bit column it is 0. None until the - device is read, or when it has no target temperature. + In Celsius the value is a half degree when any answered half degree + column is set. A column the unit ignores reads 0, so it does no harm. + In Fahrenheit the bit picks the value from the table, and the other + columns are not used. None until the device is read, or when it has + no target temperature. """ if self._target_temp_prop is None: return None @@ -995,26 +1083,34 @@ def target_temperature(self) -> float | None: return None raw_c = raw + TARGET_TEMPERATURE_OFFSETS.get(self._target_temp_prop, 0) - bit = 0 - if self._target_temp_bit_prop is not None: - bit = self._state.get(self._target_temp_bit_prop) or 0 if self.target_temperature_unit == TemperatureUnits.F: + bit = 0 + if self._target_temp_bit_prop is not None: + bit = self._state.get(self._target_temp_bit_prop) or 0 return gree_get_target_temperature_f(raw_c, bit) - return gree_get_target_temperature_c(raw_c, bit) + + half = any(self._state.get(prop) for prop in self._half_degree_props()) + return gree_get_target_temperature_c(raw_c, 1 if half else 0) def set_target_temperature(self, value: float) -> None: """Set the target temperature in target_temperature_unit. - Celsius goes to the nearest half degree, Fahrenheit to whole degrees. - The bit is sent along when the device answers it. A zone needs that, - because it keeps the old bit when only StTem is sent. + Celsius goes to the nearest half degree when half_degrees is on, and + to the nearest whole degree when it is off. Fahrenheit goes to whole + degrees. Every answered half degree column is sent along, also as 0 + for a whole degree, so a half degree set with a remote is cleared: + the bit as 1, Add0.5 as 1 and Add0.1 as 5 for a half degree in + Celsius. In Fahrenheit the bit comes from the table and the Celsius + only columns are 0. A zone needs the bit, because it keeps the old + bit when only StTem is sent. """ if self._target_temp_prop is None: _LOGGER.warning("[%s] The device has no target temperature", self.unique_id) return - if self.target_temperature_unit == TemperatureUnits.F: + fahrenheit = self.target_temperature_unit == TemperatureUnits.F + if fahrenheit: if not value.is_integer(): _LOGGER.warning( "The Gree API does not support floating Fahrenheit values, the applied value will be: %.2f -> %d", @@ -1022,13 +1118,23 @@ def set_target_temperature(self, value: float) -> None: round(value), ) raw_c, bit = gree_get_target_temp_props_from_f(round(value)) - else: + elif self.half_degrees: raw_c, bit = gree_get_target_temp_props_from_c(value) + else: + # Round a half up, so 22.5 goes to 23, not to 22 as round() does + raw_c, bit = gree_get_target_temp_props_from_c(math.floor(value + 0.5)) offset = TARGET_TEMPERATURE_OFFSETS.get(self._target_temp_prop, 0) props = {self._target_temp_prop: raw_c - offset} - if self._target_temp_bit_prop is not None: - props[self._target_temp_bit_prop] = bit + for prop in self._half_degree_props(): + if prop is self._target_temp_bit_prop: + props[prop] = bit + elif fahrenheit: + props[prop] = 0 + elif prop is GreeProp.TARGET_TEMPERATURE_TENTHS_C: + props[prop] = 5 * bit + else: + props[prop] = bit self._state.update(props) if self.feature_smart_heat or self.feature_energy_saving: diff --git a/custom_components/gree_custom/climate.py b/custom_components/gree_custom/climate.py index 53c716da..60eacb10 100755 --- a/custom_components/gree_custom/climate.py +++ b/custom_components/gree_custom/climate.py @@ -52,12 +52,10 @@ CONF_HVAC_MODES, CONF_SWING_HORIZONTAL_MODES, CONF_SWING_MODES, - CONF_TEMPERATURE_STEP, DEFAULT_FAN_MODES, DEFAULT_HVAC_MODES, DEFAULT_SWING_HORIZONTAL_MODES, DEFAULT_SWING_MODES, - DEFAULT_TARGET_TEMP_STEP, DOMAIN, GATTR_FEAT_QUIET_MODE, GATTR_FEAT_TURBO, @@ -188,9 +186,6 @@ async def async_setup_entry( fan_modes, swing_modes, swing_horizontal_modes, - temperature_step=options.get( - CONF_TEMPERATURE_STEP, DEFAULT_TARGET_TEMP_STEP - ), restore_state=coordinator.restore_states, check_availability=coordinator.check_availability, external_temperature_sensor_id=options.get( @@ -216,7 +211,6 @@ def __init__( fan_modes: list[str], swing_modes: list[str], swing_horizontal_modes: list[str], - temperature_step: int, restore_state: bool = True, check_availability: bool = True, external_temperature_sensor_id: str | None = None, @@ -233,8 +227,6 @@ def __init__( # Last external sensor value and its unit self._external_temperature: tuple[float, str] | None = None - self._attr_target_temperature_step = temperature_step - self._attr_hvac_modes = hvac_modes if hvac_modes and HVACMode.OFF in hvac_modes: @@ -587,6 +579,8 @@ def _update_attributes(self) -> None: self._attr_native_temperature_unit = self.get_temp_units() self._attr_native_target_temperature = self.get_current_target_temp() + # Follows the unit and the "Use half-degrees °C" option + self._attr_target_temperature_step = self.device.target_temperature_step if ( self._external_temperature_sensor is None diff --git a/custom_components/gree_custom/config_flow.py b/custom_components/gree_custom/config_flow.py index fe2dcfe9..92956c21 100755 --- a/custom_components/gree_custom/config_flow.py +++ b/custom_components/gree_custom/config_flow.py @@ -87,6 +87,7 @@ CONF_EXTRA_SCAN_NETWORKS, CONF_FAN_MODES, CONF_FEATURES, + CONF_HALF_DEGREES, CONF_HVAC_MODES, CONF_MAC_CONTROLLER_CLOUD, CONF_MAC_CONTROLLER_LOCAL, @@ -95,6 +96,7 @@ CONF_SWING_MODES, CONF_UID, CONFENTRY_ID_LOCAL_ONLY, + CURRENT_CONF_MINOR_VERSION, CURRENT_CONF_VERSION, DATA_YAML_UNIQUE_IDS, DEFAULT_DEVICE_UID, @@ -132,6 +134,7 @@ CONF_SWING_MODES, CONF_SWING_HORIZONTAL_MODES, CONF_FEATURES, + CONF_HALF_DEGREES, ) @@ -140,9 +143,10 @@ def _copied_options( ) -> dict[str, Any] | None: """Take the options of another device as defaults for this one. - Only the mode and feature lists carry over, not the name. The Zone Switch - is chosen per zone, because only an always open zone goes without it, so - it never carries over: a zone starts with it, any other device without it. + The mode and feature lists and the half degree option carry over, not the + name. The Zone Switch is chosen per zone, because only an always open zone + goes without it, so it never carries over: a zone starts with it, any other + device without it. """ if not options: return None @@ -229,6 +233,7 @@ class SetupConfigFlow(ConfigFlow, domain=DOMAIN): """Handle the config flow for the integration.""" VERSION = CURRENT_CONF_VERSION + MINOR_VERSION = CURRENT_CONF_MINOR_VERSION def __init__(self) -> None: """Initialize the flow.""" diff --git a/custom_components/gree_custom/config_schema.py b/custom_components/gree_custom/config_schema.py index 18c3d305..01a9eada 100644 --- a/custom_components/gree_custom/config_schema.py +++ b/custom_components/gree_custom/config_schema.py @@ -6,6 +6,7 @@ """ from collections.abc import Mapping +import logging from typing import TYPE_CHECKING, Any if TYPE_CHECKING: @@ -34,9 +35,6 @@ from homeassistant.helpers.selector import ( EntitySelector, EntitySelectorConfig, - NumberSelector, - NumberSelectorConfig, - NumberSelectorMode, SelectOptionDict, SelectSelector, SelectSelectorConfig, @@ -68,6 +66,7 @@ CONF_EXTRA_SCAN_NETWORKS, CONF_FAN_MODES, CONF_FEATURES, + CONF_HALF_DEGREES, CONF_HVAC_MODES, CONF_MAC_CONTROLLER_CLOUD, CONF_MAC_CONTROLLER_LOCAL, @@ -92,7 +91,6 @@ DEFAULT_SCAN_INTERVAL, DEFAULT_SWING_HORIZONTAL_MODES, DEFAULT_SWING_MODES, - DEFAULT_TARGET_TEMP_STEP, DOMAIN, ENCRYPTION_VERSION_AUTO, GATTR_FEAT_QUIET_MODE, @@ -103,6 +101,8 @@ ) from .helpers import get_entity_ids_from_unique_ids +_LOGGER = logging.getLogger(__name__) + HEX_CHARACTERS = "0123456789abcdef" VALID_MAC_LENGTHS = (12, 14) @@ -172,6 +172,45 @@ def _target_temp_step(value: Any) -> float: return step +def half_degrees_from_temp_step(step: float) -> bool: + """Tell if an old temperature step means "Use half-degrees °C". + + A step that is not a whole number, such as 0.5, can only reach half + degrees. A whole step, such as 2, has no match and becomes off. + """ + return not float(step).is_integer() + + +def options_without_temperature_step(options: Mapping[str, Any]) -> dict[str, Any]: + """Replace the old target_temp_step option with half_degrees. + + An option half_degrees that is already there wins. The step itself is + gone: the climate entity now takes its step from the unit and from + half_degrees. + """ + converted = dict(options) + if CONF_TEMPERATURE_STEP not in converted: + return converted + + step = converted.pop(CONF_TEMPERATURE_STEP) + if CONF_HALF_DEGREES not in converted and half_degrees_from_temp_step(step): + converted[CONF_HALF_DEGREES] = True + return converted + + +def _yaml_temperature_step(options: dict[str, Any]) -> dict[str, Any]: + """Accept target_temp_step in YAML, and turn it into half_degrees.""" + if CONF_TEMPERATURE_STEP not in options: + return options + + _LOGGER.warning( + "%s: target_temp_step is replaced by half_degrees: true or false. It" + " still works for now, but please change your YAML", + options.get(CONF_NAME), + ) + return options_without_temperature_step(options) + + CLOUD_SCHEMA = probatio.Schema( { probatio.Required(CONF_EMAIL): cv.string, @@ -223,31 +262,36 @@ def _target_temp_step(value: Any) -> float: } ) -OPTIONS_SCHEMA = probatio.Schema( - { - probatio.Required(CONF_NAME): cv.string, - probatio.Optional(CONF_HVAC_MODES): probatio.All( - cv.ensure_list, [probatio.In(VALID_HVAC_MODES)] - ), - probatio.Optional(CONF_FAN_MODES): probatio.All( - cv.ensure_list, [probatio.In(VALID_FAN_MODES)] - ), - probatio.Optional(CONF_SWING_MODES): probatio.All( - cv.ensure_list, [probatio.In(DEFAULT_SWING_MODES)] - ), - probatio.Optional(CONF_SWING_HORIZONTAL_MODES): probatio.All( - cv.ensure_list, [probatio.In(DEFAULT_SWING_HORIZONTAL_MODES)] - ), - probatio.Optional(CONF_FEATURES): probatio.All( - cv.ensure_list, [probatio.In(VALID_FEATURES)] - ), - probatio.Optional(CONF_TEMPERATURE_STEP): _target_temp_step, - probatio.Optional(ATTR_EXTERNAL_TEMPERATURE_SENSOR): cv.entity_id, - probatio.Optional(ATTR_EXTERNAL_HUMIDITY_SENSOR): cv.entity_id, - probatio.Optional( - CONF_RESTORE_STATES, default=DEFAULT_RESTORE_STATES - ): cv.boolean, - } +OPTIONS_SCHEMA = probatio.All( + probatio.Schema( + { + probatio.Required(CONF_NAME): cv.string, + probatio.Optional(CONF_HVAC_MODES): probatio.All( + cv.ensure_list, [probatio.In(VALID_HVAC_MODES)] + ), + probatio.Optional(CONF_FAN_MODES): probatio.All( + cv.ensure_list, [probatio.In(VALID_FAN_MODES)] + ), + probatio.Optional(CONF_SWING_MODES): probatio.All( + cv.ensure_list, [probatio.In(DEFAULT_SWING_MODES)] + ), + probatio.Optional(CONF_SWING_HORIZONTAL_MODES): probatio.All( + cv.ensure_list, [probatio.In(DEFAULT_SWING_HORIZONTAL_MODES)] + ), + probatio.Optional(CONF_FEATURES): probatio.All( + cv.ensure_list, [probatio.In(VALID_FEATURES)] + ), + # Replaced by half_degrees, still accepted, see _yaml_temperature_step + probatio.Optional(CONF_TEMPERATURE_STEP): _target_temp_step, + probatio.Optional(CONF_HALF_DEGREES): cv.boolean, + probatio.Optional(ATTR_EXTERNAL_TEMPERATURE_SENSOR): cv.entity_id, + probatio.Optional(ATTR_EXTERNAL_HUMIDITY_SENSOR): cv.entity_id, + probatio.Optional( + CONF_RESTORE_STATES, default=DEFAULT_RESTORE_STATES + ): cv.boolean, + } + ), + _yaml_temperature_step, ) @@ -728,23 +772,18 @@ def setup_device_options_schema( # noqa: C901 } ) - if device.supports_property(GreeProp.TARGET_TEMPERATURE_1): + # Only for a unit that answers a half degree column: TemRec, StFahFlg, + # Add0.5 or Add0.1. Answering is no proof of support, so it stays a choice. + # On by default for a zone, see GreeDevice.default_half_degrees. + if device.supports_half_degrees: schema.update( { probatio.Required( - CONF_TEMPERATURE_STEP, + CONF_HALF_DEGREES, default=defaults.get( - CONF_TEMPERATURE_STEP, DEFAULT_TARGET_TEMP_STEP + CONF_HALF_DEGREES, device.default_half_degrees ), - ): NumberSelector( - NumberSelectorConfig( - min=MIN_TARGET_TEMP_STEP, - max=MAX_TARGET_TEMP_STEP, - step=0.5, - mode=NumberSelectorMode.BOX, - unit_of_measurement="ºC", - ) - ) + ): cv.boolean } ) diff --git a/custom_components/gree_custom/const.py b/custom_components/gree_custom/const.py index ef920e63..00f9735d 100755 --- a/custom_components/gree_custom/const.py +++ b/custom_components/gree_custom/const.py @@ -23,6 +23,8 @@ ZONE_CONTROLLER_MODEL = "Zone controller" CURRENT_CONF_VERSION = 3 +# 2: the device option target_temp_step became half_degrees +CURRENT_CONF_MINOR_VERSION = 2 CONFENTRY_ID_LOCAL_ONLY = "local_only" @@ -58,10 +60,11 @@ CONF_SWING_MODES = "swing_modes" CONF_SWING_HORIZONTAL_MODES = "swing_horizontal_modes" CONF_FEATURES = "features" +# Replaced by CONF_HALF_DEGREES. Still read from 4.x, YAML and older entries. CONF_TEMPERATURE_STEP = "target_temp_step" +CONF_HALF_DEGREES = "half_degrees" CONF_PREFER_CLOUD = "prefer_cloud" -DEFAULT_TARGET_TEMP_STEP = 1 ENCRYPTION_VERSION_AUTO = "0" DEFAULT_ENCRYPTION_VERSION = ENCRYPTION_VERSION_AUTO DEFAULT_ENCRYPTION_KEY = "" diff --git a/custom_components/gree_custom/migration.py b/custom_components/gree_custom/migration.py index 2cb3666a..855e19be 100644 --- a/custom_components/gree_custom/migration.py +++ b/custom_components/gree_custom/migration.py @@ -66,6 +66,7 @@ VALID_FAN_MODES, VALID_HVAC_MODES, _target_temp_step, + half_degrees_from_temp_step, ) from .const import ( ATTR_EXTERNAL_HUMIDITY_SENSOR, @@ -79,6 +80,7 @@ CONF_ENCRYPTION_KEY, CONF_ENCRYPTION_VERSION, CONF_FAN_MODES, + CONF_HALF_DEGREES, CONF_HVAC_MODES, CONF_SWING_HORIZONTAL_MODES, CONF_SWING_MODES, @@ -88,7 +90,6 @@ DEFAULT_FAN_MODES, DEFAULT_SWING_HORIZONTAL_MODES, DEFAULT_SWING_MODES, - DEFAULT_TARGET_TEMP_STEP, DOMAIN, ) from .helpers import get_device_by_identifier @@ -183,9 +184,12 @@ LEGACY_CLIMATE_PREFIX = f"{LEGACY_DOMAIN}_" CLIMATE_KEY = "hvac" -# 4.x entities whose last state becomes an option here +# 4.x entities whose last state becomes an option here. The step number and +# the switch "Half-degree via Add0.5" (4.0.13 and later) both become +# half_degrees: on when the step is not a whole number or the switch is on. LEGACY_STATE_OPTIONS = { "target_temp_step": CONF_TEMPERATURE_STEP, + "half_degree_control": CONF_HALF_DEGREES, "external_temperature_sensor": ATTR_EXTERNAL_TEMPERATURE_SENSOR, "external_humidity_sensor": ATTR_EXTERNAL_HUMIDITY_SENSOR, } @@ -383,6 +387,23 @@ def _normalize_device( return mac, normalized +def _restored_option(option: str, value: str) -> dict[str, Any]: + """Turn the state of one 4.x entity into options here. + + The step and the switch only ever turn half_degrees on, so the one that + is on wins. Raises probatio.Invalid for a value that is not valid here. + """ + if option == CONF_TEMPERATURE_STEP: + if half_degrees_from_temp_step(_target_temp_step(value)): + return {CONF_HALF_DEGREES: True} + return {} + + if option == CONF_HALF_DEGREES: + return {CONF_HALF_DEGREES: True} if cv.boolean(value) else {} + + return {option: cv.entity_id(value)} + + def _restored_options( hass: HomeAssistant, entry_id: str | None, mac_controller: str ) -> dict[str, Any]: @@ -418,12 +439,7 @@ def _restored_options( continue try: - if option == CONF_TEMPERATURE_STEP: - step = _target_temp_step(value) - if step != DEFAULT_TARGET_TEMP_STEP: - options[option] = step - else: - options[option] = cv.entity_id(value) + options.update(_restored_option(option, value)) except probatio.Invalid: _LOGGER.info( "Migration from 4.x: %s value '%s' of %s is not valid here and is" diff --git a/custom_components/gree_custom/number.py b/custom_components/gree_custom/number.py index e36e9802..f215be35 100755 --- a/custom_components/gree_custom/number.py +++ b/custom_components/gree_custom/number.py @@ -108,12 +108,7 @@ class GreeNumberDescription( else MAX_TEMP_C ), unit_func=lambda device: UNITS_GREE_TO_HA[device.target_temperature_unit], - step_func=lambda device: ( - 0.5 - if device.target_temperature_unit is TemperatureUnits.C - and device.has_target_temperature_bit - else 1 - ), + step_func=lambda device: device.target_temperature_step, value_func=lambda device: device.target_temperature, set_func=lambda device, value: device.set_target_temperature(value), updates_device=True, diff --git a/custom_components/gree_custom/select.py b/custom_components/gree_custom/select.py index d218c7f0..86892598 100755 --- a/custom_components/gree_custom/select.py +++ b/custom_components/gree_custom/select.py @@ -75,7 +75,11 @@ def _set_humidity_control_mode(device: GreeDevice, mode: str) -> None: translation_key=GATTR_TEMP_UNITS, # Every sub-unit of a zone controller answers TemUnit, but they share # one unit, set on the ducted unit. So the zones get no select. - device_filter=lambda device: device.device_type is not DeviceType.ZONE, + # A unit without a bit column is Celsius only. + device_filter=lambda device: ( + device.device_type is not DeviceType.ZONE + and device.supports_temperature_unit_change + ), entity_category=EntityCategory.CONFIG, options=[f"º{member.name}" for member in TemperatureUnits], value_func=lambda device: f"º{device.target_temperature_unit.name}", diff --git a/custom_components/gree_custom/translations/en.json b/custom_components/gree_custom/translations/en.json index 40926e25..d380c525 100644 --- a/custom_components/gree_custom/translations/en.json +++ b/custom_components/gree_custom/translations/en.json @@ -113,7 +113,7 @@ "swing_modes": "Vertical Swing Modes", "swing_horizontal_modes": "Horizontal Swing Modes", "features": "Device Features and Modes", - "target_temp_step": "Temperature Step", + "half_degrees": "Use half-degrees °C", "external_temperature_sensor": "External Temperature Sensor", "external_humidity_sensor": "External Humidity Sensor", "restore_states": "Restore Entities" @@ -123,7 +123,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.", - "target_temp_step": "Sets the increment step for adjusting the target temperature. Fahrenheit degrees are clamped to the nearest integer." + "half_degrees": "Set the target temperature in steps of 0.5 °C. Shown because the unit answers TemRec, StFahFlg, Add0.5 or Add0.1, but some units answer these and still take only whole degrees. Fahrenheit is always in whole degrees." } }, "reconfigure": { diff --git a/custom_components/gree_custom/translations/nl.json b/custom_components/gree_custom/translations/nl.json index 52170b80..1b269253 100644 --- a/custom_components/gree_custom/translations/nl.json +++ b/custom_components/gree_custom/translations/nl.json @@ -113,7 +113,7 @@ "swing_modes": "Verticale swingmodi", "swing_horizontal_modes": "Horizontale swingmodi", "features": "Apparaatfuncties en -modi", - "target_temp_step": "Temperatuurstap", + "half_degrees": "Halve graden °C gebruiken", "external_temperature_sensor": "Externe temperatuursensor", "external_humidity_sensor": "Externe vochtigheidssensor", "restore_states": "Entiteiten herstellen" @@ -122,7 +122,7 @@ "external_temperature_sensor": "Als deze is ingesteld, vervangt hij de ingebouwde temperatuursensor van de airco voor de gegevens van de climate-entiteit", "external_humidity_sensor": "Als deze is ingesteld, vervangt hij de ingebouwde vochtigheidssensor van de airco voor de gegevens van de climate-entiteit", "restore_states": "Als dit is aangevinkt, krijgt het apparaat bij het starten van de integratie de eerder opgeslagen toestand terug in plaats van de huidige toestand van het apparaat.", - "target_temp_step": "Stelt de stapgrootte in voor het aanpassen van de doeltemperatuur. Graden Fahrenheit worden afgerond op een geheel getal." + "half_degrees": "Stel de doeltemperatuur in met stappen van 0,5 °C. Je ziet dit omdat het apparaat TemRec, StFahFlg, Add0.5 of Add0.1 beantwoordt, maar sommige apparaten beantwoorden die en kennen toch alleen hele graden. Fahrenheit is altijd in hele graden." } }, "reconfigure": { diff --git a/custom_components/gree_custom/translations/pt.json b/custom_components/gree_custom/translations/pt.json index 4ee08dc6..334fb15a 100644 --- a/custom_components/gree_custom/translations/pt.json +++ b/custom_components/gree_custom/translations/pt.json @@ -113,7 +113,7 @@ "swing_modes": "Modos de Oscilamento Vertical", "swing_horizontal_modes": "Modos de Oscilamento Horizontal", "features": "Outras Funcionalidades e Modos", - "target_temp_step": "Incremento de Temperatura", + "half_degrees": "Usar meios graus °C", "external_temperature_sensor": "Sensor de Temperatura", "external_humidity_sensor": "Sensor de Humidade", "restore_states": "Restaurar Entidades" @@ -122,7 +122,7 @@ "external_temperature_sensor": "Se definido, substitui o sensor integrado de temperatura interior do dispositivo", "external_humidity_sensor": "Se definido, substitui o sensor integrado de humidade interior do dispositivo", "restore_states": "Se ativo, quando a integração é iniciada, o estado do dispositivo será reposto para o último estado observado na integração.", - "target_temp_step": "Define o incremento da temperatura quando esta é ajustada. Graus Fahrenheit são arredondados para às unidades." + "half_degrees": "Define a temperatura alvo em incrementos de 0,5 °C. Aparece porque o dispositivo responde a TemRec, StFahFlg, Add0.5 ou Add0.1, mas alguns dispositivos respondem a estas e só aceitam graus inteiros. Fahrenheit é sempre em graus inteiros." } }, "reconfigure": { diff --git a/docs/config-entry.md b/docs/config-entry.md index ee1f9098..12817e34 100644 --- a/docs/config-entry.md +++ b/docs/config-entry.md @@ -2,7 +2,7 @@ One config entry is a hub. There is one entry per Gree Cloud account, plus one entry for all local-only devices. The local-only entry has `unique_id` `local_only`. -The entry version is `CURRENT_CONF_VERSION` in `const.py` (3 at the time of writing). +The entry version is `CURRENT_CONF_VERSION` in `const.py` (3 at the time of writing), and the minor version is `CURRENT_CONF_MINOR_VERSION` (2). ## Shape @@ -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.half_degrees` | "Use half-degrees °C". Only offered when the unit answers a half degree column, see [protocol.md](protocol.md#half-degrees-celsius). Missing means off, except on a zone of a zone controller, where it means on. So an existing zone keeps its 0.5 step after the upgrade. It replaced `options.target_temp_step` in minor version 2. | ## YAML import @@ -130,7 +131,8 @@ After the first run `gree_custom` has its own entry and starts by itself. | `hvac_modes`, `fan_modes` | the same names | | `swing_modes`, `swing_horizontal_modes` | other names, matched on the value sent to the unit (4.x `swing_downmost` and 5.0 `swing_upper` both send 7) | | `temp_sensor_offset` | dropped, the offset is detected here | -| state of the 4.x `target_temp_step` number and the two external sensor selects | `options.target_temp_step`, `options.external_temperature_sensor`, `options.external_humidity_sensor` | +| state of the 4.x `target_temp_step` number and of the `half_degree_control` switch (4.0.13 and later) | `options.half_degrees`: on when the step is not a whole number or the switch is on. Otherwise left out | +| state of the two 4.x external sensor selects | `options.external_temperature_sensor`, `options.external_humidity_sensor` | A missing mode list counts as the 4.x default list, because 4.x used that list at runtime. Values that equal the defaults here are left out. A mode list that holds every mode is left out too, except `fan_modes`: the 4.x default holds `turbo` and `quiet`, the default here does not, so that list is written out. Every converted device then goes through `ITEM_SCHEMA`, so a device that is not valid here is skipped with an error in the log. @@ -203,10 +205,14 @@ What to expect: If you change this shape: -1. Bump `CURRENT_CONF_VERSION` in `const.py`. -2. Add `async_migrate_entry` in `__init__.py`. There is no migration code yet, and Home Assistant refuses to load an entry whose version is older than the flow's version unless that function exists. +1. For a change that older code can still read, bump `CURRENT_CONF_MINOR_VERSION` in `const.py`. Home Assistant then calls `async_migrate_entry` in `__init__.py`, and a downgrade still loads the entry. For a change that older code cannot read, bump `CURRENT_CONF_VERSION`. +2. Add a step to `async_migrate_entry`. It refuses an entry of another major version, as Home Assistant did before the function existed. `get_config_entries()` in `helpers.py` compares only the major version. 3. Update the example above and `manual-configuration.yaml`. +Minor versions so far: + +- 2: the device option `target_temp_step` became `half_degrees`. A step that is not a whole number turns it on (`options_without_temperature_step()` in `config_schema.py`). The step is removed. A YAML block may still hold `target_temp_step`: `OPTIONS_SCHEMA` converts it the same way and logs a warning, because the import runs at every start. + ## Discovery preferences The extra networks and hosts entered in the local setup step are stored outside the entry, in `.storage/gree_custom_discovery_prefs`, so the next setup flow can offer them again. diff --git a/docs/configuration.md b/docs/configuration.md index 20743180..c24991fd 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -94,7 +94,7 @@ One page per device. Gree devices do not report reliably which features they hav | Vertical Swing Modes | all | The vertical positions and swing ranges. | | Horizontal Swing Modes | all | The horizontal positions and swing ranges. Only shown when the unit has horizontal swing. | | Device Features and Modes | all the unit supports, except Auxiliary Heat | Which switches and selects to create. See [entities.md](entities.md). Auxiliary Heat is not ticked for a new device, because many units answer its property without having the heater; tick it yourself when the unit has one. On a zone of a zone controller, leave out **Zone Switch** if the zone must always stay open. | -| Temperature Step | 1 | The step of the target temperature, 0.5 to 5 in steps of 0.5. In Fahrenheit the step is rounded to a whole degree. | +| Use half-degrees °C | off, on for a zone | Set the target temperature in steps of 0.5 °C instead of 1 °C. Only shown when the unit answers one of the half degree properties (`TemRec`, `StFahFlg`, `Add0.5`, `Add0.1`). Some units answer one and still take only whole degrees: if a half degree jumps back to a whole one, turn it off. A zone of a zone controller has it on by default, because zones take the half degree in `StFahFlg` and always used it before this option existed. The value you pick carries over to the next device in the same setup. Fahrenheit is always in whole degrees. The step of the climate entity follows this option and the unit's scale. | | 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). | diff --git a/docs/entities.md b/docs/entities.md index 832b0757..3ea9f5a2 100644 --- a/docs/entities.md +++ b/docs/entities.md @@ -17,7 +17,7 @@ The main entity. Its name is the device name. | Part | What it does | |---|---| | HVAC mode | Auto, Cool, Dry, Fan only, Heat, Off. You choose the list at setup. Off turns the unit off, every other mode turns it on. | -| Target temperature | 16 to 30 degrees C, or 61 to 86 degrees F. Available when Heat, Cool or Auto is in the mode list and the unit has a target temperature. The step is the **Temperature Step** option. In Auto mode the unit uses its own factory setting, so a temperature sent with Auto is ignored and logged as a warning. | +| Target temperature | 16 to 30 degrees C, or 61 to 86 degrees F. Available when Heat, Cool or Auto is in the mode list and the unit has a target temperature. The step is 0.5 in Celsius when **Use half-degrees °C** is on, and 1 otherwise. With the option off, a half degree sent by an automation goes up to the next whole degree. A half degree set with the remote still shows as it is. In Auto mode the unit uses its own factory setting, so a temperature sent with Auto is ignored and logged as a warning. | | Current temperature | The unit's room sensor, converted to the unit's temperature scale. Replaced by the **External Temperature Sensor** when one is set, also converted to the unit's scale. That changes only what Home Assistant shows; the unit keeps regulating on its own sensor. | | Current humidity | The unit's humidity sensor, when it has one. Replaced by the **External Humidity Sensor** when one is set. Display only, like the temperature. | | Fan mode | Auto, Low, Medium-Low, Medium, Medium-High, High, plus Turbo and Quiet when the unit has them. See below. | @@ -43,7 +43,7 @@ Turbo and Quiet are not fan speeds on the unit but separate features. The integr ### Temperature scale -The unit has its own temperature scale, Celsius or Fahrenheit, which you change with the **Temperature Units** select. The climate entity follows the unit, and Home Assistant converts to your display units. Fahrenheit values come from the unit's own lookup table, not from a formula. +The unit has its own temperature scale, Celsius or Fahrenheit, which you change with the **Temperature Units** select. The climate entity follows the unit, and Home Assistant converts to your display units. Fahrenheit values come from the unit's own lookup table, not from a formula. That table needs `TemRec` or `StFahFlg`, so a unit without them is Celsius only: it gets no select, and Home Assistant converts to Fahrenheit for you. ## Zone controller @@ -57,7 +57,7 @@ A zone controller is controlled locally. Add it with local discovery, or with bo | Entity | What it does | |---|---| | 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. | +| Target Temperature | The target temperature of the zone, in the unit of the controller: 16 to 30 °C, in half degrees when **Use half-degrees °C** is on, 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. | ## Sensors @@ -112,7 +112,7 @@ Two switches are integration features. They do not exist on the unit and their s | Select | Feature | Available in | Options | |---|---|---|---| -| Temperature Units | none, created when the unit answers the property | every mode | ºC, ºF. Changes the scale of the unit itself. Configuration category. | +| Temperature Units | none, created when the unit answers `TemUn` and also `TemRec` or `StFahFlg`, or on the AC unit of a zone controller | every mode | ºC, ºF. Changes the scale of the unit itself. Configuration category. | | Humidity Control | Humidity Control | Cool, Dry | Disabled, Normal Dry, Smart Dry, Continuous Dry. Smart Dry only in Cool. Continuous Dry only in Dry. The other options fail with a message. | | Auxiliary Heat | Auxiliary Heat, off by default | Heat, Auto | Off, Always On, Auto. Controls the electric heater of the unit. Auto lets the unit decide when to use it. Shows unknown when the unit reports a value that is not one of these three. | diff --git a/docs/installation.md b/docs/installation.md index e843e87f..f4919793 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -50,7 +50,7 @@ Your devices move to this version by themselves. Their entity IDs, areas, names What changes: -- The number entity for the temperature step and the selects for the external sensors are gone. Their values become the options **Temperature Step**, **External Temperature Sensor** and **External Humidity Sensor**. +- The number entity for the temperature step and the selects for the external sensors are gone. Their values become the options **Use half-degrees °C**, **External Temperature Sensor** and **External Humidity Sensor**. A step of 0.5 turns **Use half-degrees °C** on, and so does the 4.x switch **Half-degree via Add0.5**. A whole step such as 2 has no match: the step now follows the unit. - Switches for features your unit does not have are removed. 4.x created them for every unit. - `temp_sensor_offset` is gone. This version detects the offset itself. - The swing modes have other names. The migration picks the name that moves the louvers to the same position as before. diff --git a/docs/protocol.md b/docs/protocol.md index 76f4d124..25707edf 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -59,6 +59,28 @@ Facts about how Gree devices behave on the wire. Most of these are not visible f - `AssHt` (`FEAT_AUXILIARY_HEAT`) holds the mode of the electric heater: 0 off, 1 always on, 2 auto. These values were checked against the Gree+ app on one unit, in 4.x PR #539. Other models may use other values. A value outside 0 to 2 reads as no mode. - 4.x asked for `AssHt` once before it added it to the poll, because 4.x matched values to columns by position, and a unit that left the column out shifted every value after it. Here no probe is needed: values are matched by name inside one response, and the first poll drops the column on a unit that does not answer it. A gateway that answers an empty string is dropped too, because the value is not a number. +### Half degrees Celsius + +Units carry the half degree in different columns. Seen so far: + +- The bit (`TemRec`, or `StFahFlg` on a zone). In Fahrenheit it picks the value from the table, see below. Many units take it as the half degree in Celsius. +- `Add0.5` (`TARGET_TEMPERATURE_HALF_C`), 0 or 1. Seen on a split unit that ignores `TemRec` writes (PR 537). +- `Add0.1` (`TARGET_TEMPERATURE_TENTHS_C`), a tenths digit 0 to 9. The unit rounds it to the nearest half degree: 1 gives .0, 3 gives .5, 8 carries into `SetTem`. Seen on a GR-Gcloud VRF gateway, which answers `TemRec` with `""` and makes `Add0.5` follow `Add0.1` (PR 568). + +Answering a column is no proof that the unit uses it. One unit answers all three with 0 but does not support all of them (issue 569). So no single preferred column works for every known unit, and the code writes all of them: + +- `Add0.5` and `Add0.1` are normal `GreeProp` columns. They are polled, and the first poll drops them on a unit that does not answer them (an empty answer counts as not answered). +- `set_target_temperature()` writes every half degree column the unit answers, in the same command as `SetTem`. A half degree in Celsius is the bit 1, `Add0.5` 1 and `Add0.1` 5. A whole degree is 0 in all of them, so a half degree set with a remote is cleared. In Fahrenheit the bit comes from the table and `Add0.5` and `Add0.1` are 0. +- `target_temperature` reads a half degree in Celsius when any answered column is not 0. A column the unit ignores reads 0, so it does no harm. In Fahrenheit only the bit is read. +- `GreeDevice.set_half_degrees()` is the user option "Use half-degrees °C" (`half_degrees` in the device options). Without a stored choice, `default_half_degrees` decides: on for a zone of a zone controller, which takes the half degree in `StFahFlg`, and off for every other unit. Off, Celsius goes to the nearest whole degree, with a half going up (22.5 gives 23). The read side does not change, so a half degree set with a remote still shows. +- `supports_half_degrees` is true when the unit answers one of the columns. The options form only offers the checkbox then. `target_temperature_step` is 0.5 in Celsius with the option on, and 1 otherwise. The climate entity and the zone number take their step from it. +- No retry loop: nothing resends a value the unit did not take. A sub-unit holds the sent values for at most `HELD_VALUE_TTL`, see [Stale state after a command](#stale-state-after-a-command), then shows what the unit reports. A column the unit ignores is only sent again with the next temperature command. `has_pending_updates` compares with the reported value, so it does not cause a push by itself. +- Known risk: a unit that stores a column it ignores (it reads back what was written). If the setpoint then changes on the remote, the stored half stays and the value reads .5 too high, until Home Assistant sets the next whole degree. This is not tested. The unit of PR 537 is the one to check: it accepts a `TemRec` write without applying it, and it is not known if `TemRec` then reads back as 1. + +### Temperature unit + +`TemUn` (or `TemUnit`) switches the unit between Celsius and Fahrenheit, but `SetTem` is always whole degrees Celsius. Only the bit picks the Fahrenheit degree from the table. So `supports_temperature_unit_change` needs the unit column and a bit column. Without a bit the unit is Celsius only: `target_temperature_unit` is always Celsius, and the **Temperature Units** select is not created. Home Assistant converts the value for a user who shows Fahrenheit. The AC unit of a zone controller is the exception: it has no bit of its own (it drops `StFahFlg`, see [Zone controllers](#zone-controllers)), but its `TemUnit` switches the whole system and the zones do have the bit. + ## Discovery and network - Local discovery is a plain text `{"t": "scan"}` UDP broadcast. The device answers with a `dev` pack encrypted with the generic key. diff --git a/manual-configuration.yaml b/manual-configuration.yaml index 9c953bd1..83af6513 100644 --- a/manual-configuration.yaml +++ b/manual-configuration.yaml @@ -114,7 +114,7 @@ gree_custom: - "powersave" - "humidity_control" - "auxiliary_heat" - target_temp_step: 1 # Number of degrees increase or decrease when changing the temperature | 0.5 <= number <= 5, 0.5 increments | default = 1 + half_degrees: false # Set the target temperature in steps of 0.5 C | bool | default = false. Replaces target_temp_step, which still works for now: a step of 0.5 means true 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 diff --git a/tests/config_flow/test_half_degrees.py b/tests/config_flow/test_half_degrees.py new file mode 100644 index 00000000..8a2e72a8 --- /dev/null +++ b/tests/config_flow/test_half_degrees.py @@ -0,0 +1,240 @@ +"""Tests for the option "Use half-degrees °C" (issue 569) in Home Assistant. + +The option replaced the temperature step. These tests cover the form, the +climate step that follows from it, and every way an old step reaches the new +option: an entry of minor version 1, a YAML block and a 4.x migration. +""" + +from types import SimpleNamespace +from typing import Any, cast + +from pytest_homeassistant_custom_component.common import MockConfigEntry + +import custom_components.gree_custom as gree_component +from custom_components.gree_custom.aiogree.api import DeviceType +from custom_components.gree_custom.aiogree.device import GreeDevice +from custom_components.gree_custom.config_flow import _copied_options +from custom_components.gree_custom.config_schema import CONFIG_SCHEMA +from custom_components.gree_custom.const import ( + CONF_DEVICE_CONNECTION, + CONF_DEVICE_CONNECTION_LOCAL, + CONF_DEVICE_OPTIONS, + CONF_DEVICES, + CONF_EXTRA_SCAN_HOSTS, + CONF_HALF_DEGREES, + CONF_TEMPERATURE_STEP, + CURRENT_CONF_MINOR_VERSION, + CURRENT_CONF_VERSION, + DOMAIN, +) +from custom_components.gree_custom.migration import ( + _normalize_device, + _restored_option, + convert_legacy_device, +) +from homeassistant.config_entries import SOURCE_USER, ConfigEntryState +from homeassistant.const import CONF_DISCOVERY, CONF_HOST, CONF_MAC, CONF_NAME +from homeassistant.core import HomeAssistant +from homeassistant.data_entry_flow import FlowResultType +from tests.config_flow.conftest import MAC_A, GreeEnv, form_input, submit + +HALF_COLUMNS = {"TemRec", "StFahFlg", "Add0.5", "Add0.1"} + + +async def device_options_form(hass: HomeAssistant, gree: GreeEnv) -> dict[str, Any]: + """Run the local user flow for unit A up to its device options form.""" + host = await gree.start_udp(gree.devices[MAC_A]) + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_DISCOVERY: ["local"]} + ) + result = await submit(hass, result, **{CONF_EXTRA_SCAN_HOSTS: [host]}) + result = await submit(hass, result, **{CONF_DEVICES: [MAC_A]}) + assert result["step_id"] == "connection_options" + result = await submit(hass, result) + assert result["step_id"] == "device_options" + return result + + +def device_step(entry: Any) -> float: + """Return the target temperature step of unit A of a loaded entry. + + The climate entity takes its step from here. The entity itself needs the + native climate API of Home Assistant 2026.11, and the test pin is older. + """ + return entry.runtime_data[MAC_A].device.target_temperature_step + + +async def test_the_option_sets_the_climate_step( + hass: HomeAssistant, gree: GreeEnv +) -> None: + """The unit answers TemRec, so the form offers the option, off by default.""" + result = await device_options_form(hass, gree) + + assert form_input(result)[CONF_HALF_DEGREES] is False + assert CONF_TEMPERATURE_STEP not in form_input(result) + + result = await submit(hass, result, **{CONF_HALF_DEGREES: True}) + assert result["type"] is FlowResultType.CREATE_ENTRY + await hass.async_block_till_done() + + entry = result["result"] + assert entry.state is ConfigEntryState.LOADED + assert entry.minor_version == CURRENT_CONF_MINOR_VERSION + options = entry.data[CONF_DEVICES][MAC_A][CONF_DEVICE_OPTIONS] + assert options[CONF_HALF_DEGREES] is True + assert device_step(entry) == 0.5 + gree.assert_only_entry_connections() + + +async def test_a_unit_without_a_half_column_gets_no_option( + hass: HomeAssistant, gree: GreeEnv +) -> None: + """No TemRec, StFahFlg, Add0.5 or Add0.1: whole degrees, nothing to choose.""" + gree.devices[MAC_A].unsupported_props = set(HALF_COLUMNS) + + result = await device_options_form(hass, gree) + assert CONF_HALF_DEGREES not in form_input(result) + + result = await submit(hass, result) + await hass.async_block_till_done() + + assert device_step(result["result"]) == 1.0 + gree.assert_only_entry_connections() + + +# +# An entry of minor version 1 +# + + +def old_device(options: dict[str, Any]) -> dict[str, Any]: + """One device of an entry, with these options.""" + return { + CONF_DEVICE_CONNECTION: {CONF_DEVICE_CONNECTION_LOCAL: {CONF_HOST: "x"}}, + CONF_DEVICE_OPTIONS: {CONF_NAME: "Unit", **options}, + } + + +async def test_an_old_entry_gets_half_degrees_from_its_step( + hass: HomeAssistant, +) -> None: + """A step that is not whole means half degrees. The step itself goes.""" + entry = MockConfigEntry( + domain=DOMAIN, + version=CURRENT_CONF_VERSION, + minor_version=1, + data={ + CONF_DEVICES: { + "aa0000000001": old_device({CONF_TEMPERATURE_STEP: 0.5}), + "aa0000000002": old_device({CONF_TEMPERATURE_STEP: 1}), + "aa0000000003": old_device({CONF_TEMPERATURE_STEP: 2.0}), + "aa0000000004": old_device({}), + } + }, + ) + entry.add_to_hass(hass) + + assert await gree_component.async_migrate_entry(hass, entry) + + assert entry.minor_version == CURRENT_CONF_MINOR_VERSION + options = { + mac: device[CONF_DEVICE_OPTIONS] + for mac, device in entry.data[CONF_DEVICES].items() + } + assert options["aa0000000001"] == {CONF_NAME: "Unit", CONF_HALF_DEGREES: True} + assert options["aa0000000002"] == {CONF_NAME: "Unit"} + assert options["aa0000000003"] == {CONF_NAME: "Unit"} + assert options["aa0000000004"] == {CONF_NAME: "Unit"} + + +async def test_an_entry_of_another_major_version_is_refused( + hass: HomeAssistant, +) -> None: + """Home Assistant refused these before there was a migration, and still does.""" + entry = MockConfigEntry(domain=DOMAIN, version=2, data={CONF_DEVICES: {}}) + entry.add_to_hass(hass) + + assert not await gree_component.async_migrate_entry(hass, entry) + + +# +# YAML +# + + +def yaml_options(**options: Any) -> dict[str, Any]: + """Validate one YAML device with these options and return its options.""" + config = CONFIG_SCHEMA( + { + DOMAIN: [ + { + CONF_DEVICES: { + "aa0000000001": { + CONF_DEVICE_CONNECTION: { + CONF_DEVICE_CONNECTION_LOCAL: {CONF_HOST: "x"} + }, + CONF_DEVICE_OPTIONS: {CONF_NAME: "Unit", **options}, + } + } + } + ] + } + ) + return config[DOMAIN][0][CONF_DEVICES]["aa0000000001"][CONF_DEVICE_OPTIONS] + + +def test_yaml_takes_half_degrees() -> None: + """The new key, as a user writes it.""" + assert yaml_options(**{CONF_HALF_DEGREES: True})[CONF_HALF_DEGREES] is True + + +def test_yaml_still_takes_the_old_step() -> None: + """The import runs at every start, so an old key must not break the block.""" + options = yaml_options(**{CONF_TEMPERATURE_STEP: 0.5}) + assert options[CONF_HALF_DEGREES] is True + assert CONF_TEMPERATURE_STEP not in options + + assert CONF_HALF_DEGREES not in yaml_options(**{CONF_TEMPERATURE_STEP: 1}) + + +def test_yaml_half_degrees_wins_over_the_old_step() -> None: + """When both are written, the new key is what the user meant.""" + options = yaml_options(**{CONF_TEMPERATURE_STEP: 0.5, CONF_HALF_DEGREES: False}) + assert options[CONF_HALF_DEGREES] is False + + +# +# Migration from 4.x +# + + +def test_a_4x_step_or_switch_turns_half_degrees_on() -> None: + """The step number and the Add0.5 switch of 4.x both map to the new option.""" + assert _restored_option(CONF_TEMPERATURE_STEP, "0.5") == {CONF_HALF_DEGREES: True} + assert _restored_option(CONF_TEMPERATURE_STEP, "1.0") == {} + assert _restored_option(CONF_TEMPERATURE_STEP, "2.0") == {} + assert _restored_option(CONF_HALF_DEGREES, "on") == {CONF_HALF_DEGREES: True} + assert _restored_option(CONF_HALF_DEGREES, "off") == {} + + +def test_a_converted_4x_device_keeps_half_degrees() -> None: + """The converted device passes the YAML schema with the option.""" + key, device = convert_legacy_device( + {CONF_NAME: "Unit", CONF_MAC: "aa:00:00:00:00:01", CONF_HOST: "x"}, + {CONF_HALF_DEGREES: True}, + ) + normalized = _normalize_device(key, device) + + assert normalized is not None + assert normalized[1][CONF_DEVICE_OPTIONS][CONF_HALF_DEGREES] is True + + +def test_the_option_carries_over_to_the_next_zone() -> None: + """One choice on the first zone fills the form of the next one.""" + zone = cast(GreeDevice, SimpleNamespace(device_type=DeviceType.ZONE)) + copied = _copied_options(zone, {CONF_NAME: "Zone 1", CONF_HALF_DEGREES: False}) + + assert copied == {CONF_HALF_DEGREES: False} diff --git a/tests/fakes/device.py b/tests/fakes/device.py index c82f6137..b66af288 100644 --- a/tests/fakes/device.py +++ b/tests/fakes/device.py @@ -63,6 +63,7 @@ def __init__( scan_info: dict[str, Any] | None = None, stale_reads_after_cmd: int = 0, apply_commands: bool = True, + read_only_props: set[str] | None = None, ) -> None: """Set up the device. @@ -97,6 +98,9 @@ def __init__( can be several requests. `catch_up()` ends it at once. apply_commands: False means a command is acknowledged but the values do not change. That is a command the unit rejected. + read_only_props: Columns the device answers but never changes on a + command, while it applies the rest of the command. Some units + answer a half degree column such as Add0.5 that they ignore. """ self.mac = mac @@ -119,6 +123,7 @@ def __init__( self.scan_info = scan_info self.stale_reads_after_cmd = stale_reads_after_cmd self.apply_commands = apply_commands + self.read_only_props = read_only_props or set() # The cached state a gateway answers with after a command, and how # many more status requests it is used for. @@ -383,7 +388,8 @@ def build_command_result(self, pack: dict[str, Any]) -> dict[str, Any]: if self.apply_commands: for option, value in zip(options, values, strict=False): - self.values[option] = value + if option not in self.read_only_props: + self.values[option] = value return { "t": "res", "mac": self.mac, diff --git a/tests/test_device.py b/tests/test_device.py index 0d2655f3..f40ad31a 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -606,7 +606,8 @@ async def test_setting_the_swing_modes(bound: GreeDevice) -> None: async def test_the_target_temperature_in_celsius(bound: GreeDevice) -> None: - """Half degrees are kept in a separate column.""" + """Half degrees are kept in a separate column, when the option is on.""" + bound.set_half_degrees(True) bound.set_target_temperature(22.5) assert bound.target_temperature == 22.5 diff --git a/tests/test_half_degrees.py b/tests/test_half_degrees.py new file mode 100644 index 00000000..7850dc89 --- /dev/null +++ b/tests/test_half_degrees.py @@ -0,0 +1,370 @@ +"""Tests for half degrees Celsius and the temperature unit (issue 569). + +Units use different columns for the half degree: the bit (TemRec or StFahFlg), +Add0.5 (0 or 1) and Add0.1 (a tenths digit). A unit can answer a column and +still ignore it. So every answered column is written, and a value is a half +degree when any of them is set. These tests drive the real bind and poll +cycle against a fake unit and check what goes over the wire. +""" + +# 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, Callable +from typing import Any + +from aiogree.api import TemperatureUnits +from aiogree.const import HELD_VALUE_TTL +from aiogree.device import GreeDevice +from aiogree.transport_udp import GreeUdpTransport +import pytest + +from .fakes.device import FakeGreeDevice + +HALF_COLUMNS = {"TemRec", "StFahFlg", "Add0.5", "Add0.1"} + +# The columns a unit answers, by the kind of unit. The fake answers every +# other column it is asked for with 0, as some real units do. +UNITS = { + # A normal split unit: only the bit + "tem_rec": {"TemRec"}, + # The bit in the second column, as a zone has it + "st_fah_flg": {"StFahFlg"}, + # The unit of PR 537: Add0.5 + "add_0_5": {"Add0.5"}, + # The cloud gateway of PR 568: Add0.1, with TemRec read as "" + "add_0_1": {"Add0.1"}, + # A unit that answers all of them + "all": {"TemRec", "Add0.5", "Add0.1"}, + # A unit without any + "none": set(), +} + + +async def start_unit( + answers: set[str], values: dict[str, Any] | None = None, **kwargs: Any +) -> FakeGreeDevice: + """Start a fake unit that answers these half degree columns and no other.""" + fake = FakeGreeDevice(unsupported_props=HALF_COLUMNS - answers, **kwargs) + fake.values.update({"SetTem": 21, "TemUn": 0, "Mod": 1}) + fake.values.update(dict.fromkeys(answers, 0)) + fake.values.update(values or {}) + await fake.start() + return fake + + +async def bind(fake: FakeGreeDevice, mac: str | None = None) -> GreeDevice: + """Bind a device to the fake unit, or to a sub-unit behind it.""" + transport = GreeUdpTransport(fake.host, fake.port, max_retries=1, timeout=0.3) + device = GreeDevice(name="Zolderkamer", mac_addr=mac or fake.mac) + await device.bind_with_transport( + local_controller_mac=fake.mac, local_transport=transport + ) + return device + + +@pytest.fixture +async def unit_factory() -> AsyncIterator[Callable[..., Any]]: + """Start fake units and bind devices to them. Everything is closed after.""" + fakes: list[FakeGreeDevice] = [] + devices: list[GreeDevice] = [] + + async def make( + answers: set[str], values: dict[str, Any] | None = None, **kwargs: Any + ) -> tuple[FakeGreeDevice, GreeDevice]: + fake = await start_unit(answers, values, **kwargs) + fakes.append(fake) + device = await bind(fake) + devices.append(device) + return fake, device + + yield make + + for device in devices: + if device.transport is not None: + await device.transport.disconnect() + for fake in fakes: + fake.close() + + +def sent_commands(fake: FakeGreeDevice) -> list[dict[str, int]]: + """Return every command the fake got, as column to value.""" + return [ + dict(zip(pack["opt"], pack["p"], strict=True)) + for pack in fake.packs + if pack.get("t") == "cmd" + ] + + +def half_columns(command: dict[str, int]) -> dict[str, int]: + """Return the half degree columns of one command.""" + return {k: v for k, v in command.items() if k in HALF_COLUMNS} + + +async def set_and_push(device: GreeDevice, value: float) -> None: + """Set a target temperature and send it.""" + device.set_target_temperature(value) + await device.push_device_status() + + +# +# What the unit offers +# + + +@pytest.mark.parametrize( + ("kind", "half", "unit_change"), + [ + ("tem_rec", True, True), + ("st_fah_flg", True, True), + ("add_0_5", True, False), + ("add_0_1", True, False), + ("all", True, True), + ("none", False, False), + ], +) +async def test_what_a_unit_offers( + unit_factory: Callable[..., Any], kind: str, half: bool, unit_change: bool +) -> None: + """Half degrees with any half column, a unit change only with TemUn and a bit.""" + _, device = await unit_factory(UNITS[kind]) + + assert device.supports_half_degrees is half + assert device.supports_temperature_unit_change is unit_change + + +async def test_a_unit_without_a_bit_is_celsius_only( + unit_factory: Callable[..., Any], +) -> None: + """SetTem is always Celsius. Without a bit there is no Fahrenheit table.""" + _, device = await unit_factory(UNITS["add_0_5"], {"TemUn": 1, "SetTem": 22}) + + assert device.target_temperature_unit is TemperatureUnits.C + assert device.target_temperature == 22 + + device.set_target_temperature_unit(TemperatureUnits.F) + assert "TemUn" not in device.gather_diagnostics()["state_pending"] + + +# +# The step +# + + +async def test_the_step_follows_the_option_and_the_unit( + unit_factory: Callable[..., Any], +) -> None: + """0.5 only in Celsius with the option on and a half column.""" + _, device = await unit_factory(UNITS["tem_rec"]) + assert device.target_temperature_step == 1.0 + + device.set_half_degrees(True) + assert device.half_degrees + assert device.target_temperature_step == 0.5 + + device.set_target_temperature_unit(TemperatureUnits.F) + assert device.target_temperature_step == 1.0 + + +async def test_the_option_does_nothing_without_a_half_column( + unit_factory: Callable[..., Any], +) -> None: + """The option is only offered with a column, but an old config can still hold it.""" + fake, device = await unit_factory(UNITS["none"]) + device.set_half_degrees(True) + + assert not device.half_degrees + assert device.target_temperature_step == 1.0 + + await set_and_push(device, 22.5) + assert sent_commands(fake)[-1]["SetTem"] == 23 + assert not half_columns(sent_commands(fake)[-1]) + + +# +# What goes over the wire +# + + +@pytest.mark.parametrize( + ("kind", "half_sent"), + [ + ("tem_rec", {"TemRec": 1}), + ("st_fah_flg", {"StFahFlg": 1}), + ("add_0_5", {"Add0.5": 1}), + ("add_0_1", {"Add0.1": 5}), + ("all", {"TemRec": 1, "Add0.5": 1, "Add0.1": 5}), + ], +) +async def test_a_half_degree_goes_out_on_every_answered_column( + unit_factory: Callable[..., Any], kind: str, half_sent: dict[str, int] +) -> None: + """22.5 is SetTem 22 with the half on each column, and 23 clears them all.""" + fake, device = await unit_factory(UNITS[kind]) + device.set_half_degrees(True) + + await set_and_push(device, 22.5) + command = sent_commands(fake)[-1] + assert command["SetTem"] == 22 + assert half_columns(command) == half_sent + assert device.target_temperature == 22.5 + + await set_and_push(device, 23) + command = sent_commands(fake)[-1] + assert command["SetTem"] == 23 + assert half_columns(command) == dict.fromkeys(half_sent, 0) + assert device.target_temperature == 23 + + +@pytest.mark.parametrize(("value", "set_tem"), [(22.5, 23), (23.5, 24), (22.4, 22)]) +async def test_with_the_option_off_a_half_degree_rounds_up( + unit_factory: Callable[..., Any], value: float, set_tem: int +) -> None: + """Whole degrees only, and a half goes up, not to the even number.""" + fake, device = await unit_factory(UNITS["all"]) + + await set_and_push(device, value) + + command = sent_commands(fake)[-1] + assert command["SetTem"] == set_tem + assert half_columns(command) == {"TemRec": 0, "Add0.5": 0, "Add0.1": 0} + + +async def test_with_the_option_off_a_half_set_by_a_remote_still_shows( + unit_factory: Callable[..., Any], +) -> None: + """The option sets what Home Assistant sends, not what it reads.""" + _, device = await unit_factory(UNITS["add_0_5"], {"SetTem": 24, "Add0.5": 1}) + + assert device.target_temperature == 24.5 + + +async def test_fahrenheit_uses_the_bit_and_clears_the_celsius_columns( + unit_factory: Callable[..., Any], +) -> None: + """70 F is SetTem 21 with the bit 1. Add0.5 and Add0.1 have no Fahrenheit meaning.""" + fake, device = await unit_factory(UNITS["all"], {"TemUn": 1}) + device.set_half_degrees(True) + + await set_and_push(device, 70) + + command = sent_commands(fake)[-1] + assert (command["SetTem"], command["TemRec"]) == (21, 1) + assert (command["Add0.5"], command["Add0.1"]) == (0, 0) + assert device.target_temperature == 70 + + +# +# Reading back +# + + +@pytest.mark.parametrize( + "half", + [{"TemRec": 1}, {"Add0.5": 1}, {"Add0.1": 5}], +) +async def test_any_set_column_reads_as_a_half_degree( + unit_factory: Callable[..., Any], half: dict[str, int] +) -> None: + """A column the unit ignores reads 0, so any column that is set wins.""" + _, device = await unit_factory(UNITS["all"], {"SetTem": 25, **half}) + + assert device.target_temperature == 25.5 + + +async def test_a_column_answered_as_empty_is_dropped( + unit_factory: Callable[..., Any], +) -> None: + """The gateway of PR 568 answers TemRec with "". That column is not used.""" + fake, device = await unit_factory({"TemRec", "Add0.1"}, {"TemRec": ""}) + device.set_half_degrees(True) + + assert not device.has_target_temperature_bit + await set_and_push(device, 27.5) + assert half_columns(sent_commands(fake)[-1]) == {"Add0.1": 5} + + +# +# A unit that answers a column and ignores it +# + + +def command_count(fake: FakeGreeDevice) -> int: + """Return how many commands the fake got.""" + return len(sent_commands(fake)) + + +async def poll(device: GreeDevice, times: int) -> None: + """Poll the unit a few times, as the coordinator does.""" + for _ in range(times): + await device.fetch_device_status() + + +async def test_an_ignored_column_is_not_sent_again_by_itself( + unit_factory: Callable[..., Any], +) -> None: + """The unit takes TemRec and ignores Add0.5. Nothing resends Add0.5.""" + fake, device = await unit_factory({"TemRec", "Add0.5"}, read_only_props={"Add0.5"}) + device.set_half_degrees(True) + + await set_and_push(device, 22.5) + assert fake.values["TemRec"] == 1 + assert fake.values["Add0.5"] == 0 + assert device.target_temperature == 22.5 + + await poll(device, 3) + assert command_count(fake) == 1 + assert not device.has_held_values + assert device.target_temperature == 22.5 + + +async def test_an_ignored_column_on_a_sub_unit_ends_with_the_hold( + unit_factory: Callable[..., Any], +) -> None: + """A sub-unit holds what it sent. The hold of the ignored column ends at the TTL. + + After that the device shows what the unit reports, sends nothing by itself, + and has nothing pending. + """ + now = [1000.0] + fake, device = await unit_factory({"TemRec", "Add0.5"}, read_only_props={"Add0.5"}) + # Bind a sub-unit behind the same fake, with a clock the test moves + sub = await bind(fake, f"{fake.mac}01") + # The hold uses the clock of the state. No public way to set it here. + sub._state._clock = lambda: now[0] # noqa: SLF001 + sub.set_half_degrees(True) + + try: + await set_and_push(sub, 22.5) + count = command_count(fake) + assert sub.has_held_values + + await poll(sub, 2) + assert sub.has_held_values + + now[0] += HELD_VALUE_TTL + 1 + await poll(sub, 2) + + assert not sub.has_held_values + assert sub.gather_diagnostics()["state_pending"] == {} + assert command_count(fake) == count + assert sub.target_temperature == 22.5 + finally: + if sub.transport is not None: + await sub.transport.disconnect() + assert device.is_bound + + +async def test_a_unit_that_only_answers_an_ignored_column_shows_the_truth( + unit_factory: Callable[..., Any], +) -> None: + """Add0.5 answered but ignored: 22.5 lands on 22, and that is what shows.""" + fake, device = await unit_factory({"Add0.5"}, read_only_props={"Add0.5"}) + device.set_half_degrees(True) + + await set_and_push(device, 22.5) + await poll(device, 2) + + assert device.target_temperature == 22 + assert command_count(fake) == 1 diff --git a/tests/test_zone_controller.py b/tests/test_zone_controller.py index ecd8e7f3..e66e872b 100644 --- a/tests/test_zone_controller.py +++ b/tests/test_zone_controller.py @@ -302,6 +302,7 @@ async def test_a_zone_takes_half_degrees_in_celsius( ) -> None: """The bit is the half degree, like TemRec. Seen on the real controller: 2 and 1 stay 18.5.""" values = controller.units[controller.zone_macs[0]] + zone.set_half_degrees(True) zone.set_target_temperature(18.5) await zone.push_device_status() @@ -314,6 +315,31 @@ async def test_a_zone_takes_half_degrees_in_celsius( assert (values["StTem"], values["StFahFlg"]) == (5, 0) +async def test_a_zone_uses_half_degrees_until_the_user_says_no( + controller: FakeZoneController, zone: GreeDevice +) -> None: + """An entry without the option, as after the upgrade, keeps the 0.5 step.""" + values = controller.units[controller.zone_macs[0]] + zone.set_half_degrees(None) + + assert zone.default_half_degrees + assert zone.target_temperature_step == 0.5 + zone.set_target_temperature(19.5) + await zone.push_device_status() + assert (values["StTem"], values["StFahFlg"]) == (3, 1) + + zone.set_half_degrees(False) + assert zone.target_temperature_step == 1 + + +async def test_the_ac_unit_of_a_zone_controller_has_no_half_degree_default( + ac_unit: GreeDevice, +) -> None: + """Only zones default to half degrees, and the ducted unit offers none.""" + assert not ac_unit.default_half_degrees + assert not ac_unit.half_degrees + + # # Fahrenheit. The values are the ones the wall panel showed. #