Skip to content
Draft
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
42 changes: 20 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -63,34 +63,32 @@ 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
)
```

`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 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
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

Expand Down
37 changes: 25 additions & 12 deletions pyintesishome/intesishome.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand All @@ -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

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -781,6 +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),
# 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:
Expand Down Expand Up @@ -816,6 +821,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,
Expand Down
101 changes: 100 additions & 1 deletion tests/test_pyintesishome.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import aiohttp
import pytest
import pytest_asyncio
from aiohttp import web

from pyintesishome import (
IHAuthenticationError,
Expand Down Expand Up @@ -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.

Expand All @@ -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()

Expand All @@ -1081,6 +1084,99 @@ 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_reuses_connections_only_within_idle_timeout(
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='<input name="signin[_csrf_token]" value="csrf">'
)
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
await asyncio.sleep(3.1)
assert await controller.set_temperature(MOCK_DEVICE_ID, 24) is True
finally:
await controller.stop()
assert values == ["220", "230", "240"]
assert len(logins) == 1
assert len(set(transports[:5])) == 1
assert transports[-1] is not transports[0]


@pytest.mark.asyncio
async def test_stop_clears_the_cached_portal_login(
cloud_controller,
Expand All @@ -1095,9 +1191,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
Expand Down