Skip to content

Initial support for hubs and sensors #763

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

Closed
wants to merge 2 commits into from
Closed
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
20 changes: 16 additions & 4 deletions kasa/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,9 +558,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.values():
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 @@ -641,13 +646,20 @@ 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:
echo(f"Selecting child {child} from {dev}")
# TODO: Update required to initialize children
await dev.update()
dev = dev._children[child]

if isinstance(dev, IotDevice):
res = await dev._query_helper(module, command, parameters)
elif isinstance(dev, SmartDevice):
Expand Down
3 changes: 2 additions & 1 deletion kasa/device_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
BaseProtocol,
BaseTransport,
)
from .smart import SmartBulb, SmartPlug
from .smart import SmartBulb, SmartDevice, SmartPlug
from .smartprotocol import SmartProtocol
from .xortransport import XorTransport

Expand Down Expand Up @@ -138,6 +138,7 @@ def get_device_class_from_family(device_type: str) -> Optional[Type[Device]]:
"SMART.TAPOPLUG": SmartPlug,
"SMART.TAPOBULB": SmartBulb,
"SMART.TAPOSWITCH": SmartBulb,
"SMART.TAPOHUB": SmartDevice,
"SMART.KASAPLUG": SmartPlug,
"SMART.KASASWITCH": SmartBulb,
"IOT.SMARTPLUGSWITCH": IotPlug,
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
1 change: 1 addition & 0 deletions kasa/deviceconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ class DeviceFamilyType(Enum):
SmartTapoPlug = "SMART.TAPOPLUG"
SmartTapoBulb = "SMART.TAPOBULB"
SmartTapoSwitch = "SMART.TAPOSWITCH"
SmartTapoHub = "SMART.TAPOHUB"


def _dataclass_from_dict(klass, in_val):
Expand Down
9 changes: 9 additions & 0 deletions kasa/smart/modules/__init__.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,27 @@
"""Modules for SMART devices."""
from .autooffmodule import AutoOffModule
from .battery import BatterySensor
from .childdevicemodule import ChildDeviceModule
from .cloudmodule import CloudModule
from .devicemodule import DeviceModule
from .energymodule import EnergyModule
from .ledmodule import LedModule
from .lighttransitionmodule import LightTransitionModule
from .humidity import HumiditySensor
from .reportmodule import ReportModule
from .temperature import TemperatureSensor
from .timemodule import TimeModule

