diff --git a/ariston/ariston_api.py b/ariston/ariston_api.py index 0f43b19..d9160fd 100644 --- a/ariston/ariston_api.py +++ b/ariston/ariston_api.py @@ -3,6 +3,7 @@ from __future__ import annotations import logging +import re import time from typing import Any, Optional @@ -24,6 +25,11 @@ ARISTON_TIME_PROGS, ARISTON_VELIS, ARISTON_MENU_ITEMS, + ARISTON_R2_HOME, + ARISTON_R2_LOGIN_PAGE, + ARISTON_R2_SLP_GET_DATA, + ARISTON_R2_SLP_SET_DATA, + ARISTON_R2_USER_AGENT, BsbOperativeMode, BsbZoneMode, DeviceFeatures, @@ -39,6 +45,29 @@ _LOGGER = logging.getLogger(__name__) +_RATE_LIMIT_RE = re.compile(rb"blocked for (\d+) seconds", re.IGNORECASE) + + +def _parse_block_seconds(content: bytes) -> Optional[int]: + """Extract the block duration in seconds from a 429 response body.""" + match = _RATE_LIMIT_RE.search(content) + if match is None: + return None + return int(match.group(1)) + + +def _rate_limit_wait_seconds(content: bytes) -> int: + """Effective wait for a 429: parsed duration + 1s margin, else 5s.""" + parsed = _parse_block_seconds(content) + if parsed is None: + _LOGGER.warning( + "Rate limited (429) without parsable block duration; " + "falling back to 5s wait" + ) + return 5 + _LOGGER.warning("Rate limited (429) for %s seconds; waiting it out", parsed + 1) + return parsed + 1 + class ConnectionException(Exception): """When can not connect to Ariston cloud""" @@ -60,6 +89,22 @@ def __init__( self.__api_url = api_url self.__token = "" self.__user_agent = user_agent + # Web-app (R2) cookie session; created lazily (aiohttp.CookieJar + # needs a running event loop) and logged in on first use. + self.__r2_cookies: Optional[aiohttp.CookieJar] = None + self.__r2_logged_in = False + # Per-instance 429 block window: instances for different accounts or + # API URLs must not silence each other; the three coordinators for + # one account still share one API instance. + self._blocked_until = 0.0 + # Sync (requests) R2 web-app session; created lazily on first use. + self.__r2_requests_session: Optional[requests.Session] = None + + def _r2_cookies(self) -> aiohttp.CookieJar: + """Lazily create the R2 cookie jar (requires a running loop).""" + if self.__r2_cookies is None: + self.__r2_cookies = aiohttp.CookieJar() + return self.__r2_cookies def connect(self) -> bool: """Login to ariston cloud and get token""" @@ -85,14 +130,14 @@ def get_detailed_devices(self) -> list[Any]: devices = self._get(f"{self.__api_url}{ARISTON_REMOTE}/{ARISTON_PLANTS}") if devices is not None: return list(devices) - return list() + return [] def get_detailed_velis_devices(self) -> list[Any]: """Get detailed cloud devices""" devices = self._get(f"{self.__api_url}{ARISTON_VELIS}/{ARISTON_PLANTS}") if devices is not None: return list(devices) - return list() + return [] def get_devices(self) -> list[Any]: """Get cloud devices""" @@ -101,7 +146,7 @@ def get_devices(self) -> list[Any]: ) if devices is not None: return list(devices) - return list() + return [] def get_features_for_device(self, gw_id: str) -> dict[str, Any]: """Get features for the device""" @@ -110,7 +155,7 @@ def get_features_for_device(self, gw_id: str) -> dict[str, Any]: ) if features is not None: return features - return dict() + return {} def get_energy_account(self, gw_id: str) -> dict[str, Any]: """Get energy account for the device""" @@ -119,7 +164,7 @@ def get_energy_account(self, gw_id: str) -> dict[str, Any]: ) if energy_account is not None: return energy_account - return dict() + return {} def get_consumptions_sequences(self, gw_id: str, usages: str) -> list[Any]: """Get consumption sequences for the device""" @@ -128,7 +173,7 @@ def get_consumptions_sequences(self, gw_id: str, usages: str) -> list[Any]: ) if consumptions_sequences is not None: return list(consumptions_sequences) - return list() + return [] def get_consumptions_settings(self, gw_id: str) -> dict[str, Any]: """Get consumption settings""" @@ -138,7 +183,7 @@ def get_consumptions_settings(self, gw_id: str) -> dict[str, Any]: ) if consumptions_settings is not None: return consumptions_settings - return dict() + return {} def set_consumptions_settings( self, @@ -174,7 +219,7 @@ def get_properties( ) if properties is not None: return properties - return dict() + return {} def get_bsb_plant_data(self, gw_id: str) -> dict[str, Any]: """Get BSB plant data.""" @@ -183,14 +228,14 @@ def get_bsb_plant_data(self, gw_id: str) -> dict[str, Any]: ) if data is not None: return data - return dict() + return {} def get_velis_plant_data(self, plant_data: PlantData, gw_id: str) -> dict[str, Any]: """Get Velis properties""" data = self._get(f"{self.__api_url}{ARISTON_VELIS}/{plant_data.value}/{gw_id}") if data is not None: return data - return dict() + return {} def get_velis_plant_settings( self, plant_data: PlantData, gw_id: str @@ -201,7 +246,7 @@ def get_velis_plant_settings( ) if settings is not None: return settings - return dict() + return {} def get_menu_items(self, gw_id: str) -> list[dict[str, Any]]: """Get menu items""" @@ -210,7 +255,7 @@ def get_menu_items(self, gw_id: str) -> list[dict[str, Any]]: ) if items is not None: return items - return list() + return [] def set_property( self, @@ -437,7 +482,7 @@ def get_thermostat_time_progs( ) if thermostat_time_progs is not None: return thermostat_time_progs - return dict() + return {} def set_holiday( self, @@ -487,6 +532,11 @@ def __request( is_retry: bool = False, ) -> Optional[dict[str, Any]]: """Request with requests""" + if not is_retry and time.time() < self._blocked_until: + raise ConnectionException( + 429, + "Rate limited; skipping request until the block window ends", + ) headers: dict[str, Any] = { "User-Agent": self.__user_agent, "ar.authToken": self.__token, @@ -512,8 +562,9 @@ def __request( case 404: return None case 429: - content = response.content.decode() - raise ConnectionException(response.status_code, content) + return self.__handle_rate_limit( + response, is_retry, method, path, params, body + ) case _: if not is_retry: time.sleep(5) @@ -531,10 +582,121 @@ def _post(self, path: str, body: Any) -> Any: """POST request""" return self.__request("POST", path, None, body) + def __handle_rate_limit( + self, + response, + is_retry: bool, + method: str, + path: str, + params: Optional[dict[str, Any]], + body: Any, + ) -> Optional[dict[str, Any]]: + """Sleep out the 429 block window, retry once, per-instance deadline.""" + content = response.content + wait_seconds = _rate_limit_wait_seconds(content) + self._blocked_until = time.time() + wait_seconds + if not is_retry: + time.sleep(wait_seconds) + return self.__request(method, path, params, body, True) + raise ConnectionException(response.status_code, content.decode()) + def _get(self, path: str, params: Optional[dict[str, Any]] = None) -> Any: """GET request""" return self.__request("GET", path, params, None) + def _r2_session(self) -> requests.Session: + """Lazily create the R2 requests session (holds the auth cookies).""" + if self.__r2_requests_session is None: + self.__r2_requests_session = requests.Session() + self.__r2_requests_session.headers["User-Agent"] = ARISTON_R2_USER_AGENT + return self.__r2_requests_session + + def _r2_login(self) -> None: + """Log in to the R2 web app (form + anti-forgery token, cookie session).""" + self.__r2_logged_in = False + session = self._r2_session() + login_page = session.get(ARISTON_R2_LOGIN_PAGE) + if login_page.status_code != 200: + raise ConnectionException( + f"R2 login page returned HTTP {login_page.status_code}" + ) + match = re.search( + r'name="__RequestVerificationToken"[^>]*value="([^"]+)"', login_page.text + ) + if match is None: + raise ConnectionException( + "R2 login page has no __RequestVerificationToken" + ) + login = session.post( + ARISTON_R2_LOGIN_PAGE, + data={ + "__RequestVerificationToken": match.group(1), + "email": self.__username, + "password": self.__password, + "rememberMe": "false", + }, + allow_redirects=False, + ) + if login.status_code not in (200, 302): + raise ConnectionException(f"R2 login returned HTTP {login.status_code}") + self.__r2_logged_in = True + + def _r2_get_slp_plant_data(self, gw_id: str) -> dict[str, Any]: + """Read the Nuos Split plant data through the R2 web app.""" + response = self._r2_session().get(ARISTON_R2_SLP_GET_DATA.format(gw_id)) + if response.status_code != 200: + raise ConnectionException( + f"R2 GetData returned HTTP {response.status_code}" + ) + try: + body = response.json() + return body["data"]["plantData"] + except (KeyError, ValueError) as err: + # An expired R2 forms-auth session redirects to the login page: + # HTTP 200 text/html. Surface as ConnectionException so the + # caller's fresh-login retry fires. + raise ConnectionException( + "R2 GetData returned no plant data (session expired?)" + ) from err + + def _r2_post_set_data(self, gw_id: str, payload: dict[str, Any]) -> None: + """POST the R2 SetData envelope and validate the response.""" + response = self._r2_session().post( + ARISTON_R2_SLP_SET_DATA.format(gw_id), + json=payload, + headers={"X-Requested-With": "XMLHttpRequest"}, + ) + if response.status_code != 200: + raise ConnectionException( + f"R2 SetData returned HTTP {response.status_code}" + ) + try: + body = response.json() + except ValueError as err: + raise ConnectionException( + "R2 SetData returned a non-JSON body (session expired?)" + ) from err + if isinstance(body, dict) and body.get("success") is False: + raise ConnectionException(f"R2 SetData reported failure: {body}") + + def set_nuos_mode_via_r2(self, gw_id: str, value: NuosSplitOperativeMode) -> None: + """Set a Nuos Split operative mode through the R2 web app. + + api/v2 operativeMode accepts values 1+ but silently drops 0 (GREEN); + this endpoint applies every value — it is what the official app uses. + """ + if not self.__r2_logged_in: + self._r2_login() + try: + plant_data = self._r2_get_slp_plant_data(gw_id) + except ConnectionException: + # Session may have expired; one fresh login, then retry the read. + self._r2_login() + plant_data = self._r2_get_slp_plant_data(gw_id) + self._r2_post_set_data( + gw_id, self._build_nuos_r2_payload(plant_data, value.value) + ) + async def async_connect(self) -> bool: """Async login to ariston cloud and get token""" @@ -561,7 +723,7 @@ async def async_get_detailed_devices(self) -> list[Any]: ) if detailed_devices is not None: return list(detailed_devices) - return list() + return [] async def async_get_detailed_velis_devices(self) -> list[Any]: """Async get detailed cloud devices""" @@ -570,7 +732,7 @@ async def async_get_detailed_velis_devices(self) -> list[Any]: ) if detailed_velis_devices is not None: return list(detailed_velis_devices) - return list() + return [] async def async_get_devices(self) -> list[Any]: """Async get cloud devices""" @@ -579,7 +741,7 @@ async def async_get_devices(self) -> list[Any]: ) if devices is not None: return list(devices) - return list() + return [] async def async_get_features_for_device( self, gw_id: str @@ -596,7 +758,7 @@ async def async_get_energy_account(self, gw_id: str) -> dict[str, Any]: ) if energy_account is not None: return energy_account - return dict() + return {} async def async_get_consumptions_sequences( self, gw_id: str, usages: str @@ -607,7 +769,7 @@ async def async_get_consumptions_sequences( ) if consumptions_sequences is not None: return list(consumptions_sequences) - return list() + return [] async def async_get_consumptions_settings(self, gw_id: str) -> dict[str, Any]: """Async get consumption settings""" @@ -617,7 +779,7 @@ async def async_get_consumptions_settings(self, gw_id: str) -> dict[str, Any]: ) if consumptions_settings is not None: return consumptions_settings - return dict() + return {} async def async_set_consumptions_settings( self, @@ -645,7 +807,7 @@ async def async_get_properties( ) if properties is not None: return properties - return dict() + return {} async def async_get_bsb_plant_data(self, gw_id: str) -> dict[str, Any]: """Get BSB plant data.""" @@ -654,7 +816,7 @@ async def async_get_bsb_plant_data(self, gw_id: str) -> dict[str, Any]: ) if data is not None: return data - return dict() + return {} async def async_get_velis_plant_data( self, plant_data: PlantData, gw_id: str @@ -665,7 +827,7 @@ async def async_get_velis_plant_data( ) if med_plant_data is not None: return med_plant_data - return dict() + return {} async def async_get_velis_plant_settings( self, plant_data: PlantData, gw_id: str @@ -676,7 +838,7 @@ async def async_get_velis_plant_settings( ) if med_plant_settings is not None: return med_plant_settings - return dict() + return {} async def async_get_menu_items(self, gw_id: str) -> list[dict[str, Any]]: """Async get menu items""" @@ -685,7 +847,7 @@ async def async_get_menu_items(self, gw_id: str) -> list[dict[str, Any]]: ) if items is not None: return items - return list() + return [] async def async_set_property( self, @@ -753,6 +915,149 @@ async def async_set_nuos_mode( }, ) + @staticmethod + def _build_nuos_r2_payload(plant_data: dict[str, Any], op_mode: int) -> dict[str, Any]: + """Build the R2 PlantHomeSlp/SetData envelope for an operative mode. + + Mirrors the official web app: the cached plantData is echoed back + and only the viewModel fields change. + """ + return { + "plantData": { + "__type__": ["my.entities.entityiface", "my.entities.slpplantdata"], + "gatewayId": plant_data.get("gw"), + "on": plant_data.get("on"), + "mode": plant_data.get("mode"), + "waterTemp": plant_data.get("waterTemp"), + "comfortTemp": plant_data.get("comfortTemp"), + "reducedTemp": plant_data.get("reducedTemp"), + "procReqTemp": plant_data.get("procReqTemp"), + "opMode": plant_data.get("opMode"), + "holidayUntil": plant_data.get("holidayUntil"), + "boostOn": plant_data.get("boostOn"), + "hpState": plant_data.get("hpState"), + }, + "viewModel": { + "on": plant_data.get("on"), + "plantMode": plant_data.get("mode"), + "opMode": op_mode, + "boostOn": plant_data.get("boostOn"), + "comfortTemp": plant_data.get("comfortTemp"), + "holidayUntil": plant_data.get("holidayUntil"), + }, + } + + async def _async_r2_login(self) -> None: + """Log in to the R2 web app (form + anti-forgery token, cookie session).""" + self.__r2_logged_in = False + async with aiohttp.ClientSession( + cookie_jar=self._r2_cookies(), + headers={"User-Agent": ARISTON_R2_USER_AGENT}, + ) as session: + async with session.get(ARISTON_R2_LOGIN_PAGE) as response: + html = await response.text() + if response.status != 200: + raise ConnectionException( + f"R2 login page returned HTTP {response.status}" + ) + match = re.search( + r'name="__RequestVerificationToken"[^>]*value="([^"]+)"', html + ) + if match is None: + raise ConnectionException( + "R2 login page has no __RequestVerificationToken" + ) + verification_token = match.group(1) + + async with session.post( + ARISTON_R2_LOGIN_PAGE, + data={ + "__RequestVerificationToken": verification_token, + "email": self.__username, + "password": self.__password, + "rememberMe": "false", + }, + allow_redirects=False, + ) as response: + if response.status not in (200, 302): + raise ConnectionException( + f"R2 login returned HTTP {response.status}" + ) + self.__r2_logged_in = True + + async def _async_r2_get_slp_plant_data(self, gw_id: str) -> dict[str, Any]: + """Read the Nuos Split plant data through the R2 web app.""" + async with aiohttp.ClientSession( + cookie_jar=self._r2_cookies(), + headers={"User-Agent": ARISTON_R2_USER_AGENT}, + ) as session: + async with session.get( + ARISTON_R2_SLP_GET_DATA.format(gw_id) + ) as response: + if response.status != 200: + raise ConnectionException( + f"R2 GetData returned HTTP {response.status}" + ) + try: + body = await response.json() + return body["data"]["plantData"] + except (aiohttp.ContentTypeError, KeyError, ValueError) as err: + # An expired R2 forms-auth session redirects to the login + # page: HTTP 200 text/html. Surface as ConnectionException + # so the caller's fresh-login retry fires. + raise ConnectionException( + "R2 GetData returned no plant data (session expired?)" + ) from err + + async def async_set_nuos_mode_via_r2( + self, gw_id: str, value: NuosSplitOperativeMode + ) -> None: + """Set a Nuos Split operative mode through the R2 web app. + + api/v2 operativeMode accepts values 1+ but silently drops 0 (GREEN); + this endpoint applies every value — it is what the official app uses. + """ + if not self.__r2_logged_in: + await self._async_r2_login() + try: + plant_data = await self._async_r2_get_slp_plant_data(gw_id) + except ConnectionException: + # Session may have expired; one fresh login, then retry the read. + await self._async_r2_login() + plant_data = await self._async_r2_get_slp_plant_data(gw_id) + payload = self._build_nuos_r2_payload(plant_data, value.value) + await self._async_r2_post_set_data(gw_id, payload) + + async def _async_r2_post_set_data( + self, gw_id: str, payload: dict[str, Any] + ) -> None: + """POST the R2 SetData envelope and validate the response.""" + async with aiohttp.ClientSession( + cookie_jar=self._r2_cookies(), + headers={ + "User-Agent": ARISTON_R2_USER_AGENT, + "X-Requested-With": "XMLHttpRequest", + }, + ) as session: + async with session.post( + ARISTON_R2_SLP_SET_DATA.format(gw_id), json=payload + ) as response: + if response.status != 200: + raise ConnectionException( + f"R2 SetData returned HTTP {response.status}" + ) + try: + body = await response.json() + except (aiohttp.ContentTypeError, ValueError) as err: + # An expired session turns the POST into a redirect to + # the login page (HTTP 200 text/html) — auth failure, + # not success. + raise ConnectionException( + "R2 SetData returned a non-JSON body (session expired?)" + ) from err + if isinstance(body, dict) and body.get("success") is False: + raise ConnectionException(f"R2 SetData reported failure: {body}") + async def async_set_bsb_mode(self, gw_id: str, value: BsbOperativeMode) -> None: """Async set Bsb mode""" await self._async_post( @@ -966,6 +1271,11 @@ async def __async_request( is_retry: bool = False, ) -> Optional[dict[str, Any]]: """Async request with aiohttp""" + if not is_retry and time.time() < self._blocked_until: + raise ConnectionException( + 429, + "Rate limited; skipping request until the block window ends", + ) headers: dict[str, Any] = { "User-Agent": self.__user_agent, "ar.authToken": self.__token, @@ -1002,8 +1312,9 @@ async def __async_request( case 404: return None case 429: - content = await response.content.read() - raise ConnectionException(response.status, content) + return await self.__async_handle_rate_limit( + response, is_retry, method, path, params, body + ) case _: if not is_retry: await asyncio.sleep(5) @@ -1023,6 +1334,24 @@ async def _async_post(self, path: str, body: Any) -> Any: """Async POST request""" return await self.__async_request("POST", path, None, body) + async def __async_handle_rate_limit( + self, + response, + is_retry: bool, + method: str, + path: str, + params: Optional[dict[str, Any]], + body: Any, + ) -> Optional[dict[str, Any]]: + """Sleep out the 429 block window, retry once, share the deadline.""" + content = await response.content.read() + wait_seconds = _rate_limit_wait_seconds(content) + 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) + raise ConnectionException(response.status, content) + async def _async_get( self, path: str, params: Optional[dict[str, Any]] = None ) -> Any: diff --git a/ariston/const.py b/ariston/const.py index e2460ad..d927305 100644 --- a/ariston/const.py +++ b/ariston/const.py @@ -5,8 +5,24 @@ ARISTON_API_URL: Final[str] = "https://www.ariston-net.remotethermo.com/api/v2/" ARISTON_LOGIN: Final[str] = "accounts/login" +# Web-app (R2) routes. The api/v2 operativeMode endpoint silently drops +# value 0 (GREEN) for Nuos Split — proven 2026-10-18 — while the web app's +# PlantHomeSlp/SetData applies it. GREEN writes go through these routes. +ARISTON_R2_BASE_URL: Final[str] = "https://www.ariston-net.remotethermo.com" +ARISTON_R2_LOGIN_PAGE: Final[str] = ARISTON_R2_BASE_URL + "/R2/Account/Login" +ARISTON_R2_HOME: Final[str] = ARISTON_R2_BASE_URL + "/R2/Home" +ARISTON_R2_SLP_GET_DATA: Final[str] = ( + ARISTON_R2_BASE_URL + + "/R2/PlantHomeSlp/GetData/{0}?fetchSettings=true&fetchTimeProg=true" +) +ARISTON_R2_SLP_SET_DATA: Final[str] = ARISTON_R2_BASE_URL + "/R2/PlantHomeSlp/SetData/{0}" +ARISTON_R2_USER_AGENT: Final[str] = ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/128.0 Safari/537.36" +) ARISTON_REMOTE: Final[str] = "remote" ARISTON_VELIS: Final[str] = "velis" +HOLIDAY_DATE_FORMAT: Final[str] = "%Y-%m-%dT00:00:00" ARISTON_PLANTS: Final[str] = "plants" ARISTON_LITE: Final[str] = "lite" ARISTON_DATA_ITEMS: Final[str] = "dataItems" @@ -224,14 +240,22 @@ class NuosSplitPlantMode(Enum): PROGRAM = 2 -@unique class NuosSplitOperativeMode(WaterHeaterMode): - """NuosSplit operative mode enum""" + """NuosSplit operative mode enum. + + Official range (web app, 2026-10-18): Green=0, Comfort=1, Fast=2, + Auto=3, HcHp=4, Electric=5, GreenPlus=6. Only the modes the device + reliably accepts are exposed; value 3 was mislabeled IMEMORY before. + IMEMORY is kept as a deprecated alias of AUTO so existing callers + (attribute access and the string-based device setter) keep working; + iteration and the mode options stay on the canonical AUTO name. + """ GREEN = 0 COMFORT = 1 FAST = 2 - IMEMORY = 3 + AUTO = 3 + IMEMORY = 3 # deprecated alias of AUTO (pre-rename public name) GREEN_PLUS = 6 diff --git a/ariston/galevo_device.py b/ariston/galevo_device.py index 06ee5d8..7d125a4 100644 --- a/ariston/galevo_device.py +++ b/ariston/galevo_device.py @@ -18,6 +18,7 @@ DeviceProperties, GasEnergyUnit, GasType, + HOLIDAY_DATE_FORMAT, PlantMode, PropertyType, ThermostatProperties, @@ -43,9 +44,9 @@ def __init__( super().__init__(api, attributes) self.umsys = "si" if is_metric else "us" self.language_tag = language_tag - self.consumptions_settings: dict[str, Any] = dict() - self.energy_account: dict[str, Any] = dict() - self.menu_items: list[dict[str, Any]] = list() + self.consumptions_settings: dict[str, Any] = {} + self.energy_account: dict[str, Any] = {} + self.menu_items: list[dict[str, Any]] = [] @property def consumption_type(self) -> str: @@ -1008,7 +1009,9 @@ async def async_set_item_by_id( @staticmethod def _create_holiday_end_date(holiday_end: Optional[date]): return ( - None if holiday_end is None else holiday_end.strftime("%Y-%m-%dT00:00:00") + None + if holiday_end is None + else holiday_end.strftime(HOLIDAY_DATE_FORMAT) ) def _set_holiday(self, holiday_end_date: Optional[str]): diff --git a/ariston/nuos_split_device.py b/ariston/nuos_split_device.py index b64c0f7..8bfec13 100644 --- a/ariston/nuos_split_device.py +++ b/ariston/nuos_split_device.py @@ -202,20 +202,30 @@ async def async_set_water_heater_reduced_temperature(self, temperature: float): await self._async_set_water_heater_temperature(current, temperature) def set_water_heater_operation_mode(self, operation_mode: str): - """Set water heater operation mode""" - self.api.set_nuos_mode(self.gw, NuosSplitOperativeMode[operation_mode]) - self.data[NuosSplitProperties.MODE] = NuosSplitOperativeMode[ - operation_mode - ].value + """Set water heater operation mode. + + GREEN (0) goes through the R2 web-app endpoint: the api/v2 + operativeMode route silently drops value 0 (proven 2026-10-18). + """ + mode = NuosSplitOperativeMode[operation_mode] + if mode is NuosSplitOperativeMode.GREEN: + self.api.set_nuos_mode_via_r2(self.gw, mode) + else: + self.api.set_nuos_mode(self.gw, mode) + self.data[NuosSplitProperties.OP_MODE] = mode.value async def async_set_water_heater_operation_mode(self, operation_mode: str): - """Async set water heater operation mode""" - await self.api.async_set_nuos_mode( - self.gw, NuosSplitOperativeMode[operation_mode] - ) - self.data[NuosSplitProperties.MODE] = NuosSplitOperativeMode[ - operation_mode - ].value + """Async set water heater operation mode. + + GREEN (0) goes through the R2 web-app endpoint: the api/v2 + operativeMode route silently drops value 0 (proven 2026-10-18). + """ + mode = NuosSplitOperativeMode[operation_mode] + if mode is NuosSplitOperativeMode.GREEN: + await self.api.async_set_nuos_mode_via_r2(self.gw, mode) + else: + await self.api.async_set_nuos_mode(self.gw, mode) + self.data[NuosSplitProperties.OP_MODE] = mode.value def set_min_setpoint_temp(self, min_setpoint_temp: float): """Set water heater minimum setpoint temperature""" diff --git a/ariston/velis_device.py b/ariston/velis_device.py index 46393f9..6029ccf 100644 --- a/ariston/velis_device.py +++ b/ariston/velis_device.py @@ -3,10 +3,11 @@ import logging from abc import ABC, abstractmethod +from datetime import date from typing import Any, Optional from .ariston_api import AristonAPI -from .const import VelisDeviceProperties +from .const import HOLIDAY_DATE_FORMAT, VelisDeviceProperties from .velis_base_device import AristonVelisBaseDevice from .device import AristonDevice @@ -22,7 +23,7 @@ def __init__( attributes: dict[str, Any], ) -> None: super().__init__(api, attributes) - self.plant_settings: dict[str, Any] = dict() + self.plant_settings: dict[str, Any] = {} @property @abstractmethod @@ -88,6 +89,26 @@ async def async_set_max_setpoint_temp(self, max_setpoint_temp: float): ) self.plant_settings[self.max_setpoint_temp] = max_setpoint_temp + @staticmethod + def _create_holiday_end_date(holiday_end: Optional[date]) -> Optional[str]: + return ( + None + if holiday_end is None + else holiday_end.strftime(HOLIDAY_DATE_FORMAT) + ) + + def set_velis_holiday(self, holiday_end: Optional[date]) -> None: + """Set Velis holiday on device""" + self.api.set_velis_slp_holiday( + self.gw, self._create_holiday_end_date(holiday_end) + ) + + async def async_set_velis_holiday(self, holiday_end: Optional[date]) -> None: + """Async set Velis holiday on device""" + await self.api.async_set_velis_slp_holiday( + self.gw, self._create_holiday_end_date(holiday_end) + ) + @property @abstractmethod def water_heater_maximum_setpoint_temperature_minimum(self) -> Optional[float]: diff --git a/tests/test_device_models.py b/tests/test_device_models.py index c411759..e11676c 100644 --- a/tests/test_device_models.py +++ b/tests/test_device_models.py @@ -312,13 +312,19 @@ def test_nuos_split_properties_sync_async_and_missing_state_defaults(self): device.set_heating_rate(5) self.assertEqual(device.data[NuosSplitProperties.COMFORT_TEMP], 43) self.assertEqual(device.data[NuosSplitProperties.REDUCED_TEMP], 42) - self.assertEqual(device.data[NuosSplitProperties.MODE], NuosSplitOperativeMode.FAST.value) + # opMode (operative mode) is echoed, not mode (plant mode — never + # changes on an operativeMode write, proven against the live API) + self.assertEqual( + device.data[NuosSplitProperties.OP_MODE], + NuosSplitOperativeMode.FAST.value, + ) device.api.set_nuos_temperature.assert_called_with("gw-1", 43, 42, 60, 40) device.api.set_velis_plant_setting.assert_called() device.api.async_set_nous_boost = AsyncMock() device.api.async_set_nuos_temperature = AsyncMock() device.api.async_set_nuos_mode = AsyncMock() + device.api.async_set_nuos_mode_via_r2 = AsyncMock() device.api.async_set_velis_plant_setting = AsyncMock() async def set_values(): @@ -335,7 +341,10 @@ async def set_values(): asyncio.run(set_values()) self.assertTrue(device.data[NuosSplitProperties.BOOST_ON]) - self.assertEqual(device.data[NuosSplitProperties.MODE], NuosSplitOperativeMode.GREEN.value) + self.assertEqual( + device.data[NuosSplitProperties.OP_MODE], + NuosSplitOperativeMode.GREEN.value, + ) self.assertEqual(device.plant_settings[SlpDeviceSettings.SLP_HEATING_RATE], 4) self.assertEqual(device.api.async_set_velis_plant_setting.await_count, 3) @@ -429,7 +438,8 @@ def test_nuos_split_green_plus_mode_is_exposed_and_settable(self): device.set_water_heater_operation_mode("GREEN_PLUS") self.assertEqual( - device.data[NuosSplitProperties.MODE], NuosSplitOperativeMode.GREEN_PLUS.value + device.data[NuosSplitProperties.OP_MODE], + NuosSplitOperativeMode.GREEN_PLUS.value, ) device.api.set_nuos_mode.assert_called_once_with( "gw-1", NuosSplitOperativeMode.GREEN_PLUS @@ -438,7 +448,8 @@ def test_nuos_split_green_plus_mode_is_exposed_and_settable(self): device.api.async_set_nuos_mode = AsyncMock() asyncio.run(device.async_set_water_heater_operation_mode("GREEN_PLUS")) self.assertEqual( - device.data[NuosSplitProperties.MODE], NuosSplitOperativeMode.GREEN_PLUS.value + device.data[NuosSplitProperties.OP_MODE], + NuosSplitOperativeMode.GREEN_PLUS.value, ) device.api.async_set_nuos_mode.assert_awaited_once_with( "gw-1", NuosSplitOperativeMode.GREEN_PLUS diff --git a/tests/test_nuos_green_r2.py b/tests/test_nuos_green_r2.py new file mode 100644 index 0000000..5f0829a --- /dev/null +++ b/tests/test_nuos_green_r2.py @@ -0,0 +1,339 @@ +"""Unit tests for the Nuos Split GREEN write via the R2 web-app endpoint.""" + +from __future__ import annotations + +import asyncio +import unittest +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch + +import aiohttp + +from ariston.ariston_api import AristonAPI, ConnectionException +from ariston.const import NuosSplitOperativeMode +from ariston.nuos_split_device import AristonNuosSplitDevice + + +def _device() -> AristonNuosSplitDevice: + """Instantiate without the abstract machinery; only api+gw are used.""" + cls = AristonNuosSplitDevice + original = cls.__abstractmethods__ + cls.__abstractmethods__ = frozenset() + try: + device = cls.__new__(cls) + finally: + cls.__abstractmethods__ = original + device.api = AristonAPI("user", "pass") + device.gw = "3C8A1F2EDE84" + device.data = {} + return device + + +class _FakeAsyncCtx: + """Minimal async context manager yielding a fake response.""" + + def __init__(self, response: Any) -> None: + self._response = response + + async def __aenter__(self) -> Any: + return self._response + + async def __aexit__(self, *exc: Any) -> None: + return None + + +class _FakeSession: + """Stand-in for aiohttp.ClientSession used as an async context manager.""" + + def __init__(self, response: Any) -> None: + self._response = response + + async def __aenter__(self) -> "_FakeSession": + return self + + async def __aexit__(self, *exc: Any) -> None: + return None + + def get(self, *args: Any, **kwargs: Any) -> _FakeAsyncCtx: + return _FakeAsyncCtx(self._response) + + def post(self, *args: Any, **kwargs: Any) -> _FakeAsyncCtx: + return _FakeAsyncCtx(self._response) + + +class _FakeResponse: + def __init__( + self, + status: int, + json_err: Exception | None = None, + json_data: Any = None, + ) -> None: + self.status = status + self._json_err = json_err + self._json_data = json_data + + async def json(self) -> Any: + if self._json_err is not None: + raise self._json_err + return self._json_data if self._json_data is not None else {} + + +class _FakeRequestsSession: + """Stand-in for requests.Session with queued responses.""" + + def __init__(self) -> None: + self.headers: dict[str, str] = {} + self._responses: list[Any] = [] + self.posts: list[dict[str, Any]] = [] + + def queue(self, *responses: Any) -> None: + self._responses.extend(responses) + + def get(self, *args: Any, **kwargs: Any) -> Any: + return self._responses.pop(0) + + def post(self, *args: Any, **kwargs: Any) -> Any: + self.posts.append(kwargs) + return self._responses.pop(0) + + +class _FakeRequestsResponse: + def __init__( + self, + status_code: int = 200, + text: str = "", + json_data: Any = None, + ) -> None: + self.status_code = status_code + self.text = text + self.ok = status_code < 400 + self._json_data = json_data + + def json(self) -> Any: + return self._json_data if self._json_data is not None else {} + + +_LOGIN_HTML = '' + + +class NuosGreenR2Tests(unittest.TestCase): + """GREEN (0) must go through the R2 web-app route, sync and async.""" + + def test_build_nuos_r2_payload_green(self) -> None: + plant = { + "gw": "3C8A1F2EDE84", + "on": True, + "mode": 2, + "waterTemp": 49.0, + "comfortTemp": 54.0, + "reducedTemp": 16.0, + "procReqTemp": 54.0, + "opMode": 1, + "holidayUntil": None, + "boostOn": False, + "hpState": 2, + } + payload = AristonAPI._build_nuos_r2_payload( + plant, NuosSplitOperativeMode.GREEN.value + ) + + self.assertEqual(payload["viewModel"]["opMode"], 0) # the value that changes + self.assertEqual(payload["viewModel"]["plantMode"], 2) + self.assertEqual(payload["viewModel"]["comfortTemp"], 54.0) + self.assertEqual(payload["plantData"]["gatewayId"], "3C8A1F2EDE84") + self.assertEqual( + payload["plantData"]["__type__"], + ["my.entities.entityiface", "my.entities.slpplantdata"], + ) + + def test_enum_values_match_official_range(self) -> None: + self.assertEqual(NuosSplitOperativeMode.GREEN.value, 0) + self.assertEqual(NuosSplitOperativeMode.COMFORT.value, 1) + self.assertEqual(NuosSplitOperativeMode.FAST.value, 2) + self.assertEqual(NuosSplitOperativeMode.AUTO.value, 3) # was mislabeled + + def test_imemory_alias_preserved(self) -> None: + """IMEMORY (the pre-rename public name) still resolves to AUTO = 3.""" + self.assertIs(NuosSplitOperativeMode.IMEMORY, NuosSplitOperativeMode.AUTO) + self.assertEqual(NuosSplitOperativeMode["IMEMORY"].value, 3) + values = [mode.value for mode in NuosSplitOperativeMode] + self.assertEqual(values.count(3), 1) # alias adds no duplicate option + self.assertNotIn("IMEMORY", [mode.name for mode in NuosSplitOperativeMode]) + + def test_imemory_string_still_sets_auto(self) -> None: + """The string-based setter accepts the old name and writes value 3.""" + device = _device() + device.api.set_nuos_mode = MagicMock() + + device.set_water_heater_operation_mode("IMEMORY") + + device.api.set_nuos_mode.assert_called_once_with( + device.gw, NuosSplitOperativeMode.AUTO + ) + self.assertEqual(device.data["opMode"], 3) + + # -- async device setter routing -- + + def test_green_write_routes_through_r2(self) -> None: + device = _device() + device.api.async_set_nuos_mode_via_r2 = AsyncMock() # type: ignore[method-assign] + device.api.async_set_nuos_mode = AsyncMock() # type: ignore[method-assign] + + asyncio.run(device.async_set_water_heater_operation_mode("GREEN")) + + device.api.async_set_nuos_mode_via_r2.assert_awaited_once_with( + device.gw, NuosSplitOperativeMode.GREEN + ) + device.api.async_set_nuos_mode.assert_not_awaited() + self.assertEqual(device.data["opMode"], 0) + + def test_comfort_write_keeps_direct_route(self) -> None: + device = _device() + device.api.async_set_nuos_mode_via_r2 = AsyncMock() # type: ignore[method-assign] + device.api.async_set_nuos_mode = AsyncMock() # type: ignore[method-assign] + + asyncio.run(device.async_set_water_heater_operation_mode("COMFORT")) + + device.api.async_set_nuos_mode.assert_awaited_once_with( + device.gw, NuosSplitOperativeMode.COMFORT + ) + device.api.async_set_nuos_mode_via_r2.assert_not_awaited() + self.assertEqual(device.data["opMode"], 1) + + # -- async API R2 flow -- + + def test_r2_read_surfaces_connection_exception_on_bad_body(self) -> None: + """Expired R2 session: GetData answers 200 with a non-plantData body. + + The read+parse must surface ConnectionException so the caller's + fresh-login retry fires (regression guard for the silent-drop bug). + """ + for json_err in (KeyError("plantData"), ValueError("bad json")): + with self.subTest(json_err=type(json_err).__name__): + api = AristonAPI("user", "pass") + fake = _FakeSession(_FakeResponse(200, json_err=json_err)) + with patch( + "ariston.ariston_api.aiohttp.ClientSession", lambda *a, **kw: fake + ): + with self.assertRaisesRegex( + ConnectionException, "session expired" + ): + asyncio.run(api._async_r2_get_slp_plant_data("GW")) + + def test_r2_retry_fires_fresh_login_after_failed_read(self) -> None: + """One failed read -> fresh login -> retry read -> SetData POST.""" + api = AristonAPI("user", "pass") + api._async_r2_login = AsyncMock() + api._async_r2_get_slp_plant_data = AsyncMock( + side_effect=[ConnectionException("expired"), {"any": "plant"}] + ) + api._build_nuos_r2_payload = MagicMock(return_value={}) + fake = _FakeSession(_FakeResponse(200)) + with patch( + "ariston.ariston_api.aiohttp.ClientSession", lambda *a, **kw: fake + ): + asyncio.run( + api.async_set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) + ) + self.assertEqual(api._async_r2_login.await_count, 2) + self.assertEqual(api._async_r2_get_slp_plant_data.await_count, 2) + + def test_r2_setdata_success_false_raises(self) -> None: + """A 200 body with success:false is a failed write, not a success.""" + api = AristonAPI("user", "pass") + api._async_r2_login = AsyncMock() + api._async_r2_get_slp_plant_data = AsyncMock(return_value={"any": "plant"}) + fake = _FakeSession(_FakeResponse(200, json_data={"success": False})) + with patch( + "ariston.ariston_api.aiohttp.ClientSession", lambda *a, **kw: fake + ): + with self.assertRaisesRegex(ConnectionException, "reported failure"): + asyncio.run( + api.async_set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) + ) + + def test_r2_setdata_non_json_body_raises(self) -> None: + """An expired session turns the POST into a 200 login page.""" + api = AristonAPI("user", "pass") + api._async_r2_login = AsyncMock() + api._async_r2_get_slp_plant_data = AsyncMock(return_value={"any": "plant"}) + err = aiohttp.ContentTypeError(MagicMock(), ()) + fake = _FakeSession(_FakeResponse(200, json_err=err)) + with patch( + "ariston.ariston_api.aiohttp.ClientSession", lambda *a, **kw: fake + ): + with self.assertRaisesRegex(ConnectionException, "non-JSON body"): + asyncio.run( + api.async_set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) + ) + + # -- sync twin (requests) -- + + def test_sync_green_write_full_r2_flow(self) -> None: + """Sync GREEN: login -> read -> write, opMode 0 in the SetData envelope.""" + api = AristonAPI("user", "pass") + session = _FakeRequestsSession() + session.queue( + _FakeRequestsResponse(200, text=_LOGIN_HTML), + _FakeRequestsResponse(302), + _FakeRequestsResponse( + json_data={"data": {"plantData": {"mode": 2, "on": True}}} + ), + _FakeRequestsResponse(json_data={"success": True}), + ) + with patch("ariston.ariston_api.requests.Session", lambda: session): + api.set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) + + self.assertEqual(len(session.posts), 2) + login_form = session.posts[0]["data"] + self.assertEqual(login_form["__RequestVerificationToken"], "TOKEN123") + setdata_body = session.posts[1]["json"] + self.assertEqual(setdata_body["viewModel"]["opMode"], 0) + self.assertEqual(setdata_body["plantData"]["mode"], 2) # echoed back + + def test_sync_r2_retry_fires_fresh_login(self) -> None: + """Sync twin of the async retry: one failed read -> fresh login -> retry.""" + api = AristonAPI("user", "pass") + api._r2_login = MagicMock() + api._r2_get_slp_plant_data = MagicMock( + side_effect=[ConnectionException("expired"), {"any": "plant"}] + ) + session = _FakeRequestsSession() + session.queue(_FakeRequestsResponse(json_data={"success": True})) + with patch("ariston.ariston_api.requests.Session", lambda: session): + api.set_nuos_mode_via_r2("GW", NuosSplitOperativeMode.GREEN) + + self.assertEqual(api._r2_login.call_count, 2) + self.assertEqual(api._r2_get_slp_plant_data.call_count, 2) + + def test_sync_green_write_routes_through_r2(self) -> None: + """Device sync setter: GREEN must not hit the api/v2 direct route.""" + device = _device() + device.api.set_nuos_mode_via_r2 = MagicMock() + device.api.set_nuos_mode = MagicMock() + + device.set_water_heater_operation_mode("GREEN") + + device.api.set_nuos_mode_via_r2.assert_called_once_with( + device.gw, NuosSplitOperativeMode.GREEN + ) + device.api.set_nuos_mode.assert_not_called() + self.assertEqual(device.data["opMode"], 0) + + def test_sync_comfort_write_keeps_direct_route(self) -> None: + """Device sync setter: COMFORT keeps the proven api/v2 direct route.""" + device = _device() + device.api.set_nuos_mode_via_r2 = MagicMock() + device.api.set_nuos_mode = MagicMock() + + device.set_water_heater_operation_mode("COMFORT") + + device.api.set_nuos_mode.assert_called_once_with( + device.gw, NuosSplitOperativeMode.COMFORT + ) + device.api.set_nuos_mode_via_r2.assert_not_called() + self.assertEqual(device.data["opMode"], 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_rate_limit.py b/tests/test_rate_limit.py new file mode 100644 index 0000000..951952e --- /dev/null +++ b/tests/test_rate_limit.py @@ -0,0 +1,226 @@ +"""Unit tests for the 429 rate-limit handling in ariston.ariston_api.""" + +import asyncio +import time +import unittest +from typing import Any, Optional +from unittest.mock import MagicMock, patch + +from ariston.ariston_api import ( + AristonAPI, + ConnectionException, + _parse_block_seconds, +) + + +def _api() -> AristonAPI: + return AristonAPI("user", "pass") + + +def _sync_response(status: int, content: bytes = b"", json_data: Any = None): + response = MagicMock() + response.ok = status < 400 + response.status_code = status + response.content = content + if json_data is not None: + response.json.return_value = json_data + return response + + +class _FakeAiohttpContent: + def __init__(self, payload: bytes) -> None: + self._payload = payload + + async def read(self) -> bytes: + return self._payload + + +class _FakeAiohttpResponse: + def __init__( + self, status: int, payload: bytes = b"", json_data: Any = None + ) -> None: + self.status = status + self.ok = status < 400 + self.content = _FakeAiohttpContent(payload) + self.content_length = len(payload) + self._json_data = json_data + + async def json(self) -> Any: + return self._json_data + + +def _fake_session_cls(responses: list, calls: list): + class _Session: + def __init__(self, *args: Any, **kwargs: Any) -> None: + pass + + async def __aenter__(self) -> "_Session": + return self + + async def __aexit__(self, *exc: Any) -> bool: + return False + + async def request(self, *args: Any, **kwargs: Any): + calls.append(1) + return responses.pop(0) + + return _Session + + +class RateLimitTests(unittest.TestCase): + """429 handling: parse, sleep-out with a single retry, per-instance window.""" + + # -- parse helper -- + + def test_parse_block_seconds(self): + self.assertEqual( + _parse_block_seconds(b"Requests are blocked for 66 seconds"), 66 + ) + self.assertEqual(_parse_block_seconds(b"Requests are blocked for 5 seconds"), 5) + self.assertIsNone(_parse_block_seconds(b"Too many requests")) + + # -- sync path (requests) -- + + def test_429_parses_wait_seconds(self): + responses = [ + _sync_response(429, b"Requests are blocked for 66 seconds"), + _sync_response(200, b"{}", {"ok": True}), + ] + http = MagicMock(side_effect=responses) + sleeps: list[int] = [] + api = _api() + with patch("ariston.ariston_api.requests.request", http), patch( + "ariston.ariston_api.time.sleep", side_effect=sleeps.append + ): + result = api._get("https://example/api") + + self.assertEqual(result, {"ok": True}) + self.assertEqual(http.call_count, 2) # exactly one retry + self.assertEqual(sleeps, [67]) # parsed 66 + 1s margin + self.assertGreater(api._blocked_until, 0) # block window was set + + def test_429_without_parsable_body(self): + responses = [ + _sync_response(429, b"Too many requests"), + _sync_response(200, b"{}", {"ok": True}), + ] + http = MagicMock(side_effect=responses) + sleeps: list[int] = [] + with patch("ariston.ariston_api.requests.request", http), patch( + "ariston.ariston_api.time.sleep", side_effect=sleeps.append + ): + result = _api()._get("https://example/api") + + self.assertEqual(result, {"ok": True}) + self.assertEqual(sleeps, [5]) # documented fallback + self.assertEqual(http.call_count, 2) + + def test_429_twice_raises(self): + body = b"Requests are blocked for 10 seconds" + http = MagicMock( + side_effect=[_sync_response(429, body), _sync_response(429, body)] + ) + api = _api() + with patch("ariston.ariston_api.requests.request", http), patch( + "ariston.ariston_api.time.sleep" + ): + with self.assertRaises(ConnectionException): + api._get("https://example/api") + + self.assertEqual(http.call_count, 2) # one retry, then raise + + def test_blocked_until_short_circuits(self): + api = _api() + api._blocked_until = time.time() + 30 + http = MagicMock() + with patch("ariston.ariston_api.requests.request", http): + with self.assertRaises(ConnectionException): + api._get("https://example/api") + + http.assert_not_called() # no network call inside the block window + + def test_block_window_is_per_instance(self): + """A 429 on one instance must not silence other instances.""" + blocked = _api() + other = _api() + http = MagicMock( + side_effect=[ + _sync_response(429, b"Requests are blocked for 30 seconds"), + _sync_response(200, b"{}", {"ok": True}), + ] + ) + with patch("ariston.ariston_api.requests.request", http), patch( + "ariston.ariston_api.time.sleep" + ): + self.assertEqual(blocked._get("https://example/api"), {"ok": True}) + + self.assertGreater(blocked._blocked_until, 0) + self.assertEqual(other._blocked_until, 0.0) # untouched by the 429 + + # -- async path (aiohttp) -- + + def test_async_429_parses_and_retries(self): + responses = [ + _FakeAiohttpResponse(429, b"Requests are blocked for 66 seconds"), + _FakeAiohttpResponse(200, b"{}", {"ok": True}), + ] + calls: list[int] = [] + sleeps: list[Optional[int]] = [] + + async def run() -> Any: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls(responses, calls), + ), patch( + "ariston.ariston_api.asyncio.sleep", side_effect=sleeps.append + ): + return await _api()._async_get("https://example/api") + + result = asyncio.run(run()) + + self.assertEqual(result, {"ok": True}) + self.assertEqual(len(calls), 2) # exactly one retry + self.assertEqual(sleeps, [67]) # parsed 66 + 1s margin + + def test_async_blocked_until_short_circuits(self): + calls: list[int] = [] + api = _api() + api._blocked_until = time.time() + 30 + + async def run() -> None: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls([], calls), + ): + with self.assertRaises(ConnectionException): + await api._async_get("https://example/api") + + asyncio.run(run()) + + self.assertEqual(calls, []) # no network call inside the block window + + def test_async_block_window_is_per_instance(self): + """Async twin: a 429 on one instance must not silence other instances.""" + blocked = _api() + other = _api() + responses = [ + _FakeAiohttpResponse(429, b"Requests are blocked for 30 seconds"), + _FakeAiohttpResponse(200, b"{}", {"ok": True}), + ] + calls: list[int] = [] + + async def run() -> Any: + with patch( + "ariston.ariston_api.aiohttp.ClientSession", + _fake_session_cls(responses, calls), + ), patch("ariston.ariston_api.asyncio.sleep"): + return await blocked._async_get("https://example/api") + + self.assertEqual(asyncio.run(run()), {"ok": True}) + + self.assertGreater(blocked._blocked_until, 0) + self.assertEqual(other._blocked_until, 0.0) # untouched by the 429 + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_velis_holiday.py b/tests/test_velis_holiday.py new file mode 100644 index 0000000..f0aadb8 --- /dev/null +++ b/tests/test_velis_holiday.py @@ -0,0 +1,93 @@ +"""Unit tests for the Velis holiday write (endpoint proven by live write-test).""" + +import asyncio +import unittest +from datetime import date +from typing import Any +from unittest.mock import patch + +from ariston.ariston_api import AristonAPI +from ariston.const import ARISTON_API_URL, ARISTON_VELIS +from ariston.velis_device import AristonVelisDevice + +GW = "3C8A1F2EDE84" +EXPECTED_URL = ( + f"{ARISTON_API_URL}{ARISTON_VELIS}/slpPlantData/{GW}/holiday" +) + + +def _fake_session_cls(posts: list): + class _Session: + def __init__(self, *args: Any, **kwargs: Any) -> None: + pass + + async def __aenter__(self) -> "_Session": + return self + + async def __aexit__(self, *exc: Any) -> bool: + return False + + async def request(self, method: str, path: str, params=None, json=None, + headers=None): + if method == "POST": + posts.append({"path": path, "json": json}) + class _Resp: + status = 200 + ok = True + content_length = 0 + return _Resp() + + return _Session + + +def _device() -> AristonVelisDevice: + """Instantiate without the abstract machinery; only api+gw are used.""" + cls = AristonVelisDevice + original = cls.__abstractmethods__ + cls.__abstractmethods__ = frozenset() + try: + device = cls.__new__(cls) + finally: + cls.__abstractmethods__ = original + device.api = AristonAPI("user", "pass") + device.gw = GW + return device + + +class VelisHolidayTests(unittest.TestCase): + """Device wrapper delegates to the API holiday pair with date formatting.""" + + def test_holiday_end_date_format(self): + self.assertEqual( + AristonVelisDevice._create_holiday_end_date(date(2026, 9, 15)), + "2026-09-15T00:00:00", + ) + self.assertIsNone(AristonVelisDevice._create_holiday_end_date(None)) + + def test_async_set_velis_holiday_on_posts_date(self): + posts: list = [] + device = _device() + with patch( + "ariston.ariston_api.aiohttp.ClientSession", _fake_session_cls(posts) + ): + asyncio.run(device.async_set_velis_holiday(date(2026, 9, 15))) + + self.assertEqual(len(posts), 1) + self.assertEqual(posts[0]["path"], EXPECTED_URL) + self.assertEqual(posts[0]["json"], {"new": "2026-09-15T00:00:00"}) + + def test_async_set_velis_holiday_off_posts_null(self): + posts: list = [] + device = _device() + with patch( + "ariston.ariston_api.aiohttp.ClientSession", _fake_session_cls(posts) + ): + asyncio.run(device.async_set_velis_holiday(None)) + + self.assertEqual(len(posts), 1) + self.assertEqual(posts[0]["path"], EXPECTED_URL) + self.assertEqual(posts[0]["json"], {"new": None}) + + +if __name__ == "__main__": + unittest.main()