2020-05-27 14:55:18 +00:00
|
|
|
"""Module for multi-socket devices (HS300, HS107, KP303, ..)."""
|
2024-04-16 18:21:20 +00:00
|
|
|
|
2024-04-17 13:39:24 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2019-01-08 19:13:25 +00:00
|
|
|
import logging
|
2020-03-17 23:40:06 +00:00
|
|
|
from collections import defaultdict
|
2024-10-08 07:16:51 +00:00
|
|
|
from datetime import datetime, timedelta
|
2024-11-21 18:40:13 +00:00
|
|
|
from typing import TYPE_CHECKING, Any
|
2022-04-05 16:25:41 +00:00
|
|
|
|
2024-02-04 15:20:08 +00:00
|
|
|
from ..device_type import DeviceType
|
|
|
|
from ..deviceconfig import DeviceConfig
|
2024-06-17 10:22:05 +00:00
|
|
|
from ..emeterstatus import EmeterStatus
|
2024-02-21 15:52:55 +00:00
|
|
|
from ..exceptions import KasaException
|
2024-06-07 09:52:11 +00:00
|
|
|
from ..feature import Feature
|
2024-06-17 10:22:05 +00:00
|
|
|
from ..interfaces import Energy
|
2024-05-11 18:28:18 +00:00
|
|
|
from ..module import Module
|
2024-11-13 17:50:21 +00:00
|
|
|
from ..protocols import BaseProtocol
|
2024-02-04 15:20:08 +00:00
|
|
|
from .iotdevice import (
|
|
|
|
IotDevice,
|
2022-04-05 16:25:41 +00:00
|
|
|
requires_update,
|
2020-03-16 13:52:40 +00:00
|
|
|
)
|
2024-06-17 10:22:05 +00:00
|
|
|
from .iotmodule import IotModule
|
2024-02-04 15:20:08 +00:00
|
|
|
from .iotplug import IotPlug
|
2024-06-25 16:24:05 +00:00
|
|
|
from .modules import Antitheft, Cloud, Countdown, Emeter, Led, Schedule, Time, Usage
|
2021-11-07 01:41:12 +00:00
|
|
|
|
2019-01-08 19:13:25 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
def merge_sums(dicts: list[dict]) -> dict:
|
2021-09-23 22:24:44 +00:00
|
|
|
"""Merge the sum of dicts."""
|
2024-04-17 13:39:24 +00:00
|
|
|
total_dict: defaultdict[int, float] = defaultdict(lambda: 0.0)
|
2021-09-23 22:24:44 +00:00
|
|
|
for sum_dict in dicts:
|
|
|
|
for day, value in sum_dict.items():
|
|
|
|
total_dict[day] += value
|
|
|
|
return total_dict
|
|
|
|
|
|
|
|
|
2024-02-04 15:20:08 +00:00
|
|
|
class IotStrip(IotDevice):
|
2022-04-05 23:41:08 +00:00
|
|
|
r"""Representation of a TP-Link Smart Power Strip.
|
2019-01-08 19:13:25 +00:00
|
|
|
|
2020-06-30 00:29:52 +00:00
|
|
|
A strip consists of the parent device and its children.
|
|
|
|
All methods of the parent act on all children, while the child devices
|
|
|
|
share the common API with the :class:`SmartPlug` class.
|
API and tests cleanup (#151)
* Add new cli commands: raw_command and dump_discover
- raw_command can be used to execute raw commands with given parameters
* Useful for testing new calls before implementing them properly
- dump_discover can be used to dump the device discovery information (into a file)
* The discovery is extended to request more modules and methods from devices
* smartlife.iot.dimmer get_dimmer_parameters
* smartlife.iot.common.emeter get_realtime
* smartlife.iot.smartbulb.lightingservice get_light_state
* This is used to dump more information for proper tests, and will also allow better discovery in the future
This commit contains also some documentation updates and dropping click_datetime in favor of click's built-in datetime
* Docstring fixes
* Major API cleanup
Properties shall no more change the state of the device, this work in still in progress, the main goal being making the API more user-friendly and to make implementing new features simpler.
The newly deprecated functionality will remain working and will simply warn the user about deprecation.
Previously deprecated 'features' property and 'identify' method are now finally removed.
Deprecate and replace the following property setters:
* state with turn_on() and turn_off()
* hsv with set_hsv()
* color_temp with set_color_temp()
* brightness with set_brightness()
* led with set_led()
* alias with set_alias()
* mac with set_mac()
And getters:
* state with is_on and is_off
The {BULB,PLUG}_STATE_{ON,OFF} is simplified to STATE_ON and STATE_OFF, UNKNOWN state is removed.
These are now deprecated and will be removed in the future.
* is_on and is_off can be used to check for the state
* turn_on() and turn_off() for changing the device state.
Trying to use functionality not supported by the device will cause SmartDeviceExceptions instead of failing silently and/or returning None.
This includes, e.g., trying to set a color temperature on non-supported bulb.
ValueErrors are raised instead of SmartDeviceExceptions where appropriate (e.g. when trying to set an invalid hsv or brightness).
New enum type DeviceType is added to allow detecting device types without resorting to isinstance() calling. SmartDevice class' device_type property can be used to query the type. is_plug and is_bulb helpers are added.
* Cleanup tests and improve test coverage
* Make writing tests easier by sharing code for common implementations
* Instead of storing test data inside python files, dump-discover based information is used
* This will simplify adding new tests and remove code duplication
* fixtures are based on https://github.com/plasticrake/tplink-smarthome-simulator
* run black on newfakes
* Add HS300 tests and update SmartStrip API according to earlier changes, still WIP
* run black and avoid wildcard imports
* Black on conftest
* bump minimum required version to 3.5
* Rename fixture_tests to test_fixtures for autocollect
* fix typoed type to _type, black
* run black on several files with -79 to fix hound issues
* Fix broken merge on hue
* Fix tests (hue update, pass context to smartdevice), add is_strip property, disable emeter tests for HS300 until a solution for API is found.
* Fix old tests
* Run black on changed files
* Add real HS220 discovery, thanks to @poiyo
* add is_dimmable and is_variable_color_temp to smartdevice class, simplifies interfacing with homeassistant
* add KL120(US) fixture
* Add a simple query cache
This commit adds a simple query cache to speed up the process for users
requesting lots of different properties from the device, as done by the
cli tool as well as homeassistant.
The logic for caching is very simple:
1. A timestamp for last fetch for each module+command is stored alongside the response.
2. If the issued command starts with `get_` and the TTL has not expired, the cache result is returned.
3. Otherwise the cache for the whole corresponding module gets invalidated, the device will be queried and the result will be stored in the cache.
* add deprecation to tox.ini
* make tests pass again
* remove old tests, add flake8 to tox reqs
* run black against pyhs100 module, add it to precommit hooks, fix flake8 configuration to conform to black standards (https://ljvmiranda921.github.io/notebook/2018/06/21/precommits-using-black-and-flake8/)
* fix syntax
* cleanup conftest
2019-06-16 21:05:00 +00:00
|
|
|
|
2020-06-30 00:29:52 +00:00
|
|
|
To initialize, you have to await :func:`update()` at least once.
|
|
|
|
This will allow accessing the properties using the exposed properties.
|
2019-11-11 21:14:34 +00:00
|
|
|
|
2020-06-30 00:29:52 +00:00
|
|
|
All changes to the device are done using awaitable methods,
|
2023-10-29 22:15:42 +00:00
|
|
|
which will not change the cached values,
|
|
|
|
but you must await :func:`update()` separately.
|
API and tests cleanup (#151)
* Add new cli commands: raw_command and dump_discover
- raw_command can be used to execute raw commands with given parameters
* Useful for testing new calls before implementing them properly
- dump_discover can be used to dump the device discovery information (into a file)
* The discovery is extended to request more modules and methods from devices
* smartlife.iot.dimmer get_dimmer_parameters
* smartlife.iot.common.emeter get_realtime
* smartlife.iot.smartbulb.lightingservice get_light_state
* This is used to dump more information for proper tests, and will also allow better discovery in the future
This commit contains also some documentation updates and dropping click_datetime in favor of click's built-in datetime
* Docstring fixes
* Major API cleanup
Properties shall no more change the state of the device, this work in still in progress, the main goal being making the API more user-friendly and to make implementing new features simpler.
The newly deprecated functionality will remain working and will simply warn the user about deprecation.
Previously deprecated 'features' property and 'identify' method are now finally removed.
Deprecate and replace the following property setters:
* state with turn_on() and turn_off()
* hsv with set_hsv()
* color_temp with set_color_temp()
* brightness with set_brightness()
* led with set_led()
* alias with set_alias()
* mac with set_mac()
And getters:
* state with is_on and is_off
The {BULB,PLUG}_STATE_{ON,OFF} is simplified to STATE_ON and STATE_OFF, UNKNOWN state is removed.
These are now deprecated and will be removed in the future.
* is_on and is_off can be used to check for the state
* turn_on() and turn_off() for changing the device state.
Trying to use functionality not supported by the device will cause SmartDeviceExceptions instead of failing silently and/or returning None.
This includes, e.g., trying to set a color temperature on non-supported bulb.
ValueErrors are raised instead of SmartDeviceExceptions where appropriate (e.g. when trying to set an invalid hsv or brightness).
New enum type DeviceType is added to allow detecting device types without resorting to isinstance() calling. SmartDevice class' device_type property can be used to query the type. is_plug and is_bulb helpers are added.
* Cleanup tests and improve test coverage
* Make writing tests easier by sharing code for common implementations
* Instead of storing test data inside python files, dump-discover based information is used
* This will simplify adding new tests and remove code duplication
* fixtures are based on https://github.com/plasticrake/tplink-smarthome-simulator
* run black on newfakes
* Add HS300 tests and update SmartStrip API according to earlier changes, still WIP
* run black and avoid wildcard imports
* Black on conftest
* bump minimum required version to 3.5
* Rename fixture_tests to test_fixtures for autocollect
* fix typoed type to _type, black
* run black on several files with -79 to fix hound issues
* Fix broken merge on hue
* Fix tests (hue update, pass context to smartdevice), add is_strip property, disable emeter tests for HS300 until a solution for API is found.
* Fix old tests
* Run black on changed files
* Add real HS220 discovery, thanks to @poiyo
* add is_dimmable and is_variable_color_temp to smartdevice class, simplifies interfacing with homeassistant
* add KL120(US) fixture
* Add a simple query cache
This commit adds a simple query cache to speed up the process for users
requesting lots of different properties from the device, as done by the
cli tool as well as homeassistant.
The logic for caching is very simple:
1. A timestamp for last fetch for each module+command is stored alongside the response.
2. If the issued command starts with `get_` and the TTL has not expired, the cache result is returned.
3. Otherwise the cache for the whole corresponding module gets invalidated, the device will be queried and the result will be stored in the cache.
* add deprecation to tox.ini
* make tests pass again
* remove old tests, add flake8 to tox reqs
* run black against pyhs100 module, add it to precommit hooks, fix flake8 configuration to conform to black standards (https://ljvmiranda921.github.io/notebook/2018/06/21/precommits-using-black-and-flake8/)
* fix syntax
* cleanup conftest
2019-06-16 21:05:00 +00:00
|
|
|
|
2024-02-21 15:52:55 +00:00
|
|
|
Errors reported by the device are raised as :class:`KasaException`\s,
|
2019-01-08 19:13:25 +00:00
|
|
|
and should be handled by the user of the library.
|
2020-06-30 00:29:52 +00:00
|
|
|
|
|
|
|
Examples:
|
|
|
|
>>> import asyncio
|
2024-02-04 15:20:08 +00:00
|
|
|
>>> strip = IotStrip("127.0.0.1")
|
2020-06-30 00:29:52 +00:00
|
|
|
>>> asyncio.run(strip.update())
|
|
|
|
>>> strip.alias
|
2024-06-03 09:14:10 +00:00
|
|
|
Bedroom Power Strip
|
2020-06-30 00:29:52 +00:00
|
|
|
|
|
|
|
All methods act on the whole strip:
|
|
|
|
|
|
|
|
>>> for plug in strip.children:
|
|
|
|
>>> print(f"{plug.alias}: {plug.is_on}")
|
|
|
|
Plug 1: True
|
|
|
|
Plug 2: False
|
|
|
|
Plug 3: False
|
|
|
|
>>> strip.is_on
|
|
|
|
True
|
|
|
|
>>> asyncio.run(strip.turn_off())
|
2024-04-24 11:25:16 +00:00
|
|
|
>>> asyncio.run(strip.update())
|
2020-06-30 00:29:52 +00:00
|
|
|
|
|
|
|
Accessing individual plugs can be done using the `children` property:
|
|
|
|
|
|
|
|
>>> len(strip.children)
|
|
|
|
3
|
|
|
|
>>> for plug in strip.children:
|
|
|
|
>>> print(f"{plug.alias}: {plug.is_on}")
|
|
|
|
Plug 1: False
|
|
|
|
Plug 2: False
|
|
|
|
Plug 3: False
|
|
|
|
>>> asyncio.run(strip.children[1].turn_on())
|
|
|
|
>>> asyncio.run(strip.update())
|
|
|
|
>>> strip.is_on
|
|
|
|
True
|
|
|
|
|
2024-05-16 16:13:44 +00:00
|
|
|
For more examples, see the :class:`Device` class.
|
2019-01-08 19:13:25 +00:00
|
|
|
"""
|
|
|
|
|
2023-09-13 13:46:38 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
host: str,
|
|
|
|
*,
|
2024-04-17 13:39:24 +00:00
|
|
|
config: DeviceConfig | None = None,
|
|
|
|
protocol: BaseProtocol | None = None,
|
2023-09-13 13:46:38 +00:00
|
|
|
) -> None:
|
2023-12-29 19:17:15 +00:00
|
|
|
super().__init__(host=host, config=config, protocol=protocol)
|
2019-01-08 19:13:25 +00:00
|
|
|
self.emeter_type = "emeter"
|
API and tests cleanup (#151)
* Add new cli commands: raw_command and dump_discover
- raw_command can be used to execute raw commands with given parameters
* Useful for testing new calls before implementing them properly
- dump_discover can be used to dump the device discovery information (into a file)
* The discovery is extended to request more modules and methods from devices
* smartlife.iot.dimmer get_dimmer_parameters
* smartlife.iot.common.emeter get_realtime
* smartlife.iot.smartbulb.lightingservice get_light_state
* This is used to dump more information for proper tests, and will also allow better discovery in the future
This commit contains also some documentation updates and dropping click_datetime in favor of click's built-in datetime
* Docstring fixes
* Major API cleanup
Properties shall no more change the state of the device, this work in still in progress, the main goal being making the API more user-friendly and to make implementing new features simpler.
The newly deprecated functionality will remain working and will simply warn the user about deprecation.
Previously deprecated 'features' property and 'identify' method are now finally removed.
Deprecate and replace the following property setters:
* state with turn_on() and turn_off()
* hsv with set_hsv()
* color_temp with set_color_temp()
* brightness with set_brightness()
* led with set_led()
* alias with set_alias()
* mac with set_mac()
And getters:
* state with is_on and is_off
The {BULB,PLUG}_STATE_{ON,OFF} is simplified to STATE_ON and STATE_OFF, UNKNOWN state is removed.
These are now deprecated and will be removed in the future.
* is_on and is_off can be used to check for the state
* turn_on() and turn_off() for changing the device state.
Trying to use functionality not supported by the device will cause SmartDeviceExceptions instead of failing silently and/or returning None.
This includes, e.g., trying to set a color temperature on non-supported bulb.
ValueErrors are raised instead of SmartDeviceExceptions where appropriate (e.g. when trying to set an invalid hsv or brightness).
New enum type DeviceType is added to allow detecting device types without resorting to isinstance() calling. SmartDevice class' device_type property can be used to query the type. is_plug and is_bulb helpers are added.
* Cleanup tests and improve test coverage
* Make writing tests easier by sharing code for common implementations
* Instead of storing test data inside python files, dump-discover based information is used
* This will simplify adding new tests and remove code duplication
* fixtures are based on https://github.com/plasticrake/tplink-smarthome-simulator
* run black on newfakes
* Add HS300 tests and update SmartStrip API according to earlier changes, still WIP
* run black and avoid wildcard imports
* Black on conftest
* bump minimum required version to 3.5
* Rename fixture_tests to test_fixtures for autocollect
* fix typoed type to _type, black
* run black on several files with -79 to fix hound issues
* Fix broken merge on hue
* Fix tests (hue update, pass context to smartdevice), add is_strip property, disable emeter tests for HS300 until a solution for API is found.
* Fix old tests
* Run black on changed files
* Add real HS220 discovery, thanks to @poiyo
* add is_dimmable and is_variable_color_temp to smartdevice class, simplifies interfacing with homeassistant
* add KL120(US) fixture
* Add a simple query cache
This commit adds a simple query cache to speed up the process for users
requesting lots of different properties from the device, as done by the
cli tool as well as homeassistant.
The logic for caching is very simple:
1. A timestamp for last fetch for each module+command is stored alongside the response.
2. If the issued command starts with `get_` and the TTL has not expired, the cache result is returned.
3. Otherwise the cache for the whole corresponding module gets invalidated, the device will be queried and the result will be stored in the cache.
* add deprecation to tox.ini
* make tests pass again
* remove old tests, add flake8 to tox reqs
* run black against pyhs100 module, add it to precommit hooks, fix flake8 configuration to conform to black standards (https://ljvmiranda921.github.io/notebook/2018/06/21/precommits-using-black-and-flake8/)
* fix syntax
* cleanup conftest
2019-06-16 21:05:00 +00:00
|
|
|
self._device_type = DeviceType.Strip
|
2024-06-17 10:22:05 +00:00
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
async def _initialize_modules(self) -> None:
|
2024-06-17 10:22:05 +00:00
|
|
|
"""Initialize modules."""
|
|
|
|
# Strip has different modules to plug so do not call super
|
2024-05-11 18:28:18 +00:00
|
|
|
self.add_module(Module.IotAntitheft, Antitheft(self, "anti_theft"))
|
|
|
|
self.add_module(Module.IotSchedule, Schedule(self, "schedule"))
|
|
|
|
self.add_module(Module.IotUsage, Usage(self, "schedule"))
|
2024-10-15 07:59:25 +00:00
|
|
|
self.add_module(Module.Time, Time(self, "time"))
|
2024-05-11 18:28:18 +00:00
|
|
|
self.add_module(Module.IotCountdown, Countdown(self, "countdown"))
|
2024-06-25 16:24:05 +00:00
|
|
|
self.add_module(Module.Led, Led(self, "system"))
|
|
|
|
self.add_module(Module.IotCloud, Cloud(self, "cnCloud"))
|
2024-06-17 10:22:05 +00:00
|
|
|
if self.has_emeter:
|
|
|
|
_LOGGER.debug(
|
|
|
|
"The device has emeter, querying its information along sysinfo"
|
|
|
|
)
|
|
|
|
self.add_module(Module.Energy, StripEmeter(self, self.emeter_type))
|
2019-01-08 19:13:25 +00:00
|
|
|
|
2019-12-12 09:46:40 +00:00
|
|
|
@property # type: ignore
|
2019-11-15 16:48:36 +00:00
|
|
|
@requires_update
|
|
|
|
def is_on(self) -> bool:
|
2019-11-11 21:14:34 +00:00
|
|
|
"""Return if any of the outlets are on."""
|
2021-09-23 22:24:44 +00:00
|
|
|
return any(plug.is_on for plug in self.children)
|
2019-01-08 19:13:25 +00:00
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
async def update(self, update_children: bool = True) -> None:
|
2019-11-15 16:48:36 +00:00
|
|
|
"""Update some of the attributes.
|
|
|
|
|
|
|
|
Needed for methods that are decorated with `requires_update`.
|
|
|
|
"""
|
2024-06-17 10:22:05 +00:00
|
|
|
# Super initializes modules and features
|
2021-09-24 21:25:43 +00:00
|
|
|
await super().update(update_children)
|
2020-01-12 21:44:19 +00:00
|
|
|
|
2024-06-17 10:22:05 +00:00
|
|
|
initialize_children = not self.children
|
2020-01-12 21:44:19 +00:00
|
|
|
# Initialize the child devices during the first update.
|
2024-06-17 10:22:05 +00:00
|
|
|
if initialize_children:
|
2020-01-12 21:44:19 +00:00
|
|
|
children = self.sys_info["children"]
|
2020-03-16 13:52:40 +00:00
|
|
|
_LOGGER.debug("Initializing %s child sockets", len(children))
|
2024-02-22 19:46:19 +00:00
|
|
|
self._children = {
|
|
|
|
f"{self.mac}_{child['id']}": IotStripPlug(
|
|
|
|
self.host, parent=self, child_id=child["id"]
|
|
|
|
)
|
2024-02-04 15:20:08 +00:00
|
|
|
for child in children
|
2024-02-22 19:46:19 +00:00
|
|
|
}
|
2024-06-07 09:52:11 +00:00
|
|
|
for child in self._children.values():
|
2024-06-17 10:22:05 +00:00
|
|
|
await child._initialize_modules()
|
2020-01-12 21:44:19 +00:00
|
|
|
|
2024-06-17 10:22:05 +00:00
|
|
|
if update_children:
|
2021-09-23 22:24:44 +00:00
|
|
|
for plug in self.children:
|
2024-11-21 18:40:13 +00:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
assert isinstance(plug, IotStripPlug)
|
2024-07-02 13:11:19 +00:00
|
|
|
await plug._update()
|
2021-09-23 22:24:44 +00:00
|
|
|
|
2024-06-17 10:22:05 +00:00
|
|
|
if not self.features:
|
|
|
|
await self._initialize_features()
|
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
async def _initialize_features(self) -> None:
|
2024-06-17 10:22:05 +00:00
|
|
|
"""Initialize common features."""
|
|
|
|
# Do not initialize features until children are created
|
|
|
|
if not self.children:
|
|
|
|
return
|
|
|
|
await super()._initialize_features()
|
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
async def turn_on(self, **kwargs) -> dict:
|
2020-05-27 14:55:18 +00:00
|
|
|
"""Turn the strip on."""
|
2024-11-10 18:55:13 +00:00
|
|
|
return await self._query_helper("system", "set_relay_state", {"state": 1})
|
2019-01-08 19:13:25 +00:00
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
async def turn_off(self, **kwargs) -> dict:
|
2020-05-27 14:55:18 +00:00
|
|
|
"""Turn the strip off."""
|
2024-11-10 18:55:13 +00:00
|
|
|
return await self._query_helper("system", "set_relay_state", {"state": 0})
|
2019-01-08 19:13:25 +00:00
|
|
|
|
2019-12-12 09:46:40 +00:00
|
|
|
@property # type: ignore
|
2019-11-15 16:48:36 +00:00
|
|
|
@requires_update
|
2024-04-17 13:39:24 +00:00
|
|
|
def on_since(self) -> datetime | None:
|
2019-11-11 21:14:34 +00:00
|
|
|
"""Return the maximum on-time of all outlets."""
|
2020-04-24 14:47:57 +00:00
|
|
|
if self.is_off:
|
|
|
|
return None
|
|
|
|
|
2024-06-14 21:04:20 +00:00
|
|
|
return min(plug.on_since for plug in self.children if plug.on_since is not None)
|
2019-01-08 19:13:25 +00:00
|
|
|
|
2024-06-17 10:22:05 +00:00
|
|
|
|
|
|
|
class StripEmeter(IotModule, Energy):
|
|
|
|
"""Energy module implementation to aggregate child modules."""
|
|
|
|
|
|
|
|
_supported = (
|
|
|
|
Energy.ModuleFeature.CONSUMPTION_TOTAL
|
|
|
|
| Energy.ModuleFeature.PERIODIC_STATS
|
|
|
|
| Energy.ModuleFeature.VOLTAGE_CURRENT
|
|
|
|
)
|
|
|
|
|
|
|
|
def supports(self, module_feature: Energy.ModuleFeature) -> bool:
|
|
|
|
"""Return True if module supports the feature."""
|
|
|
|
return module_feature in self._supported
|
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
def query(self) -> dict:
|
2024-06-17 10:22:05 +00:00
|
|
|
"""Return the base query."""
|
|
|
|
return {}
|
|
|
|
|
|
|
|
@property
|
|
|
|
def current_consumption(self) -> float | None:
|
2020-05-27 14:55:18 +00:00
|
|
|
"""Get the current power consumption in watts."""
|
2024-06-17 10:22:05 +00:00
|
|
|
return sum(
|
|
|
|
v if (v := plug.modules[Module.Energy].current_consumption) else 0.0
|
|
|
|
for plug in self._device.children
|
|
|
|
)
|
2019-11-11 19:44:12 +00:00
|
|
|
|
2024-06-17 10:22:05 +00:00
|
|
|
async def get_status(self) -> EmeterStatus:
|
2021-09-23 22:24:44 +00:00
|
|
|
"""Retrieve current energy readings."""
|
2024-06-17 10:22:05 +00:00
|
|
|
emeter_rt = await self._async_get_emeter_sum("get_status", {})
|
2021-09-23 22:24:44 +00:00
|
|
|
# Voltage is averaged since each read will result
|
|
|
|
# in a slightly different voltage since they are not atomic
|
2024-06-17 10:22:05 +00:00
|
|
|
emeter_rt["voltage_mv"] = int(
|
|
|
|
emeter_rt["voltage_mv"] / len(self._device.children)
|
|
|
|
)
|
2021-09-23 22:24:44 +00:00
|
|
|
return EmeterStatus(emeter_rt)
|
API and tests cleanup (#151)
* Add new cli commands: raw_command and dump_discover
- raw_command can be used to execute raw commands with given parameters
* Useful for testing new calls before implementing them properly
- dump_discover can be used to dump the device discovery information (into a file)
* The discovery is extended to request more modules and methods from devices
* smartlife.iot.dimmer get_dimmer_parameters
* smartlife.iot.common.emeter get_realtime
* smartlife.iot.smartbulb.lightingservice get_light_state
* This is used to dump more information for proper tests, and will also allow better discovery in the future
This commit contains also some documentation updates and dropping click_datetime in favor of click's built-in datetime
* Docstring fixes
* Major API cleanup
Properties shall no more change the state of the device, this work in still in progress, the main goal being making the API more user-friendly and to make implementing new features simpler.
The newly deprecated functionality will remain working and will simply warn the user about deprecation.
Previously deprecated 'features' property and 'identify' method are now finally removed.
Deprecate and replace the following property setters:
* state with turn_on() and turn_off()
* hsv with set_hsv()
* color_temp with set_color_temp()
* brightness with set_brightness()
* led with set_led()
* alias with set_alias()
* mac with set_mac()
And getters:
* state with is_on and is_off
The {BULB,PLUG}_STATE_{ON,OFF} is simplified to STATE_ON and STATE_OFF, UNKNOWN state is removed.
These are now deprecated and will be removed in the future.
* is_on and is_off can be used to check for the state
* turn_on() and turn_off() for changing the device state.
Trying to use functionality not supported by the device will cause SmartDeviceExceptions instead of failing silently and/or returning None.
This includes, e.g., trying to set a color temperature on non-supported bulb.
ValueErrors are raised instead of SmartDeviceExceptions where appropriate (e.g. when trying to set an invalid hsv or brightness).
New enum type DeviceType is added to allow detecting device types without resorting to isinstance() calling. SmartDevice class' device_type property can be used to query the type. is_plug and is_bulb helpers are added.
* Cleanup tests and improve test coverage
* Make writing tests easier by sharing code for common implementations
* Instead of storing test data inside python files, dump-discover based information is used
* This will simplify adding new tests and remove code duplication
* fixtures are based on https://github.com/plasticrake/tplink-smarthome-simulator
* run black on newfakes
* Add HS300 tests and update SmartStrip API according to earlier changes, still WIP
* run black and avoid wildcard imports
* Black on conftest
* bump minimum required version to 3.5
* Rename fixture_tests to test_fixtures for autocollect
* fix typoed type to _type, black
* run black on several files with -79 to fix hound issues
* Fix broken merge on hue
* Fix tests (hue update, pass context to smartdevice), add is_strip property, disable emeter tests for HS300 until a solution for API is found.
* Fix old tests
* Run black on changed files
* Add real HS220 discovery, thanks to @poiyo
* add is_dimmable and is_variable_color_temp to smartdevice class, simplifies interfacing with homeassistant
* add KL120(US) fixture
* Add a simple query cache
This commit adds a simple query cache to speed up the process for users
requesting lots of different properties from the device, as done by the
cli tool as well as homeassistant.
The logic for caching is very simple:
1. A timestamp for last fetch for each module+command is stored alongside the response.
2. If the issued command starts with `get_` and the TTL has not expired, the cache result is returned.
3. Otherwise the cache for the whole corresponding module gets invalidated, the device will be queried and the result will be stored in the cache.
* add deprecation to tox.ini
* make tests pass again
* remove old tests, add flake8 to tox reqs
* run black against pyhs100 module, add it to precommit hooks, fix flake8 configuration to conform to black standards (https://ljvmiranda921.github.io/notebook/2018/06/21/precommits-using-black-and-flake8/)
* fix syntax
* cleanup conftest
2019-06-16 21:05:00 +00:00
|
|
|
|
2024-06-17 10:22:05 +00:00
|
|
|
async def get_daily_stats(
|
2024-04-17 13:39:24 +00:00
|
|
|
self, year: int | None = None, month: int | None = None, kwh: bool = True
|
|
|
|
) -> dict:
|
2019-11-11 21:14:34 +00:00
|
|
|
"""Retrieve daily statistics for a given month.
|
2019-01-08 19:13:25 +00:00
|
|
|
|
|
|
|
:param year: year for which to retrieve statistics (default: this year)
|
|
|
|
:param month: month for which to retrieve statistics (default: this
|
|
|
|
month)
|
|
|
|
:param kwh: return usage in kWh (default: True)
|
|
|
|
:return: mapping of day of month to value
|
|
|
|
"""
|
2021-09-23 22:24:44 +00:00
|
|
|
return await self._async_get_emeter_sum(
|
2024-06-17 10:22:05 +00:00
|
|
|
"get_daily_stats", {"year": year, "month": month, "kwh": kwh}
|
2021-09-23 22:24:44 +00:00
|
|
|
)
|
API and tests cleanup (#151)
* Add new cli commands: raw_command and dump_discover
- raw_command can be used to execute raw commands with given parameters
* Useful for testing new calls before implementing them properly
- dump_discover can be used to dump the device discovery information (into a file)
* The discovery is extended to request more modules and methods from devices
* smartlife.iot.dimmer get_dimmer_parameters
* smartlife.iot.common.emeter get_realtime
* smartlife.iot.smartbulb.lightingservice get_light_state
* This is used to dump more information for proper tests, and will also allow better discovery in the future
This commit contains also some documentation updates and dropping click_datetime in favor of click's built-in datetime
* Docstring fixes
* Major API cleanup
Properties shall no more change the state of the device, this work in still in progress, the main goal being making the API more user-friendly and to make implementing new features simpler.
The newly deprecated functionality will remain working and will simply warn the user about deprecation.
Previously deprecated 'features' property and 'identify' method are now finally removed.
Deprecate and replace the following property setters:
* state with turn_on() and turn_off()
* hsv with set_hsv()
* color_temp with set_color_temp()
* brightness with set_brightness()
* led with set_led()
* alias with set_alias()
* mac with set_mac()
And getters:
* state with is_on and is_off
The {BULB,PLUG}_STATE_{ON,OFF} is simplified to STATE_ON and STATE_OFF, UNKNOWN state is removed.
These are now deprecated and will be removed in the future.
* is_on and is_off can be used to check for the state
* turn_on() and turn_off() for changing the device state.
Trying to use functionality not supported by the device will cause SmartDeviceExceptions instead of failing silently and/or returning None.
This includes, e.g., trying to set a color temperature on non-supported bulb.
ValueErrors are raised instead of SmartDeviceExceptions where appropriate (e.g. when trying to set an invalid hsv or brightness).
New enum type DeviceType is added to allow detecting device types without resorting to isinstance() calling. SmartDevice class' device_type property can be used to query the type. is_plug and is_bulb helpers are added.
* Cleanup tests and improve test coverage
* Make writing tests easier by sharing code for common implementations
* Instead of storing test data inside python files, dump-discover based information is used
* This will simplify adding new tests and remove code duplication
* fixtures are based on https://github.com/plasticrake/tplink-smarthome-simulator
* run black on newfakes
* Add HS300 tests and update SmartStrip API according to earlier changes, still WIP
* run black and avoid wildcard imports
* Black on conftest
* bump minimum required version to 3.5
* Rename fixture_tests to test_fixtures for autocollect
* fix typoed type to _type, black
* run black on several files with -79 to fix hound issues
* Fix broken merge on hue
* Fix tests (hue update, pass context to smartdevice), add is_strip property, disable emeter tests for HS300 until a solution for API is found.
* Fix old tests
* Run black on changed files
* Add real HS220 discovery, thanks to @poiyo
* add is_dimmable and is_variable_color_temp to smartdevice class, simplifies interfacing with homeassistant
* add KL120(US) fixture
* Add a simple query cache
This commit adds a simple query cache to speed up the process for users
requesting lots of different properties from the device, as done by the
cli tool as well as homeassistant.
The logic for caching is very simple:
1. A timestamp for last fetch for each module+command is stored alongside the response.
2. If the issued command starts with `get_` and the TTL has not expired, the cache result is returned.
3. Otherwise the cache for the whole corresponding module gets invalidated, the device will be queried and the result will be stored in the cache.
* add deprecation to tox.ini
* make tests pass again
* remove old tests, add flake8 to tox reqs
* run black against pyhs100 module, add it to precommit hooks, fix flake8 configuration to conform to black standards (https://ljvmiranda921.github.io/notebook/2018/06/21/precommits-using-black-and-flake8/)
* fix syntax
* cleanup conftest
2019-06-16 21:05:00 +00:00
|
|
|
|
2024-06-17 10:22:05 +00:00
|
|
|
async def get_monthly_stats(
|
2024-04-17 13:39:24 +00:00
|
|
|
self, year: int | None = None, kwh: bool = True
|
|
|
|
) -> dict:
|
API and tests cleanup (#151)
* Add new cli commands: raw_command and dump_discover
- raw_command can be used to execute raw commands with given parameters
* Useful for testing new calls before implementing them properly
- dump_discover can be used to dump the device discovery information (into a file)
* The discovery is extended to request more modules and methods from devices
* smartlife.iot.dimmer get_dimmer_parameters
* smartlife.iot.common.emeter get_realtime
* smartlife.iot.smartbulb.lightingservice get_light_state
* This is used to dump more information for proper tests, and will also allow better discovery in the future
This commit contains also some documentation updates and dropping click_datetime in favor of click's built-in datetime
* Docstring fixes
* Major API cleanup
Properties shall no more change the state of the device, this work in still in progress, the main goal being making the API more user-friendly and to make implementing new features simpler.
The newly deprecated functionality will remain working and will simply warn the user about deprecation.
Previously deprecated 'features' property and 'identify' method are now finally removed.
Deprecate and replace the following property setters:
* state with turn_on() and turn_off()
* hsv with set_hsv()
* color_temp with set_color_temp()
* brightness with set_brightness()
* led with set_led()
* alias with set_alias()
* mac with set_mac()
And getters:
* state with is_on and is_off
The {BULB,PLUG}_STATE_{ON,OFF} is simplified to STATE_ON and STATE_OFF, UNKNOWN state is removed.
These are now deprecated and will be removed in the future.
* is_on and is_off can be used to check for the state
* turn_on() and turn_off() for changing the device state.
Trying to use functionality not supported by the device will cause SmartDeviceExceptions instead of failing silently and/or returning None.
This includes, e.g., trying to set a color temperature on non-supported bulb.
ValueErrors are raised instead of SmartDeviceExceptions where appropriate (e.g. when trying to set an invalid hsv or brightness).
New enum type DeviceType is added to allow detecting device types without resorting to isinstance() calling. SmartDevice class' device_type property can be used to query the type. is_plug and is_bulb helpers are added.
* Cleanup tests and improve test coverage
* Make writing tests easier by sharing code for common implementations
* Instead of storing test data inside python files, dump-discover based information is used
* This will simplify adding new tests and remove code duplication
* fixtures are based on https://github.com/plasticrake/tplink-smarthome-simulator
* run black on newfakes
* Add HS300 tests and update SmartStrip API according to earlier changes, still WIP
* run black and avoid wildcard imports
* Black on conftest
* bump minimum required version to 3.5
* Rename fixture_tests to test_fixtures for autocollect
* fix typoed type to _type, black
* run black on several files with -79 to fix hound issues
* Fix broken merge on hue
* Fix tests (hue update, pass context to smartdevice), add is_strip property, disable emeter tests for HS300 until a solution for API is found.
* Fix old tests
* Run black on changed files
* Add real HS220 discovery, thanks to @poiyo
* add is_dimmable and is_variable_color_temp to smartdevice class, simplifies interfacing with homeassistant
* add KL120(US) fixture
* Add a simple query cache
This commit adds a simple query cache to speed up the process for users
requesting lots of different properties from the device, as done by the
cli tool as well as homeassistant.
The logic for caching is very simple:
1. A timestamp for last fetch for each module+command is stored alongside the response.
2. If the issued command starts with `get_` and the TTL has not expired, the cache result is returned.
3. Otherwise the cache for the whole corresponding module gets invalidated, the device will be queried and the result will be stored in the cache.
* add deprecation to tox.ini
* make tests pass again
* remove old tests, add flake8 to tox reqs
* run black against pyhs100 module, add it to precommit hooks, fix flake8 configuration to conform to black standards (https://ljvmiranda921.github.io/notebook/2018/06/21/precommits-using-black-and-flake8/)
* fix syntax
* cleanup conftest
2019-06-16 21:05:00 +00:00
|
|
|
"""Retrieve monthly statistics for a given year.
|
2019-01-08 19:13:25 +00:00
|
|
|
|
|
|
|
:param year: year for which to retrieve statistics (default: this year)
|
|
|
|
:param kwh: return usage in kWh (default: True)
|
|
|
|
"""
|
2021-09-23 22:24:44 +00:00
|
|
|
return await self._async_get_emeter_sum(
|
2024-06-17 10:22:05 +00:00
|
|
|
"get_monthly_stats", {"year": year, "kwh": kwh}
|
2021-09-23 22:24:44 +00:00
|
|
|
)
|
2020-05-24 15:57:54 +00:00
|
|
|
|
2024-04-17 13:39:24 +00:00
|
|
|
async def _async_get_emeter_sum(self, func: str, kwargs: dict[str, Any]) -> dict:
|
2024-06-17 10:22:05 +00:00
|
|
|
"""Retrieve emeter stats for a time period from children."""
|
2021-09-23 22:24:44 +00:00
|
|
|
return merge_sums(
|
2024-06-17 10:22:05 +00:00
|
|
|
[
|
|
|
|
await getattr(plug.modules[Module.Energy], func)(**kwargs)
|
|
|
|
for plug in self._device.children
|
|
|
|
]
|
2021-09-23 22:24:44 +00:00
|
|
|
)
|
2019-11-11 21:14:34 +00:00
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
async def erase_stats(self) -> dict:
|
2020-05-27 14:55:18 +00:00
|
|
|
"""Erase energy meter statistics for all plugs."""
|
2024-06-17 10:22:05 +00:00
|
|
|
for plug in self._device.children:
|
|
|
|
await plug.modules[Module.Energy].erase_stats()
|
2020-03-16 13:52:40 +00:00
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
return {}
|
|
|
|
|
2021-09-23 22:24:44 +00:00
|
|
|
@property # type: ignore
|
2024-06-17 10:22:05 +00:00
|
|
|
def consumption_this_month(self) -> float | None:
|
2021-09-23 22:24:44 +00:00
|
|
|
"""Return this month's energy consumption in kWh."""
|
2024-06-17 10:22:05 +00:00
|
|
|
return sum(
|
|
|
|
v if (v := plug.modules[Module.Energy].consumption_this_month) else 0.0
|
|
|
|
for plug in self._device.children
|
|
|
|
)
|
2021-09-23 22:24:44 +00:00
|
|
|
|
|
|
|
@property # type: ignore
|
2024-06-17 10:22:05 +00:00
|
|
|
def consumption_today(self) -> float | None:
|
2021-09-23 22:24:44 +00:00
|
|
|
"""Return this month's energy consumption in kWh."""
|
2024-06-17 10:22:05 +00:00
|
|
|
return sum(
|
|
|
|
v if (v := plug.modules[Module.Energy].consumption_today) else 0.0
|
|
|
|
for plug in self._device.children
|
|
|
|
)
|
2021-09-23 22:24:44 +00:00
|
|
|
|
|
|
|
@property # type: ignore
|
2024-06-17 10:22:05 +00:00
|
|
|
def consumption_total(self) -> float | None:
|
|
|
|
"""Return total energy consumption since reboot in kWh."""
|
|
|
|
return sum(
|
|
|
|
v if (v := plug.modules[Module.Energy].consumption_total) else 0.0
|
|
|
|
for plug in self._device.children
|
|
|
|
)
|
|
|
|
|
|
|
|
@property # type: ignore
|
|
|
|
def status(self) -> EmeterStatus:
|
2021-09-23 22:24:44 +00:00
|
|
|
"""Return current energy readings."""
|
2024-06-17 10:22:05 +00:00
|
|
|
emeter = merge_sums(
|
|
|
|
[plug.modules[Module.Energy].status for plug in self._device.children]
|
|
|
|
)
|
2021-09-23 22:24:44 +00:00
|
|
|
# Voltage is averaged since each read will result
|
|
|
|
# in a slightly different voltage since they are not atomic
|
2024-06-17 10:22:05 +00:00
|
|
|
emeter["voltage_mv"] = int(emeter["voltage_mv"] / len(self._device.children))
|
2021-09-23 22:24:44 +00:00
|
|
|
return EmeterStatus(emeter)
|
|
|
|
|
2024-06-17 10:22:05 +00:00
|
|
|
@property
|
|
|
|
def current(self) -> float | None:
|
|
|
|
"""Return the current in A."""
|
|
|
|
return self.status.current
|
|
|
|
|
|
|
|
@property
|
|
|
|
def voltage(self) -> float | None:
|
|
|
|
"""Get the current voltage in V."""
|
|
|
|
return self.status.voltage
|
|
|
|
|
2020-03-16 13:52:40 +00:00
|
|
|
|
2024-02-04 15:20:08 +00:00
|
|
|
class IotStripPlug(IotPlug):
|
2020-03-16 13:52:40 +00:00
|
|
|
"""Representation of a single socket in a power strip.
|
|
|
|
|
|
|
|
This allows you to use the sockets as they were SmartPlug objects.
|
|
|
|
Instead of calling an update on any of these, you should call an update
|
|
|
|
on the parent device before accessing the properties.
|
async++, small powerstrip improvements (#46)
* async++, small powerstrip improvements
* use asyncclick instead of click, allows defining the commands with async def to avoid manual eventloop/asyncio.run handling
* improve powerstrip support:
* new powerstrip api: turn_{on,off}_by_{name,index} methods
* cli: fix on/off for powerstrip using the new apis
* add missing update()s for cli's hsv, led, temperature (fixes #43)
* prettyprint the received payloads when debug mode in use
* cli: debug mode can be activated now with '-d'
* update requirements_test.txt
* remove outdated click-datetime, replace click with asyncclick
* debug is a flag
* make smartstripplug to inherit the sysinfo from its parent, allows for simple access of general plug properties
* proper bound checking for index accesses, allow controlling the plug at index 0
* remove the mess of turn_{on,off}_by_{name,index}, get_plug_by_{name,index} are enough.
* adapt cli to use that
* allow changing the alias per index
* use f-strings consistently everywhere in the cli
* add tests for get_plug_by_{index,name}
2020-04-21 18:46:13 +00:00
|
|
|
|
|
|
|
The plug inherits (most of) the system information from the parent.
|
2020-03-16 13:52:40 +00:00
|
|
|
"""
|
|
|
|
|
2024-07-01 10:51:06 +00:00
|
|
|
_parent: IotStrip
|
|
|
|
|
2024-04-17 13:39:24 +00:00
|
|
|
def __init__(self, host: str, parent: IotStrip, child_id: str) -> None:
|
2020-04-12 13:57:49 +00:00
|
|
|
super().__init__(host)
|
2020-03-16 13:52:40 +00:00
|
|
|
|
2024-07-01 10:51:06 +00:00
|
|
|
self._parent = parent
|
2020-03-16 13:52:40 +00:00
|
|
|
self.child_id = child_id
|
2020-05-24 15:57:54 +00:00
|
|
|
self._last_update = parent._last_update
|
2023-10-07 19:18:47 +00:00
|
|
|
self._set_sys_info(parent.sys_info)
|
2021-09-21 11:25:14 +00:00
|
|
|
self._device_type = DeviceType.StripSocket
|
2022-04-05 16:16:36 +00:00
|
|
|
self.protocol = parent.protocol # Must use the same connection as the parent
|
2024-10-02 14:04:16 +00:00
|
|
|
self._on_since: datetime | None = None
|
2024-05-13 16:34:44 +00:00
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
async def _initialize_modules(self) -> None:
|
2024-05-13 16:34:44 +00:00
|
|
|
"""Initialize modules not added in init."""
|
2024-06-25 16:24:05 +00:00
|
|
|
if self.has_emeter:
|
|
|
|
self.add_module(Module.Energy, Emeter(self, self.emeter_type))
|
|
|
|
self.add_module(Module.IotUsage, Usage(self, "schedule"))
|
|
|
|
self.add_module(Module.IotAntitheft, Antitheft(self, "anti_theft"))
|
|
|
|
self.add_module(Module.IotSchedule, Schedule(self, "schedule"))
|
|
|
|
self.add_module(Module.IotCountdown, Countdown(self, "countdown"))
|
2020-03-16 13:52:40 +00:00
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
async def _initialize_features(self) -> None:
|
2024-06-07 09:52:11 +00:00
|
|
|
"""Initialize common features."""
|
|
|
|
self._add_feature(
|
|
|
|
Feature(
|
|
|
|
self,
|
|
|
|
id="state",
|
|
|
|
name="State",
|
|
|
|
attribute_getter="is_on",
|
|
|
|
attribute_setter="set_state",
|
|
|
|
type=Feature.Type.Switch,
|
|
|
|
category=Feature.Category.Primary,
|
|
|
|
)
|
|
|
|
)
|
|
|
|
self._add_feature(
|
|
|
|
Feature(
|
|
|
|
device=self,
|
|
|
|
id="on_since",
|
|
|
|
name="On since",
|
|
|
|
attribute_getter="on_since",
|
|
|
|
icon="mdi:clock",
|
2024-06-21 16:42:43 +00:00
|
|
|
category=Feature.Category.Info,
|
2024-06-25 16:30:36 +00:00
|
|
|
type=Feature.Type.Sensor,
|
2024-06-07 09:52:11 +00:00
|
|
|
)
|
|
|
|
)
|
2024-11-10 18:55:13 +00:00
|
|
|
|
|
|
|
for module in self.modules.values():
|
2024-06-17 10:22:05 +00:00
|
|
|
module._initialize_features()
|
|
|
|
for module_feat in module._module_features.values():
|
|
|
|
self._add_feature(module_feat)
|
2024-06-07 09:52:11 +00:00
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
async def update(self, update_children: bool = True) -> None:
|
2021-09-23 22:24:44 +00:00
|
|
|
"""Query the device to update the data.
|
|
|
|
|
|
|
|
Needed for properties that are decorated with `requires_update`.
|
|
|
|
"""
|
2024-07-02 13:11:19 +00:00
|
|
|
await self._update(update_children)
|
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
async def _update(self, update_children: bool = True) -> None:
|
2024-07-02 13:11:19 +00:00
|
|
|
"""Query the device to update the data.
|
|
|
|
|
|
|
|
Internal implementation to allow patching of public update in the cli
|
|
|
|
or test framework.
|
|
|
|
"""
|
2022-04-05 16:16:36 +00:00
|
|
|
await self._modular_update({})
|
2024-06-25 17:58:07 +00:00
|
|
|
for module in self._modules.values():
|
2024-10-08 07:16:51 +00:00
|
|
|
await module._post_update_hook()
|
2024-06-25 17:58:07 +00:00
|
|
|
|
2024-06-17 10:22:05 +00:00
|
|
|
if not self._features:
|
|
|
|
await self._initialize_features()
|
2022-01-29 19:35:10 +00:00
|
|
|
|
2021-09-23 22:24:44 +00:00
|
|
|
def _create_request(
|
2024-11-10 18:55:13 +00:00
|
|
|
self,
|
|
|
|
target: str,
|
|
|
|
cmd: str,
|
|
|
|
arg: dict | None = None,
|
|
|
|
child_ids: list | None = None,
|
|
|
|
) -> dict:
|
2024-04-17 13:39:24 +00:00
|
|
|
request: dict[str, Any] = {
|
2021-09-23 22:24:44 +00:00
|
|
|
"context": {"child_ids": [self.child_id]},
|
|
|
|
target: {cmd: arg},
|
|
|
|
}
|
|
|
|
return request
|
2020-03-16 13:52:40 +00:00
|
|
|
|
|
|
|
async def _query_helper(
|
2024-11-10 18:55:13 +00:00
|
|
|
self,
|
|
|
|
target: str,
|
|
|
|
cmd: str,
|
|
|
|
arg: dict | None = None,
|
|
|
|
child_ids: list | None = None,
|
|
|
|
) -> dict:
|
2020-03-16 13:52:40 +00:00
|
|
|
"""Override query helper to include the child_ids."""
|
2024-07-01 10:51:06 +00:00
|
|
|
return await self._parent._query_helper(
|
2020-03-16 13:52:40 +00:00
|
|
|
target, cmd, arg, child_ids=[self.child_id]
|
|
|
|
)
|
|
|
|
|
|
|
|
@property # type: ignore
|
|
|
|
@requires_update
|
|
|
|
def is_on(self) -> bool:
|
2020-05-27 14:55:18 +00:00
|
|
|
"""Return whether device is on."""
|
2020-03-16 13:52:40 +00:00
|
|
|
info = self._get_child_info()
|
2020-06-30 00:29:52 +00:00
|
|
|
return bool(info["state"])
|
2020-03-16 13:52:40 +00:00
|
|
|
|
|
|
|
@property # type: ignore
|
|
|
|
@requires_update
|
|
|
|
def led(self) -> bool:
|
|
|
|
"""Return the state of the led.
|
|
|
|
|
|
|
|
This is always false for subdevices.
|
|
|
|
"""
|
|
|
|
return False
|
|
|
|
|
|
|
|
@property # type: ignore
|
|
|
|
@requires_update
|
|
|
|
def device_id(self) -> str:
|
|
|
|
"""Return unique ID for the socket.
|
|
|
|
|
|
|
|
This is a combination of MAC and child's ID.
|
|
|
|
"""
|
|
|
|
return f"{self.mac}_{self.child_id}"
|
|
|
|
|
|
|
|
@property # type: ignore
|
|
|
|
@requires_update
|
|
|
|
def alias(self) -> str:
|
2020-05-27 14:55:18 +00:00
|
|
|
"""Return device name (alias)."""
|
2020-03-16 13:52:40 +00:00
|
|
|
info = self._get_child_info()
|
|
|
|
return info["alias"]
|
|
|
|
|
async++, small powerstrip improvements (#46)
* async++, small powerstrip improvements
* use asyncclick instead of click, allows defining the commands with async def to avoid manual eventloop/asyncio.run handling
* improve powerstrip support:
* new powerstrip api: turn_{on,off}_by_{name,index} methods
* cli: fix on/off for powerstrip using the new apis
* add missing update()s for cli's hsv, led, temperature (fixes #43)
* prettyprint the received payloads when debug mode in use
* cli: debug mode can be activated now with '-d'
* update requirements_test.txt
* remove outdated click-datetime, replace click with asyncclick
* debug is a flag
* make smartstripplug to inherit the sysinfo from its parent, allows for simple access of general plug properties
* proper bound checking for index accesses, allow controlling the plug at index 0
* remove the mess of turn_{on,off}_by_{name,index}, get_plug_by_{name,index} are enough.
* adapt cli to use that
* allow changing the alias per index
* use f-strings consistently everywhere in the cli
* add tests for get_plug_by_{index,name}
2020-04-21 18:46:13 +00:00
|
|
|
@property # type: ignore
|
|
|
|
@requires_update
|
2024-04-17 13:39:24 +00:00
|
|
|
def next_action(self) -> dict:
|
async++, small powerstrip improvements (#46)
* async++, small powerstrip improvements
* use asyncclick instead of click, allows defining the commands with async def to avoid manual eventloop/asyncio.run handling
* improve powerstrip support:
* new powerstrip api: turn_{on,off}_by_{name,index} methods
* cli: fix on/off for powerstrip using the new apis
* add missing update()s for cli's hsv, led, temperature (fixes #43)
* prettyprint the received payloads when debug mode in use
* cli: debug mode can be activated now with '-d'
* update requirements_test.txt
* remove outdated click-datetime, replace click with asyncclick
* debug is a flag
* make smartstripplug to inherit the sysinfo from its parent, allows for simple access of general plug properties
* proper bound checking for index accesses, allow controlling the plug at index 0
* remove the mess of turn_{on,off}_by_{name,index}, get_plug_by_{name,index} are enough.
* adapt cli to use that
* allow changing the alias per index
* use f-strings consistently everywhere in the cli
* add tests for get_plug_by_{index,name}
2020-04-21 18:46:13 +00:00
|
|
|
"""Return next scheduled(?) action."""
|
|
|
|
info = self._get_child_info()
|
|
|
|
return info["next_action"]
|
|
|
|
|
2020-03-16 13:52:40 +00:00
|
|
|
@property # type: ignore
|
|
|
|
@requires_update
|
2024-04-17 13:39:24 +00:00
|
|
|
def on_since(self) -> datetime | None:
|
2020-05-27 14:55:18 +00:00
|
|
|
"""Return on-time, if available."""
|
2020-04-24 14:47:57 +00:00
|
|
|
if self.is_off:
|
2024-10-02 14:04:16 +00:00
|
|
|
self._on_since = None
|
2020-04-24 14:47:57 +00:00
|
|
|
return None
|
|
|
|
|
2020-03-16 13:52:40 +00:00
|
|
|
info = self._get_child_info()
|
|
|
|
on_time = info["on_time"]
|
|
|
|
|
2024-10-08 07:16:51 +00:00
|
|
|
time = self._parent.time
|
2024-10-02 14:04:16 +00:00
|
|
|
|
|
|
|
on_since = time - timedelta(seconds=on_time)
|
|
|
|
if not self._on_since or timedelta(
|
|
|
|
seconds=0
|
|
|
|
) < on_since - self._on_since > timedelta(seconds=5):
|
|
|
|
self._on_since = on_since
|
|
|
|
return self._on_since
|
2020-03-16 13:52:40 +00:00
|
|
|
|
|
|
|
@property # type: ignore
|
|
|
|
@requires_update
|
|
|
|
def model(self) -> str:
|
2020-05-27 14:55:18 +00:00
|
|
|
"""Return device model for a child socket."""
|
2024-07-01 10:51:06 +00:00
|
|
|
sys_info = self._parent.sys_info
|
2020-03-16 13:52:40 +00:00
|
|
|
return f"Socket for {sys_info['model']}"
|
|
|
|
|
2024-04-17 13:39:24 +00:00
|
|
|
def _get_child_info(self) -> dict:
|
2020-05-27 14:55:18 +00:00
|
|
|
"""Return the subdevice information for this device."""
|
2024-07-01 10:51:06 +00:00
|
|
|
for plug in self._parent.sys_info["children"]:
|
2020-03-16 13:52:40 +00:00
|
|
|
if plug["id"] == self.child_id:
|
|
|
|
return plug
|
2020-05-27 14:55:18 +00:00
|
|
|
|
2024-07-01 10:51:06 +00:00
|
|
|
raise KasaException(
|
|
|
|
f"Unable to find children {self.child_id}"
|
|
|
|
) # pragma: no cover
|