From 99354e6ca612d68018a607b37c4a634e222eefcb Mon Sep 17 00:00:00 2001 From: Max Scheffler Date: Sun, 25 Oct 2026 13:47:53 +1100 Subject: [PATCH 1/2] Allow HTTPS-only commands and avoid reusing portal connections --- README.md | 41 +++++++-------- pyintesishome/intesishome.py | 36 ++++++++----- tests/test_pyintesishome.py | 98 +++++++++++++++++++++++++++++++++++- 3 files changed, 140 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 8cb86dc..f588cde 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ climate: - Instantiate the IntesisHome controller device with username and password for the accloud.intesis.com website. - `connect()` authenticates, loads state over HTTPS, and starts a poller. It does **not** open a socket, so start-up doesn't depend on a high port being reachable. - State comes from polling the same HTTPS endpoint the mobile app uses, every `poll_interval` seconds. -- **Commands are the only thing that opens the TCP socket**, because it is the one transport that accepts them. It is opened on demand and reopened by the next command whenever it has died. +- Commands try TCP first, then fall back to the HTTPS web portal. Set `use_tcp=False` to send commands directly over HTTPS without attempting the command socket. - While that socket is open it also **pushes status**, and polling stands down — so for the duration it is the source of state, not merely a bonus. - Callbacks to be notified of state updates can be added with the add_update_callback() method. - Use the `is_available` property to decide whether the device is usable — see below. @@ -63,6 +63,7 @@ controller = IntesisHome( "username", "password", use_socket=True, # default. False = never open a socket (read-only) + use_tcp=False, # HTTPS-only commands; omit to retain TCP-first behavior poll_interval=120, # seconds between HTTPS state polls ) ``` @@ -70,27 +71,23 @@ controller = IntesisHome( `poll_interval` is clamped to a 60 second floor to stay a good citizen of a third-party API; pass `0` or `None` to disable polling entirely. -#### Limitation: commands require the socket - -The cloud HTTPS endpoint appears to be read-only, so sending a command -(`set_temperature`, `set_power_on`, …) needs the socket. If it cannot be -established — for example on a network that blocks it outbound — the -controller still reports state correctly but is effectively **read-only**, and -the `set_*` methods return `False`. - -This is a limitation of what has been implemented, not a proven property of -the API. `examples/probe_cloud_set.py` establishes that `api.php/get/control` -has no write command: it dispatches solely on the `cmd` parameter, treats that -as a map of section names, and echoes unknown sections back as `{"": ""}` -stubs — identically for `set`, `setdatapointvalue`, `control` and a deliberately -invented name. Request bodies are ignored, and `POST /api.php/set/control` -returns HTTP 404. - -That result is scoped to one path. The API is path-based, and at least one -other path does perform writes: the official app activates a scene via -`POST /api.php/scenes/exe`. Since scene actions are `{deviceId, uid, value}` -triples — the same shape as a SET — a scene-based write path over HTTPS may -well be reachable. That has not been investigated yet. +#### HTTPS-only commands + +`use_tcp=False` skips TCP connection attempts while retaining HTTPS state +polling and commands through `accloud.intesis.com/device/setVal`. The portal +is currently supported only for `device_type="IntesisHome"`; other brands +return `False` for commands without a working TCP connection. + +The portal login is cached, but each request uses a fresh connection to avoid +disconnects when reusing the server's connections. Accepted commands schedule +one background refresh three seconds after the last command, allowing the +cloud state to catch up without delaying the command's return. Acceptance +does not prove that the physical device has applied the setting; polls confirm +the resulting state. Failed commands return `False`. + +`use_socket=False` retains its existing read-only meaning regardless of +`use_tcp`. These are library arguments; the HA integration must expose them +before they can be used in HA configuration. ### Library basic example diff --git a/pyintesishome/intesishome.py b/pyintesishome/intesishome.py index 979953b..a73c802 100644 --- a/pyintesishome/intesishome.py +++ b/pyintesishome/intesishome.py @@ -77,13 +77,14 @@ def __init__( device_type=DEVICE_INTESISHOME, *, use_socket: bool = True, + use_tcp: bool = True, poll_interval: int = 120, ): """Construct a cloud controller. - Commands are the only thing that *opens* the socket, since it is - the sole transport that accepts them - but while it is open it is - also the state source, and polling stands down for the duration. + Commands open the socket unless use_tcp=False selects HTTPS only. + While it is open it is also the state source, and polling stands + down for the duration. Outside that window state comes from polling the HTTP endpoint. The socket's lifetime is therefore command-scoped: opened on @@ -103,6 +104,8 @@ def __init__( :param use_socket: allow the socket to be opened for commands at all. False makes the controller read-only - it disables the web portal command fallback too, so nothing sends commands. + :param use_tcp: False sends commands directly through the HTTPS + portal (IntesisHome only). use_socket=False remains read-only. :param poll_interval: seconds between HTTP state polls. Clamped to a 60s floor to stay a good citizen of a third-party cloud API. Pass 0 or None to disable polling, which leaves state @@ -130,6 +133,7 @@ def __init__( self._auth_token = None self._controller_id = username self._use_socket = use_socket + self._use_tcp = use_tcp self._stopping = False if poll_interval and poll_interval < POLL_INTERVAL_MIN: _LOGGER.debug( @@ -171,6 +175,7 @@ def __init__( self._portal_session: aiohttp.ClientSession = None self._portal_user_id: str = None self._portal_lock = asyncio.Lock() + self._portal_refresh: asyncio.TimerHandle | None = None async def _parse_response(self, decoded_data): _LOGGER.debug("%s API Received: %s", self._device_type, decoded_data) @@ -352,6 +357,9 @@ async def stop(self): if not pending.future.done(): pending.future.set_result(False) self._pending_set_acks.clear() + if self._portal_refresh: + self._portal_refresh.cancel() + self._portal_refresh = None if self._portal_session: if not self._portal_session.closed: await self._portal_session.close() @@ -368,13 +376,11 @@ async def _ensure_socket(self) -> bool: Returns True if a usable socket exists afterwards. Called only from the command path - nothing else should be opening one. """ + if not self._use_socket or not self._use_tcp: + _LOGGER.debug("TCP commands disabled for %s", self._device_type) + return False if self._connected: return True - if not self._use_socket: - _LOGGER.warning( - "Cannot open a socket to %s: use_socket=False", self._device_type - ) - return False if self._connecting: return False @@ -686,11 +692,8 @@ async def _set_value(self, device_id, uid, value) -> bool: if await self._portal_set_value(device_id, uid, value): return True _LOGGER.warning( - "Cannot send SET to %s: no command socket. Commands need " - "outbound access to %s:%s", + "Cannot send SET to %s: command transports unavailable or disabled", self._device_type, - self._cmd_server, - self._cmd_server_port, ) return False @@ -781,6 +784,7 @@ async def _portal_login(self) -> None: self._portal_session = aiohttp.ClientSession( headers={"User-Agent": PORTAL_USER_AGENT}, timeout=aiohttp.ClientTimeout(total=PORTAL_TIMEOUT), + connector=aiohttp.TCPConnector(force_close=True), ) base = PORTAL_URL[self._device_type] async with self._portal_session.get(f"{base}/login") as resp: @@ -816,6 +820,14 @@ async def _portal_post_set(self, device_id, uid, value) -> bool: async with self._portal_session.post(url, headers=_PORTAL_XHR_HEADERS) as resp: body = (await resp.text()).strip() if body == "OK": + # The state endpoint can still return the old value immediately + # after OK. Coalesce command bursts into one delayed refresh. + if self._poll_interval: + if self._portal_refresh: + self._portal_refresh.cancel() + self._portal_refresh = self._event_loop.call_later( + 3, self._poll_wakeup.set + ) _LOGGER.info( "SET uid=%s value=%s sent via the web portal (no socket)", uid, diff --git a/tests/test_pyintesishome.py b/tests/test_pyintesishome.py index d93540c..d0a3f6a 100644 --- a/tests/test_pyintesishome.py +++ b/tests/test_pyintesishome.py @@ -9,6 +9,7 @@ import aiohttp import pytest import pytest_asyncio +from aiohttp import web from pyintesishome import ( IHAuthenticationError, @@ -1058,8 +1059,10 @@ def _mock_working_portal(mock_aioresponse): # noqa: F811 @pytest.mark.asyncio +@pytest.mark.parametrize("use_tcp", [True, False]) async def test_use_socket_false_does_not_use_the_portal_fallback( mock_aioresponse, # noqa: F811 + use_tcp, ): """use_socket=False means read-only, and the portal must not undo that. @@ -1070,7 +1073,7 @@ async def test_use_socket_false_does_not_use_the_portal_fallback( _mock_working_portal(mock_aioresponse) async with aiohttp.ClientSession() as session: controller = IntesisHome( - MOCK_USER, MOCK_PASS, websession=session, use_socket=False + MOCK_USER, MOCK_PASS, websession=session, use_socket=False, use_tcp=use_tcp ) await controller.connect() @@ -1081,6 +1084,96 @@ async def test_use_socket_false_does_not_use_the_portal_fallback( await controller.stop() +@pytest.mark.asyncio +async def test_https_only_commands_refresh_state_without_tcp(mock_aioresponse): # noqa: F811 + """HTTPS-only commands skip TCP and wake the existing state poller.""" + _mock_working_portal(mock_aioresponse) + async with aiohttp.ClientSession() as session: + controller = IntesisHome( + MOCK_USER, MOCK_PASS, websession=session, use_tcp=False + ) + try: + with patch("asyncio.open_connection") as open_connection: + await controller.connect() + callback = AsyncMock() + controller.add_update_callback(callback) + assert await controller.set_temperature(MOCK_DEVICE_ID, 22) is True + refresh = controller._portal_refresh + callback.assert_not_awaited() + assert await controller.set_temperature(MOCK_DEVICE_ID, 23) is True + assert refresh.cancelled() + await wait_until(lambda: callback.await_count > 0) + assert callback.await_count == 2 # one update for each account device + assert controller.is_available + assert not controller.is_connected + open_connection.assert_not_called() + finally: + await controller.stop() + + +@pytest.mark.asyncio +async def test_https_only_failure_does_not_attempt_tcp(mock_aioresponse): # noqa: F811 + """A rejected portal login fails without falling back to disabled TCP.""" + mock_aioresponse.get(f"{PORTAL_URL[DEVICE_INTESISHOME]}/login", body="maintenance") + async with aiohttp.ClientSession() as session: + controller = IntesisHome( + MOCK_USER, MOCK_PASS, websession=session, use_tcp=False + ) + try: + with patch("asyncio.open_connection") as open_connection: + assert await controller.set_temperature(MOCK_DEVICE_ID, 22) is False + assert not controller._poll_wakeup.is_set() + open_connection.assert_not_called() + finally: + await controller.stop() + + +@pytest.mark.asyncio +async def test_portal_keeps_login_without_reusing_connections( + aiohttp_server, + mock_aioresponse, # noqa: F811 +): + """Exercise real HTTP connections and cookies across consecutive commands.""" + transports, logins, values = [], [], [] + + async def portal(request): + transports.append(request.transport) + if request.path == "/login": + if request.method == "GET": + return web.Response( + text='' + ) + logins.append(await request.post()) + response = web.Response() + response.set_cookie("session", "test-login") + return response + if request.cookies.get("session") != "test-login": + return web.Response(status=403) + if request.path == "/panel/headers": + return web.Response(text="userId=4242,") + values.append(request.query["value"]) + return web.Response(text="OK") + + app = web.Application() + app.router.add_route("*", "/{path:.*}", portal) + server = await aiohttp_server(app) + base = str(server.make_url("")).replace("127.0.0.1", "localhost").rstrip("/") + mock_aioresponse.stop() + with patch.dict(PORTAL_URL, {DEVICE_INTESISHOME: base}): + async with aiohttp.ClientSession() as session: + controller = IntesisHome( + MOCK_USER, MOCK_PASS, websession=session, use_tcp=False + ) + try: + assert await controller.set_temperature(MOCK_DEVICE_ID, 22) is True + assert await controller.set_temperature(MOCK_DEVICE_ID, 23) is True + finally: + await controller.stop() + assert values == ["220", "230"] + assert len(logins) == 1 + assert len(transports) == len(set(transports)) == 5 + + @pytest.mark.asyncio async def test_stop_clears_the_cached_portal_login( cloud_controller, @@ -1095,9 +1188,12 @@ async def test_stop_clears_the_cached_portal_login( assert await cloud_controller._set_value(MOCK_DEVICE_ID, 9, 220) is True assert cloud_controller._portal_user_id == "4242" + refresh = cloud_controller._portal_refresh await cloud_controller.stop() assert cloud_controller._portal_session is None + assert refresh.cancelled() + assert cloud_controller._portal_refresh is None assert cloud_controller._portal_user_id is None # The next SET must log in again rather than post through the session From 064f0ece2c40a3f7c390aa75af595739a353f465 Mon Sep 17 00:00:00 2001 From: Max Scheffler Date: Sun, 25 Oct 2026 18:20:55 +1100 Subject: [PATCH 2/2] Reuse portal connections within a short idle timeout --- README.md | 5 +++-- pyintesishome/intesishome.py | 3 ++- tests/test_pyintesishome.py | 9 ++++++--- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index f588cde..94a6e69 100644 --- a/README.md +++ b/README.md @@ -78,8 +78,9 @@ polling and commands through `accloud.intesis.com/device/setVal`. The portal is currently supported only for `device_type="IntesisHome"`; other brands return `False` for commands without a working TCP connection. -The portal login is cached, but each request uses a fresh connection to avoid -disconnects when reusing the server's connections. Accepted commands schedule +The portal login is cached and consecutive commands reuse the connection. +Connections idle for three seconds are retired before the portal closes them. +Accepted commands schedule one background refresh three seconds after the last command, allowing the cloud state to catch up without delaying the command's return. Acceptance does not prove that the physical device has applied the setting; polls confirm diff --git a/pyintesishome/intesishome.py b/pyintesishome/intesishome.py index a73c802..35c37b7 100644 --- a/pyintesishome/intesishome.py +++ b/pyintesishome/intesishome.py @@ -784,7 +784,8 @@ async def _portal_login(self) -> None: self._portal_session = aiohttp.ClientSession( headers={"User-Agent": PORTAL_USER_AGENT}, timeout=aiohttp.ClientTimeout(total=PORTAL_TIMEOUT), - connector=aiohttp.TCPConnector(force_close=True), + # Reuse command bursts, but retire before the portal's idle close. + connector=aiohttp.TCPConnector(keepalive_timeout=3), ) base = PORTAL_URL[self._device_type] async with self._portal_session.get(f"{base}/login") as resp: diff --git a/tests/test_pyintesishome.py b/tests/test_pyintesishome.py index d0a3f6a..867fb69 100644 --- a/tests/test_pyintesishome.py +++ b/tests/test_pyintesishome.py @@ -1129,7 +1129,7 @@ async def test_https_only_failure_does_not_attempt_tcp(mock_aioresponse): # noq @pytest.mark.asyncio -async def test_portal_keeps_login_without_reusing_connections( +async def test_portal_reuses_connections_only_within_idle_timeout( aiohttp_server, mock_aioresponse, # noqa: F811 ): @@ -1167,11 +1167,14 @@ async def portal(request): try: assert await controller.set_temperature(MOCK_DEVICE_ID, 22) is True assert await controller.set_temperature(MOCK_DEVICE_ID, 23) is True + await asyncio.sleep(3.1) + assert await controller.set_temperature(MOCK_DEVICE_ID, 24) is True finally: await controller.stop() - assert values == ["220", "230"] + assert values == ["220", "230", "240"] assert len(logins) == 1 - assert len(transports) == len(set(transports)) == 5 + assert len(set(transports[:5])) == 1 + assert transports[-1] is not transports[0] @pytest.mark.asyncio