Skip to content
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
58 changes: 44 additions & 14 deletions kasa/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
DeviceFamilyType,
Discover,
EncryptType,
Feature,
KasaException,
UnsupportedDeviceError,
)
Expand Down Expand Up @@ -583,6 +584,41 @@ async def sysinfo(dev):
return dev.sys_info


def _echo_features(
features: dict[str, Feature], title: str, category: Feature.Category | None = None
):
"""Print out a listing of features and their values."""
if category is not None:
features = {
id_: feat for id_, feat in features.items() if feat.category == category
}

if not features:
return
echo(f"[bold]{title}[/bold]")
for _, feat in features.items():
try:
echo(f"\t{feat}")
except Exception as ex:
echo(f"\t{feat.name} ({feat.id}): got exception (%s)" % ex)


def _echo_all_features(features, title_prefix=None):
"""Print out all features by category."""
if title_prefix is not None:
echo(f"[bold]\n\t == {title_prefix} ==[/bold]")
_echo_features(
features, title="\n\t== Primary features ==", category=Feature.Category.Primary
)
_echo_features(
features, title="\n\t== Information ==", category=Feature.Category.Info
)
_echo_features(
features, title="\n\t== Configuration ==", category=Feature.Category.Config
)
_echo_features(features, title="\n\t== Debug ==", category=Feature.Category.Debug)


@cli.command()
@pass_dev
@click.pass_context
Expand All @@ -595,15 +631,13 @@ async def state(ctx, dev: Device):
echo(f"\tPort: {dev.port}")
echo(f"\tDevice state: {dev.is_on}")
if dev.children:
echo("\t[bold]== Children ==[/bold]")
echo("\t== Children ==")
for child in dev.children:
echo(f"\t* {child.alias} ({child.model}, {child.device_type})")
for id_, feat in child.features.items():
try:
unit = f" {feat.unit}" if feat.unit else ""
echo(f"\t\t{feat.name} ({id_}): {feat.value}{unit}")
except Exception as ex:
echo(f"\t\t{feat.name}: got exception (%s)" % ex)
_echo_all_features(
child.features,
title_prefix=f"{child.alias} ({child.model}, {child.device_type})",
)

echo()

echo("\t[bold]== Generic information ==[/bold]")
Expand All @@ -613,19 +647,15 @@ async def state(ctx, dev: Device):
echo(f"\tMAC (rssi): {dev.mac} ({dev.rssi})")
echo(f"\tLocation: {dev.location}")

echo("\n\t[bold]== Device-specific information == [/bold]")
for id_, feature in dev.features.items():
unit = f" {feature.unit}" if feature.unit else ""
echo(f"\t{feature.name} ({id_}): {feature.value}{unit}")
_echo_all_features(dev.features)

echo("\n\t[bold]== Modules ==[/bold]")
for module in dev.modules.values():
echo(f"\t[green]+ {module}[/green]")

if verbose:
echo("\n\t[bold]== Verbose information ==[/bold]")
echo("\n\t[bold]== Protocol information ==[/bold]")
echo(f"\tCredentials hash: {dev.credentials_hash}")
echo(f"\tDevice ID: {dev.device_id}")
echo()
_echo_discovery_info(dev._discovery_info)
return dev.internal_state
Expand Down
8 changes: 4 additions & 4 deletions kasa/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,10 +318,10 @@ def features(self) -> dict[str, Feature]:

def _add_feature(self, feature: Feature):
"""Add a new feature to the device."""
desc_name = feature.name.lower().replace(" ", "_")
if desc_name in self._features:
raise KasaException("Duplicate feature name %s" % desc_name)
self._features[desc_name] = feature
if feature.id in self._features:
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved the id generation into Feature to allow overriding it, which we may need to do to keep backwards compat with homeassistant's emeter sensors.

raise KasaException("Duplicate feature id %s" % feature.id)
assert feature.id is not None # TODO: hack for typing # noqa: S101
self._features[feature.id] = feature

@property
@abstractmethod
Expand Down
44 changes: 44 additions & 0 deletions kasa/feature.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from .device import Device


# TODO: This is only useful for Feature, so maybe move to Feature.Type?
class FeatureType(Enum):
"""Type to help decide how to present the feature."""

Expand All @@ -24,6 +25,22 @@ class FeatureType(Enum):
class Feature:
"""Feature defines a generic interface for device features."""

class Category(Enum):
"""Category hint for downstreams."""

#: Primary features control the device state directly.
#: Examples including turning the device on, or adjust its brightness.
Primary = auto()
#: Config features change device behavior without immediate state changes.
Config = auto()
#: Informative/sensor features deliver some potentially interesting information.
Info = auto()
#: Debug features deliver more verbose information then informative features.
#: You may want to hide these per default to avoid cluttering your UI.
Debug = auto()
#: The default category if none is specified.
Unset = -1

#: Device instance required for getting and setting values
device: Device
#: User-friendly short description
Expand All @@ -38,6 +55,8 @@ class Feature:
icon: str | None = None
#: Unit, if applicable
unit: str | None = None
#: Category hint for downstreams
category: Feature.Category = Category.Unset
#: Type of the feature
type: FeatureType = FeatureType.Sensor

Expand All @@ -50,14 +69,29 @@ class Feature:
#: If set, this property will be used to set *minimum_value* and *maximum_value*.
range_getter: str | None = None

#: Identifier
id: str | None = None

def __post_init__(self):
"""Handle late-binding of members."""
# Set id, if unset
if self.id is None:
self.id = self.name.lower().replace(" ", "_")

