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
94 changes: 82 additions & 12 deletions ariston/ariston_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,14 +248,49 @@
return settings
return {}

def get_menu_items(self, gw_id: str) -> list[dict[str, Any]]:
"""Get menu items"""
def get_menu_items(

Check failure on line 251 in ariston/ariston_api.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 27 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=fustom_python-ariston-api&issues=AaHctJ1KH6_68wC1NTC0&open=AaHctJ1KH6_68wC1NTC0&pullRequest=194
self, gw_id: str, include_hybrid_items: bool = False
) -> list[dict[str, Any]]:
"""Get core menu items and, when requested, optional hybrid values."""
items = self._get(
f"{self.__api_url}{ARISTON_MENU_ITEMS}/{gw_id}?menuItems={MenuItemNames.values()}"
f"{self.__api_url}{ARISTON_MENU_ITEMS}/{gw_id}"
f"?menuItems={MenuItemNames.core_values()}"
)
if items is not None:
return items
return []
if items is None or not include_hybrid_items:
return items or []

for group in MenuItemNames.hybrid_groups():
group_ids = ",".join(str(item.value) for item in group)
path = (
f"{self.__api_url}{ARISTON_MENU_ITEMS}/{gw_id}"
f"?menuItems={group_ids}"
)
try:
additional_items = self._get(path)
except ConnectionException as error:
if error.args[:1] != (500,):
raise
additional_items = []
for menu_item in group:
item_path = (
f"{self.__api_url}{ARISTON_MENU_ITEMS}/{gw_id}"
f"?menuItems={menu_item.value}"
)
try:
item_response = self._get(item_path)
except ConnectionException as item_error:
if item_error.args[:1] != (500,):
raise
_LOGGER.debug(
"Skipping unsupported GALEVO menu item %s",
menu_item.value,
)
continue
if item_response:
additional_items.extend(item_response)
if additional_items:
items.extend(additional_items)
return items

