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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 124 additions & 7 deletions ariston/ariston_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
48 changes: 48 additions & 0 deletions ariston/galevo_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import asyncio

import logging
import math
from datetime import date
from typing import Any, Optional

Expand Down Expand Up @@ -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
)
Expand Down Expand Up @@ -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"""
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ dependencies = [
]
requires-python = ">=3.11"
license = { file = "LICENSE" }
version = "0.19.12"
version = "0.19.13"
dynamic = ['description']

[project.urls]
Expand Down
103 changes: 103 additions & 0 deletions tests/test_ariston_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = (
Expand Down
Loading
Loading