python-kasa/pyHS100/smartstrip.py

200 lines
6.1 KiB
Python
Raw Normal View History

"""Module for multi-socket devices (HS300, HS107).
.. todo:: describe how this interfaces with single plugs.
"""
import datetime
import logging
from collections import defaultdict
from typing import Any, DefaultDict, Dict, List
2019-11-11 16:55:56 +00:00
from pyHS100.protocol import TPLinkSmartHomeProtocol
from pyHS100.smartdevice import DeviceType, requires_update
from pyHS100.smartplug import SmartPlug
_LOGGER = logging.getLogger(__name__)
class SmartStrip(SmartPlug):
"""Representation of a TP-Link Smart Power Strip.
Usage example when used as library:
2019-11-15 15:05:46 +00:00
```python
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
# query the state of the strip
print(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
# change state of all outlets
p.sync.turn_on()
p.sync.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
# individual outlets are accessible through plugs variable
for plug in p.plugs:
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
# change state of a single outlet
p.plugs[0].sync.turn_on()
2019-11-15 15:05:46 +00:00
```
Omit the `sync` attribute to get coroutines.
Errors reported by the device are raised as SmartDeviceExceptions,
and should be handled by the user of the library.
"""
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
def __init__(
2019-11-11 18:16:55 +00:00
self,
host: str,
protocol: TPLinkSmartHomeProtocol = None,
cache_ttl: int = 3,
ioloop=None,
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
) -> None:
SmartPlug.__init__(self, host=host, protocol=protocol, cache_ttl=cache_ttl)
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
self.plugs: List[SmartPlug] = []
children = self.sync.get_sys_info()["children"]
self.num_children = len(children)
for child in children:
self.plugs.append(
SmartPlug(
host,
protocol,
context=child["id"],
cache_ttl=cache_ttl,
ioloop=ioloop,
)
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
)
@property
@requires_update
def is_on(self) -> bool:
"""Return if any of the outlets are on."""
for plug in self.plugs:
is_on = plug.is_on
if is_on:
return True
return False
async def update(self):
"""Update some of the attributes.
Needed for methods that are decorated with `requires_update`.
"""
await super().update()
for plug in self.plugs:
await plug.update()
async def turn_on(self):
"""Turn the strip on.
:raises SmartDeviceException: on error
"""
await self._query_helper("system", "set_relay_state", {"state": 1})
await self.update()
async def turn_off(self):
"""Turn the strip off.
:raises SmartDeviceException: on error
"""
await self._query_helper("system", "set_relay_state", {"state": 0})
await self.update()
@property
@requires_update
def on_since(self) -> datetime.datetime:
"""Return the maximum on-time of all outlets."""
return max(plug.on_since for plug in self.plugs)
@property
@requires_update
def state_information(self) -> Dict[str, Any]:
"""Return strip-specific state information.
:return: Strip information dict, keys in user-presentable form.
:rtype: dict
"""
state: Dict[str, Any] = {"LED state": self.led}
for plug in self.plugs:
if plug.is_on:
state["Plug %s on since" % str(plug)] = self.on_since
return state
async def current_consumption(self) -> float:
"""Get the current power consumption in watts.
:return: the current power consumption in watts.
:rtype: float
:raises SmartDeviceException: on error
"""
consumption = sum([await plug.current_consumption() for plug in self.plugs])
return consumption
2019-11-11 19:44:12 +00:00
async def get_icon(self) -> Dict:
"""Icon for the device.
Overriden to keep the API, as the SmartStrip and children do not
have icons, we just return dummy strings.
"""
return {"icon": "SMARTSTRIP-DUMMY", "hash": "SMARTSTRIP-DUMMY"}
async def set_alias(self, alias: str) -> None:
"""Set the alias for the strip.
:param alias: new alias
:raises SmartDeviceException: on error
"""
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
@requires_update
2019-11-11 16:55:56 +00:00
async def get_emeter_daily(
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:
"""Retrieve daily statistics for a given month.
: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
"""
emeter_daily: DefaultDict[int, float] = defaultdict(lambda: 0.0)
for plug in self.plugs:
plug_emeter_daily = await plug.get_emeter_daily(
2019-11-11 16:55:56 +00:00
year=year, month=month, kwh=kwh
)
for day, value in plug_emeter_daily.items():
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
@requires_update
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.
: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
"""
emeter_monthly: DefaultDict[int, float] = defaultdict(lambda: 0.0)
for plug in self.plugs:
plug_emeter_monthly = await plug.get_emeter_monthly(year=year, kwh=kwh)
for month, value in plug_emeter_monthly:
emeter_monthly[month] += value
return emeter_monthly
@requires_update
async def erase_emeter_stats(self):
"""Erase energy meter statistics for all plugs.
:raises SmartDeviceException: on error
"""
for plug in self.plugs:
await plug.erase_emeter_stats()