Skip to content

Generalize smartdevice child support #775

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Feb 22, 2024
Merged
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
22 changes: 18 additions & 4 deletions kasa/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -582,9 +582,14 @@ async def state(ctx, dev: Device):
echo(f"\tPort: {dev.port}")
echo(f"\tDevice state: {dev.is_on}")
if dev.is_strip:
echo("\t[bold]== Plugs ==[/bold]")
for plug in dev.children: # type: ignore
echo(f"\t* Socket '{plug.alias}' state: {plug.is_on} since {plug.on_since}")
echo("\t[bold]== Children ==[/bold]")
for child in dev.children:
echo(f"\t* {child.alias} ({child.model}, {child.device_type})")
for feat in child.features.values():
try:
echo(f"\t\t{feat.name}: {feat.value}")
except Exception as ex:
echo(f"\t\t{feat.name}: got exception (%s)" % ex)
echo()

echo("\t[bold]== Generic information ==[/bold]")
Expand Down Expand Up @@ -665,13 +670,22 @@ async def raw_command(ctx, dev: Device, module, command, parameters):
@cli.command(name="command")
@pass_dev
@click.option("--module", required=False, help="Module for IOT protocol.")
@click.option("--child", required=False, help="Child ID for controlling sub-devices")
@click.argument("command")
@click.argument("parameters", default=None, required=False)
async def cmd_command(dev: Device, module, command, parameters):
async def cmd_command(dev: Device, module, child, command, parameters):
"""Run a raw command on the device."""
if parameters is not None:
parameters = ast.literal_eval(parameters)

if child:
# The way child devices are accessed requires a ChildDevice to
# wrap the communications. Doing this properly would require creating
# a common interfaces for both IOT and SMART child devices.
# As a stop-gap solution, we perform an update instead.
await dev.update()
dev = dev.get_child_device(child)

if isinstance(dev, IotDevice):
res = await dev._query_helper(module, command, parameters)
elif isinstance(dev, SmartDevice):
Expand Down
10 changes: 8 additions & 2 deletions kasa/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Dict, List, Optional, Sequence, Union
from typing import Any, Dict, List, Mapping, Optional, Sequence, Union

