2019-11-11 21:14:34 +00:00
|
|
|
"""Module for multi-socket devices (HS300, HS107).
|
|
|
|
|
|
|
|
.. todo:: describe how this interfaces with single plugs.
|
|
|
|
"""
|
2019-01-08 19:13:25 +00:00
|
|
|
import logging
|
2020-03-17 23:40:06 +00:00
|
|
|
from collections import defaultdict
|
2020-04-24 14:47:57 +00:00
|
|
|
from datetime import datetime, timedelta
|
2020-03-16 13:52:40 +00:00
|
|
|
from typing import Any, DefaultDict, Dict, List, Optional
|
|
|
|
|
|
|
|
from kasa.smartdevice import (
|
|
|
|
DeviceType,
|
|
|
|
SmartDevice,
|
|
|
|
SmartDeviceException,
|
|
|
|
requires_update,
|
|
|
|
)
|
2019-12-18 08:11:18 +00:00
|
|
|
from kasa.smartplug import SmartPlug
|
2019-01-08 19:13:25 +00:00
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2020-03-16 13:52:40 +00:00
|
|
|
class SmartStrip(SmartDevice):
|
2019-01-08 19:13:25 +00:00
|
|
|
"""Representation of a TP-Link Smart Power Strip.
|
|
|
|
|
|
|
|
Usage example when used as library:
|
2019-11-15 15:05:46 +00:00
|
|
|
```python
|
2019-01-08 19:13:25 +00:00
|
|
|
p = SmartStrip("192.168.1.105")
|
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
|
|
|
|
2019-11-11 21:14:34 +00:00
|
|
|
# query the state of the strip
|
2020-01-12 21:44:19 +00:00
|
|
|
await p.update()
|
2019-11-15 16:48:36 +00:00
|
|
|
print(p.is_on)
|
2019-11-11 21:14:34 +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
|
|
|
# change state of all outlets
|
2020-01-12 21:44:19 +00:00
|
|
|
await p.turn_on()
|
|
|
|
await p.turn_off()
|
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
|
|
|
|
2019-11-11 21:14:34 +00:00
|
|
|
# individual outlets are accessible through plugs variable
|
|
|
|
for plug in p.plugs:
|
2019-11-15 16:48:36 +00:00
|
|
|
print(f"{p}: {p.is_on}")
|
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
|
|
|
|
2019-11-11 21:14:34 +00:00
|
|
|
# change state of a single outlet
|
2020-01-12 21:44:19 +00:00
|
|
|
await p.plugs[0].turn_on()
|
2019-11-15 15:05:46 +00:00
|
|
|
```
|
|
|
|
|
2019-01-08 19:13:25 +00:00
|
|
|
Errors reported by the device are raised as SmartDeviceExceptions,
|
|
|
|
and should be handled by the user of the library.
|
|
|
|
"""
|
|
|
|
|
2020-04-18 21:35:39 +00:00
|
|
|
def __init__(self, host: str) -> None:
|
2020-04-12 13:57:49 +00:00
|
|
|
super().__init__(host=host)
|
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
|
2020-03-16 13:52:40 +00:00
|
|
|
self.plugs: List[SmartStripPlug] = []
|
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."""
|
2019-11-15 13:08:49 +00:00
|
|
|
for plug in self.plugs:
|
2019-11-15 16:48:36 +00:00
|
|
|
is_on = plug.is_on
|
2019-11-15 13:08:49 +00:00
|
|
|
if is_on:
|
|
|
|
return True
|
|
|
|
return False
|
2019-01-08 19:13:25 +00:00
|
|
|
|
2019-11-15 16:48:36 +00:00
|
|
|
async def update(self):
|
|
|
|
"""Update some of the attributes.
|
|
|
|
|
|
|
|
Needed for methods that are decorated with `requires_update`.
|
|
|
|
"""
|
|
|
|
await super().update()
|
2020-01-12 21:44:19 +00:00
|
|
|
|
|
|
|
# Initialize the child devices during the first update.
|
|
|
|
if not self.plugs:
|
|
|
|
children = self.sys_info["children"]
|
2020-03-16 13:52:40 +00:00
|
|
|
_LOGGER.debug("Initializing %s child sockets", len(children))
|
2020-01-12 21:44:19 +00:00
|
|
|
for child in children:
|
|
|
|
self.plugs.append(
|
2020-04-12 13:57:49 +00:00
|
|
|
SmartStripPlug(self.host, parent=self, child_id=child["id"])
|
2020-01-12 21:44:19 +00:00
|
|
|
)
|
|
|
|
|
2019-11-15 13:08:49 +00:00
|
|
|
async def turn_on(self):
|
2019-11-11 21:14:34 +00:00
|
|
|
"""Turn the strip on.
|
2019-01-08 19:13:25 +00:00
|
|
|
|
|
|
|
:raises SmartDeviceException: on error
|
|
|
|
"""
|
2019-11-15 13:08:49 +00:00
|
|
|
await self._query_helper("system", "set_relay_state", {"state": 1})
|
2019-11-15 16:48:36 +00:00
|
|
|
await self.update()
|
2019-01-08 19:13:25 +00:00
|
|
|
|
2019-11-15 13:08:49 +00:00
|
|
|
async def turn_off(self):
|
2019-11-11 21:14:34 +00:00
|
|
|
"""Turn the strip off.
|
2019-01-08 19:13:25 +00:00
|
|
|
|
|
|
|
:raises SmartDeviceException: on error
|
|
|
|
"""
|
2019-11-15 13:08:49 +00:00
|
|
|
await self._query_helper("system", "set_relay_state", {"state": 0})
|
2019-11-15 16:48:36 +00:00
|
|
|
await self.update()
|
2019-01-08 19:13:25 +00:00
|
|
|
|
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
|
|
|
def get_plug_by_name(self, name: str) -> "SmartStripPlug":
|
|
|
|
"""Return child plug for given name."""
|
|
|
|
for p in self.plugs:
|
|
|
|
if p.alias == name:
|
|
|
|
return p
|
|
|
|
|
|
|
|
raise SmartDeviceException(f"Device has no child with {name}")
|
|
|
|
|
|
|
|
def get_plug_by_index(self, index: int) -> "SmartStripPlug":
|
|
|
|
"""Return child plug for given index."""
|
|
|
|
if index + 1 > len(self.plugs) or index < 0:
|
|
|
|
raise SmartDeviceException(
|
|
|
|
f"Invalid index {index}, device has {len(self.plugs)} plugs"
|
|
|
|
)
|
|
|
|
return self.plugs[index]
|
|
|
|
|
2019-12-12 09:46:40 +00:00
|
|
|
@property # type: ignore
|
2019-11-15 16:48:36 +00:00
|
|
|
@requires_update
|
2020-04-24 14:47:57 +00:00
|
|
|
def on_since(self) -> Optional[datetime]:
|
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
|
|
|
|
|
|
|
|
return max(plug.on_since for plug in self.plugs if plug.on_since is not None)
|
2019-01-08 19:13:25 +00:00
|
|
|
|
2020-03-16 13:52:40 +00:00
|
|
|
@property # type: ignore
|
|
|
|
@requires_update
|
|
|
|
def led(self) -> bool:
|
|
|
|
"""Return the state of the led.
|
|
|
|
|
|
|
|
:return: True if led is on, False otherwise
|
|
|
|
:rtype: bool
|
|
|
|
"""
|
|
|
|
sys_info = self.sys_info
|
|
|
|
return bool(1 - sys_info["led_off"])
|
|
|
|
|
|
|
|
async def set_led(self, state: bool):
|
|
|
|
"""Set the state of the led (night mode).
|
|
|
|
|
|
|
|
:param bool state: True to set led on, False to set led off
|
|
|
|
:raises SmartDeviceException: on error
|
|
|
|
"""
|
|
|
|
await self._query_helper("system", "set_led_off", {"off": int(not state)})
|
|
|
|
await self.update()
|
|
|
|
|
2019-12-12 09:46:40 +00:00
|
|
|
@property # type: ignore
|
2019-11-15 16:48:36 +00:00
|
|
|
@requires_update
|
|
|
|
def state_information(self) -> Dict[str, Any]:
|
2019-11-11 21:14:34 +00:00
|
|
|
"""Return strip-specific state information.
|
2019-01-08 19:13:25 +00:00
|
|
|
|
|
|
|
:return: Strip information dict, keys in user-presentable form.
|
|
|
|
:rtype: dict
|
|
|
|
"""
|
2020-05-24 15:57:54 +00:00
|
|
|
return {
|
|
|
|
"LED state": self.led,
|
|
|
|
"Childs count": len(self.plugs),
|
|
|
|
"On since": self.on_since,
|
|
|
|
}
|
2019-01-08 19:13:25 +00:00
|
|
|
|
2019-11-15 13:08:49 +00:00
|
|
|
async def current_consumption(self) -> float:
|
2019-11-11 21:14:34 +00:00
|
|
|
"""Get the current power consumption in watts.
|
|
|
|
|
|
|
|
:return: the current power consumption in watts.
|
|
|
|
:rtype: float
|
2019-01-08 19:13:25 +00:00
|
|
|
:raises SmartDeviceException: on error
|
|
|
|
"""
|
2019-11-15 13:08:49 +00:00
|
|
|
consumption = sum([await plug.current_consumption() for plug in self.plugs])
|
2019-01-08 19:13:25 +00:00
|
|
|
|
2019-11-11 21:14:34 +00:00
|
|
|
return consumption
|
2019-11-11 19:44:12 +00:00
|
|
|
|
2019-11-15 16:48:36 +00:00
|
|
|
async def get_icon(self) -> Dict:
|
2019-11-11 21:14:34 +00:00
|
|
|
"""Icon for the device.
|
2019-01-08 19:13:25 +00:00
|
|
|
|
2019-11-11 21:14:34 +00:00
|
|
|
Overriden to keep the API, as the SmartStrip and children do not
|
|
|
|
have icons, we just return dummy strings.
|
2019-01-08 19:13:25 +00:00
|
|
|
"""
|
2019-11-11 21:14:34 +00:00
|
|
|
return {"icon": "SMARTSTRIP-DUMMY", "hash": "SMARTSTRIP-DUMMY"}
|
2019-01-08 19:13:25 +00:00
|
|
|
|
2019-11-15 13:08:49 +00:00
|
|
|
async def set_alias(self, alias: str) -> None:
|
2019-11-11 21:14:34 +00:00
|
|
|
"""Set the alias for the strip.
|
2019-01-08 19:13:25 +00:00
|
|
|
|
|
|
|
:param alias: new alias
|
|
|
|
:raises SmartDeviceException: on error
|
|
|
|
"""
|
2019-11-15 13:08:49 +00:00
|
|
|
return await super().set_alias(alias)
|
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
|
|
|
|
2019-11-15 16:48:36 +00:00
|
|
|
@requires_update
|
2019-11-11 16:55:56 +00:00
|
|
|
async def get_emeter_daily(
|
2019-11-11 21:14:34 +00:00
|
|
|
self, year: int = None, month: int = None, kwh: bool = True
|
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
|
|
|
) -> 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
|
|
|
|
:rtype: dict
|
|
|
|
:raises SmartDeviceException: on error
|
|
|
|
"""
|
2019-11-11 21:14:34 +00:00
|
|
|
emeter_daily: DefaultDict[int, float] = defaultdict(lambda: 0.0)
|
|
|
|
for plug in self.plugs:
|
2019-11-15 13:08:49 +00:00
|
|
|
plug_emeter_daily = await plug.get_emeter_daily(
|
2019-11-11 16:55:56 +00:00
|
|
|
year=year, month=month, kwh=kwh
|
|
|
|
)
|
2019-11-15 13:08:49 +00:00
|
|
|
for day, value in plug_emeter_daily.items():
|
2019-11-11 21:14:34 +00:00
|
|
|
emeter_daily[day] += value
|
|
|
|
return emeter_daily
|
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
|
|
|
|
2019-11-15 16:48:36 +00:00
|
|
|
@requires_update
|
2019-11-15 13:08:49 +00:00
|
|
|
async def get_emeter_monthly(self, year: int = 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)
|
|
|
|
:return: dict: mapping of month to value
|
|
|
|
:rtype: dict
|
|
|
|
:raises SmartDeviceException: on error
|
|
|
|
"""
|
2019-11-11 21:14:34 +00:00
|
|
|
emeter_monthly: DefaultDict[int, float] = defaultdict(lambda: 0.0)
|
|
|
|
for plug in self.plugs:
|
2019-11-15 13:08:49 +00:00
|
|
|
plug_emeter_monthly = await plug.get_emeter_monthly(year=year, kwh=kwh)
|
|
|
|
for month, value in plug_emeter_monthly:
|
2019-11-11 21:14:34 +00:00
|
|
|
emeter_monthly[month] += value
|
2020-05-24 15:57:54 +00:00
|
|
|
|
2019-11-11 21:14:34 +00:00
|
|
|
return emeter_monthly
|
|
|
|
|
2019-11-15 16:48:36 +00:00
|
|
|
@requires_update
|
2019-11-15 13:08:49 +00:00
|
|
|
async def erase_emeter_stats(self):
|
2019-11-11 21:14:34 +00:00
|
|
|
"""Erase energy meter statistics for all plugs.
|
|
|
|
|
2019-01-08 19:13:25 +00:00
|
|
|
:raises SmartDeviceException: on error
|
|
|
|
"""
|
2019-11-11 21:14:34 +00:00
|
|
|
for plug in self.plugs:
|
2019-11-15 13:08:49 +00:00
|
|
|
await plug.erase_emeter_stats()
|
2020-03-16 13:52:40 +00:00
|
|
|
|
|
|
|
|
|
|
|
class SmartStripPlug(SmartPlug):
|
|
|
|
"""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
|
|
|
"""
|
|
|
|
|
2020-04-12 13:57:49 +00:00
|
|
|
def __init__(self, host: str, parent: "SmartStrip", child_id: str) -> None:
|
|
|
|
super().__init__(host)
|
2020-03-16 13:52:40 +00:00
|
|
|
|
|
|
|
self.parent = parent
|
|
|
|
self.child_id = child_id
|
2020-05-24 15:57:54 +00:00
|
|
|
self._last_update = parent._last_update
|
|
|
|
self._sys_info = parent._sys_info
|
2020-03-16 13:52:40 +00:00
|
|
|
|
|
|
|
async def update(self):
|
|
|
|
"""Override the update to no-op and inform the user."""
|
|
|
|
_LOGGER.warning(
|
|
|
|
"You called update() on a child device, which has no effect."
|
|
|
|
"Call update() on the parent device instead."
|
|
|
|
)
|
|
|
|
return
|
|
|
|
|
|
|
|
async def _query_helper(
|
|
|
|
self, target: str, cmd: str, arg: Optional[Dict] = None, child_ids=None
|
|
|
|
) -> Any:
|
|
|
|
"""Override query helper to include the child_ids."""
|
|
|
|
return await self.parent._query_helper(
|
|
|
|
target, cmd, arg, child_ids=[self.child_id]
|
|
|
|
)
|
|
|
|
|
|
|
|
@property # type: ignore
|
|
|
|
@requires_update
|
|
|
|
def is_on(self) -> bool:
|
|
|
|
"""Return whether device is on.
|
|
|
|
|
|
|
|
:return: True if device is on, False otherwise
|
|
|
|
"""
|
|
|
|
info = self._get_child_info()
|
|
|
|
return info["state"]
|
|
|
|
|
|
|
|
@property # type: ignore
|
|
|
|
@requires_update
|
|
|
|
def led(self) -> bool:
|
|
|
|
"""Return the state of the led.
|
|
|
|
|
|
|
|
This is always false for subdevices.
|
|
|
|
|
|
|
|
:return: True if led is on, False otherwise
|
|
|
|
:rtype: bool
|
|
|
|
"""
|
|
|
|
return False
|
|
|
|
|
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
|
|
|
|
def has_emeter(self) -> bool:
|
|
|
|
"""Children have no emeter to my knowledge."""
|
|
|
|
return False
|
|
|
|
|
2020-03-16 13:52:40 +00:00
|
|
|
@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:
|
|
|
|
"""Return device name (alias).
|
|
|
|
|
|
|
|
:return: Device name aka alias.
|
|
|
|
:rtype: str
|
|
|
|
"""
|
|
|
|
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
|
|
|
|
def next_action(self) -> Dict:
|
|
|
|
"""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
|
2020-04-24 14:47:57 +00:00
|
|
|
def on_since(self) -> Optional[datetime]:
|
2020-03-16 13:52:40 +00:00
|
|
|
"""Return pretty-printed on-time.
|
|
|
|
|
|
|
|
:return: datetime for on since
|
|
|
|
:rtype: datetime
|
|
|
|
"""
|
2020-04-24 14:47:57 +00:00
|
|
|
if self.is_off:
|
|
|
|
return None
|
|
|
|
|
2020-03-16 13:52:40 +00:00
|
|
|
info = self._get_child_info()
|
|
|
|
on_time = info["on_time"]
|
|
|
|
|
2020-04-24 14:47:57 +00:00
|
|
|
return datetime.now() - timedelta(seconds=on_time)
|
2020-03-16 13:52:40 +00:00
|
|
|
|
|
|
|
@property # type: ignore
|
|
|
|
@requires_update
|
|
|
|
def model(self) -> str:
|
|
|
|
"""Return device model for a child socket.
|
|
|
|
|
|
|
|
:return: device model
|
|
|
|
:rtype: str
|
|
|
|
:raises SmartDeviceException: on error
|
|
|
|
"""
|
|
|
|
sys_info = self.parent.sys_info
|
|
|
|
return f"Socket for {sys_info['model']}"
|
|
|
|
|
|
|
|
def _get_child_info(self) -> Dict:
|
|
|
|
"""Return the subdevice information for this device.
|
|
|
|
|
|
|
|
:raises SmartDeviceException: if the information is not found.
|
|
|
|
"""
|
|
|
|
for plug in self.parent.sys_info["children"]:
|
|
|
|
if plug["id"] == self.child_id:
|
|
|
|
return plug
|
|
|
|
raise SmartDeviceException(f"Unable to find children {self.child_id}")
|