diff --git a/ariston/ariston_api.py b/ariston/ariston_api.py index 0420cef..09ba46f 100644 --- a/ariston/ariston_api.py +++ b/ariston/ariston_api.py @@ -837,11 +837,14 @@ async def async_get_properties( properties = await self._async_request_properties( path, items, features, culture, False ) - except ConnectionException as error: - if error.args[:1] != (500,) or not items: + except (ConnectionException, asyncio.TimeoutError) as error: + if ( + isinstance(error, ConnectionException) + and error.args[:1] != (500,) + ) or not items: raise _LOGGER.warning( - "GALEVO properties batch returned HTTP 500; retrying in pairs" + "GALEVO properties batch failed with HTTP 500 or timed out; retrying in pairs" ) properties = await self._async_recover_properties( path, items, features, culture, error @@ -867,6 +870,7 @@ async def _async_request_properties( "features": features, "culture": culture, }, + timeout_seconds=90, ) async def _async_cached_property( @@ -876,9 +880,9 @@ async def _async_cached_property( features: dict[str, Any], culture: str, ) -> Any: - """Retry a property with the provider cache after HTTP 500.""" + """Retry a property with the provider cache after a server error or timeout.""" _LOGGER.warning( - "GALEVO property %s returned HTTP 500; trying cached value", + "GALEVO property %s failed or timed out; trying cached value", item["id"], ) try: @@ -900,13 +904,13 @@ async def _async_recover_property( features: dict[str, Any], culture: str, ) -> Any: - """Retry one property fresh, then cached on HTTP 500.""" + """Retry one property fresh, then cached on server error or timeout.""" try: return await self._async_request_properties( path, [item], features, culture, False ) - except ConnectionException as error: - if error.args[:1] != (500,): + except (ConnectionException, asyncio.TimeoutError) as error: + if isinstance(error, ConnectionException) and error.args[:1] != (500,): raise return await self._async_cached_property(path, item, features, culture) @@ -917,13 +921,13 @@ async def _async_recover_property_chunk( features: dict[str, Any], culture: str, ) -> list[dict[str, Any]]: - """Retry a pair, splitting only when the pair returns HTTP 500.""" + """Retry a pair, splitting on server error or timeout.""" try: response = await self._async_request_properties( path, chunk, features, culture, False ) - except ConnectionException as error: - if error.args[:1] != (500,): + except (ConnectionException, asyncio.TimeoutError) as error: + if isinstance(error, ConnectionException) and error.args[:1] != (500,): raise if len(chunk) == 1: response = await self._async_cached_property( @@ -946,7 +950,7 @@ async def _async_recover_properties( items: list[dict[str, Any]], features: dict[str, Any], culture: str, - initial_error: ConnectionException, + initial_error: ConnectionException | asyncio.TimeoutError, ) -> dict[str, Any]: """Collect pair retries, preserving the original error if none succeed.""" properties = {"features": features, "items": []} @@ -1456,6 +1460,7 @@ async def __async_request( params: Optional[dict[str, Any]] = None, body: Any = None, is_retry: bool = False, + timeout_seconds: int = 30, ) -> Optional[dict[str, Any]]: """Async request with aiohttp""" if not is_retry and time.time() < self._blocked_until: @@ -1475,10 +1480,8 @@ async def __async_request( params, ) - # Apply an explicit total timeout so a stalled request fails fast - # instead of relying on aiohttp's 5 minute default. This mirrors the - # 30 second timeout used by the synchronous `requests` path. - timeout = aiohttp.ClientTimeout(total=30) + # GALEVO property batches can take longer than other API requests. + timeout = aiohttp.ClientTimeout(total=timeout_seconds) async with aiohttp.ClientSession(timeout=timeout) as session: response = await session.request( method, path, params=params, json=body, headers=headers @@ -1490,7 +1493,7 @@ async def __async_request( if not is_retry: if await self.async_connect(): return await self.__async_request( - method, path, params, body, True + method, path, params, body, True, timeout_seconds ) raise ConnectionException( "Login failed (password changed?)" @@ -1500,13 +1503,13 @@ async def __async_request( return None case 429: return await self.__async_handle_rate_limit( - response, is_retry, method, path, params, body + response, is_retry, method, path, params, body, timeout_seconds ) case _: if not is_retry: await asyncio.sleep(5) return await self.__async_request( - method, path, params, body, True + method, path, params, body, True, timeout_seconds ) raise ConnectionException(response.status) @@ -1517,9 +1520,13 @@ async def __async_request( return None - async def _async_post(self, path: str, body: Any) -> Any: + async def _async_post( + self, path: str, body: Any, timeout_seconds: int = 30 + ) -> Any: """Async POST request""" - return await self.__async_request("POST", path, None, body) + return await self.__async_request( + "POST", path, None, body, timeout_seconds=timeout_seconds + ) async def __async_handle_rate_limit( self, @@ -1529,6 +1536,7 @@ async def __async_handle_rate_limit( path: str, params: Optional[dict[str, Any]], body: Any, + timeout_seconds: int, ) -> Optional[dict[str, Any]]: """Sleep out the 429 block window, retry once, share the deadline.""" content = await response.content.read() @@ -1536,7 +1544,9 @@ async def __async_handle_rate_limit( self._blocked_until = time.time() + wait_seconds if not is_retry: await asyncio.sleep(wait_seconds) - return await self.__async_request(method, path, params, body, True) + return await self.__async_request( + method, path, params, body, True, timeout_seconds + ) raise ConnectionException(response.status, content) async def _async_get( diff --git a/ariston/galevo_device.py b/ariston/galevo_device.py index 00d7c19..2717027 100644 --- a/ariston/galevo_device.py +++ b/ariston/galevo_device.py @@ -17,7 +17,6 @@ CustomDeviceFeatures, DeviceFeatures, DeviceProperties, - GalevoDeviceAttribute, GasEnergyUnit, GasType, HOLIDAY_DATE_FORMAT, @@ -125,7 +124,7 @@ def update_state(self) -> None: self.menu_items = self.api.get_menu_items( self.gw, include_hybrid_items=( - self.attributes.get(GalevoDeviceAttribute.HYBRID_SYS) is True + self.features.get(DeviceFeatures.HYBRID_SYS) is True ), ) except ConnectionException as error: @@ -147,7 +146,7 @@ async def async_update_state(self) -> None: ), self._async_get_menu_items( include_hybrid_items=( - self.attributes.get(GalevoDeviceAttribute.HYBRID_SYS) is True + self.features.get(DeviceFeatures.HYBRID_SYS) is True ) ), ) diff --git a/pyproject.toml b/pyproject.toml index 48e2be6..9895ea9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,7 +14,7 @@ dependencies = [ ] requires-python = ">=3.11" license = { file = "LICENSE" } -version = "0.19.14" +version = "0.19.15" dynamic = ['description'] [project.urls] diff --git a/tests/test_ariston_api.py b/tests/test_ariston_api.py index 63fa268..948fef6 100644 --- a/tests/test_ariston_api.py +++ b/tests/test_ariston_api.py @@ -439,47 +439,66 @@ async def exercise(): ["124,119", "123,125,115", "123", "125", "115", "349,348", "127"], ) - 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], - } + def test_async_properties_recovers_from_batch_errors_with_small_requests(self): + scenarios = ( + ( + "HTTP 500", + ConnectionException(500), + [{"id": name, "zn": 0} for name in ("A", "B", "PlantMode")], + [ + (["A", "B", "PlantMode"], False), + (["A", "B"], False), + (["PlantMode"], False), + (["PlantMode"], True), + ], + ), + ( + "timeout", + asyncio.TimeoutError(), + [{"id": name, "zn": 0} for name in ("A", "B", "C")], + [ + (["A", "B", "C"], False), + (["A", "B"], False), + (["C"], False), + ], + ), + ) - 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") + for scenario, failure, items, expected_requests in scenarios: + with self.subTest(scenario=scenario): + api = AristonAPI("user", "password", api_url="https://example.test/api/") + features = {DeviceFeatures.ZONES: [{ZoneAttribute.NUM: 1}]} + requests = [] + + async def post(path, body, **kwargs): + requested = [item["id"] for item in body["items"]] + requests.append((requested, body["useCache"])) + if len(requested) > 2 or ( + isinstance(failure, ConnectionException) + and requested == ["PlantMode"] + and not body["useCache"] + ): + raise failure + 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), - ], - ) + result = asyncio.run(exercise()) + self.assertEqual( + [item["id"] for item in result["items"]], + [item["id"] for item in items], + ) + self.assertEqual(result["features"], features) + self.assertEqual(requests, expected_requests) def test_async_properties_splits_failing_pair_before_using_cache(self): api = AristonAPI("user", "password") @@ -487,7 +506,7 @@ def test_async_properties_splits_failing_pair_before_using_cache(self): items = [{"id": name, "zn": 0} for name in ("A", "B", "C", "D")] requests = [] - async def post(path, body): + async def post(path, body, **kwargs): requested = [item["id"] for item in body["items"]] requests.append((requested, body["useCache"])) if len(requested) > 2 or requested == ["A", "B"]: diff --git a/tests/test_galevo_device.py b/tests/test_galevo_device.py index 209d5bb..f3ba04b 100644 --- a/tests/test_galevo_device.py +++ b/tests/test_galevo_device.py @@ -92,7 +92,11 @@ def test_hybrid_menu_values_supply_flow_temperature_and_feature_flags(self): def test_async_update_requests_hybrid_menu_items_only_for_hybrid_devices(self): device = self.make_device() - device.attributes[GalevoDeviceAttribute.HYBRID_SYS] = True + device.attributes["hybrSys"] = True + device.features = {} + device.api.async_get_features_for_device = AsyncMock( + return_value={DeviceFeatures.HYBRID_SYS: True} + ) device.api.async_get_properties = AsyncMock(return_value=self.make_data()) device.api.async_get_menu_items = AsyncMock(return_value=device.menu_items) @@ -102,6 +106,30 @@ def test_async_update_requests_hybrid_menu_items_only_for_hybrid_devices(self): "gw-1", include_hybrid_items=True ) + device.features[DeviceFeatures.HYBRID_SYS] = False + device.attributes[GalevoDeviceAttribute.HYBRID_SYS] = True + device.api.async_get_menu_items.reset_mock() + asyncio.run(device.async_update_state()) + device.api.async_get_menu_items.assert_awaited_once_with( + "gw-1", include_hybrid_items=False + ) + + def test_sync_update_requests_hybrid_menu_items_from_features(self): + device = self.make_device() + device.attributes["hybrSys"] = True + device.features = {} + device.api.get_features_for_device.return_value = { + DeviceFeatures.HYBRID_SYS: True + } + device.api.get_properties.return_value = self.make_data() + device.api.get_menu_items.return_value = device.menu_items + + device.update_state() + + device.api.get_menu_items.assert_called_once_with( + "gw-1", include_hybrid_items=True + ) + 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") @@ -431,26 +459,13 @@ 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"] - ] - } - + def _assert_async_refresh_data(self, device, api, requested_items, transport_patch): 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=[])): + with ( + patch.object(api, "get_items", return_value=requested_items), + transport_patch, + patch.object(api, "async_get_menu_items", new=AsyncMock(return_value=[])), + ): await device.async_update_state() asyncio.run(refresh()) @@ -459,6 +474,71 @@ async def refresh(): [item["id"] for item in requested_items], ) + def test_async_update_state_recovers_from_property_batch_failures(self): + for failure in (ConnectionException(500), asyncio.TimeoutError()): + with self.subTest(failure=type(failure).__name__): + device = self.make_device() + api = AristonAPI("user", "password") + device.api = api + requested_items = DeviceProperties.list(0)[:3] + + async def post(path, body, **kwargs): + if len(body["items"]) > 2: + raise failure + return { + "items": [ + {"id": item["id"], "zn": item["zn"], "value": 1} + for item in body["items"] + ] + } + + self._assert_async_refresh_data( + device, + api, + requested_items, + patch.object(api, "_async_post", new=AsyncMock(side_effect=post)), + ) + + def test_async_update_state_accepts_slow_properties_response(self): + device = self.make_device() + api = AristonAPI("user", "password") + device.api = api + requested_items = DeviceProperties.list(0)[:3] + + class SlowResponse: + ok = True + content_length = 1 + + async def json(self): + return { + "items": [ + {"id": item["id"], "zn": item["zn"], "value": 1} + for item in requested_items + ] + } + + class SlowSession: + def __init__(self, timeout): + self.timeout = timeout + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc_value, traceback): + pass + + async def request(self, *args, **kwargs): + if self.timeout.total < 37.8: + raise asyncio.TimeoutError + return SlowResponse() + + self._assert_async_refresh_data( + device, + api, + requested_items, + patch("ariston.ariston_api.aiohttp.ClientSession", SlowSession), + ) + def test_menu_http_failure_on_first_refresh_and_recovery(self): device = self.make_device() device.menu_items = []