# Populate minimum & maximum values, if range_getter is given
container = self.container if self.container is not None else self.device
if self.range_getter is not None:
self.minimum_value, self.maximum_value = getattr(
container, self.range_getter
)

# Set the category, if unset
if self.category is Feature.Category.Unset:
if self.attribute_setter:
self.category = Feature.Category.Config
else:
self.category = Feature.Category.Info

@property
def value(self):
"""Return the current value."""
Expand All @@ -79,3 +113,13 @@ async def set_value(self, value):

container = self.container if self.container is not None else self.device
return await getattr(container, self.attribute_setter)(value)

def __repr__(self):
s = f"{self.name} ({self.id}): {self.value}"
if self.unit is not None:
s += f" {self.unit}"

if self.type == FeatureType.Number:
s += f" (range: {self.minimum_value}-{self.maximum_value})"

return s
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added this here to make printing out features simpler inside cli.py.

2 changes: 2 additions & 0 deletions kasa/iot/iotbulb.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ async def _initialize_features(self):
minimum_value=1,
maximum_value=100,
type=FeatureType.Number,
category=Feature.Category.Primary,
)
)

Expand All @@ -233,6 +234,7 @@ async def _initialize_features(self):
attribute_getter="color_temp",
attribute_setter="set_color_temp",
range_getter="valid_temperature_range",
category=Feature.Category.Primary,
)
)

Expand Down
6 changes: 5 additions & 1 deletion kasa/iot/iotdevice.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,11 @@ async def update(self, update_children: bool = True):
async def _initialize_features(self):
self._add_feature(
Feature(
device=self, name="RSSI", attribute_getter="rssi", icon="mdi:signal"
device=self,
name="RSSI",
attribute_getter="rssi",
icon="mdi:signal",
category=Feature.Category.Debug,
)
)
if "on_time" in self._sys_info:
Expand Down
1 change: 1 addition & 0 deletions kasa/smart/modules/brightness.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def __init__(self, device: SmartDevice, module: str):
minimum_value=BRIGHTNESS_MIN,
maximum_value=BRIGHTNESS_MAX,
type=FeatureType.Number,
category=Feature.Category.Primary,
)
)

Expand Down
1 change: 1 addition & 0 deletions kasa/smart/modules/colortemp.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ def __init__(self, device: SmartDevice, module: str):
attribute_getter="color_temp",
attribute_setter="set_color_temp",
range_getter="valid_temperature_range",
category=Feature.Category.Primary,
)
)

Expand Down
1 change: 1 addition & 0 deletions kasa/smart/modules/fanmodule.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ def __init__(self, device: SmartDevice, module: str):
type=FeatureType.Number,
minimum_value=1,
maximum_value=4,
category=Feature.Category.Primary,
)
)
self._add_feature(
Expand Down
1 change: 1 addition & 0 deletions kasa/smart/modules/ledmodule.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ def __init__(self, device: SmartDevice, module: str):
attribute_getter="led",
attribute_setter="set_led",
type=FeatureType.Switch,
category=Feature.Category.Config,
)
)

Expand Down
1 change: 1 addition & 0 deletions kasa/smart/modules/reportmodule.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def __init__(self, device: SmartDevice, module: str):
"Report interval",
container=self,
attribute_getter="report_interval",
category=Feature.Category.Debug,
)
)

Expand Down
1 change: 1 addition & 0 deletions kasa/smart/modules/timemodule.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ def __init__(self, device: SmartDevice, module: str):
name="Time",
attribute_getter="time",
container=self,
category=Feature.Category.Debug,
)
)

Expand Down
20 changes: 18 additions & 2 deletions kasa/smart/smartdevice.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,14 @@ async def _initialize_modules(self):

async def _initialize_features(self):
"""Initialize device features."""
self._add_feature(Feature(self, "Device ID", attribute_getter="device_id"))
self._add_feature(
Feature(
self,
"Device ID",
attribute_getter="device_id",
category=Feature.Category.Debug,
)
)
if "device_on" in self._info:
self._add_feature(
Feature(
Expand All @@ -185,6 +192,7 @@ async def _initialize_features(self):
attribute_getter="is_on",
attribute_setter="set_state",
type=FeatureType.Switch,
category=Feature.Category.Primary,
)
)

Expand All @@ -195,6 +203,7 @@ async def _initialize_features(self):
"Signal Level",
attribute_getter=lambda x: x._info["signal_level"],
icon="mdi:signal",
category=Feature.Category.Info,
)
)

Expand All @@ -205,13 +214,18 @@ async def _initialize_features(self):
"RSSI",
attribute_getter=lambda x: x._info["rssi"],
icon="mdi:signal",
category=Feature.Category.Debug,
)
)

if "ssid" in self._info:
self._add_feature(
Feature(
device=self, name="SSID", attribute_getter="ssid", icon="mdi:wifi"
device=self,
name="SSID",
attribute_getter="ssid",
icon="mdi:wifi",
category=Feature.Category.Debug,
)
)

Expand All @@ -223,6 +237,7 @@ async def _initialize_features(self):
attribute_getter=lambda x: x._info["overheated"],
icon="mdi:heat-wave",
type=FeatureType.BinarySensor,
category=Feature.Category.Debug,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering if we should have a separate category for warnings, or make them informational?

)
)

Expand All @@ -235,6 +250,7 @@ async def _initialize_features(self):
name="On since",
attribute_getter="on_since",
icon="mdi:clock",
category=Feature.Category.Debug,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably be info, too.

)
)

Expand Down