__all__ = [
"AlarmModule",
"TimeModule",
"EnergyModule",
"DeviceModule",
"ChildDeviceModule",
"BatterySensor",
"HumiditySensor",
"TemperatureSensor",
"ReportModule",
"AutoOffModule",
"LedModule",
"CloudModule",
Expand Down
87 changes: 87 additions & 0 deletions kasa/smart/modules/alarmmodule.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"""Implementation of alarm module."""
from typing import TYPE_CHECKING, Dict, List, Optional

from ...feature import Feature, FeatureType
from ..smartmodule import SmartModule

if TYPE_CHECKING:
from ..smartdevice import SmartDevice


class AlarmModule(SmartModule):
"""Implementation of alarm module."""

REQUIRED_COMPONENT = "alarm"

def query(self) -> Dict:
"""Query to execute during the update cycle."""
return {
"get_alarm_configure": None,
"get_support_alarm_type_list": None, # This should be needed only once
}

def __init__(self, device: "SmartDevice", module: str):
super().__init__(device, module)
self._add_feature(
Feature(
device,
"Alarm",
container=self,
attribute_getter="active",
icon="mdi:bell",
type=FeatureType.BinarySensor,
)
)
self._add_feature(
Feature(
device,
"Alarm source",
container=self,
attribute_getter="source",
icon="mdi:bell",
)
)
self._add_feature(
Feature(
device, "Alarm sound", container=self, attribute_getter="alarm_sound"
)
)
self._add_feature(
Feature(
device, "Alarm volume", container=self, attribute_getter="alarm_volume"
)
)

@property
def alarm_sound(self):
"""Return current alarm sound."""
return self.data["get_alarm_configure"]["type"]

@property
def alarm_sounds(self) -> List[str]:
"""Return list of available alarm sounds."""
return self.data["get_support_alarm_type_list"]["alarm_type_list"]

@property
def alarm_volume(self):
"""Return alarm volume."""
return self.data["get_alarm_configure"]["volume"]

@property
def active(self) -> bool:
"""Return true if alarm is active."""
return self._device.sys_info["in_alarm"]

@property
def source(self) -> Optional[str]:
"""Return the alarm cause."""
src = self._device.sys_info["in_alarm_source"]
return src if src else None

async def play(self):
"""Play alarm."""
return self.call("play_alarm")

async def stop(self):
"""Stop alarm."""
return self.call("stop_alarm")
47 changes: 47 additions & 0 deletions kasa/smart/modules/battery.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""Implementation of battery module."""
from typing import TYPE_CHECKING

from ...feature import Feature, FeatureType
from ..smartmodule import SmartModule

if TYPE_CHECKING:
from ..smartdevice import SmartDevice


class BatterySensor(SmartModule):
"""Implementation of battery module."""

REQUIRED_COMPONENT = "battery_detect"
QUERY_GETTER_NAME = "get_battery_detect_info"

def __init__(self, device: "SmartDevice", module: str):
super().__init__(device, module)
self._add_feature(
Feature(
device,
"Battery level",
container=self,
attribute_getter="battery",
icon="mdi:battery",
)
)
self._add_feature(
Feature(
device,
"Battery low",
container=self,
attribute_getter="battery_low",
icon="mdi:alert",
type=FeatureType.BinarySensor,
)
)

@property
def battery(self):
"""Return battery level."""
return self._device.sys_info["battery_percentage"]

@property
def battery_low(self):
"""Return True if battery is low."""
return self._device.sys_info["at_low_battery"]
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,
}
47 changes: 47 additions & 0 deletions kasa/smart/modules/humidity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""Implementation of humidity module."""
from typing import TYPE_CHECKING

from ...feature import Feature, FeatureType
from ..smartmodule import SmartModule

if TYPE_CHECKING:
from ..smartdevice import SmartDevice


class HumiditySensor(SmartModule):
"""Implementation of humidity module."""

REQUIRED_COMPONENT = "humidity"
QUERY_GETTER_NAME = "get_comfort_humidity_config"

def __init__(self, device: "SmartDevice", module: str):
super().__init__(device, module)
self._add_feature(
Feature(
device,
"Humidity",
container=self,
attribute_getter="humidity",
icon="mdi:water-percent",
)
)
self._add_feature(
Feature(
device,
"Humidity warning",
container=self,
attribute_getter="humidity_warning",
type=FeatureType.BinarySensor,
icon="mdi:alert",
)
)

@property
def humidity(self):
"""Return current humidity in percentage."""
return self._device.sys_info["current_humidity"]

@property
def humidity_warning(self) -> bool:
"""Return true if humidity is outside of the wanted range."""
return self._device.sys_info["current_humidity_exception"] != 0
31 changes: 31 additions & 0 deletions kasa/smart/modules/reportmodule.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""Implementation of report module."""
from typing import TYPE_CHECKING

from ...feature import Feature
from ..smartmodule import SmartModule

if TYPE_CHECKING:
from ..smartdevice import SmartDevice


class ReportModule(SmartModule):
"""Implementation of report module."""

REQUIRED_COMPONENT = "report_mode"
QUERY_GETTER_NAME = "get_report_mode"

def __init__(self, device: "SmartDevice", module: str):
super().__init__(device, module)
self._add_feature(
Feature(
device,
"Report interval",
container=self,
attribute_getter="report_interval",
)
)

@property
def report_interval(self):
"""Reporting interval of a sensor device."""
return self._device.sys_info["report_interval"]
57 changes: 57 additions & 0 deletions kasa/smart/modules/temperature.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""Implementation of temperature module."""
from typing import TYPE_CHECKING, Literal

from ...feature import Feature, FeatureType
from ..smartmodule import SmartModule

if TYPE_CHECKING:
from ..smartdevice import SmartDevice


class TemperatureSensor(SmartModule):
"""Implementation of temperature module."""

REQUIRED_COMPONENT = "humidity"
QUERY_GETTER_NAME = "get_comfort_temp_config"

def __init__(self, device: "SmartDevice", module: str):
super().__init__(device, module)
self._add_feature(
Feature(
device,
"Temperature",
container=self,
attribute_getter="temperature",
icon="mdi:thermometer",
)
)
self._add_feature(
Feature(
device,
"Temperature warning",
container=self,
attribute_getter="temperature_warning",
type=FeatureType.BinarySensor,
icon="mdi:alert",
)
)
# TODO: use temperature_unit for feature creation

@property
def temperature(self):
"""Return current humidity in percentage."""
return self._device.sys_info["current_temp"]

@property
def temperature_warning(self) -> bool:
"""Return True if humidity is outside of the wanted range."""
return self._device.sys_info["current_temp_exception"] != 0

@property
def temperature_unit(self):
"""Return current temperature unit."""
return self._device.sys_info["temp_unit"]

async def set_temperature_unit(self, unit: Literal["celsius", "fahrenheit"]):
"""Set the device temperature unit."""
return await self.call("set_temperature_unit", {"temp_unit": unit})
Loading