FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

fix: query IoT HomeKit separately to avoid legacy device timeouts by cheeseandcereal · Pull Request #1792 · python-kasa/python-kasa · GitHub

Repository navigation

Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .py  (3) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
6 changes: 6 additions & 0 deletions kasa/iot/iotdevice.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,12 @@ async def _modular_update(self, req: dict) -> None:
_LOGGER.debug("Module %s not supported, skipping", module)
continue

# Some legacy firmware times out if an unsupported HomeKit query
# follows another module in the same request.
if isinstance(module, HomeKit):
request_list.append(module.query())
continue

est_response_size += module.estimated_query_response_size
if est_response_size > self.max_device_response_size:
request_list.append(req)
Expand Down
84 changes: 83 additions & 1 deletion tests/iot/modules/test_homekit.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import asyncio
from unittest.mock import PropertyMock, patch

import pytest

from kasa import Module
from kasa.exceptions import TimeoutError
from kasa.iot import IotDevice
from kasa.iot.modules.homekit import HomeKit

from ...device_fixtures import device_iot
from ...device_fixtures import device_iot, get_device_for_fixture, get_fixture_info

HOMEKIT = "smartlife.iot.homekit"


@device_iot
Expand Down Expand Up @@ -57,3 +61,81 @@ def test_initialize_features_skips_when_no_data(dev: IotDevice) -> None:
homekit._initialize_features()
# Since there was no data, no features should be added
assert "homekit_setup_code" not in homekit._all_features


@pytest.mark.requires_dummy
@pytest.mark.parametrize("discovered", [True, False])
@pytest.mark.parametrize(
"fixture",
[
"EP10(US)_1.0_1.0.2.json",
"HS103(US)_2.1_1.1.4.json",
"KP115(US)_1.0_1.0.17.json",
"HS300(US)_1.0_1.0.21.json",
"EP25(US)_1.0_1.0.14.json",
],
)
async def test_homekit_update_with_order_sensitive_firmware(
mocker, fixture, discovered
):
"""Unsupported HomeKit following another module must not block updates."""
info = get_fixture_info(fixture, "IOT")
dev = await get_device_for_fixture(info, update_after_init=False)
if not discovered:
dev._last_update = {}
supported = HOMEKIT in info.data
query = dev.protocol.query

async def query_with_homekit(request):
if HOMEKIT in request and not supported:
if next(iter(request)) != HOMEKIT:
raise TimeoutError("HomeKit following another module times out")
return {HOMEKIT: {"err_code": -1, "err_msg": "module not support"}}
return await query(request)

query_mock = mocker.patch.object(
dev.protocol, "query", side_effect=query_with_homekit
)
for update in range(3):
query_mock.reset_mock()
await dev.update()
requests = [call.args[0] for call in query_mock.call_args_list]
homekit_requests = [request for request in requests if HOMEKIT in request]
assert len(homekit_requests) == (1 if supported or update == 0 else 0)
if homekit_requests:
assert homekit_requests == [{HOMEKIT: {"setup_info_get": {}}}]
assert any("system" in request for request in requests)
assert (Module.IotHomeKit in dev.modules) == supported
assert ("homekit_setup_code" in dev.features) == supported
if supported:
assert (
dev.features["homekit_setup_code"].value
== info.data[HOMEKIT]["setup_info_get"]["setup_code"]
)
if dev.has_emeter:
assert dev.modules[Module.Energy].current_consumption is not None


@pytest.mark.requires_dummy
@pytest.mark.parametrize("failure_module", [HOMEKIT, "schedule"])
@pytest.mark.parametrize("exception", [TimeoutError, asyncio.CancelledError])
async def test_homekit_update_propagates_errors(mocker, failure_module, exception):
"""Communication failures must propagate without disabling HomeKit."""
info = get_fixture_info("EP25(US)_1.0_1.0.14.json", "IOT")
dev = await get_device_for_fixture(info, update_after_init=False)
query = dev.protocol.query

async def failing_query(request):
if failure_module in request:
raise exception("Device unavailable")
return await query(request)

query_mock = mocker.patch.object(dev.protocol, "query", side_effect=failing_query)
with pytest.raises(exception, match="Device unavailable"):
await dev.update()
assert not dev.features

query_mock.side_effect = query
await dev.update()
assert Module.IotHomeKit in dev.modules
assert "homekit_setup_code" in dev.features
13 changes: 6 additions & 7 deletions tests/iot/test_iotdevice.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -99,19 +99,19 @@ async def test_invalid_connection(mocker: MockerFixture, dev: IotDevice) -> None

@has_emeter_iot
async def test_initial_update_emeter(dev: IotDevice, mocker: MockerFixture) -> None:
"""Test that the initial update performs second query if emeter is available."""
"""Test initial sysinfo, HomeKit, and batched energy queries."""
dev._last_update = {}
dev._legacy_features = set()
spy = mocker.spy(dev.protocol, "query")
await dev.update()
# Devices with small buffers may require 3 queries
expected_queries = 2 if dev.max_device_response_size > 4096 else 3
# Devices with small buffers require an additional batch.
expected_queries = 3 if dev.max_device_response_size > 4096 else 4
assert spy.call_count == expected_queries + len(dev.children)


@no_emeter_iot
async def test_initial_update_no_emeter(dev: IotDevice, mocker: MockerFixture) -> None:
"""Test that the initial update performs second query if emeter is available."""
"""Test initial sysinfo, HomeKit, and batched queries without energy data."""
dev._last_update = {}
dev._legacy_features = set()
spy = mocker.spy(dev.protocol, "query")
Expand All @@ -123,9 +123,8 @@ async def test_initial_update_no_emeter(dev: IotDevice, mocker: MockerFixture) -
if module.query():
child_calls += 1
break
# 2 parent are necessary as some devices crash on unexpected modules
# See #105, #120, #161
assert spy.call_count == 2 + child_calls
# Sysinfo and HomeKit each need a separate request from the normal batch.
assert spy.call_count == 3 + child_calls


@device_iot
Expand Down
Loading

Back | FazBrowse Home | New Git URL