def set_property(
self,
Expand Down Expand Up @@ -957,14 +992,49 @@
return med_plant_settings
return {}

async def async_get_menu_items(self, gw_id: str) -> list[dict[str, Any]]:
"""Async get menu items"""
async def async_get_menu_items(

Check failure on line 995 in ariston/ariston_api.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 27 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=fustom_python-ariston-api&issues=AaHctJ1KH6_68wC1NTC1&open=AaHctJ1KH6_68wC1NTC1&pullRequest=194
self, gw_id: str, include_hybrid_items: bool = False
) -> list[dict[str, Any]]:
"""Async get core menu items and optional hybrid values."""
items = await self._async_get(
f"{self.__api_url}{ARISTON_MENU_ITEMS}/{gw_id}?menuItems={MenuItemNames.values()}"
f"{self.__api_url}{ARISTON_MENU_ITEMS}/{gw_id}"
f"?menuItems={MenuItemNames.core_values()}"
)
if items is not None:
return items
return []
if items is None or not include_hybrid_items:
return items or []

for group in MenuItemNames.hybrid_groups():
group_ids = ",".join(str(item.value) for item in group)
path = (
f"{self.__api_url}{ARISTON_MENU_ITEMS}/{gw_id}"
f"?menuItems={group_ids}"
)
try:
additional_items = await self._async_get(path)
except ConnectionException as error:
if error.args[:1] != (500,):
raise
additional_items = []
for menu_item in group:
item_path = (
f"{self.__api_url}{ARISTON_MENU_ITEMS}/{gw_id}"
f"?menuItems={menu_item.value}"
)
try:
item_response = await self._async_get(item_path)
except ConnectionException as item_error:
if item_error.args[:1] != (500,):
raise
_LOGGER.debug(
"Skipping unsupported GALEVO menu item %s",
menu_item.value,
)
continue
if item_response:
additional_items.extend(item_response)
if additional_items:
items.extend(additional_items)
return items

async def async_set_property(
self,
Expand Down
22 changes: 22 additions & 0 deletions ariston/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -670,8 +670,30 @@ class MenuItemNames(IntEnum):

CH_RETURN_TEMP = 124
SIGNAL_STRENGTH = 119
CH_FLOW_TEMP_BOILER = 123
GAS_POWER = 125
DHW_FLOW_RATE = 127
PUMP_MODULATION = 115
HP_WATER_FLOW_TEMP = 348
CH_FLOW_TEMP_SYSTEM = 349

@classmethod
def values(cls) -> str:
"""Return all menu items values"""
return ",".join(str(c.value) for c in cls)

@classmethod
def core_values(cls) -> str:
"""Return the established menu items that work on all GALEVO devices."""
return ",".join(
str(item.value) for item in (cls.CH_RETURN_TEMP, cls.SIGNAL_STRENGTH)
)

@classmethod
def hybrid_groups(cls) -> tuple[tuple["MenuItemNames", ...], ...]:
"""Return small groups of optional menu items for hybrid systems."""
return (
(cls.CH_FLOW_TEMP_BOILER, cls.GAS_POWER, cls.PUMP_MODULATION),
(cls.CH_FLOW_TEMP_SYSTEM, cls.HP_WATER_FLOW_TEMP),
(cls.DHW_FLOW_RATE,),
)
65 changes: 59 additions & 6 deletions ariston/galevo_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
CustomDeviceFeatures,
DeviceFeatures,
DeviceProperties,
GalevoDeviceAttribute,
GasEnergyUnit,
GasType,
HOLIDAY_DATE_FORMAT,
Expand All @@ -30,6 +31,7 @@
from .device import AristonDevice

_LOGGER = logging.getLogger(__name__)
_MENU_ITEM_UNAVAILABLE_VALUE = 3276


class AristonGalevoDevice(AristonDevice):
Expand Down Expand Up @@ -86,6 +88,16 @@ def _update_state(self) -> None:
self.custom_features[DeviceProperties.CH_FLOW_TEMP] = (
self.ch_flow_temp_value is not None
)
for menu_item in (
MenuItemNames.CH_FLOW_TEMP_BOILER,
MenuItemNames.GAS_POWER,
MenuItemNames.DHW_FLOW_RATE,
MenuItemNames.PUMP_MODULATION,
MenuItemNames.HP_WATER_FLOW_TEMP,
):
self.custom_features[str(menu_item.value)] = (
self.get_menu_item_value(menu_item.value) is not None
)
for item_id in (
DeviceProperties.DHW_TIMEPROG_COMFORT_TEMP,
DeviceProperties.DHW_TIMEPROG_ECONOMY_TEMP,
Expand All @@ -110,7 +122,12 @@ def update_state(self) -> None:
self.umsys,
)
try:
self.menu_items = self.api.get_menu_items(self.gw)
self.menu_items = self.api.get_menu_items(
self.gw,
include_hybrid_items=(
self.attributes.get(GalevoDeviceAttribute.HYBRID_SYS) is True
),
)
except ConnectionException as error:
if not self._should_retain_menu_items_after_error(error):
raise
Expand All @@ -128,14 +145,22 @@ async def async_update_state(self) -> None:
self.language_tag,
self.umsys,
),
self._async_get_menu_items(),
self._async_get_menu_items(
include_hybrid_items=(
self.attributes.get(GalevoDeviceAttribute.HYBRID_SYS) is True
)
),
)
self._update_state()

async def _async_get_menu_items(self) -> list[dict[str, Any]]:
async def _async_get_menu_items(
self, include_hybrid_items: bool = False
) -> list[dict[str, Any]]:
"""Get menu items while retaining the last values for server errors."""
try:
return await self.api.async_get_menu_items(self.gw)
return await self.api.async_get_menu_items(
self.gw, include_hybrid_items=include_hybrid_items
)
except ConnectionException as error:
if not self._should_retain_menu_items_after_error(error):
raise
Expand Down Expand Up @@ -440,7 +465,12 @@ def ch_flow_setpoint_temp_value(self) -> str:
@property
def ch_flow_temp_value(self) -> Optional[str]:
"""Get central heating flow temperature value"""
return self._get_item_by_id(DeviceProperties.CH_FLOW_TEMP, PropertyType.VALUE)
value = self._get_item_by_id(
DeviceProperties.CH_FLOW_TEMP, PropertyType.VALUE
)
if value is not None:
return value
return self.get_menu_item_value(MenuItemNames.CH_FLOW_TEMP_SYSTEM.value)