from .credentials import Credentials
from .device_type import DeviceType
Expand Down Expand Up @@ -71,6 +71,8 @@ def __init__(

self.modules: Dict[str, Any] = {}
self._features: Dict[str, Feature] = {}
self._parent: Optional["Device"] = None
self._children: Mapping[str, "Device"] = {}

@staticmethod
async def connect(
Expand Down Expand Up @@ -182,9 +184,13 @@ async def _raw_query(self, request: Union[str, Dict]) -> Any:
return await self.protocol.query(request=request)

@property
@abstractmethod
def children(self) -> Sequence["Device"]:
"""Returns the child devices."""
return list(self._children.values())

def get_child_device(self, id_: str) -> "Device":
"""Return child device by its ID."""
return self._children[id_]

@property
@abstractmethod
Expand Down
1 change: 1 addition & 0 deletions kasa/device_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class DeviceType(Enum):
StripSocket = "stripsocket"
Dimmer = "dimmer"
LightStrip = "lightstrip"
Sensor = "sensor"
Unknown = "unknown"

@staticmethod
Expand Down
20 changes: 3 additions & 17 deletions kasa/iot/iotdevice.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import inspect
import logging
from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional, Sequence, Set
from typing import Any, Dict, List, Mapping, Optional, Sequence, Set

from ..device import Device, WifiNetwork
from ..deviceconfig import DeviceConfig
Expand Down Expand Up @@ -183,19 +183,14 @@ def __init__(
super().__init__(host=host, config=config, protocol=protocol)

self._sys_info: Any = None # TODO: this is here to avoid changing tests
self._children: Sequence["IotDevice"] = []
self._supported_modules: Optional[Dict[str, IotModule]] = None
self._legacy_features: Set[str] = set()
self._children: Mapping[str, "IotDevice"] = {}

@property
def children(self) -> Sequence["IotDevice"]:
"""Return list of children."""
return self._children

@children.setter
def children(self, children):
"""Initialize from a list of children."""
self._children = children
return list(self._children.values())

def add_module(self, name: str, module: IotModule):
"""Register a module."""
Expand Down Expand Up @@ -408,15 +403,6 @@ def model(self) -> str:
sys_info = self._sys_info
return str(sys_info["model"])

@property
def has_children(self) -> bool:
"""Return true if the device has children devices."""
# Ideally we would check for the 'child_num' key in sys_info,
# but devices that speak klap do not populate this key via
# update_from_discover_info so we check for the devices
# we know have children instead.
return self.is_strip

@property # type: ignore
def alias(self) -> Optional[str]:
"""Return device name (alias)."""
Expand Down
8 changes: 5 additions & 3 deletions kasa/iot/iotstrip.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,12 @@ async def update(self, update_children: bool = True):
if not self.children:
children = self.sys_info["children"]
_LOGGER.debug("Initializing %s child sockets", len(children))
self.children = [
IotStripPlug(self.host, parent=self, child_id=child["id"])
self._children = {
f"{self.mac}_{child['id']}": IotStripPlug(
self.host, parent=self, child_id=child["id"]
)
for child in children
]
}

if update_children and self.has_emeter:
for plug in self.children:
Expand Down
12 changes: 11 additions & 1 deletion kasa/smart/modules/childdevicemodule.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
"""Implementation for child devices."""
from typing import Dict

from ..smartmodule import SmartModule


class ChildDeviceModule(SmartModule):
"""Implementation for child devices."""

REQUIRED_COMPONENT = "child_device"
QUERY_GETTER_NAME = "get_child_device_list"

def query(self) -> Dict:
"""Query to execute during the update cycle."""
# TODO: There is no need to fetch the component list every time,
# so this should be optimized only for the init.
return {
"get_child_device_list": None,
"get_child_device_component_list": None,
}
37 changes: 29 additions & 8 deletions kasa/smart/smartchilddevice.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
"""Child device implementation."""
import logging
from typing import Optional

from ..device_type import DeviceType
from ..deviceconfig import DeviceConfig
from ..smartprotocol import SmartProtocol, _ChildProtocolWrapper
from .smartdevice import SmartDevice

_LOGGER = logging.getLogger(__name__)


class SmartChildDevice(SmartDevice):
"""Presentation of a child device.
Expand All @@ -16,23 +19,41 @@ class SmartChildDevice(SmartDevice):
def __init__(
self,
parent: SmartDevice,
child_id: str,
info,
component_info,
config: Optional[DeviceConfig] = None,
protocol: Optional[SmartProtocol] = None,
) -> None:
super().__init__(parent.host, config=parent.config, protocol=parent.protocol)
self._parent = parent
self._id = child_id
self.protocol = _ChildProtocolWrapper(child_id, parent.protocol)
self._device_type = DeviceType.StripSocket
self._update_internal_state(info)
self._components = component_info
self._id = info["device_id"]
self.protocol = _ChildProtocolWrapper(self._id, parent.protocol)

async def update(self, update_children: bool = True):
"""Noop update. The parent updates our internals."""

def update_internal_state(self, info):
"""Set internal state for the child."""
# TODO: cleanup the _last_update, _sys_info, _info, _data mess.
self._last_update = self._sys_info = self._info = info
@classmethod
async def create(cls, parent: SmartDevice, child_info, child_components):
"""Create a child device based on device info and component listing."""
child: "SmartChildDevice" = cls(parent, child_info, child_components)
await child._initialize_modules()
await child._initialize_features()
return child

@property
def device_type(self) -> DeviceType:
"""Return child device type."""
child_device_map = {
"plug.powerstrip.sub-plug": DeviceType.Plug,
"subg.trigger.temp-hmdt-sensor": DeviceType.Sensor,
}
dev_type = child_device_map.get(self.sys_info["category"])
if dev_type is None:
_LOGGER.warning("Unknown child device type, please open issue ")
dev_type = DeviceType.Unknown
return dev_type

def __repr__(self):
return f"<ChildDevice {self.alias} of {self._parent}>"
Loading