Detect offline hub children and fail fast on writes to them (#1830)
Some checks failed
CI / Perform Lint Checks (3.15) (push) Has been cancelled
CodeQL Checks / Analyze (python) (push) Has been cancelled
CI / Python 3.11 on macos-latest (push) Has been cancelled
CI / Python 3.12 on macos-latest (push) Has been cancelled
CI / Python 3.13 on macos-latest (push) Has been cancelled
CI / Python 3.14 on macos-latest (push) Has been cancelled
CI / Python 3.15 on macos-latest (push) Has been cancelled
CI / Python 3.11 on ubuntu-latest (push) Has been cancelled
CI / Python 3.12 on ubuntu-latest (push) Has been cancelled
CI / Python 3.13 on ubuntu-latest (push) Has been cancelled
CI / Python 3.14 on ubuntu-latest (push) Has been cancelled
CI / Python 3.15 on ubuntu-latest (push) Has been cancelled
CI / Python 3.11 on windows-latest (push) Has been cancelled
CI / Python 3.12 on windows-latest (push) Has been cancelled
CI / Python 3.13 on windows-latest (push) Has been cancelled
CI / Python 3.14 on windows-latest (push) Has been cancelled
CI / Python 3.15 on windows-latest (push) Has been cancelled
Stale / stale (push) Has been cancelled

Hubs keep reporting for children they have lost contact with, so callers
see stale values as if they were live. Trying to write to such devices
fail after timeouts with a generic error.
This PR exposes the offline/online information as reported by the hub,
and refuses writes to unreachable child devices without waiting for
device errors.

In details:
- Add new API: `Device.is_available`; hub children report unavailable
when the hub marks them offline or no longer lists them.
- New feature `available` for child devices to make it visible to the
CLI.
- Refuse writes to unavailable children with the new
`DeviceUnavailableError` instead of waiting for the hub to time out.
This commit is contained in:
Teemu R.
2026-11-01 18:18:03 +01:00
committed by GitHub
parent 81243ed87f
commit a68f2b3304
13 changed files with 229 additions and 16 deletions

View File

@@ -30,6 +30,7 @@ from kasa.emeterstatus import EmeterStatus
from kasa.exceptions import (
AuthenticationError,
DeviceError,
DeviceUnavailableError,
KasaException,
TimeoutError,
UnsupportedDeviceError,
@@ -68,6 +69,7 @@ __all__ = [
"KasaException",
"AuthenticationError",
"DeviceError",
"DeviceUnavailableError",
"UnsupportedDeviceError",
"TimeoutError",
"Credentials",

View File

@@ -34,8 +34,12 @@ async def hub(dev: Device):
@pass_dev
async def hub_list(dev: Device):
"""List hub paired child devices."""
for c in dev.children:
echo(f"{c.device_id}: {c}")
echo(f"{'INDEX':<5} {'DEVICE ID':<40} {'MODEL':<9} {'AVAILABLE':<9} ALIAS")
for index, child in enumerate(dev.children):
echo(
f"{index:<5} {child.device_id:<40} {child.model:<9} "
f"{child.is_available!s:<9} {child.alias}"
)
@hub.command(name="supported")

View File

@@ -277,6 +277,11 @@ class Device(ABC):
"""Return True if device is off."""
return not self.is_on
@property
def is_available(self) -> bool:
"""Return False if the device is known to be unreachable."""
return True
@abstractmethod
async def turn_on(self, **kwargs) -> dict:
"""Turn on the device."""

View File

@@ -55,6 +55,10 @@ class AuthenticationError(DeviceError):
"""Base exception for device authentication errors."""
class DeviceUnavailableError(DeviceError):
"""Exception for commands to an unreachable device."""
class _RetryableError(DeviceError):
"""Retryable exception for device errors."""

View File

@@ -9,6 +9,8 @@ from typing import Any
from ..device import DeviceInfo
from ..device_type import DeviceType
from ..deviceconfig import DeviceConfig
from ..exceptions import DeviceUnavailableError
from ..feature import Feature
from ..protocols.smartprotocol import SmartProtocol, _ChildProtocolWrapper
from .smartdevice import ComponentsRaw, SmartDevice
from .smartmodule import SmartModule
@@ -49,6 +51,7 @@ class SmartChildDevice(SmartDevice):
_protocol = protocol or _ChildProtocolWrapper(self._id, parent.protocol)
super().__init__(parent.host, config=parent.config, protocol=_protocol)
self._parent = parent
self._was_available = True
self._update_internal_state(info)
self._components_raw = component_info_raw
self._components = self._parse_components(self._components_raw)
@@ -83,6 +86,10 @@ class SmartChildDevice(SmartDevice):
Internal implementation to allow patching of public update in the cli
or test framework.
"""
if (available := self.is_available) != self._was_available:
self._was_available = available
_LOGGER.debug("%s (%s) available: %s", self.alias, self._id, available)
now = time.monotonic()
module_queries: list[SmartModule] = []
req: dict[str, Any] = {}
@@ -160,6 +167,34 @@ class SmartChildDevice(SmartDevice):
return self._device_type
@property
def is_available(self) -> bool:
"""Return False if the hub reports the device offline or no longer lists it."""
listed = self._parent is None or self._id in self._parent._children
return listed and self._info.get("status") != "offline"
async def _initialize_features(self) -> None:
"""Initialize device features."""
await super()._initialize_features()
if "status" in self._info:
self._add_feature(
Feature(
self,
id="available",
name="Available",
attribute_getter="is_available",
category=Feature.Category.Info,
type=Feature.Type.BinarySensor,
)
)
async def _query_helper(self, method: str, params: dict | None = None) -> dict:
# Fail fast on writes, the hub rejects them only after a timeout.
if not method.startswith("get") and not self.is_available:
raise DeviceUnavailableError(f"{self.alias} is not available")
return await super()._query_helper(method, params)
def __repr__(self) -> str:
if not self._parent:
return f"<{self.device_type}(child) without parent>"

View File

@@ -730,7 +730,7 @@ class SmartDevice(Device):
See :meth:`is_on`.
"""
return await self.protocol.query({"set_device_info": {"device_on": on}})
return await self._query_helper("set_device_info", {"device_on": on})
async def turn_on(self, **kwargs: Any) -> dict:
"""Turn on the device."""
@@ -833,8 +833,8 @@ class SmartDevice(Device):
async def set_alias(self, alias: str) -> dict:
"""Set the device name (alias)."""
return await self.protocol.query(
{"set_device_info": {"nickname": base64.b64encode(alias.encode()).decode()}}
return await self._query_helper(
"set_device_info", {"nickname": base64.b64encode(alias.encode()).decode()}
)
async def reboot(self, delay: int = 1) -> None:
@@ -843,14 +843,14 @@ class SmartDevice(Device):
Note that giving a delay of zero causes this to block,
as the device reboots immediately without responding to the call.
"""
await self.protocol.query({"device_reboot": {"delay": delay}})
await self._query_helper("device_reboot", {"delay": delay})
async def factory_reset(self) -> None:
"""Reset device back to factory settings.
Note, this does not downgrade the firmware.
"""
await self.protocol.query("device_reset")
await self._query_helper("device_reset")
@property
def device_type(self) -> DeviceType:

View File

@@ -85,6 +85,12 @@ class SmartCamChild(SmartChildDevice, SmartCamDevice):
# devices
self._info = self._map_child_info_from_parent(info)
@property
def is_available(self) -> bool:
"""Return False if the hub reports the camera offline or no longer lists it."""
# Camera children report "online" instead of an "offline" status.
return super().is_available and self._info.get("online") is not False
@property
def device_type(self) -> DeviceType:
"""Return the device type."""

View File

@@ -215,7 +215,7 @@ class SmartCamDevice(SmartDevice):
async def _query_setter_helper(
self, method: str, module: str, section: str, params: dict | None = None
) -> dict:
res = await self.protocol.query({method: {module: {section: params}}})
res = await self._query_helper(method, {module: {section: params}})
return res
@@ -293,10 +293,8 @@ class SmartCamDevice(SmartDevice):
async def set_alias(self, alias: str) -> dict:
"""Set the device name (alias)."""
return await self.protocol.query(
{
"setDeviceAlias": {"system": {"sys": {"dev_alias": alias}}},
}
return await self._query_helper(
"setDeviceAlias", {"system": {"sys": {"dev_alias": alias}}}
)
@property