@property
def outside_temp_value(self) -> str:
Expand All @@ -462,7 +492,14 @@ def ch_flow_setpoint_temp_unit(self) -> str:
@property
def ch_flow_temp_unit(self) -> str:
"""Get central heating flow temperature unit"""
return self._get_item_by_id(DeviceProperties.CH_FLOW_TEMP, PropertyType.UNIT)
unit = self._get_item_by_id(
DeviceProperties.CH_FLOW_TEMP, PropertyType.UNIT
)
if unit is not None:
return unit
return self._get_menu_item_by_id(
MenuItemNames.CH_FLOW_TEMP_SYSTEM.value, PropertyType.UNIT
)

@property
def is_flame_on_value(self) -> bool:
Expand Down Expand Up @@ -559,6 +596,22 @@ def ch_return_temp_unit(self) -> Any:
MenuItemNames.CH_RETURN_TEMP.value, PropertyType.UNIT
)

def get_menu_item_value(self, menu_item_id: int) -> Any:
"""Return a value, treating the gateway's unavailable marker as empty."""
value = self._get_menu_item_by_id(menu_item_id, PropertyType.VALUE)
if value is None:
return None
try:
if float(value) == _MENU_ITEM_UNAVAILABLE_VALUE:
return None
except (TypeError, ValueError):
pass
return value

def get_menu_item_unit(self, menu_item_id: int) -> Any:
"""Return a menu item's reported unit."""
return self._get_menu_item_by_id(menu_item_id, PropertyType.UNIT)

def get_measured_temp_unit(self, zone: int) -> str:
"""Get zone measured temp unit"""
return self._get_item_by_id(
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.13"
version = "0.19.14"
dynamic = ['description']

[project.urls]
Expand Down
53 changes: 53 additions & 0 deletions tests/test_ariston_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,59 @@ async def run_all():

asyncio.run(run_all())

def test_sync_menu_items_fetch_optional_hybrid_groups_and_split_failures(self):
api = AristonAPI("user", "password", api_url="https://example.test/api/")
requests = []

def get(path):
requested = path.split("menuItems=", 1)[1]
requests.append(requested)
if requested == "123,125,115":
raise ConnectionException(500)
if requested == "125":
raise ConnectionException(500)
return [{"id": int(item_id)} for item_id in requested.split(",")]

with patch.object(api, "_get", side_effect=get):
items = api.get_menu_items("gw-1", include_hybrid_items=True)

self.assertEqual(
[item["id"] for item in items], [124, 119, 123, 115, 349, 348, 127]
)
self.assertEqual(
requests,
["124,119", "123,125,115", "123", "125", "115", "349,348", "127"],
)

def test_async_menu_items_fetch_optional_hybrid_groups_and_split_failures(self):
api = AristonAPI("user", "password", api_url="https://example.test/api/")
requests = []

async def get(path):
requested = path.split("menuItems=", 1)[1]
requests.append(requested)
if requested == "123,125,115":
raise ConnectionException(500)
if requested == "125":
raise ConnectionException(500)
return [{"id": int(item_id)} for item_id in requested.split(",")]

async def exercise():
with patch.object(api, "_async_get", new=AsyncMock(side_effect=get)):
return await api.async_get_menu_items(
"gw-1", include_hybrid_items=True
)

items = asyncio.run(exercise())

self.assertEqual(
[item["id"] for item in items], [124, 119, 123, 115, 349, 348, 127]
)
self.assertEqual(
requests,
["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}]}
Expand Down
Loading
Loading