diff --git a/ariston/ariston_api.py b/ariston/ariston_api.py index d9160fd..75f7149 100644 --- a/ariston/ariston_api.py +++ b/ariston/ariston_api.py @@ -796,18 +796,135 @@ async def async_get_properties( self, gw_id: str, features: dict[str, Any], culture: str, umsys: str ) -> dict[str, Any]: """Async get device properties""" - properties = await self._async_post( - f"{self.__api_url}{ARISTON_REMOTE}/{ARISTON_DATA_ITEMS}/{gw_id}/get?umsys={umsys}", + path = f"{self.__api_url}{ARISTON_REMOTE}/{ARISTON_DATA_ITEMS}/{gw_id}/get?umsys={umsys}" + items = self.get_items(features) + try: + properties = await self._async_request_properties( + path, items, features, culture, False + ) + except ConnectionException as error: + if error.args[:1] != (500,) or not items: + raise + _LOGGER.warning( + "GALEVO properties batch returned HTTP 500; retrying in pairs" + ) + properties = await self._async_recover_properties( + path, items, features, culture, error + ) + if properties is not None: + return properties + return {} + + async def _async_request_properties( + self, + path: str, + items: list[dict[str, Any]], + features: dict[str, Any], + culture: str, + use_cache: bool, + ) -> Any: + """Request a group of GALEVO properties.""" + return await self._async_post( + path, { - "useCache": False, - "items": self.get_items(features), + "useCache": use_cache, + "items": items, "features": features, "culture": culture, }, ) - if properties is not None: - return properties - return {} + + async def _async_cached_property( + self, + path: str, + item: dict[str, Any], + features: dict[str, Any], + culture: str, + ) -> Any: + """Retry a property with the provider cache after HTTP 500.""" + _LOGGER.warning( + "GALEVO property %s returned HTTP 500; trying cached value", + item["id"], + ) + try: + return await self._async_request_properties( + path, [item], features, culture, True + ) + except ConnectionException as error: + _LOGGER.warning( + "GALEVO property %s also failed with cache (HTTP %s)", + item["id"], + error.args[0] if error.args else "unknown", + ) + raise + + async def _async_recover_property( + self, + path: str, + item: dict[str, Any], + features: dict[str, Any], + culture: str, + ) -> Any: + """Retry one property fresh, then cached on HTTP 500.""" + try: + return await self._async_request_properties( + path, [item], features, culture, False + ) + except ConnectionException as error: + if error.args[:1] != (500,): + raise + return await self._async_cached_property(path, item, features, culture) + + async def _async_recover_property_chunk( + self, + path: str, + chunk: list[dict[str, Any]], + features: dict[str, Any], + culture: str, + ) -> list[dict[str, Any]]: + """Retry a pair, splitting only when the pair returns HTTP 500.""" + try: + response = await self._async_request_properties( + path, chunk, features, culture, False + ) + except ConnectionException as error: + if error.args[:1] != (500,): + raise + if len(chunk) == 1: + response = await self._async_cached_property( + path, chunk[0], features, culture + ) + return response.get("items", []) if response else [] + recovered = [] + for item in chunk: + response = await self._async_recover_property( + path, item, features, culture + ) + if response: + recovered.extend(response.get("items", [])) + return recovered + return response.get("items", []) if response else [] + + async def _async_recover_properties( + self, + path: str, + items: list[dict[str, Any]], + features: dict[str, Any], + culture: str, + initial_error: ConnectionException, + ) -> dict[str, Any]: + """Collect pair retries, preserving the original error if none succeed.""" + properties = {"features": features, "items": []} + for index in range(0, len(items), 2): + chunk = items[index : index + 2] + properties["items"].extend( + await self._async_recover_property_chunk( + path, chunk, features, culture + ) + ) + if not properties["items"]: + raise initial_error + return properties async def async_get_bsb_plant_data(self, gw_id: str) -> dict[str, Any]: """Get BSB plant data.""" diff --git a/ariston/galevo_device.py b/ariston/galevo_device.py index 7d125a4..a797343 100644 --- a/ariston/galevo_device.py +++ b/ariston/galevo_device.py @@ -4,6 +4,7 @@ import asyncio import logging +import math from datetime import date from typing import Any, Optional @@ -85,6 +86,14 @@ def _update_state(self) -> None: self.custom_features[DeviceProperties.CH_FLOW_TEMP] = ( self.ch_flow_temp_value is not None ) + for item_id in ( + DeviceProperties.DHW_TIMEPROG_COMFORT_TEMP, + DeviceProperties.DHW_TIMEPROG_ECONOMY_TEMP, + ): + self.custom_features[item_id] = ( + self._get_dhw_program_temperature(item_id) is not None + and self._get_item_by_id(item_id, PropertyType.UNIT) in ("°C", "°F") + ) self.custom_features[DeviceProperties.IS_QUIET] = ( self.is_quiet_value is not None ) @@ -201,6 +210,45 @@ def water_heater_target_temperature(self) -> Optional[float]: """Get water heater target temperature""" return self._get_item_by_id(DeviceProperties.DHW_TEMP, PropertyType.VALUE) + def _get_dhw_program_temperature(self, item_id: DeviceProperties) -> Optional[float]: + """Return a valid DHW program temperature, including zero.""" + value = self._get_item_by_id(item_id, PropertyType.VALUE) + if isinstance(value, bool): + return None + try: + temperature = float(value) + except (TypeError, ValueError): + return None + return temperature if math.isfinite(temperature) else None + + @property + def dhw_program_comfort_temp_value(self) -> Optional[float]: + """Get the DHW time program comfort temperature.""" + return self._get_dhw_program_temperature( + DeviceProperties.DHW_TIMEPROG_COMFORT_TEMP + ) + + @property + def dhw_program_comfort_temp_unit(self) -> Optional[str]: + """Get the DHW time program comfort temperature unit.""" + return self._get_item_by_id( + DeviceProperties.DHW_TIMEPROG_COMFORT_TEMP, PropertyType.UNIT + ) + + @property + def dhw_program_economy_temp_value(self) -> Optional[float]: + """Get the DHW time program economy temperature.""" + return self._get_dhw_program_temperature( + DeviceProperties.DHW_TIMEPROG_ECONOMY_TEMP + ) + + @property + def dhw_program_economy_temp_unit(self) -> Optional[str]: + """Get the DHW time program economy temperature unit.""" + return self._get_item_by_id( + DeviceProperties.DHW_TIMEPROG_ECONOMY_TEMP, PropertyType.UNIT + ) + @property def water_heater_temperature_decimals(self) -> int: """Get water heater temperature decimals""" diff --git a/pyproject.toml b/pyproject.toml index fa408b5..0118487 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,7 +14,7 @@ dependencies = [ ] requires-python = ">=3.11" license = { file = "LICENSE" } -version = "0.19.12" +version = "0.19.13" dynamic = ['description'] [project.urls] diff --git a/tests/test_ariston_api.py b/tests/test_ariston_api.py index ca9b8eb..a2aedee 100644 --- a/tests/test_ariston_api.py +++ b/tests/test_ariston_api.py @@ -386,6 +386,109 @@ async def run_all(): asyncio.run(run_all()) + def test_async_properties_recovers_from_batch_500_with_small_requests(self): + api = AristonAPI("user", "password", api_url="https://example.test/api/") + features = {DeviceFeatures.ZONES: [{ZoneAttribute.NUM: 1}]} + items = [{"id": name, "zn": 0} for name in ("A", "B", "PlantMode")] + requests = [] + + async def post(path, body): + requests.append(body) + requested = [item["id"] for item in body["items"]] + if len(requested) > 2 or ( + requested == ["PlantMode"] and not body["useCache"] + ): + raise ConnectionException(500) + return { + "features": features, + "items": [{"id": name} for name in requested], + } + + async def exercise(): + with patch.object(api, "get_items", return_value=items), patch.object( + api, "_async_post", new=AsyncMock(side_effect=post) + ): + return await api.async_get_properties("gw-1", features, "en", "si") + + result = asyncio.run(exercise()) + self.assertEqual( + [item["id"] for item in result["items"]], ["A", "B", "PlantMode"] + ) + self.assertEqual(result["features"], features) + self.assertEqual( + [ + ([item["id"] for item in body["items"]], body["useCache"]) + for body in requests + ], + [ + (["A", "B", "PlantMode"], False), + (["A", "B"], False), + (["PlantMode"], False), + (["PlantMode"], True), + ], + ) + + def test_async_properties_splits_failing_pair_before_using_cache(self): + api = AristonAPI("user", "password") + features = {DeviceFeatures.ZONES: []} + items = [{"id": name, "zn": 0} for name in ("A", "B", "C", "D")] + requests = [] + + async def post(path, body): + requested = [item["id"] for item in body["items"]] + requests.append((requested, body["useCache"])) + if len(requested) > 2 or requested == ["A", "B"]: + raise ConnectionException(500) + if requested == ["B"] and not body["useCache"]: + raise ConnectionException(500) + return {"items": [{"id": name} for name in requested]} + + async def exercise(): + with patch.object(api, "get_items", return_value=items), patch.object( + api, "_async_post", new=AsyncMock(side_effect=post) + ): + return await api.async_get_properties("gw-1", features, "en", "si") + + result = asyncio.run(exercise()) + self.assertEqual( + [item["id"] for item in result["items"]], ["A", "B", "C", "D"] + ) + self.assertEqual( + requests, + [ + (["A", "B", "C", "D"], False), + (["A", "B"], False), + (["A"], False), + (["B"], False), + (["B"], True), + (["C", "D"], False), + ], + ) + + def test_async_properties_does_not_hide_persistent_or_other_errors(self): + api = AristonAPI("user", "password") + features = {DeviceFeatures.ZONES: []} + items = [{"id": name, "zn": 0} for name in ("A", "B", "C", "D")] + + async def exercise(status): + with patch.object(api, "get_items", return_value=items), patch.object( + api, "_async_post", new=AsyncMock(side_effect=ConnectionException(status)) + ) as post: + with self.assertRaises(ConnectionException) as error: + await api.async_get_properties("gw-1", features, "en", "si") + return error.exception, post.await_args_list + + with self.assertLogs("ariston.ariston_api", level="WARNING") as logs: + server_error, server_calls = asyncio.run(exercise(500)) + self.assertEqual(server_error.args, (500,)) + self.assertEqual(len(server_calls), 4) + self.assertTrue(server_calls[-1].args[1]["useCache"]) + self.assertIn("property A also failed with cache", logs.output[-1]) + + auth_error, auth_calls = asyncio.run(exercise(401)) + self.assertEqual(auth_error.args, (401,)) + self.assertEqual(len(auth_calls), 1) + def test_async_write_endpoints_send_values_to_transport(self): api = AristonAPI("user", "password", api_url="https://example.test/api/") writes = ( diff --git a/tests/test_galevo_device.py b/tests/test_galevo_device.py index 3975157..5f92534 100644 --- a/tests/test_galevo_device.py +++ b/tests/test_galevo_device.py @@ -3,9 +3,9 @@ import asyncio import unittest from datetime import date -from unittest.mock import AsyncMock, Mock +from unittest.mock import AsyncMock, Mock, patch -from ariston.ariston_api import ConnectionException +from ariston.ariston_api import AristonAPI, ConnectionException from ariston.const import ( ConsumptionProperties, ConsumptionTimeInterval, @@ -28,6 +28,46 @@ class AristonGalevoDeviceTests(unittest.TestCase): + def test_dhw_program_temperatures_are_typed_and_optional(self): + device = self.make_device() + device._set_item_by_id(DeviceProperties.DHW_TIMEPROG_COMFORT_TEMP, "52.5") + device._set_item_by_id(DeviceProperties.DHW_TIMEPROG_ECONOMY_TEMP, 0) + + self.assertEqual(device.dhw_program_comfort_temp_value, 52.5) + self.assertEqual(device.dhw_program_economy_temp_value, 0.0) + self.assertEqual(device.dhw_program_comfort_temp_unit, "°C") + self.assertEqual(device.dhw_program_economy_temp_unit, "°C") + device._update_state() + self.assertTrue(device.custom_features[DeviceProperties.DHW_TIMEPROG_COMFORT_TEMP]) + self.assertTrue(device.custom_features[DeviceProperties.DHW_TIMEPROG_ECONOMY_TEMP]) + + for item in device.data["items"]: + if item["id"] == DeviceProperties.DHW_TIMEPROG_COMFORT_TEMP: + item[PropertyType.VALUE] = "nan" + elif item["id"] == DeviceProperties.DHW_TIMEPROG_ECONOMY_TEMP: + item[PropertyType.VALUE] = None + device._update_state() + self.assertIsNone(device.dhw_program_comfort_temp_value) + self.assertIsNone(device.dhw_program_economy_temp_value) + self.assertFalse(device.custom_features[DeviceProperties.DHW_TIMEPROG_COMFORT_TEMP]) + self.assertFalse(device.custom_features[DeviceProperties.DHW_TIMEPROG_ECONOMY_TEMP]) + + device._set_item_by_id(DeviceProperties.DHW_TIMEPROG_COMFORT_TEMP, True) + self.assertIsNone(device.dhw_program_comfort_temp_value) + + device.data["items"] = [ + item for item in device.data["items"] + if item["id"] != DeviceProperties.DHW_TIMEPROG_ECONOMY_TEMP + ] + self.assertIsNone(device.dhw_program_economy_temp_value) + device._set_item_by_id(DeviceProperties.DHW_TIMEPROG_COMFORT_TEMP, 45) + next( + item for item in device.data["items"] + if item["id"] == DeviceProperties.DHW_TIMEPROG_COMFORT_TEMP + )[PropertyType.UNIT] = "%" + device._update_state() + self.assertFalse(device.custom_features[DeviceProperties.DHW_TIMEPROG_COMFORT_TEMP]) + def make_device(self, metric=True): api = Mock() device = AristonGalevoDevice( @@ -317,6 +357,34 @@ async def refresh(): self.assertEqual(device.menu_items, previous_menu_items) self.assertEqual(device.signal_strength_value, 4) + def test_async_update_state_survives_properties_batch_500(self): + device = self.make_device() + api = AristonAPI("user", "password") + device.api = api + requested_items = DeviceProperties.list(0)[:3] + + async def post(path, body): + if len(body["items"]) > 2: + raise ConnectionException(500) + return { + "items": [ + {"id": item["id"], "zn": item["zn"], "value": 1} + for item in body["items"] + ] + } + + async def refresh(): + with patch.object(api, "get_items", return_value=requested_items), patch.object( + api, "_async_post", new=AsyncMock(side_effect=post) + ), patch.object(api, "async_get_menu_items", new=AsyncMock(return_value=[])): + await device.async_update_state() + + asyncio.run(refresh()) + self.assertEqual( + [item["id"] for item in device.data["items"]], + [item["id"] for item in requested_items], + ) + def test_menu_http_failure_on_first_refresh_and_recovery(self): device = self.make_device() device.menu_items = []