mirror of
https://github.com/python-kasa/python-kasa.git
synced 2024-12-22 19:23: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
This commit is contained in:
parent
e82746da24
commit
2d60467bea
5
.flake8
Normal file
5
.flake8
Normal file
@ -0,0 +1,5 @@
|
||||
[flake8]
|
||||
ignore = E203, E266, E501, W503, F403, F401
|
||||
max-line-length = 79
|
||||
max-complexity = 18
|
||||
select = B,C,E,F,W,T4,B9
|
@ -1,2 +1,5 @@
|
||||
python:
|
||||
enabled: true
|
||||
flake8:
|
||||
enabled: true
|
||||
config_file: .flake8
|
||||
|
6
.pre-commit-config.yaml
Normal file
6
.pre-commit-config.yaml
Normal file
@ -0,0 +1,6 @@
|
||||
repos:
|
||||
- repo: https://github.com/python/black
|
||||
rev: stable
|
||||
hooks:
|
||||
- id: black
|
||||
language_version: python3.7
|
@ -2,9 +2,9 @@ sudo: false
|
||||
language: python
|
||||
dist: xenial
|
||||
python:
|
||||
- "3.4"
|
||||
- "3.5"
|
||||
- "3.6"
|
||||
- "3.7"
|
||||
install: pip install tox-travis coveralls
|
||||
script: tox
|
||||
after_success: coveralls
|
||||
|
@ -14,6 +14,7 @@ to be handled by the user of the library.
|
||||
"""
|
||||
# flake8: noqa
|
||||
from .smartdevice import SmartDevice, SmartDeviceException, EmeterStatus
|
||||
from .smartdevice import SmartDevice, SmartDeviceException, EmeterStatus, DeviceType
|
||||
from .smartplug import SmartPlug
|
||||
from .smartbulb import SmartBulb
|
||||
from .smartstrip import SmartStrip, SmartStripException
|
||||
|
175
pyHS100/cli.py
175
pyHS100/cli.py
@ -1,36 +1,49 @@
|
||||
"""pyHS100 cli tool."""
|
||||
import sys
|
||||
import click
|
||||
import logging
|
||||
from click_datetime import Datetime
|
||||
from pprint import pformat as pf
|
||||
|
||||
if sys.version_info < (3, 4):
|
||||
print("To use this script you need python 3.4 or newer! got %s" %
|
||||
sys.version_info)
|
||||
print("To use this script you need python 3.4 or newer! got %s" % sys.version_info)
|
||||
sys.exit(1)
|
||||
|
||||
from pyHS100 import (SmartDevice,
|
||||
SmartPlug,
|
||||
SmartBulb,
|
||||
SmartStrip,
|
||||
Discover) # noqa: E402
|
||||
from pyHS100 import (
|
||||
SmartDevice,
|
||||
SmartPlug,
|
||||
SmartBulb,
|
||||
SmartStrip,
|
||||
Discover,
|
||||
) # noqa: E402
|
||||
|
||||
pass_dev = click.make_pass_decorator(SmartDevice)
|
||||
|
||||
|
||||
@click.group(invoke_without_command=True)
|
||||
@click.option('--ip', envvar="PYHS100_IP", required=False,
|
||||
help='The IP address of the device to connect to. This option '
|
||||
'is deprecated and will be removed in the future; use --host '
|
||||
'instead.')
|
||||
@click.option('--host', envvar="PYHS100_HOST", required=False,
|
||||
help='The host name or IP address of the device to connect to.')
|
||||
@click.option('--alias', envvar="PYHS100_NAME", required=False,
|
||||
help='The device name, or alias, of the device to connect to.')
|
||||
@click.option('--debug/--normal', default=False)
|
||||
@click.option('--bulb', default=False, is_flag=True)
|
||||
@click.option('--plug', default=False, is_flag=True)
|
||||
@click.option('--strip', default=False, is_flag=True)
|
||||
@click.option(
|
||||
"--ip",
|
||||
envvar="PYHS100_IP",
|
||||
required=False,
|
||||
help="The IP address of the device to connect to. This option "
|
||||
"is deprecated and will be removed in the future; use --host "
|
||||
"instead.",
|
||||
)
|
||||
@click.option(
|
||||
"--host",
|
||||
envvar="PYHS100_HOST",
|
||||
required=False,
|
||||
help="The host name or IP address of the device to connect to.",
|
||||
)
|
||||
@click.option(
|
||||
"--alias",
|
||||
envvar="PYHS100_NAME",
|
||||
required=False,
|
||||
help="The device name, or alias, of the device to connect to.",
|
||||
)
|
||||
@click.option("--debug/--normal", default=False)
|
||||
@click.option("--bulb", default=False, is_flag=True)
|
||||
@click.option("--plug", default=False, is_flag=True)
|
||||
@click.option("--strip", default=False, is_flag=True)
|
||||
@click.pass_context
|
||||
def cli(ctx, ip, host, alias, debug, bulb, plug, strip):
|
||||
"""A cli tool for controlling TP-Link smart home plugs."""
|
||||
@ -46,8 +59,7 @@ def cli(ctx, ip, host, alias, debug, bulb, plug, strip):
|
||||
host = ip
|
||||
|
||||
if alias is not None and host is None:
|
||||
click.echo("Alias is given, using discovery to find host %s" %
|
||||
alias)
|
||||
click.echo("Alias is given, using discovery to find host %s" % alias)
|
||||
host = find_host_from_alias(alias=alias)
|
||||
if host:
|
||||
click.echo("Found hostname is {}".format(host))
|
||||
@ -70,8 +82,7 @@ def cli(ctx, ip, host, alias, debug, bulb, plug, strip):
|
||||
elif strip:
|
||||
dev = SmartStrip(host)
|
||||
else:
|
||||
click.echo(
|
||||
"Unable to detect type, use --strip or --bulb or --plug!")
|
||||
click.echo("Unable to detect type, use --strip or --bulb or --plug!")
|
||||
return
|
||||
ctx.obj = dev
|
||||
|
||||
@ -80,15 +91,33 @@ def cli(ctx, ip, host, alias, debug, bulb, plug, strip):
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.option('--timeout', default=3, required=False)
|
||||
@click.option('--discover-only', default=False)
|
||||
@click.option("--save")
|
||||
def dump_discover(save):
|
||||
for dev in Discover.discover(return_raw=True).values():
|
||||
model = dev["system"]["get_sysinfo"]["model"]
|
||||
hw_version = dev["system"]["get_sysinfo"]["hw_ver"]
|
||||
save_to = "%s_%s.json" % (model, hw_version)
|
||||
click.echo("Saving info to %s" % save_to)
|
||||
with open(save_to, "w") as f:
|
||||
import json
|
||||
|
||||
json.dump(dev, f, sort_keys=True, indent=4)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.option("--timeout", default=3, required=False)
|
||||
@click.option("--discover-only", default=False)
|
||||
@click.option("--dump-raw", is_flag=True)
|
||||
@click.pass_context
|
||||
def discover(ctx, timeout, discover_only):
|
||||
def discover(ctx, timeout, discover_only, dump_raw):
|
||||
"""Discover devices in the network."""
|
||||
click.echo("Discovering devices for %s seconds" % timeout)
|
||||
found_devs = Discover.discover(timeout=timeout).items()
|
||||
found_devs = Discover.discover(timeout=timeout, return_raw=dump_raw).items()
|
||||
if not discover_only:
|
||||
for ip, dev in found_devs:
|
||||
if dump_raw:
|
||||
click.echo(dev)
|
||||
continue
|
||||
ctx.obj = dev
|
||||
ctx.invoke(state)
|
||||
print()
|
||||
@ -97,10 +126,12 @@ def discover(ctx, timeout, discover_only):
|
||||
|
||||
|
||||
def find_host_from_alias(alias, timeout=1, attempts=3):
|
||||
"""Discover a device identified by its alias"""
|
||||
"""Discover a device identified by its alias."""
|
||||
host = None
|
||||
click.echo("Trying to discover %s using %s attempts of %s seconds" %
|
||||
(alias, attempts, timeout))
|
||||
click.echo(
|
||||
"Trying to discover %s using %s attempts of %s seconds"
|
||||
% (alias, attempts, timeout)
|
||||
)
|
||||
for attempt in range(1, attempts):
|
||||
click.echo("Attempt %s of %s" % (attempt, attempts))
|
||||
found_devs = Discover.discover(timeout=timeout).items()
|
||||
@ -124,20 +155,26 @@ def sysinfo(dev):
|
||||
@click.pass_context
|
||||
def state(ctx, dev):
|
||||
"""Print out device state and versions."""
|
||||
click.echo(click.style("== %s - %s ==" % (dev.alias, dev.model),
|
||||
bold=True))
|
||||
click.echo(click.style("== %s - %s ==" % (dev.alias, dev.model), bold=True))
|
||||
|
||||
click.echo(click.style("Device state: %s" % "ON" if dev.is_on else "OFF",
|
||||
fg="green" if dev.is_on else "red"))
|
||||
click.echo(
|
||||
click.style(
|
||||
"Device state: %s" % "ON" if dev.is_on else "OFF",
|
||||
fg="green" if dev.is_on else "red",
|
||||
)
|
||||
)
|
||||
if dev.num_children > 0:
|
||||
is_on = dev.is_on()
|
||||
aliases = dev.get_alias()
|
||||
for child in range(dev.num_children):
|
||||
click.echo(
|
||||
click.style(" * %s state: %s" %
|
||||
(aliases[child],
|
||||
"ON" if is_on[child] else "OFF"),
|
||||
fg="green" if is_on[child] else "red"))
|
||||
click.style(
|
||||
" * %s state: %s"
|
||||
% (aliases[child], "ON" if is_on[child] else "OFF"),
|
||||
fg="green" if is_on[child] else "red",
|
||||
)
|
||||
)
|
||||
|
||||
click.echo("Host/IP: %s" % dev.host)
|
||||
for k, v in dev.state_information.items():
|
||||
click.echo("%s: %s" % (k, v))
|
||||
@ -153,7 +190,7 @@ def state(ctx, dev):
|
||||
|
||||
@cli.command()
|
||||
@pass_dev
|
||||
@click.argument('new_alias', required=False, default=None)
|
||||
@click.argument("new_alias", required=False, default=None)
|
||||
def alias(dev, new_alias):
|
||||
"""Get or set the device alias."""
|
||||
if new_alias is not None:
|
||||
@ -165,11 +202,24 @@ def alias(dev, new_alias):
|
||||
|
||||
@cli.command()
|
||||
@pass_dev
|
||||
@click.option('--year', type=Datetime(format='%Y'),
|
||||
default=None, required=False)
|
||||
@click.option('--month', type=Datetime(format='%Y-%m'),
|
||||
default=None, required=False)
|
||||
@click.option('--erase', is_flag=True)
|
||||
@click.argument("module")
|
||||
@click.argument("command")
|
||||
@click.argument("parameters", default=None, required=False)
|
||||
def raw_command(dev: SmartDevice, module, command, parameters):
|
||||
"""Run a raw command on the device."""
|
||||
import ast
|
||||
|
||||
if parameters is not None:
|
||||
parameters = ast.literal_eval(parameters)
|
||||
res = dev._query_helper(module, command, parameters)
|
||||
click.echo(res)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@pass_dev
|
||||
@click.option("--year", type=click.DateTime(["%Y"]), default=None, required=False)
|
||||
@click.option("--month", type=click.DateTime(["%Y-%m"]), default=None, required=False)
|
||||
@click.option("--erase", is_flag=True)
|
||||
def emeter(dev, year, month, erase):
|
||||
"""Query emeter for historical consumption."""
|
||||
click.echo(click.style("== Emeter ==", bold=True))
|
||||
@ -187,8 +237,7 @@ def emeter(dev, year, month, erase):
|
||||
emeter_status = dev.get_emeter_monthly(year.year)
|
||||
elif month:
|
||||
click.echo("== For month %s of %s ==" % (month.month, month.year))
|
||||
emeter_status = dev.get_emeter_daily(year=month.year,
|
||||
month=month.month)
|
||||
emeter_status = dev.get_emeter_daily(year=month.year, month=month.month)
|
||||
else:
|
||||
emeter_status = dev.get_emeter_realtime()
|
||||
click.echo("== Current State ==")
|
||||
@ -201,8 +250,7 @@ def emeter(dev, year, month, erase):
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.argument("brightness", type=click.IntRange(0, 100), default=None,
|
||||
required=False)
|
||||
@click.argument("brightness", type=click.IntRange(0, 100), default=None, required=False)
|
||||
@pass_dev
|
||||
def brightness(dev, brightness):
|
||||
"""Get or set brightness."""
|
||||
@ -217,21 +265,24 @@ def brightness(dev, brightness):
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.argument("temperature", type=click.IntRange(2500, 9000), default=None,
|
||||
required=False)
|
||||
@click.argument(
|
||||
"temperature", type=click.IntRange(2500, 9000), default=None, required=False
|
||||
)
|
||||
@pass_dev
|
||||
def temperature(dev, temperature):
|
||||
"""Get or set color temperature. (Bulb only)"""
|
||||
def temperature(dev: SmartBulb, temperature):
|
||||
"""Get or set color temperature."""
|
||||
if temperature is None:
|
||||
click.echo("Color temperature: %s" % dev.color_temp)
|
||||
if dev.valid_temperature_range != (0, 0):
|
||||
click.echo("(min: %s, max: %s)" % dev.valid_temperature_range)
|
||||
else:
|
||||
click.echo("Temperature range unknown, please open a github issue"
|
||||
" or a pull request for model '%s'" % dev.model)
|
||||
click.echo(
|
||||
"Temperature range unknown, please open a github issue"
|
||||
" or a pull request for model '%s'" % dev.model
|
||||
)
|
||||
else:
|
||||
click.echo("Setting color temperature to %s" % temperature)
|
||||
dev.color_temp = temperature
|
||||
dev.set_color_temp(temperature)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@ -242,20 +293,20 @@ def temperature(dev, temperature):
|
||||
@pass_dev
|
||||
def hsv(dev, ctx, h, s, v):
|
||||
"""Get or set color in HSV. (Bulb only)"""
|
||||
if h is None:
|
||||
if h is None or s is None or v is None:
|
||||
click.echo("Current HSV: %s %s %s" % dev.hsv)
|
||||
elif s is None or v is None:
|
||||
raise click.BadArgumentUsage("Setting a color requires 3 values.", ctx)
|
||||
else:
|
||||
click.echo("Setting HSV: %s %s %s" % (h, s, v))
|
||||
dev.hsv = (h, s, v)
|
||||
dev.set_hsv(h, s, v)
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.argument('state', type=bool, required=False)
|
||||
@click.argument("state", type=bool, required=False)
|
||||
@pass_dev
|
||||
def led(dev, state):
|
||||
"""Get or set led state. (Plug only)"""
|
||||
"""Get or set (Plug's) led state."""
|
||||
if state is not None:
|
||||
click.echo("Turning led to %s" % state)
|
||||
dev.led = state
|
||||
@ -271,7 +322,7 @@ def time(dev):
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.argument('index', type=int, required=False)
|
||||
@click.argument("index", type=int, required=False)
|
||||
@pass_dev
|
||||
def on(plug, index):
|
||||
"""Turn the device on."""
|
||||
@ -283,7 +334,7 @@ def on(plug, index):
|
||||
|
||||
|
||||
@cli.command()
|
||||
@click.argument('index', type=int, required=False)
|
||||
@click.argument("index", type=int, required=False)
|
||||
@pass_dev
|
||||
def off(plug, index):
|
||||
"""Turn the device off."""
|
||||
|
@ -1,23 +1,54 @@
|
||||
import socket
|
||||
import logging
|
||||
import json
|
||||
from typing import Dict, Type
|
||||
from typing import Dict, Type, Optional
|
||||
|
||||
from pyHS100 import (TPLinkSmartHomeProtocol, SmartDevice, SmartPlug,
|
||||
SmartBulb, SmartStrip)
|
||||
from pyHS100 import (
|
||||
TPLinkSmartHomeProtocol,
|
||||
SmartDevice,
|
||||
SmartPlug,
|
||||
SmartBulb,
|
||||
SmartStrip,
|
||||
SmartDeviceException,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Discover:
|
||||
DISCOVERY_QUERY = {"system": {"get_sysinfo": None},
|
||||
"emeter": {"get_realtime": None}}
|
||||
"""Discover TPLink Smart Home devices.
|
||||
|
||||
The main entry point for this library is Discover.discover(),
|
||||
which returns a dictionary of the found devices. The key is the IP address
|
||||
of the device and the value contains ready-to-use, SmartDevice-derived
|
||||
device object.
|
||||
|
||||
discover_single() can be used to initialize a single device given its
|
||||
IP address. If the type of the device and its IP address is already known,
|
||||
you can initialize the corresponding device class directly without this.
|
||||
|
||||
The protocol uses UDP broadcast datagrams on port 9999 for discovery.
|
||||
|
||||
|
||||
"""
|
||||
|
||||
DISCOVERY_QUERY = {
|
||||
"system": {"get_sysinfo": None},
|
||||
"emeter": {"get_realtime": None},
|
||||
"smartlife.iot.dimmer": {"get_dimmer_parameters": None},
|
||||
"smartlife.iot.common.emeter": {"get_realtime": None},
|
||||
"smartlife.iot.smartbulb.lightingservice": {"get_light_state": None},
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def discover(protocol: TPLinkSmartHomeProtocol = None,
|
||||
port: int = 9999,
|
||||
timeout: int = 3,
|
||||
discovery_packets = 3) -> Dict[str, SmartDevice]:
|
||||
def discover(
|
||||
protocol: TPLinkSmartHomeProtocol = None,
|
||||
port: int = 9999,
|
||||
timeout: int = 3,
|
||||
discovery_packets=3,
|
||||
return_raw=False,
|
||||
) -> Dict[str, SmartDevice]:
|
||||
|
||||
"""
|
||||
Sends discovery message to 255.255.255.255:9999 in order
|
||||
to detect available supported devices in the local network,
|
||||
@ -55,21 +86,22 @@ class Discover:
|
||||
ip, port = addr
|
||||
info = json.loads(protocol.decrypt(data))
|
||||
device_class = Discover._get_device_class(info)
|
||||
if device_class is not None:
|
||||
if return_raw:
|
||||
devices[ip] = info
|
||||
elif device_class is not None:
|
||||
devices[ip] = device_class(ip)
|
||||
except socket.timeout:
|
||||
_LOGGER.debug("Got socket timeout, which is okay.")
|
||||
except Exception as ex:
|
||||
_LOGGER.error("Got exception %s", ex, exc_info=True)
|
||||
_LOGGER.debug("Found %s devices: %s", len(devices), devices)
|
||||
return devices
|
||||
|
||||
@staticmethod
|
||||
def discover_single(host: str,
|
||||
protocol: TPLinkSmartHomeProtocol = None
|
||||
) -> SmartDevice:
|
||||
"""
|
||||
Similar to discover(), except only return device object for a single
|
||||
host.
|
||||
def discover_single(
|
||||
host: str, protocol: TPLinkSmartHomeProtocol = None
|
||||
) -> Optional[SmartDevice]:
|
||||
"""Discover a single device by the given IP address.
|
||||
|
||||
:param host: Hostname of device to query
|
||||
:param protocol: Protocol implementation to use
|
||||
@ -84,29 +116,28 @@ class Discover:
|
||||
device_class = Discover._get_device_class(info)
|
||||
if device_class is not None:
|
||||
return device_class(host)
|
||||
else:
|
||||
return None
|
||||
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _get_device_class(info: dict) -> Type[SmartDevice]:
|
||||
def _get_device_class(info: dict) -> Optional[Type[SmartDevice]]:
|
||||
"""Find SmartDevice subclass for device described by passed data."""
|
||||
if "system" in info and "get_sysinfo" in info["system"]:
|
||||
sysinfo = info["system"]["get_sysinfo"]
|
||||
if "type" in sysinfo:
|
||||
type = sysinfo["type"]
|
||||
type_ = sysinfo["type"]
|
||||
elif "mic_type" in sysinfo:
|
||||
type = sysinfo["mic_type"]
|
||||
type_ = sysinfo["mic_type"]
|
||||
else:
|
||||
_LOGGER.error("Unable to find the device type field!")
|
||||
type = "UNKNOWN"
|
||||
raise SmartDeviceException("Unable to find the device type field!")
|
||||
else:
|
||||
_LOGGER.error("No 'system' nor 'get_sysinfo' in response")
|
||||
raise SmartDeviceException("No 'system' nor 'get_sysinfo' in response")
|
||||
|
||||
if "smartplug" in type.lower() and "children" in sysinfo:
|
||||
if "smartplug" in type_.lower() and "children" in sysinfo:
|
||||
return SmartStrip
|
||||
elif "smartplug" in type.lower():
|
||||
elif "smartplug" in type_.lower():
|
||||
return SmartPlug
|
||||
elif "smartbulb" in type.lower():
|
||||
elif "smartbulb" in type_.lower():
|
||||
return SmartBulb
|
||||
|
||||
return None
|
||||
|
@ -8,8 +8,7 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TPLinkSmartHomeProtocol:
|
||||
"""
|
||||
Implementation of the TP-Link Smart Home Protocol
|
||||
"""Implementation of the TP-Link Smart Home Protocol.
|
||||
|
||||
Encryption/Decryption methods based on the works of
|
||||
Lubomir Stroetmann and Tobias Esser
|
||||
@ -20,23 +19,20 @@ class TPLinkSmartHomeProtocol:
|
||||
which are licensed under the Apache License, Version 2.0
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
"""
|
||||
|
||||
INITIALIZATION_VECTOR = 171
|
||||
DEFAULT_PORT = 9999
|
||||
DEFAULT_TIMEOUT = 5
|
||||
|
||||
@staticmethod
|
||||
def query(host: str,
|
||||
request: Union[str, Dict],
|
||||
port: int = DEFAULT_PORT) -> Any:
|
||||
"""
|
||||
Request information from a TP-Link SmartHome Device and return the
|
||||
response.
|
||||
def query(host: str, request: Union[str, Dict], port: int = DEFAULT_PORT) -> Any:
|
||||
"""Request information from a TP-Link SmartHome Device.
|
||||
|
||||
:param str host: host name or ip address of the device
|
||||
:param int port: port on the device (default: 9999)
|
||||
:param request: command to send to the device (can be either dict or
|
||||
json string)
|
||||
:return:
|
||||
:return: response dict
|
||||
"""
|
||||
if isinstance(request, dict):
|
||||
request = json.dumps(request)
|
||||
|
@ -1,14 +1,20 @@
|
||||
from pyHS100 import SmartDevice, SmartDeviceException
|
||||
from pyHS100 import DeviceType, SmartDevice, SmartDeviceException
|
||||
from .protocol import TPLinkSmartHomeProtocol
|
||||
from deprecation import deprecated
|
||||
import re
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, Tuple
|
||||
|
||||
TPLINK_KELVIN = {'LB130': (2500, 9000),
|
||||
'LB120': (2700, 6500),
|
||||
'LB230': (2500, 9000),
|
||||
'KB130': (2500, 9000),
|
||||
'KL130': (2500, 9000),
|
||||
'KL120\(EU\)': (2700, 6500),
|
||||
'KL120\(US\)': (2700, 5000)}
|
||||
|
||||
TPLINK_KELVIN = {
|
||||
"LB130": (2500, 9000),
|
||||
"LB120": (2700, 6500),
|
||||
"LB230": (2500, 9000),
|
||||
"KB130": (2500, 9000),
|
||||
"KL130": (2500, 9000),
|
||||
"KL120\(EU\)": (2700, 6500),
|
||||
"KL120\(US\)": (2700, 5000),
|
||||
}
|
||||
|
||||
|
||||
class SmartBulb(SmartDevice):
|
||||
@ -16,82 +22,89 @@ class SmartBulb(SmartDevice):
|
||||
|
||||
Usage example when used as library:
|
||||
p = SmartBulb("192.168.1.105")
|
||||
|
||||
# print the devices alias
|
||||
print(p.alias)
|
||||
|
||||
# change state of bulb
|
||||
p.state = "ON"
|
||||
p.state = "OFF"
|
||||
p.turn_on()
|
||||
p.turn_off()
|
||||
|
||||
# query and print current state of plug
|
||||
print(p.state)
|
||||
|
||||
# check whether the bulb supports color changes
|
||||
if p.is_color:
|
||||
|
||||
# set the color to an HSV tuple
|
||||
p.hsv = (180, 100, 100)
|
||||
p.set_hsv(180, 100, 100)
|
||||
# get the current HSV value
|
||||
print(p.hsv)
|
||||
|
||||
# check whether the bulb supports setting color temperature
|
||||
if p.is_variable_color_temp:
|
||||
# set the color temperature in Kelvin
|
||||
p.color_temp = 3000
|
||||
p.set_color_temp(3000)
|
||||
# get the current color temperature
|
||||
print(p.color_temp)
|
||||
|
||||
# check whether the bulb is dimmable
|
||||
if p.is_dimmable:
|
||||
# set the bulb to 50% brightness
|
||||
p.brightness = 50
|
||||
p.set_brightness(50)
|
||||
# check the current brightness
|
||||
print(p.brightness)
|
||||
|
||||
Errors reported by the device are raised as SmartDeviceExceptions,
|
||||
and should be handled by the user of the library.
|
||||
|
||||
"""
|
||||
# bulb states
|
||||
BULB_STATE_ON = 'ON'
|
||||
BULB_STATE_OFF = 'OFF'
|
||||
|
||||
def __init__(self,
|
||||
host: str,
|
||||
protocol: 'TPLinkSmartHomeProtocol' = None) -> None:
|
||||
SmartDevice.__init__(self, host, protocol)
|
||||
LIGHT_SERVICE = "smartlife.iot.smartbulb.lightingservice"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
host: str,
|
||||
protocol: TPLinkSmartHomeProtocol = None,
|
||||
context: str = None,
|
||||
cache_ttl: int = 3,
|
||||
) -> None:
|
||||
SmartDevice.__init__(
|
||||
self, host=host, protocol=protocol, context=context, cache_ttl=cache_ttl
|
||||
)
|
||||
self.emeter_type = "smartlife.iot.common.emeter"
|
||||
self._device_type = DeviceType.Bulb
|
||||
|
||||
@property
|
||||
def is_color(self) -> bool:
|
||||
"""
|
||||
Whether the bulb supports color changes
|
||||
"""Whether the bulb supports color changes.
|
||||
|
||||
:return: True if the bulb supports color changes, False otherwise
|
||||
:rtype: bool
|
||||
"""
|
||||
return bool(self.sys_info['is_color'])
|
||||
return bool(self.sys_info["is_color"])
|
||||
|
||||
@property
|
||||
def is_dimmable(self) -> bool:
|
||||
"""
|
||||
Whether the bulb supports brightness changes
|
||||
"""Whether the bulb supports brightness changes.
|
||||
|
||||
:return: True if the bulb supports brightness changes, False otherwise
|
||||
:rtype: bool
|
||||
"""
|
||||
return bool(self.sys_info['is_dimmable'])
|
||||
return bool(self.sys_info["is_dimmable"])
|
||||
|
||||
@property
|
||||
def is_variable_color_temp(self) -> bool:
|
||||
"""
|
||||
Whether the bulb supports color temperature changes
|
||||
"""Whether the bulb supports color temperature changes.
|
||||
|
||||
:return: True if the bulb supports color temperature changes, False
|
||||
otherwise
|
||||
:rtype: bool
|
||||
"""
|
||||
return bool(self.sys_info['is_variable_color_temp'])
|
||||
return bool(self.sys_info["is_variable_color_temp"])
|
||||
|
||||
@property
|
||||
def valid_temperature_range(self) -> Tuple[int, int]:
|
||||
"""
|
||||
Returns the white temperature range (in Kelvin)
|
||||
depending on the bulb model
|
||||
"""Return the device-specific white temperature range (in Kelvin).
|
||||
|
||||
:return: White temperature range in Kelvin (minimun, maximum)
|
||||
:rtype: tuple
|
||||
@ -99,190 +112,200 @@ class SmartBulb(SmartDevice):
|
||||
if not self.is_variable_color_temp:
|
||||
return (0, 0)
|
||||
for model, temp_range in TPLINK_KELVIN.items():
|
||||
if re.match(model, self.sys_info['model']):
|
||||
if re.match(model, self.sys_info["model"]):
|
||||
return temp_range
|
||||
return (0, 0)
|
||||
|
||||
def get_light_state(self) -> Dict:
|
||||
return self._query_helper("smartlife.iot.smartbulb.lightingservice",
|
||||
"get_light_state")
|
||||
"""Query the light state."""
|
||||
return self._query_helper(self.LIGHT_SERVICE, "get_light_state")
|
||||
|
||||
def set_light_state(self, state: Dict) -> Dict:
|
||||
return self._query_helper("smartlife.iot.smartbulb.lightingservice",
|
||||
"transition_light_state", state)
|
||||
"""Set the light state."""
|
||||
return self._query_helper(self.LIGHT_SERVICE, "transition_light_state", state)
|
||||
|
||||
@property
|
||||
def hsv(self) -> Optional[Tuple[int, int, int]]:
|
||||
"""
|
||||
Returns the current HSV state of the bulb, if supported
|
||||
def hsv(self) -> Tuple[int, int, int]:
|
||||
"""Return the current HSV state of the bulb.
|
||||
|
||||
:return: hue, saturation and value (degrees, %, %)
|
||||
:rtype: tuple
|
||||
"""
|
||||
|
||||
if not self.is_color:
|
||||
return None
|
||||
raise SmartDeviceException("Bulb does not support color.")
|
||||
|
||||
light_state = self.get_light_state()
|
||||
if not self.is_on:
|
||||
hue = light_state['dft_on_state']['hue']
|
||||
saturation = light_state['dft_on_state']['saturation']
|
||||
value = light_state['dft_on_state']['brightness']
|
||||
hue = light_state["dft_on_state"]["hue"]
|
||||
saturation = light_state["dft_on_state"]["saturation"]
|
||||
value = light_state["dft_on_state"]["brightness"]
|
||||
else:
|
||||
hue = light_state['hue']
|
||||
saturation = light_state['saturation']
|
||||
value = light_state['brightness']
|
||||
hue = light_state["hue"]
|
||||
saturation = light_state["saturation"]
|
||||
value = light_state["brightness"]
|
||||
|
||||
return hue, saturation, value
|
||||
|
||||
@hsv.setter
|
||||
@hsv.setter # type: ignore
|
||||
@deprecated(details="Use set_hsv()")
|
||||
def hsv(self, state: Tuple[int, int, int]):
|
||||
"""
|
||||
Sets new HSV, if supported
|
||||
return self.set_hsv(state[0], state[1], state[2])
|
||||
|
||||
def _raise_for_invalid_brightness(self, value):
|
||||
if not isinstance(value, int) or not (0 <= value <= 100):
|
||||
raise ValueError(
|
||||
"Invalid brightness value: {} " "(valid range: 0-100%)".format(value)
|
||||
)
|
||||
|
||||
def set_hsv(self, hue: int, saturation: int, value: int):
|
||||
"""Set new HSV.
|
||||
|
||||
:param tuple state: hue, saturation and value (degrees, %, %)
|
||||
"""
|
||||
if not self.is_color:
|
||||
return None
|
||||
raise SmartDeviceException("Bulb does not support color.")
|
||||
|
||||
if not isinstance(state[0], int) or not (0 <= state[0] <= 360):
|
||||
raise SmartDeviceException(
|
||||
'Invalid hue value: {} '
|
||||
'(valid range: 0-360)'.format(state[0]))
|
||||
if not isinstance(hue, int) or not (0 <= hue <= 360):
|
||||
raise ValueError(
|
||||
"Invalid hue value: {} " "(valid range: 0-360)".format(hue)
|
||||
)
|
||||
|
||||
if not isinstance(state[1], int) or not (0 <= state[1] <= 100):
|
||||
raise SmartDeviceException(
|
||||
'Invalid saturation value: {} '
|
||||
'(valid range: 0-100%)'.format(state[1]))
|
||||
if not isinstance(saturation, int) or not (0 <= saturation <= 100):
|
||||
raise ValueError(
|
||||
"Invalid saturation value: {} "
|
||||
"(valid range: 0-100%)".format(saturation)
|
||||
)
|
||||
|
||||
if not isinstance(state[2], int) or not (0 <= state[2] <= 100):
|
||||
raise SmartDeviceException(
|
||||
'Invalid brightness value: {} '
|
||||
'(valid range: 0-100%)'.format(state[2]))
|
||||
self._raise_for_invalid_brightness(value)
|
||||
|
||||
light_state = {
|
||||
"hue": state[0],
|
||||
"saturation": state[1],
|
||||
"brightness": state[2],
|
||||
"color_temp": 0
|
||||
}
|
||||
"hue": hue,
|
||||
"saturation": saturation,
|
||||
"brightness": value,
|
||||
"color_temp": 0,
|
||||
}
|
||||
self.set_light_state(light_state)
|
||||
|
||||
@property
|
||||
def color_temp(self) -> Optional[int]:
|
||||
"""
|
||||
Color temperature of the device, if supported
|
||||
def color_temp(self) -> int:
|
||||
"""Return color temperature of the device.
|
||||
|
||||
:return: Color temperature in Kelvin
|
||||
:rtype: int
|
||||
"""
|
||||
if not self.is_variable_color_temp:
|
||||
return None
|
||||
raise SmartDeviceException("Bulb does not support colortemp.")
|
||||
|
||||
light_state = self.get_light_state()
|
||||
if not self.is_on:
|
||||
return int(light_state['dft_on_state']['color_temp'])
|
||||
return int(light_state["dft_on_state"]["color_temp"])
|
||||
else:
|
||||
return int(light_state['color_temp'])
|
||||
return int(light_state["color_temp"])
|
||||
|
||||
@color_temp.setter
|
||||
@color_temp.setter # type: ignore
|
||||
@deprecated(details="use set_color_temp")
|
||||
def color_temp(self, temp: int) -> None:
|
||||
"""
|
||||
Set the color temperature of the device, if supported
|
||||
self.set_color_temp(temp)
|
||||
|
||||
def set_color_temp(self, temp: int) -> None:
|
||||
"""Set the color temperature of the device.
|
||||
|
||||
:param int temp: The new color temperature, in Kelvin
|
||||
"""
|
||||
if not self.is_variable_color_temp:
|
||||
return None
|
||||
raise SmartDeviceException("Bulb does not support colortemp.")
|
||||
|
||||
if temp < self.valid_temperature_range[0] or \
|
||||
temp > self.valid_temperature_range[1]:
|
||||
raise ValueError("Temperature should be between {} "
|
||||
"and {}".format(*self.valid_temperature_range))
|
||||
if (
|
||||
temp < self.valid_temperature_range[0]
|
||||
or temp > self.valid_temperature_range[1]
|
||||
):
|
||||
raise ValueError(
|
||||
"Temperature should be between {} "
|
||||
"and {}".format(*self.valid_temperature_range)
|
||||
)
|
||||
|
||||
light_state = {
|
||||
"color_temp": temp,
|
||||
}
|
||||
light_state = {"color_temp": temp}
|
||||
self.set_light_state(light_state)
|
||||
|
||||
@property
|
||||
def brightness(self) -> Optional[int]:
|
||||
"""
|
||||
Current brightness of the device, if supported
|
||||
def brightness(self) -> int:
|
||||
"""Current brightness of the device.
|
||||
|
||||
:return: brightness in percent
|
||||
:rtype: int
|
||||
"""
|
||||
if not self.is_dimmable:
|
||||
return None
|
||||
if not self.is_dimmable: # pragma: no cover
|
||||
raise SmartDeviceException("Bulb is not dimmable.")
|
||||
|
||||
light_state = self.get_light_state()
|
||||
if not self.is_on:
|
||||
return int(light_state['dft_on_state']['brightness'])
|
||||
return int(light_state["dft_on_state"]["brightness"])
|
||||
else:
|
||||
return int(light_state['brightness'])
|
||||
return int(light_state["brightness"])
|
||||
|
||||
@brightness.setter
|
||||
@brightness.setter # type: ignore
|
||||
@deprecated(details="use set_brightness")
|
||||
def brightness(self, brightness: int) -> None:
|
||||
"""
|
||||
Set the current brightness of the device, if supported
|
||||
self.set_brightness(brightness)
|
||||
|
||||
def set_brightness(self, brightness: int) -> None:
|
||||
"""Set the current brightness of the device.
|
||||
|
||||
:param int brightness: brightness in percent
|
||||
"""
|
||||
if not self.is_dimmable:
|
||||
return None
|
||||
if not self.is_dimmable: # pragma: no cover
|
||||
raise SmartDeviceException("Bulb is not dimmable.")
|
||||
|
||||
light_state = {
|
||||
"brightness": brightness,
|
||||
}
|
||||
self._raise_for_invalid_brightness(brightness)
|
||||
|
||||
light_state = {"brightness": brightness}
|
||||
self.set_light_state(light_state)
|
||||
|
||||
@property
|
||||
@property # type: ignore
|
||||
@deprecated(details="use is_on() and is_off()")
|
||||
def state(self) -> str:
|
||||
"""
|
||||
Retrieve the bulb state
|
||||
"""Retrieve the bulb state.
|
||||
|
||||
:returns: one of
|
||||
BULB_STATE_ON
|
||||
BULB_STATE_OFF
|
||||
STATE_ON
|
||||
STATE_OFF
|
||||
:rtype: str
|
||||
"""
|
||||
light_state = self.get_light_state()
|
||||
if light_state['on_off']:
|
||||
return self.BULB_STATE_ON
|
||||
return self.BULB_STATE_OFF
|
||||
if self.is_on:
|
||||
return self.STATE_ON
|
||||
|
||||
@state.setter
|
||||
return self.STATE_OFF
|
||||
|
||||
@state.setter # type: ignore
|
||||
@deprecated(details="use turn_on() and turn_off()")
|
||||
def state(self, bulb_state: str) -> None:
|
||||
"""
|
||||
Set the new bulb state
|
||||
"""Set the new bulb state.
|
||||
|
||||
:param bulb_state: one of
|
||||
BULB_STATE_ON
|
||||
BULB_STATE_OFF
|
||||
STATE_ON
|
||||
STATE_OFF
|
||||
"""
|
||||
if bulb_state == self.BULB_STATE_ON:
|
||||
if bulb_state == self.STATE_ON:
|
||||
new_state = 1
|
||||
elif bulb_state == self.BULB_STATE_OFF:
|
||||
elif bulb_state == self.STATE_OFF:
|
||||
new_state = 0
|
||||
else:
|
||||
raise ValueError
|
||||
|
||||
light_state = {
|
||||
"on_off": new_state,
|
||||
}
|
||||
light_state = {"on_off": new_state}
|
||||
self.set_light_state(light_state)
|
||||
|
||||
@property
|
||||
def state_information(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Return bulb-specific state information.
|
||||
"""Return bulb-specific state information.
|
||||
|
||||
:return: Bulb information dict, keys in user-presentable form.
|
||||
:rtype: dict
|
||||
"""
|
||||
info = {
|
||||
'Brightness': self.brightness,
|
||||
'Is dimmable': self.is_dimmable,
|
||||
"Brightness": self.brightness,
|
||||
"Is dimmable": self.is_dimmable,
|
||||
} # type: Dict[str, Any]
|
||||
if self.is_variable_color_temp:
|
||||
info["Color temperature"] = self.color_temp
|
||||
@ -294,19 +317,17 @@ class SmartBulb(SmartDevice):
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool:
|
||||
return bool(self.state == self.BULB_STATE_ON)
|
||||
"""Return whether the device is on."""
|
||||
light_state = self.get_light_state()
|
||||
return bool(light_state["on_off"])
|
||||
|
||||
def turn_off(self) -> None:
|
||||
"""
|
||||
Turn the bulb off.
|
||||
"""
|
||||
self.state = self.BULB_STATE_OFF
|
||||
"""Turn the bulb off."""
|
||||
self.set_light_state({"on_off": 0})
|
||||
|
||||
def turn_on(self) -> None:
|
||||
"""
|
||||
Turn the bulb on.
|
||||
"""
|
||||
self.state = self.BULB_STATE_ON
|
||||
"""Turn the bulb on."""
|
||||
self.set_light_state({"on_off": 1})
|
||||
|
||||
@property
|
||||
def has_emeter(self) -> bool:
|
||||
|
@ -13,22 +13,30 @@ Stroetmann which is licensed under the Apache License, Version 2.0.
|
||||
You may obtain a copy of the license at
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
"""
|
||||
import datetime
|
||||
from datetime import datetime, timedelta
|
||||
import logging
|
||||
import warnings
|
||||
from collections import defaultdict
|
||||
from typing import Any, Dict, List, Tuple, Optional
|
||||
from typing import Any, Dict, Optional
|
||||
from enum import Enum
|
||||
|
||||
from deprecation import deprecated
|
||||
|
||||
from .protocol import TPLinkSmartHomeProtocol
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DeviceType(Enum):
|
||||
"""Device type enum."""
|
||||
|
||||
Plug = 1
|
||||
Bulb = 2
|
||||
Strip = 3
|
||||
Unknown = -1
|
||||
|
||||
|
||||
class SmartDeviceException(Exception):
|
||||
"""
|
||||
SmartDeviceException gets raised for errors reported by device.
|
||||
"""
|
||||
pass
|
||||
"""Base exception for device errors."""
|
||||
|
||||
|
||||
class EmeterStatus(dict):
|
||||
@ -42,10 +50,18 @@ class EmeterStatus(dict):
|
||||
"""
|
||||
|
||||
def __getitem__(self, item):
|
||||
valid_keys = ['voltage_mv', 'power_mw', 'current_ma',
|
||||
'energy_wh', 'total_wh',
|
||||
'voltage', 'power', 'current', 'total',
|
||||
'energy']
|
||||
valid_keys = [
|
||||
"voltage_mv",
|
||||
"power_mw",
|
||||
"current_ma",
|
||||
"energy_wh",
|
||||
"total_wh",
|
||||
"voltage",
|
||||
"power",
|
||||
"current",
|
||||
"total",
|
||||
"energy",
|
||||
]
|
||||
|
||||
# 1. if requested data is available, return it
|
||||
if item in super().keys():
|
||||
@ -54,48 +70,88 @@ class EmeterStatus(dict):
|
||||
else:
|
||||
if item not in valid_keys:
|
||||
raise KeyError(item)
|
||||
if '_' in item: # upscale
|
||||
return super().__getitem__(item[:item.find('_')]) * 10**3
|
||||
if "_" in item: # upscale
|
||||
return super().__getitem__(item[: item.find("_")]) * 10 ** 3
|
||||
else: # downscale
|
||||
for i in super().keys():
|
||||
if i.startswith(item):
|
||||
return self.__getitem__(i) / 10**3
|
||||
return self.__getitem__(i) / 10 ** 3
|
||||
|
||||
raise SmartDeviceException("Unable to find a value for '%s'" %
|
||||
item)
|
||||
raise SmartDeviceException("Unable to find a value for '%s'" % item)
|
||||
|
||||
|
||||
class SmartDevice(object):
|
||||
# possible device features
|
||||
FEATURE_ENERGY_METER = 'ENE'
|
||||
FEATURE_TIMER = 'TIM'
|
||||
class SmartDevice:
|
||||
"""Base class for all supported device types."""
|
||||
|
||||
ALL_FEATURES = (FEATURE_ENERGY_METER, FEATURE_TIMER)
|
||||
STATE_ON = "ON"
|
||||
STATE_OFF = "OFF"
|
||||
|
||||
def __init__(self,
|
||||
host: str,
|
||||
protocol: Optional[TPLinkSmartHomeProtocol] = None,
|
||||
context: str = None) -> None:
|
||||
"""
|
||||
Create a new SmartDevice instance.
|
||||
def __init__(
|
||||
self,
|
||||
host: str,
|
||||
protocol: Optional[TPLinkSmartHomeProtocol] = None,
|
||||
context: str = None,
|
||||
cache_ttl: int = 3,
|
||||
) -> None:
|
||||
"""Create a new SmartDevice instance.
|
||||
|
||||
:param str host: host name or ip address on which the device listens
|
||||
:param context: optional child ID for context in a parent device
|
||||
"""
|
||||
self.host = host
|
||||
if not protocol:
|
||||
if protocol is None: # pragma: no cover
|
||||
protocol = TPLinkSmartHomeProtocol()
|
||||
self.protocol = protocol
|
||||
self.emeter_type = "emeter" # type: str
|
||||
self.context = context
|
||||
self.num_children = 0
|
||||
self.cache_ttl = timedelta(seconds=cache_ttl)
|
||||
_LOGGER.debug(
|
||||
"Initializing %s using context %s and cache ttl %s",
|
||||
self.host,
|
||||
self.context,
|
||||
self.cache_ttl,
|
||||
)
|
||||
self.cache = defaultdict(lambda: defaultdict(lambda: None))
|
||||
self._device_type = DeviceType.Unknown
|
||||
|
||||
def _query_helper(self,
|
||||
target: str,
|
||||
cmd: str,
|
||||
arg: Optional[Dict] = None) -> Any:
|
||||
def _result_from_cache(self, target, cmd) -> Optional[Dict]:
|
||||
"""Return query result from cache if still fresh.
|
||||
Only results from commands starting with `get_` are considered cacheable.
|
||||
|
||||
:param target: Target system
|
||||
:param cmd: Command
|
||||
:rtype: query result or None if expired.
|
||||
"""
|
||||
Helper returning unwrapped result object and doing error handling.
|
||||
_LOGGER.debug("Checking cache for %s %s", target, cmd)
|
||||
if cmd not in self.cache[target]:
|
||||
return None
|
||||
|
||||
cached = self.cache[target][cmd]
|
||||
if cached and cached["last_updated"] is not None:
|
||||
if cached[
|
||||
"last_updated"
|
||||
] + self.cache_ttl > datetime.utcnow() and cmd.startswith("get_"):
|
||||
_LOGGER.debug("Got cached %s %s", target, cmd)
|
||||
return self.cache[target][cmd]
|
||||
else:
|
||||
_LOGGER.debug("Invalidating the cache for %s cmd %s", target, cmd)
|
||||
for cache_entry in self.cache[target].values():
|
||||
cache_entry["last_updated"] = datetime.utcfromtimestamp(0)
|
||||
return None
|
||||
|
||||
def _insert_to_cache(self, target: str, cmd: str, response: Dict) -> None:
|
||||
"""Internal function to add response to cache.
|
||||
|
||||
:param target: Target system
|
||||
:param cmd: Command
|
||||
:param response: Response to be cached
|
||||
"""
|
||||
self.cache[target][cmd] = response.copy()
|
||||
self.cache[target][cmd]["last_updated"] = datetime.utcnow()
|
||||
|
||||
def _query_helper(self, target: str, cmd: str, arg: Optional[Dict] = None) -> Any:
|
||||
"""Handle result unwrapping and error handling.
|
||||
|
||||
:param target: Target system {system, time, emeter, ..}
|
||||
:param cmd: Command to execute
|
||||
@ -107,73 +163,42 @@ class SmartDevice(object):
|
||||
if self.context is None:
|
||||
request = {target: {cmd: arg}}
|
||||
else:
|
||||
request = {"context": {"child_ids": [self.context]},
|
||||
target: {cmd: arg}}
|
||||
if arg is None:
|
||||
arg = {}
|
||||
request = {"context": {"child_ids": [self.context]}, target: {cmd: arg}}
|
||||
|
||||
try:
|
||||
response = self.protocol.query(
|
||||
host=self.host,
|
||||
request=request,
|
||||
)
|
||||
response = self._result_from_cache(target, cmd)
|
||||
if response is None:
|
||||
_LOGGER.debug("Got no result from cache, querying the device.")
|
||||
response = self.protocol.query(host=self.host, request=request)
|
||||
self._insert_to_cache(target, cmd, response)
|
||||
except Exception as ex:
|
||||
raise SmartDeviceException('Communication error') from ex
|
||||
raise SmartDeviceException(
|
||||
"Communication error on %s:%s" % (target, cmd)
|
||||
) from ex
|
||||
|
||||
if target not in response:
|
||||
raise SmartDeviceException("No required {} in response: {}"
|
||||
.format(target, response))
|
||||
raise SmartDeviceException(
|
||||
"No required {} in response: {}".format(target, response)
|
||||
)
|
||||
|
||||
result = response[target]
|
||||
if "err_code" in result and result["err_code"] != 0:
|
||||
raise SmartDeviceException("Error on {} {}: {}"
|
||||
.format(target, cmd, result))
|
||||
raise SmartDeviceException("Error on {}.{}: {}".format(target, cmd, result))
|
||||
|
||||
if cmd not in result:
|
||||
raise SmartDeviceException("No command in response: {}"
|
||||
.format(response))
|
||||
|
||||
raise SmartDeviceException("No command in response: {}".format(response))
|
||||
result = result[cmd]
|
||||
if "err_code" in result and result["err_code"] != 0:
|
||||
raise SmartDeviceException("Error on {} {}: {}"
|
||||
.format(target, cmd, result))
|
||||
raise SmartDeviceException("Error on {} {}: {}".format(target, cmd, result))
|
||||
|
||||
del result["err_code"]
|
||||
if "err_code" in result:
|
||||
del result["err_code"]
|
||||
|
||||
return result
|
||||
|
||||
@property
|
||||
def features(self) -> List[str]:
|
||||
"""
|
||||
Returns features of the devices
|
||||
|
||||
:return: list of features
|
||||
:rtype: list
|
||||
"""
|
||||
warnings.simplefilter('always', DeprecationWarning)
|
||||
warnings.warn(
|
||||
"features works only on plugs and its use is discouraged, "
|
||||
"and it will likely to be removed at some point",
|
||||
DeprecationWarning,
|
||||
stacklevel=2
|
||||
)
|
||||
warnings.simplefilter('default', DeprecationWarning)
|
||||
if "feature" not in self.sys_info:
|
||||
return []
|
||||
|
||||
features = self.sys_info['feature'].split(':')
|
||||
|
||||
for feature in features:
|
||||
if feature not in SmartDevice.ALL_FEATURES:
|
||||
_LOGGER.warning("Unknown feature %s on device %s.",
|
||||
feature, self.model)
|
||||
|
||||
return features
|
||||
|
||||
@property
|
||||
def has_emeter(self) -> bool:
|
||||
"""
|
||||
Checks feature list for energy meter support.
|
||||
Note: this has to be implemented on a device specific class.
|
||||
"""Return if device has an energy meter.
|
||||
|
||||
:return: True if energey meter is available
|
||||
False if energymeter is missing
|
||||
@ -182,17 +207,16 @@ class SmartDevice(object):
|
||||
|
||||
@property
|
||||
def sys_info(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Returns the complete system information from the device.
|
||||
"""Return the complete system information.
|
||||
|
||||
:return: System information dict.
|
||||
:rtype: dict
|
||||
"""
|
||||
return defaultdict(lambda: None, self.get_sysinfo())
|
||||
|
||||
return self.get_sysinfo()
|
||||
|
||||
def get_sysinfo(self) -> Dict:
|
||||
"""
|
||||
Retrieve system information.
|
||||
"""Retrieve system information.
|
||||
|
||||
:return: sysinfo
|
||||
:rtype dict
|
||||
@ -202,29 +226,33 @@ class SmartDevice(object):
|
||||
|
||||
@property
|
||||
def model(self) -> str:
|
||||
"""
|
||||
Get model of the device
|
||||
"""Return device model.
|
||||
|
||||
:return: device model
|
||||
:rtype: str
|
||||
:raises SmartDeviceException: on error
|
||||
"""
|
||||
return str(self.sys_info['model'])
|
||||
return str(self.sys_info["model"])
|
||||
|
||||
@property
|
||||
def alias(self) -> str:
|
||||
"""
|
||||
Get current device alias (name)
|
||||
"""Return device name (alias).
|
||||
|
||||
:return: Device name aka alias.
|
||||
:rtype: str
|
||||
"""
|
||||
return str(self.sys_info['alias'])
|
||||
return str(self.sys_info["alias"])
|
||||
|
||||
@alias.setter
|
||||
def get_alias(self) -> str:
|
||||
return self.alias
|
||||
|
||||
@alias.setter # type: ignore
|
||||
@deprecated(details="use set_alias")
|
||||
def alias(self, alias: str) -> None:
|
||||
"""
|
||||
Sets the device name aka alias.
|
||||
self.set_alias(alias)
|
||||
|
||||
def set_alias(self, alias: str) -> None:
|
||||
"""Set the device name (alias).
|
||||
|
||||
:param alias: New alias (name)
|
||||
:raises SmartDeviceException: on error
|
||||
@ -233,8 +261,7 @@ class SmartDevice(object):
|
||||
|
||||
@property
|
||||
def icon(self) -> Dict:
|
||||
"""
|
||||
Returns device icon
|
||||
"""Return device icon.
|
||||
|
||||
Note: not working on HS110, but is always empty.
|
||||
|
||||
@ -246,7 +273,8 @@ class SmartDevice(object):
|
||||
|
||||
@icon.setter
|
||||
def icon(self, icon: str) -> None:
|
||||
"""
|
||||
"""Set device icon.
|
||||
|
||||
Content for hash and icon are unknown.
|
||||
|
||||
:param str icon: Icon path(?)
|
||||
@ -260,28 +288,33 @@ class SmartDevice(object):
|
||||
# self.initialize()
|
||||
|
||||
@property
|
||||
def time(self) -> Optional[datetime.datetime]:
|
||||
"""
|
||||
Returns current time from the device.
|
||||
def time(self) -> Optional[datetime]:
|
||||
"""Return current time from the device.
|
||||
|
||||
:return: datetime for device's time
|
||||
:rtype: datetime.datetime or None when not available
|
||||
:rtype: datetime or None when not available
|
||||
:raises SmartDeviceException: on error
|
||||
"""
|
||||
try:
|
||||
res = self._query_helper("time", "get_time")
|
||||
return datetime.datetime(res["year"], res["month"], res["mday"],
|
||||
res["hour"], res["min"], res["sec"])
|
||||
return datetime(
|
||||
res["year"],
|
||||
res["month"],
|
||||
res["mday"],
|
||||
res["hour"],
|
||||
res["min"],
|
||||
res["sec"],
|
||||
)
|
||||
except SmartDeviceException:
|
||||
return None
|
||||
|
||||
@time.setter
|
||||
def time(self, ts: datetime.datetime) -> None:
|
||||
"""
|
||||
Sets time based on datetime object.
|
||||
def time(self, ts: datetime) -> None:
|
||||
"""Set the device time.
|
||||
|
||||
Note: this calls set_timezone() for setting.
|
||||
|
||||
:param datetime.datetime ts: New date and time
|
||||
:param datetime ts: New date and time
|
||||
:return: result
|
||||
:type: dict
|
||||
:raises NotImplemented: when not implemented.
|
||||
@ -311,8 +344,7 @@ class SmartDevice(object):
|
||||
|
||||
@property
|
||||
def timezone(self) -> Dict:
|
||||
"""
|
||||
Returns timezone information
|
||||
"""Return timezone information.
|
||||
|
||||
:return: Timezone information
|
||||
:rtype: dict
|
||||
@ -322,28 +354,35 @@ class SmartDevice(object):
|
||||
|
||||
@property
|
||||
def hw_info(self) -> Dict:
|
||||
"""
|
||||
Returns information about hardware
|
||||
"""Return hardware information.
|
||||
|
||||
:return: Information about hardware
|
||||
:rtype: dict
|
||||
"""
|
||||
keys = ["sw_ver", "hw_ver", "mac", "mic_mac", "type",
|
||||
"mic_type", "hwId", "fwId", "oemId", "dev_name"]
|
||||
keys = [
|
||||
"sw_ver",
|
||||
"hw_ver",
|
||||
"mac",
|
||||
"mic_mac",
|
||||
"type",
|
||||
"mic_type",
|
||||
"hwId",
|
||||
"fwId",
|
||||
"oemId",
|
||||
"dev_name",
|
||||
]
|
||||
info = self.sys_info
|
||||
return {key: info[key] for key in keys if key in info}
|
||||
|
||||
@property
|
||||
def location(self) -> Dict:
|
||||
"""
|
||||
Location of the device, as read from sysinfo
|
||||
"""Return geographical location.
|
||||
|
||||
:return: latitude and longitude
|
||||
:rtype: dict
|
||||
"""
|
||||
info = self.sys_info
|
||||
loc = {"latitude": None,
|
||||
"longitude": None}
|
||||
loc = {"latitude": None, "longitude": None}
|
||||
|
||||
if "latitude" in info and "longitude" in info:
|
||||
loc["latitude"] = info["latitude"]
|
||||
@ -358,8 +397,7 @@ class SmartDevice(object):
|
||||
|
||||
@property
|
||||
def rssi(self) -> Optional[int]:
|
||||
"""
|
||||
Returns WiFi signal strenth (rssi)
|
||||
"""Return WiFi signal strenth (rssi).
|
||||
|
||||
:return: rssi
|
||||
:rtype: int
|
||||
@ -370,35 +408,37 @@ class SmartDevice(object):
|
||||
|
||||
@property
|
||||
def mac(self) -> str:
|
||||
"""
|
||||
Returns mac address
|
||||
"""Return mac address.
|
||||
|
||||
:return: mac address in hexadecimal with colons, e.g. 01:23:45:67:89:ab
|
||||
:rtype: str
|
||||
"""
|
||||
info = self.sys_info
|
||||
|
||||
if 'mac' in info:
|
||||
if "mac" in info:
|
||||
return str(info["mac"])
|
||||
elif 'mic_mac' in info:
|
||||
return str(info['mic_mac'])
|
||||
else:
|
||||
raise SmartDeviceException("Unknown mac, please submit a bug"
|
||||
"with sysinfo output.")
|
||||
elif "mic_mac" in info:
|
||||
return ":".join(format(s, "02x") for s in bytes.fromhex(info["mic_mac"]))
|
||||
|
||||
raise SmartDeviceException(
|
||||
"Unknown mac, please submit a bug " "with sysinfo output."
|
||||
)
|
||||
|
||||
@mac.setter
|
||||
@deprecated(details="use set_mac")
|
||||
def mac(self, mac: str) -> None:
|
||||
"""
|
||||
Sets new mac address
|
||||
self.set_mac(mac)
|
||||
|
||||
def set_mac(self, mac):
|
||||
"""Set the mac address.
|
||||
|
||||
:param str mac: mac in hexadecimal with colons, e.g. 01:23:45:67:89:ab
|
||||
:raises SmartDeviceException: on error
|
||||
"""
|
||||
self._query_helper("system", "set_mac_addr", {"mac": mac})
|
||||
|
||||
def get_emeter_realtime(self) -> Optional[Dict]:
|
||||
"""
|
||||
Retrieve current energy readings from device.
|
||||
def get_emeter_realtime(self) -> EmeterStatus:
|
||||
"""Retrive current energy readings.
|
||||
|
||||
:returns: current readings or False
|
||||
:rtype: dict, None
|
||||
@ -406,17 +446,14 @@ class SmartDevice(object):
|
||||
:raises SmartDeviceException: on error
|
||||
"""
|
||||
if not self.has_emeter:
|
||||
return None
|
||||
raise SmartDeviceException("Device has no emeter")
|
||||
|
||||
return EmeterStatus(self._query_helper(self.emeter_type,
|
||||
"get_realtime"))
|
||||
return EmeterStatus(self._query_helper(self.emeter_type, "get_realtime"))
|
||||
|
||||
def get_emeter_daily(self,
|
||||
year: int = None,
|
||||
month: int = None,
|
||||
kwh: bool = True) -> Optional[Dict]:
|
||||
"""
|
||||
Retrieve daily statistics for a given month
|
||||
def get_emeter_daily(
|
||||
self, year: int = None, month: int = None, kwh: bool = True
|
||||
) -> 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
|
||||
@ -428,30 +465,28 @@ class SmartDevice(object):
|
||||
:raises SmartDeviceException: on error
|
||||
"""
|
||||
if not self.has_emeter:
|
||||
return None
|
||||
raise SmartDeviceException("Device has no emeter")
|
||||
|
||||
if year is None:
|
||||
year = datetime.datetime.now().year
|
||||
year = datetime.now().year
|
||||
if month is None:
|
||||
month = datetime.datetime.now().month
|
||||
month = datetime.now().month
|
||||
|
||||
response = self._query_helper(self.emeter_type, "get_daystat",
|
||||
{'month': month, 'year': year})
|
||||
response = self._query_helper(
|
||||
self.emeter_type, "get_daystat", {"month": month, "year": year}
|
||||
)
|
||||
response = [EmeterStatus(**x) for x in response["day_list"]]
|
||||
|
||||
key = 'energy_wh'
|
||||
key = "energy_wh"
|
||||
if kwh:
|
||||
key = 'energy'
|
||||
key = "energy"
|
||||
|
||||
data = {entry['day']: entry[key]
|
||||
for entry in response}
|
||||
data = {entry["day"]: entry[key] for entry in response}
|
||||
|
||||
return data
|
||||
|
||||
def get_emeter_monthly(self, year: int = None,
|
||||
kwh: bool = True) -> Optional[Dict]:
|
||||
"""
|
||||
Retrieve monthly statistics for a given year.
|
||||
def get_emeter_monthly(self, year: int = None, kwh: bool = True) -> Dict:
|
||||
"""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)
|
||||
@ -461,25 +496,22 @@ class SmartDevice(object):
|
||||
:raises SmartDeviceException: on error
|
||||
"""
|
||||
if not self.has_emeter:
|
||||
return None
|
||||
raise SmartDeviceException("Device has no emeter")
|
||||
|
||||
if year is None:
|
||||
year = datetime.datetime.now().year
|
||||
year = datetime.now().year
|
||||
|
||||
response = self._query_helper(self.emeter_type, "get_monthstat",
|
||||
{'year': year})
|
||||
response = self._query_helper(self.emeter_type, "get_monthstat", {"year": year})
|
||||
response = [EmeterStatus(**x) for x in response["month_list"]]
|
||||
|
||||
key = 'energy_wh'
|
||||
key = "energy_wh"
|
||||
if kwh:
|
||||
key = 'energy'
|
||||
key = "energy"
|
||||
|
||||
return {entry['month']: entry[key]
|
||||
for entry in response}
|
||||
return {entry["month"]: entry[key] for entry in response}
|
||||
|
||||
def erase_emeter_stats(self) -> bool:
|
||||
"""
|
||||
Erase energy meter statistics
|
||||
"""Erase energy meter statistics.
|
||||
|
||||
:return: True if statistics were deleted
|
||||
False if device has no energy meter.
|
||||
@ -487,7 +519,7 @@ class SmartDevice(object):
|
||||
:raises SmartDeviceException: on error
|
||||
"""
|
||||
if not self.has_emeter:
|
||||
return False
|
||||
raise SmartDeviceException("Device has no emeter")
|
||||
|
||||
self._query_helper(self.emeter_type, "erase_emeter_stat", None)
|
||||
|
||||
@ -496,40 +528,36 @@ class SmartDevice(object):
|
||||
return True
|
||||
|
||||
def current_consumption(self) -> Optional[float]:
|
||||
"""
|
||||
Get the current power consumption in Watts.
|
||||
"""Get the current power consumption in Watt.
|
||||
|
||||
:return: the current power consumption in Watts.
|
||||
None if device has no energy meter.
|
||||
:raises SmartDeviceException: on error
|
||||
"""
|
||||
if not self.has_emeter:
|
||||
return None
|
||||
raise SmartDeviceException("Device has no emeter")
|
||||
|
||||
response = EmeterStatus(self.get_emeter_realtime())
|
||||
return response['power']
|
||||
return response["power"]
|
||||
|
||||
def reboot(self, delay=1) -> None:
|
||||
"""
|
||||
Reboot the device.
|
||||
"""Reboot the device.
|
||||
|
||||
Note that giving a delay of zero causes this to block,
|
||||
as the device reboots immediately without responding to the call.
|
||||
|
||||
:param delay: Delay the reboot for `delay` seconds.
|
||||
:return: None
|
||||
|
||||
Note that giving a delay of zero causes this to block.
|
||||
"""
|
||||
self._query_helper("system", "reboot", {"delay": delay})
|
||||
|
||||
def turn_off(self) -> None:
|
||||
"""
|
||||
Turns the device off.
|
||||
"""
|
||||
"""Turn off the device."""
|
||||
raise NotImplementedError("Device subclass needs to implement this.")
|
||||
|
||||
@property
|
||||
def is_off(self) -> bool:
|
||||
"""
|
||||
Returns whether device is off.
|
||||
"""Return True if device is off.
|
||||
|
||||
:return: True if device is off, False otherwise.
|
||||
:rtype: bool
|
||||
@ -537,15 +565,12 @@ class SmartDevice(object):
|
||||
return not self.is_on
|
||||
|
||||
def turn_on(self) -> None:
|
||||
"""
|
||||
Turns the device on.
|
||||
"""
|
||||
"""Turn device on."""
|
||||
raise NotImplementedError("Device subclass needs to implement this.")
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool:
|
||||
"""
|
||||
Returns whether the device is on.
|
||||
"""Return if the device is on.
|
||||
|
||||
:return: True if the device is on, False otherwise.
|
||||
:rtype: bool
|
||||
@ -555,20 +580,47 @@ class SmartDevice(object):
|
||||
|
||||
@property
|
||||
def state_information(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Returns device-type specific, end-user friendly state information.
|
||||
"""Return device-type specific, end-user friendly state information.
|
||||
|
||||
:return: dict with state information.
|
||||
:rtype: dict
|
||||
"""
|
||||
raise NotImplementedError("Device subclass needs to implement this.")
|
||||
|
||||
@property
|
||||
def device_type(self) -> DeviceType:
|
||||
"""Return the device type."""
|
||||
return self._device_type
|
||||
|
||||
@property
|
||||
def is_bulb(self) -> bool:
|
||||
return self._device_type == DeviceType.Bulb
|
||||
|
||||
@property
|
||||
def is_plug(self) -> bool:
|
||||
return self._device_type == DeviceType.Plug
|
||||
|
||||
@property
|
||||
def is_strip(self) -> bool:
|
||||
return self._device_type == DeviceType.Strip
|
||||
|
||||
@property
|
||||
def is_dimmable(self):
|
||||
return False
|
||||
|
||||
@property
|
||||
def is_variable_color_temp(self) -> bool:
|
||||
return False
|
||||
|
||||
def __repr__(self):
|
||||
is_on = self.is_on
|
||||
if callable(is_on):
|
||||
is_on = is_on()
|
||||
return "<%s at %s (%s), is_on: %s - dev specific: %s>" % (
|
||||
self.__class__.__name__,
|
||||
self.model,
|
||||
self.host,
|
||||
self.alias,
|
||||
is_on,
|
||||
self.state_information)
|
||||
self.state_information,
|
||||
)
|
||||
|
@ -1,8 +1,11 @@
|
||||
import datetime
|
||||
import logging
|
||||
from typing import Any, Dict, Optional
|
||||
from typing import Any, Dict
|
||||
|
||||
from pyHS100 import SmartDevice
|
||||
from deprecation import deprecated
|
||||
|
||||
from pyHS100 import SmartDevice, DeviceType, SmartDeviceException
|
||||
from .protocol import TPLinkSmartHomeProtocol
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@ -15,90 +18,82 @@ class SmartPlug(SmartDevice):
|
||||
# print the devices alias
|
||||
print(p.alias)
|
||||
# change state of plug
|
||||
p.state = "ON"
|
||||
p.state = "OFF"
|
||||
p.turn_on()
|
||||
p.turn_off()
|
||||
# query and print current state of plug
|
||||
print(p.state)
|
||||
|
||||
Errors reported by the device are raised as SmartDeviceExceptions,
|
||||
and should be handled by the user of the library.
|
||||
|
||||
Note:
|
||||
The library references the same structure as defined for the D-Link Switch
|
||||
"""
|
||||
# switch states
|
||||
SWITCH_STATE_ON = 'ON'
|
||||
SWITCH_STATE_OFF = 'OFF'
|
||||
SWITCH_STATE_UNKNOWN = 'UNKNOWN'
|
||||
|
||||
def __init__(self,
|
||||
host: str,
|
||||
protocol: 'TPLinkSmartHomeProtocol' = None,
|
||||
context: str = None) -> None:
|
||||
SmartDevice.__init__(self, host, protocol, context)
|
||||
self._type = "emeter"
|
||||
def __init__(
|
||||
self,
|
||||
host: str,
|
||||
protocol: "TPLinkSmartHomeProtocol" = None,
|
||||
context: str = None,
|
||||
cache_ttl: int = 3,
|
||||
) -> None:
|
||||
SmartDevice.__init__(self, host, protocol, context, cache_ttl)
|
||||
self.emeter_type = "emeter"
|
||||
self._device_type = DeviceType.Plug
|
||||
|
||||
@property
|
||||
@property # type: ignore
|
||||
@deprecated(details="use is_on()")
|
||||
def state(self) -> str:
|
||||
"""
|
||||
Retrieve the switch state
|
||||
"""Retrieve the switch state.
|
||||
|
||||
:returns: one of
|
||||
SWITCH_STATE_ON
|
||||
SWITCH_STATE_OFF
|
||||
SWITCH_STATE_UNKNOWN
|
||||
STATE_ON
|
||||
STATE_OFF
|
||||
:rtype: str
|
||||
"""
|
||||
relay_state = self.sys_info['relay_state']
|
||||
if self.is_on:
|
||||
return self.STATE_ON
|
||||
return self.STATE_OFF
|
||||
|
||||
if relay_state == 0:
|
||||
return SmartPlug.SWITCH_STATE_OFF
|
||||
elif relay_state == 1:
|
||||
return SmartPlug.SWITCH_STATE_ON
|
||||
else:
|
||||
_LOGGER.warning("Unknown state %s returned.", relay_state)
|
||||
return SmartPlug.SWITCH_STATE_UNKNOWN
|
||||
|
||||
@state.setter
|
||||
@state.setter # type: ignore
|
||||
@deprecated(details="use turn_on() and turn_off()")
|
||||
def state(self, value: str):
|
||||
"""
|
||||
Set the new switch state
|
||||
"""Set the new switch state.
|
||||
|
||||
:param value: one of
|
||||
SWITCH_STATE_ON
|
||||
SWITCH_STATE_OFF
|
||||
STATE_ON
|
||||
STATE_OFF
|
||||
:raises ValueError: on invalid state
|
||||
:raises SmartDeviceException: on error
|
||||
|
||||
"""
|
||||
if not isinstance(value, str):
|
||||
raise ValueError("State must be str, not of %s.", type(value))
|
||||
elif value.upper() == SmartPlug.SWITCH_STATE_ON:
|
||||
self.turn_on()
|
||||
elif value.upper() == SmartPlug.SWITCH_STATE_OFF:
|
||||
self.turn_off()
|
||||
else:
|
||||
raise ValueError("State %s is not valid.", value)
|
||||
raise ValueError("State must be str, not of %s." % type(value))
|
||||
|
||||
if value.upper() == self.STATE_ON:
|
||||
return self.turn_on()
|
||||
elif value.upper() == self.STATE_OFF:
|
||||
return self.turn_off()
|
||||
|
||||
raise ValueError("State %s is not valid." % value)
|
||||
|
||||
@property
|
||||
def brightness(self) -> Optional[int]:
|
||||
"""
|
||||
Current brightness of the device, if supported.
|
||||
Will return a a range between 0 - 100.
|
||||
def brightness(self) -> int:
|
||||
"""Return current brightness on dimmers.
|
||||
|
||||
Will return a range between 0 - 100.
|
||||
|
||||
:returns: integer
|
||||
:rtype: int
|
||||
|
||||
"""
|
||||
if not self.is_dimmable:
|
||||
return None
|
||||
raise SmartDeviceException("Device is not dimmable.")
|
||||
|
||||
return int(self.sys_info['brightness'])
|
||||
return int(self.sys_info["brightness"])
|
||||
|
||||
@brightness.setter
|
||||
@brightness.setter # type: ignore
|
||||
@deprecated(details="use set_brightness()")
|
||||
def brightness(self, value: int):
|
||||
"""
|
||||
Set the new switch brightness level.
|
||||
self.set_brightness(value)
|
||||
|
||||
def set_brightness(self, value: int):
|
||||
"""Set the new dimmer brightness level.
|
||||
|
||||
Note:
|
||||
When setting brightness, if the light is not
|
||||
@ -108,22 +103,21 @@ class SmartPlug(SmartDevice):
|
||||
|
||||
"""
|
||||
if not self.is_dimmable:
|
||||
return
|
||||
raise SmartDeviceException("Device is not dimmable.")
|
||||
|
||||
if not isinstance(value, int):
|
||||
raise ValueError("Brightness must be integer, "
|
||||
"not of %s.", type(value))
|
||||
elif value > 0 and value <= 100:
|
||||
raise ValueError("Brightness must be integer, " "not of %s.", type(value))
|
||||
elif 0 < value <= 100:
|
||||
self.turn_on()
|
||||
self._query_helper("smartlife.iot.dimmer", "set_brightness",
|
||||
{"brightness": value})
|
||||
self._query_helper(
|
||||
"smartlife.iot.dimmer", "set_brightness", {"brightness": value}
|
||||
)
|
||||
else:
|
||||
raise ValueError("Brightness value %s is not valid.", value)
|
||||
raise ValueError("Brightness value %s is not valid." % value)
|
||||
|
||||
@property
|
||||
def is_dimmable(self):
|
||||
"""
|
||||
Whether the switch supports brightness changes
|
||||
"""Whether the switch supports brightness changes.
|
||||
|
||||
:return: True if switch supports brightness changes, False otherwise
|
||||
:rtype: bool
|
||||
@ -132,34 +126,31 @@ class SmartPlug(SmartDevice):
|
||||
|
||||
@property
|
||||
def has_emeter(self):
|
||||
"""
|
||||
Returns whether device has an energy meter.
|
||||
"""Return whether device has an energy meter.
|
||||
|
||||
:return: True if energy meter is available
|
||||
False otherwise
|
||||
"""
|
||||
features = self.sys_info['feature'].split(':')
|
||||
return SmartDevice.FEATURE_ENERGY_METER in features
|
||||
features = self.sys_info["feature"].split(":")
|
||||
return "ENE" in features
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool:
|
||||
"""
|
||||
Returns whether device is on.
|
||||
"""Return whether device is on.
|
||||
|
||||
:return: True if device is on, False otherwise
|
||||
"""
|
||||
return bool(self.sys_info['relay_state'])
|
||||
return bool(self.sys_info["relay_state"])
|
||||
|
||||
def turn_on(self):
|
||||
"""
|
||||
Turn the switch on.
|
||||
"""Turn the switch on.
|
||||
|
||||
:raises SmartDeviceException: on error
|
||||
"""
|
||||
self._query_helper("system", "set_relay_state", {"state": 1})
|
||||
|
||||
def turn_off(self):
|
||||
"""
|
||||
Turn the switch off.
|
||||
"""Turn the switch off.
|
||||
|
||||
:raises SmartDeviceException: on error
|
||||
"""
|
||||
@ -167,18 +158,20 @@ class SmartPlug(SmartDevice):
|
||||
|
||||
@property
|
||||
def led(self) -> bool:
|
||||
"""
|
||||
Returns the state of the led.
|
||||
"""Return the state of the led.
|
||||
|
||||
:return: True if led is on, False otherwise
|
||||
:rtype: bool
|
||||
"""
|
||||
return bool(1 - self.sys_info["led_off"])
|
||||
|
||||
@led.setter
|
||||
@led.setter # type: ignore
|
||||
@deprecated(details="use set_led")
|
||||
def led(self, state: bool):
|
||||
"""
|
||||
Sets the state of the led (night mode)
|
||||
self.set_led(state)
|
||||
|
||||
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
|
||||
@ -187,8 +180,7 @@ class SmartPlug(SmartDevice):
|
||||
|
||||
@property
|
||||
def on_since(self) -> datetime.datetime:
|
||||
"""
|
||||
Returns pretty-printed on-time
|
||||
"""Return pretty-printed on-time.
|
||||
|
||||
:return: datetime for on since
|
||||
:rtype: datetime
|
||||
@ -205,16 +197,12 @@ class SmartPlug(SmartDevice):
|
||||
|
||||
@property
|
||||
def state_information(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Return switch-specific state information.
|
||||
"""Return switch-specific state information.
|
||||
|
||||
:return: Switch information dict, keys in user-presentable form.
|
||||
:rtype: dict
|
||||
"""
|
||||
info = {
|
||||
'LED state': self.led,
|
||||
'On since': self.on_since
|
||||
}
|
||||
info = {"LED state": self.led, "On since": self.on_since}
|
||||
if self.is_dimmable:
|
||||
info["Brightness"] = self.brightness
|
||||
return info
|
||||
|
@ -1,16 +1,17 @@
|
||||
import datetime
|
||||
import logging
|
||||
from typing import Any, Dict, Optional, Union
|
||||
from deprecation import deprecated
|
||||
|
||||
from pyHS100 import SmartPlug, SmartDeviceException, EmeterStatus
|
||||
from pyHS100 import SmartPlug, SmartDeviceException, EmeterStatus, DeviceType
|
||||
from .protocol import TPLinkSmartHomeProtocol
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SmartStripException(SmartDeviceException):
|
||||
"""
|
||||
SmartStripException gets raised for errors specific to the smart strip.
|
||||
"""
|
||||
"""SmartStripException gets raised for errors specific to the smart strip."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
@ -19,32 +20,34 @@ class SmartStrip(SmartPlug):
|
||||
|
||||
Usage example when used as library:
|
||||
p = SmartStrip("192.168.1.105")
|
||||
# print the devices alias
|
||||
print(p.alias)
|
||||
# change state of plug
|
||||
p.state = "ON"
|
||||
p.state = "OFF"
|
||||
# query and print current state of plug
|
||||
print(p.state)
|
||||
|
||||
# change state of all outlets
|
||||
p.turn_on()
|
||||
p.turn_off()
|
||||
|
||||
# change state of a single outlet
|
||||
p.turn_on(index=1)
|
||||
|
||||
# query and print current state of all outlets
|
||||
print(p.get_state())
|
||||
|
||||
Errors reported by the device are raised as SmartDeviceExceptions,
|
||||
and should be handled by the user of the library.
|
||||
|
||||
Note:
|
||||
The library references the same structure as defined for the D-Link Switch
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
host: str,
|
||||
protocol: 'TPLinkSmartHomeProtocol' = None) -> None:
|
||||
SmartPlug.__init__(self, host, protocol)
|
||||
def __init__(
|
||||
self, host: str, protocol: TPLinkSmartHomeProtocol = None, cache_ttl: int = 3
|
||||
) -> None:
|
||||
SmartPlug.__init__(self, host=host, protocol=protocol, cache_ttl=cache_ttl)
|
||||
self.emeter_type = "emeter"
|
||||
self._device_type = DeviceType.Strip
|
||||
self.plugs = {}
|
||||
children = self.sys_info["children"]
|
||||
self.num_children = len(children)
|
||||
for plug in range(self.num_children):
|
||||
self.plugs[plug] = SmartPlug(host, protocol,
|
||||
context=children[plug]["id"])
|
||||
self.plugs[plug] = SmartPlug(
|
||||
host, protocol, context=children[plug]["id"], cache_ttl=cache_ttl
|
||||
)
|
||||
|
||||
def raise_for_index(self, index: int):
|
||||
"""
|
||||
@ -54,65 +57,61 @@ class SmartStrip(SmartPlug):
|
||||
:raises SmartStripException: index out of bounds
|
||||
"""
|
||||
if index not in range(self.num_children):
|
||||
raise SmartStripException("plug index of %d "
|
||||
"is out of bounds" % index)
|
||||
raise SmartStripException("plug index of %d " "is out of bounds" % index)
|
||||
|
||||
@property
|
||||
def state(self) -> Dict[int, str]:
|
||||
"""
|
||||
Retrieve the switch state
|
||||
@deprecated(details="use is_on, get_is_on()")
|
||||
def state(self) -> bool:
|
||||
if self.is_on:
|
||||
return self.STATE_ON
|
||||
return self.STATE_OFF
|
||||
|
||||
def get_state(self, *, index=-1) -> Dict[int, str]:
|
||||
"""Retrieve the switch state
|
||||
|
||||
:returns: list with the state of each child plug
|
||||
SWITCH_STATE_ON
|
||||
SWITCH_STATE_OFF
|
||||
SWITCH_STATE_UNKNOWN
|
||||
STATE_ON
|
||||
STATE_OFF
|
||||
:rtype: dict
|
||||
"""
|
||||
states = {}
|
||||
children = self.sys_info["children"]
|
||||
for plug in range(self.num_children):
|
||||
relay_state = children[plug]["state"]
|
||||
|
||||
if relay_state == 0:
|
||||
switch_state = SmartPlug.SWITCH_STATE_OFF
|
||||
elif relay_state == 1:
|
||||
switch_state = SmartPlug.SWITCH_STATE_ON
|
||||
else:
|
||||
_LOGGER.warning("Unknown state %s returned for plug %u.",
|
||||
relay_state, plug)
|
||||
switch_state = SmartPlug.SWITCH_STATE_UNKNOWN
|
||||
def _state_for_bool(b):
|
||||
return SmartPlug.STATE_ON if b else SmartPlug.STATE_OFF
|
||||
|
||||
states[plug] = switch_state
|
||||
is_on = self.get_is_on(index=index)
|
||||
if isinstance(is_on, bool):
|
||||
return _state_for_bool(is_on)
|
||||
|
||||
return states
|
||||
print(is_on)
|
||||
|
||||
return {k: _state_for_bool(v) for k, v in self.get_is_on().items()}
|
||||
|
||||
@state.setter
|
||||
@deprecated(details="use turn_on(), turn_off()")
|
||||
def state(self, value: str):
|
||||
"""
|
||||
Sets the state of all plugs in the strip
|
||||
"""Sets the state of all plugs in the strip
|
||||
|
||||
:param value: one of
|
||||
SWITCH_STATE_ON
|
||||
SWITCH_STATE_OFF
|
||||
STATE_ON
|
||||
STATE_OFF
|
||||
:raises ValueError: on invalid state
|
||||
:raises SmartDeviceException: on error
|
||||
"""
|
||||
if not isinstance(value, str):
|
||||
raise ValueError("State must be str, not of %s.", type(value))
|
||||
elif value.upper() == SmartPlug.SWITCH_STATE_ON:
|
||||
elif value.upper() == SmartPlug.STATE_ON:
|
||||
self.turn_on()
|
||||
elif value.upper() == SmartPlug.SWITCH_STATE_OFF:
|
||||
elif value.upper() == SmartPlug.STATE_OFF:
|
||||
self.turn_off()
|
||||
else:
|
||||
raise ValueError("State %s is not valid.", value)
|
||||
|
||||
def set_state(self, value: str, *, index: int = -1):
|
||||
"""
|
||||
Sets the state of a plug on the strip
|
||||
"""Sets the state of a plug on the strip
|
||||
|
||||
:param value: one of
|
||||
SWITCH_STATE_ON
|
||||
SWITCH_STATE_OFF
|
||||
STATE_ON
|
||||
STATE_OFF
|
||||
:param index: plug index (-1 for all)
|
||||
:raises ValueError: on invalid state
|
||||
:raises SmartDeviceException: on error
|
||||
@ -124,7 +123,12 @@ class SmartStrip(SmartPlug):
|
||||
self.raise_for_index(index)
|
||||
self.plugs[index].state = value
|
||||
|
||||
def is_on(self, *, index: int = -1) -> Any:
|
||||
@property
|
||||
def is_on(self) -> bool:
|
||||
"""Return if any of the outlets are on"""
|
||||
return any(state == "ON" for state in self.get_state().values())
|
||||
|
||||
def get_is_on(self, *, index: int = -1) -> Any:
|
||||
"""
|
||||
Returns whether device is on.
|
||||
|
||||
@ -144,6 +148,13 @@ class SmartStrip(SmartPlug):
|
||||
self.raise_for_index(index)
|
||||
return bool(children[index]["state"])
|
||||
|
||||
def get_is_off(self, *, index: int = -1) -> Any:
|
||||
is_on = self.get_is_on(index=index)
|
||||
if isinstance(is_on, bool):
|
||||
return not is_on
|
||||
else:
|
||||
return {k: not v for k, v in is_on}
|
||||
|
||||
def turn_on(self, *, index: int = -1):
|
||||
"""
|
||||
Turns outlets on
|
||||
@ -172,7 +183,12 @@ class SmartStrip(SmartPlug):
|
||||
self.raise_for_index(index)
|
||||
self.plugs[index].turn_off()
|
||||
|
||||
def on_since(self, *, index: int = -1) -> Any:
|
||||
@property
|
||||
def on_since(self) -> datetime:
|
||||
"""Returns the maximum on-time of all outlets."""
|
||||
return max(v for v in self.get_on_since().values())
|
||||
|
||||
def get_on_since(self, *, index: int = -1) -> Any:
|
||||
"""
|
||||
Returns pretty-printed on-time
|
||||
|
||||
@ -185,10 +201,12 @@ class SmartStrip(SmartPlug):
|
||||
if index < 0:
|
||||
on_since = {}
|
||||
children = self.sys_info["children"]
|
||||
|
||||
for plug in range(self.num_children):
|
||||
on_since[plug] = \
|
||||
datetime.datetime.now() - \
|
||||
datetime.timedelta(seconds=children[plug]["on_time"])
|
||||
child_ontime = children[plug]["on_time"]
|
||||
on_since[plug] = datetime.datetime.now() - datetime.timedelta(
|
||||
seconds=child_ontime
|
||||
)
|
||||
return on_since
|
||||
else:
|
||||
self.raise_for_index(index)
|
||||
@ -202,13 +220,13 @@ class SmartStrip(SmartPlug):
|
||||
:return: Strip information dict, keys in user-presentable form.
|
||||
:rtype: dict
|
||||
"""
|
||||
state = {'LED state': self.led}
|
||||
on_since = self.on_since()
|
||||
is_on = self.is_on()
|
||||
state = {"LED state": self.led}
|
||||
is_on = self.get_is_on()
|
||||
on_since = self.get_on_since()
|
||||
for plug_index in range(self.num_children):
|
||||
plug_number = plug_index + 1
|
||||
if is_on[plug_index]:
|
||||
state['Plug %d on since' % plug_number] = on_since[plug_index]
|
||||
state["Plug %d on since" % plug_number] = on_since[plug_index]
|
||||
|
||||
return state
|
||||
|
||||
@ -225,8 +243,8 @@ class SmartStrip(SmartPlug):
|
||||
:raises SmartDeviceException: on error
|
||||
:raises SmartStripException: index out of bounds
|
||||
"""
|
||||
if not self.has_emeter:
|
||||
return None
|
||||
if not self.has_emeter: # pragma: no cover
|
||||
raise SmartStripException("Device has no emeter")
|
||||
|
||||
if index < 0:
|
||||
emeter_status = {}
|
||||
@ -251,8 +269,8 @@ class SmartStrip(SmartPlug):
|
||||
:raises SmartDeviceException: on error
|
||||
:raises SmartStripException: index out of bounds
|
||||
"""
|
||||
if not self.has_emeter:
|
||||
return None
|
||||
if not self.has_emeter: # pragma: no cover
|
||||
raise SmartStripException("Device has no emeter")
|
||||
|
||||
if index < 0:
|
||||
consumption = {}
|
||||
@ -268,17 +286,13 @@ class SmartStrip(SmartPlug):
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Override for base class icon property, SmartStrip and children do not
|
||||
have icons so we return dummy strings.
|
||||
"""
|
||||
Override for base class icon property, SmartStrip and children do not
|
||||
have icons.
|
||||
|
||||
:raises NotImplementedError: always
|
||||
"""
|
||||
raise NotImplementedError("no icons for this device")
|
||||
return {"icon": "SMARTSTRIP-DUMMY", "hash": "SMARTSTRIP-DUMMY"}
|
||||
|
||||
def get_alias(self, *, index: int = -1) -> Union[str, Dict[int, str]]:
|
||||
"""
|
||||
Gets the alias for a plug.
|
||||
"""Gets the alias for a plug.
|
||||
|
||||
:param index: plug index (-1 for all)
|
||||
:return: the current power consumption in Watts.
|
||||
@ -298,26 +312,25 @@ class SmartStrip(SmartPlug):
|
||||
self.raise_for_index(index)
|
||||
return children[index]["alias"]
|
||||
|
||||
def set_alias(self, alias: str, index: int):
|
||||
"""
|
||||
Sets the alias for a plug
|
||||
def set_alias(self, alias: str, *, index: int = -1):
|
||||
"""Sets the alias for a plug
|
||||
|
||||
:param index: plug index
|
||||
:param alias: new alias
|
||||
:raises SmartDeviceException: on error
|
||||
:raises SmartStripException: index out of bounds
|
||||
"""
|
||||
self.raise_for_index(index)
|
||||
self.plugs[index].alias = alias
|
||||
# Renaming the whole strip
|
||||
if index < 0:
|
||||
return super().set_alias(alias)
|
||||
|
||||
def get_emeter_daily(self,
|
||||
year: int = None,
|
||||
month: int = None,
|
||||
kwh: bool = True,
|
||||
*,
|
||||
index: int = -1) -> Optional[Dict]:
|
||||
"""
|
||||
Retrieve daily statistics for a given month
|
||||
self.raise_for_index(index)
|
||||
self.plugs[index].set_alias(alias)
|
||||
|
||||
def get_emeter_daily(
|
||||
self, year: int = None, month: int = None, kwh: bool = True, *, index: int = -1
|
||||
) -> 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
|
||||
@ -329,29 +342,24 @@ class SmartStrip(SmartPlug):
|
||||
:raises SmartDeviceException: on error
|
||||
:raises SmartStripException: index out of bounds
|
||||
"""
|
||||
if not self.has_emeter:
|
||||
return None
|
||||
if not self.has_emeter: # pragma: no cover
|
||||
raise SmartStripException("Device has no emeter")
|
||||
|
||||
emeter_daily = {}
|
||||
if index < 0:
|
||||
for plug in range(self.num_children):
|
||||
emeter_daily = self.plugs[plug].get_emeter_daily(year=year,
|
||||
month=month,
|
||||
kwh=kwh)
|
||||
emeter_daily = self.plugs[plug].get_emeter_daily(
|
||||
year=year, month=month, kwh=kwh
|
||||
)
|
||||
return emeter_daily
|
||||
else:
|
||||
self.raise_for_index(index)
|
||||
return self.plugs[index].get_emeter_daily(year=year,
|
||||
month=month,
|
||||
kwh=kwh)
|
||||
return self.plugs[index].get_emeter_daily(year=year, month=month, kwh=kwh)
|
||||
|
||||
def get_emeter_monthly(self,
|
||||
year: int = None,
|
||||
kwh: bool = True,
|
||||
*,
|
||||
index: int = -1) -> Optional[Dict]:
|
||||
"""
|
||||
Retrieve monthly statistics for a given year.
|
||||
def get_emeter_monthly(
|
||||
self, year: int = None, kwh: bool = True, *, index: int = -1
|
||||
) -> Dict:
|
||||
"""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)
|
||||
@ -361,23 +369,20 @@ class SmartStrip(SmartPlug):
|
||||
:raises SmartDeviceException: on error
|
||||
:raises SmartStripException: index out of bounds
|
||||
"""
|
||||
if not self.has_emeter:
|
||||
return None
|
||||
if not self.has_emeter: # pragma: no cover
|
||||
raise SmartStripException("Device has no emeter")
|
||||
|
||||
emeter_monthly = {}
|
||||
if index < 0:
|
||||
for plug in range(self.num_children):
|
||||
emeter_monthly = self.plugs[plug].get_emeter_monthly(year=year,
|
||||
kwh=kwh)
|
||||
emeter_monthly = self.plugs[plug].get_emeter_monthly(year=year, kwh=kwh)
|
||||
return emeter_monthly
|
||||
else:
|
||||
self.raise_for_index(index)
|
||||
return self.plugs[index].get_emeter_monthly(year=year,
|
||||
kwh=kwh)
|
||||
return self.plugs[index].get_emeter_monthly(year=year, kwh=kwh)
|
||||
|
||||
def erase_emeter_stats(self, *, index: int = -1) -> bool:
|
||||
"""
|
||||
Erase energy meter statistics
|
||||
"""Erase energy meter statistics
|
||||
|
||||
:param index: plug index (-1 for all)
|
||||
:return: True if statistics were deleted
|
||||
@ -386,8 +391,8 @@ class SmartStrip(SmartPlug):
|
||||
:raises SmartDeviceException: on error
|
||||
:raises SmartStripException: index out of bounds
|
||||
"""
|
||||
if not self.has_emeter:
|
||||
return False
|
||||
if not self.has_emeter: # pragma: no cover
|
||||
raise SmartStripException("Device has no emeter")
|
||||
|
||||
if index < 0:
|
||||
for plug in range(self.num_children):
|
||||
|
113
pyHS100/tests/conftest.py
Normal file
113
pyHS100/tests/conftest.py
Normal file
@ -0,0 +1,113 @@
|
||||
import pytest
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
from .newfakes import FakeTransportProtocol
|
||||
from os.path import basename
|
||||
from pyHS100 import SmartPlug, SmartBulb, SmartStrip, Discover
|
||||
|
||||
SUPPORTED_DEVICES = glob.glob(
|
||||
os.path.dirname(os.path.abspath(__file__)) + "/fixtures/*.json"
|
||||
)
|
||||
|
||||
BULBS = {"LB100", "LB120", "LB130", "KL120"}
|
||||
VARIABLE_TEMP = {"LB120", "LB130", "KL120"}
|
||||
PLUGS = {"HS100", "HS105", "HS110", "HS200", "HS220", "HS300"}
|
||||
STRIPS = {"HS300"}
|
||||
COLOR_BULBS = {"LB130"}
|
||||
DIMMABLE = {*BULBS, "HS220"}
|
||||
EMETER = {"HS110", "HS300", *BULBS}
|
||||
|
||||
ALL_DEVICES = BULBS.union(PLUGS)
|
||||
|
||||
|
||||
def filter_model(filter):
|
||||
print(filter)
|
||||
filtered = list()
|
||||
for dev in SUPPORTED_DEVICES:
|
||||
for filt in filter:
|
||||
if filt in basename(dev):
|
||||
filtered.append(dev)
|
||||
|
||||
return filtered
|
||||
|
||||
|
||||
has_emeter = pytest.mark.parametrize("dev", filter_model(EMETER), indirect=True)
|
||||
no_emeter = pytest.mark.parametrize(
|
||||
"dev", filter_model(ALL_DEVICES - EMETER), indirect=True
|
||||
)
|
||||
|
||||
bulb = pytest.mark.parametrize("dev", filter_model(BULBS), indirect=True)
|
||||
plug = pytest.mark.parametrize("dev", filter_model(PLUGS), indirect=True)
|
||||
strip = pytest.mark.parametrize("dev", filter_model(STRIPS), indirect=True)
|
||||
|
||||
dimmable = pytest.mark.parametrize("dev", filter_model(DIMMABLE), indirect=True)
|
||||
non_dimmable = pytest.mark.parametrize(
|
||||
"dev", filter_model(ALL_DEVICES - DIMMABLE), indirect=True
|
||||
)
|
||||
|
||||
variable_temp = pytest.mark.parametrize(
|
||||
"dev", filter_model(VARIABLE_TEMP), indirect=True
|
||||
)
|
||||
non_variable_temp = pytest.mark.parametrize(
|
||||
"dev", filter_model(BULBS - VARIABLE_TEMP), indirect=True
|
||||
)
|
||||
|
||||
color_bulb = pytest.mark.parametrize("dev", filter_model(COLOR_BULBS), indirect=True)
|
||||
non_color_bulb = pytest.mark.parametrize(
|
||||
"dev", filter_model(BULBS - COLOR_BULBS), indirect=True
|
||||
)
|
||||
|
||||
|
||||
# Parametrize tests to run with device both on and off
|
||||
turn_on = pytest.mark.parametrize("turn_on", [True, False])
|
||||
|
||||
|
||||
def handle_turn_on(dev, turn_on):
|
||||
if turn_on:
|
||||
dev.turn_on()
|
||||
else:
|
||||
dev.turn_off()
|
||||
|
||||
|
||||
@pytest.fixture(params=SUPPORTED_DEVICES)
|
||||
def dev(request):
|
||||
file = request.param
|
||||
|
||||
ip = request.config.getoption("--ip")
|
||||
if ip:
|
||||
d = Discover.discover_single(ip)
|
||||
print(d.model)
|
||||
if d.model in file:
|
||||
return d
|
||||
return
|
||||
|
||||
with open(file) as f:
|
||||
sysinfo = json.load(f)
|
||||
model = basename(file)
|
||||
params = {
|
||||
"host": "123.123.123.123",
|
||||
"protocol": FakeTransportProtocol(sysinfo),
|
||||
"cache_ttl": 0,
|
||||
}
|
||||
if "LB" in model or "KL" in model:
|
||||
p = SmartBulb(**params)
|
||||
elif "HS300" in model:
|
||||
p = SmartStrip(**params)
|
||||
elif "HS" in model:
|
||||
p = SmartPlug(**params)
|
||||
else:
|
||||
raise Exception("No tests for %s" % model)
|
||||
yield p
|
||||
|
||||
|
||||
def pytest_addoption(parser):
|
||||
parser.addoption("--ip", action="store", default=None, help="run against device")
|
||||
|
||||
|
||||
def pytest_collection_modifyitems(config, items):
|
||||
if not config.getoption("--ip"):
|
||||
print("Testing against fixtures.")
|
||||
return
|
||||
else:
|
||||
print("Running against ip %s" % config.getoption("--ip"))
|
@ -1,684 +0,0 @@
|
||||
from ..protocol import TPLinkSmartHomeProtocol
|
||||
from .. import SmartDeviceException
|
||||
import logging
|
||||
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_realtime(obj, x, child_ids=[]):
|
||||
return {"current":0.268587,"voltage":125.836131,"power":33.495623,"total":0.199000}
|
||||
|
||||
|
||||
def get_monthstat(obj, x, child_ids=[]):
|
||||
if x["year"] < 2016:
|
||||
return {"month_list":[]}
|
||||
|
||||
return {"month_list": [{"year": 2016, "month": 11, "energy": 1.089000}, {"year": 2016, "month": 12, "energy": 1.582000}]}
|
||||
|
||||
|
||||
def get_daystat(obj, x, child_ids=[]):
|
||||
if x["year"] < 2016:
|
||||
return {"day_list":[]}
|
||||
|
||||
return {"day_list": [{"year": 2016, "month": 11, "day": 24, "energy": 0.026000},
|
||||
{"year": 2016, "month": 11, "day": 25, "energy": 0.109000}]}
|
||||
|
||||
|
||||
emeter_support = {"get_realtime": get_realtime,
|
||||
"get_monthstat": get_monthstat,
|
||||
"get_daystat": get_daystat,}
|
||||
|
||||
|
||||
def get_realtime_units(obj, x):
|
||||
return {"power_mw": 10800}
|
||||
|
||||
|
||||
def get_monthstat_units(obj, x):
|
||||
if x["year"] < 2016:
|
||||
return {"month_list":[]}
|
||||
|
||||
return {"month_list": [{"year": 2016, "month": 11, "energy_wh": 32}, {"year": 2016, "month": 12, "energy_wh": 16}]}
|
||||
|
||||
|
||||
def get_daystat_units(obj, x):
|
||||
if x["year"] < 2016:
|
||||
return {"day_list":[]}
|
||||
|
||||
return {"day_list": [{"year": 2016, "month": 11, "day": 24, "energy_wh": 20},
|
||||
{"year": 2016, "month": 11, "day": 25, "energy_wh": 32}]}
|
||||
|
||||
|
||||
emeter_units_support = {"get_realtime": get_realtime_units,
|
||||
"get_monthstat": get_monthstat_units,
|
||||
"get_daystat": get_daystat_units,}
|
||||
|
||||
sysinfo_hs300 = {
|
||||
'system': {
|
||||
'get_sysinfo': {
|
||||
'sw_ver': '1.0.6 Build 180627 Rel.081000',
|
||||
'hw_ver': '1.0',
|
||||
'model': 'HS300(US)',
|
||||
'deviceId': '7003ADE7030B7EFADE747104261A7A70931DADF4',
|
||||
'oemId': 'FFF22CFF774A0B89F7624BFC6F50D5DE',
|
||||
'hwId': '22603EA5E716DEAEA6642A30BE87AFCB',
|
||||
'rssi': -53,
|
||||
'longitude_i': -1198698,
|
||||
'latitude_i': 352737,
|
||||
'alias': 'TP-LINK_Power Strip_2233',
|
||||
'mic_type': 'IOT.SMARTPLUGSWITCH',
|
||||
'feature': 'TIM:ENE',
|
||||
'mac': '50:C7:BF:11:22:33',
|
||||
'updating': 0,
|
||||
'led_off': 0,
|
||||
'children': [
|
||||
{
|
||||
'id': '7003ADE7030B7EFADE747104261A7A70931DADF400',
|
||||
'state': 1,
|
||||
'alias': 'my plug 1 device',
|
||||
'on_time': 5423,
|
||||
'next_action': {
|
||||
'type': -1
|
||||
}
|
||||
},
|
||||
{
|
||||
'id': '7003ADE7030B7EFADE747104261A7A70931DADF401',
|
||||
'state': 1,
|
||||
'alias': 'my plug 2 device',
|
||||
'on_time': 4750,
|
||||
'next_action': {
|
||||
'type': -1
|
||||
}
|
||||
},
|
||||
{
|
||||
'id': '7003ADE7030B7EFADE747104261A7A70931DADF402',
|
||||
'state': 1,
|
||||
'alias': 'my plug 3 device',
|
||||
'on_time': 4748,
|
||||
'next_action': {
|
||||
'type': -1
|
||||
}
|
||||
},
|
||||
{
|
||||
'id': '7003ADE7030B7EFADE747104261A7A70931DADF403',
|
||||
'state': 1,
|
||||
'alias': 'my plug 4 device',
|
||||
'on_time': 4742,
|
||||
'next_action': {
|
||||
'type': -1
|
||||
}
|
||||
},
|
||||
{
|
||||
'id': '7003ADE7030B7EFADE747104261A7A70931DADF404',
|
||||
'state': 1,
|
||||
'alias': 'my plug 5 device',
|
||||
'on_time': 4745,
|
||||
'next_action': {
|
||||
'type': -1
|
||||
}
|
||||
},
|
||||
{
|
||||
'id': '7003ADE7030B7EFADE747104261A7A70931DADF405',
|
||||
'state': 1,
|
||||
'alias': 'my plug 6 device',
|
||||
'on_time': 5028,
|
||||
'next_action': {
|
||||
'type': -1
|
||||
}
|
||||
}
|
||||
],
|
||||
'child_num': 6,
|
||||
'err_code': 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sysinfo_hs100 = {'system': {'get_sysinfo':
|
||||
{'active_mode': 'schedule',
|
||||
'alias': 'My Smart Plug',
|
||||
'dev_name': 'Wi-Fi Smart Plug',
|
||||
'deviceId': '80061E93E28EEBA9FA1929D15C4678C7172A8AF2',
|
||||
'feature': 'TIM',
|
||||
'fwId': 'BFF24826FBC561803E49379DBE74FD71',
|
||||
'hwId': '22603EA5E716DEAEA6642A30BE87AFCA',
|
||||
'hw_ver': '1.0',
|
||||
'icon_hash': '',
|
||||
'latitude': 12.2,
|
||||
'led_off': 0,
|
||||
'longitude': 12.2,
|
||||
'mac': '50:C7:BF:11:22:33',
|
||||
'model': 'HS100(EU)',
|
||||
'oemId': '812A90EB2FCF306A993FAD8748024B07',
|
||||
'on_time': 255419,
|
||||
'relay_state': 1,
|
||||
'sw_ver': '1.0.8 Build 151101 Rel.24452',
|
||||
'type': 'smartplug',
|
||||
'updating': 0}}}
|
||||
|
||||
sysinfo_hs105 = {'system': {'get_sysinfo':
|
||||
{'sw_ver': '1.0.6 Build 160722 Rel.081616',
|
||||
'hw_ver': '1.0', 'type': 'IOT.SMARTPLUGSWITCH',
|
||||
'model': 'HS105(US)',
|
||||
'mac': '50:C7:BF:11:22:33',
|
||||
'dev_name': 'Smart Wi-Fi Plug Mini',
|
||||
'alias': 'TP-LINK_Smart Plug_CF0B',
|
||||
'relay_state': 0,
|
||||
'on_time': 0,
|
||||
'active_mode': 'none',
|
||||
'feature': 'TIM',
|
||||
'updating': 0,
|
||||
'icon_hash': '',
|
||||
'rssi': 33,
|
||||
'led_off': 0,
|
||||
'longitude_i': -12.2,
|
||||
'latitude_i': 12.2,
|
||||
'hwId': '60FF6B258734EA6880E186F8C96DDC61',
|
||||
'fwId': '00000000000000000000000000000000',
|
||||
'deviceId': '800654F32938FCBA8F7327887A38647617',
|
||||
'oemId': 'FFF22CFF774A0B89F7624BFC6F50D5DE'}}}
|
||||
|
||||
sysinfo_hs110 = {'system': {'get_sysinfo':
|
||||
{'active_mode': 'schedule',
|
||||
'alias': 'Mobile Plug',
|
||||
'dev_name': 'Wi-Fi Smart Plug With Energy Monitoring',
|
||||
'deviceId': '800654F32938FCBA8F7327887A386476172B5B53',
|
||||
'err_code': 0,
|
||||
'feature': 'TIM:ENE',
|
||||
'fwId': 'E16EB3E95DB6B47B5B72B3FD86FD1438',
|
||||
'hwId': '60FF6B258734EA6880E186F8C96DDC61',
|
||||
'hw_ver': '1.0',
|
||||
'icon_hash': '',
|
||||
'latitude': 12.2,
|
||||
'led_off': 0,
|
||||
'longitude': -12.2,
|
||||
'mac': 'AA:BB:CC:11:22:33',
|
||||
'model': 'HS110(US)',
|
||||
'oemId': 'FFF22CFF774A0B89F7624BFC6F50D5DE',
|
||||
'on_time': 9022,
|
||||
'relay_state': 1,
|
||||
'rssi': -61,
|
||||
'sw_ver': '1.0.8 Build 151113 Rel.24658',
|
||||
'type': 'IOT.SMARTPLUGSWITCH',
|
||||
'updating': 0}
|
||||
},
|
||||
'emeter': emeter_support,
|
||||
}
|
||||
|
||||
sysinfo_hs110_au_v2 = {'system': {'get_sysinfo':
|
||||
{'active_mode': 'none',
|
||||
'alias': 'Tplink Test',
|
||||
'dev_name': 'Smart Wi-Fi Plug With Energy Monitoring',
|
||||
'deviceId': '80062952E2F3D9461CFB91FF21B7868F194F627A',
|
||||
'feature': 'TIM:ENE',
|
||||
'fwId': '00000000000000000000000000000000',
|
||||
'hwId': 'A28C8BB92AFCB6CAFB83A8C00145F7E2',
|
||||
'hw_ver': '2.0',
|
||||
'icon_hash': '',
|
||||
'latitude_i': -1.1,
|
||||
'led_off': 0,
|
||||
'longitude_i': 2.2,
|
||||
'mac': '70:4F:57:12:12:12',
|
||||
'model': 'HS110(AU)',
|
||||
'oemId': '6480C2101948463DC65D7009CAECDECC',
|
||||
'on_time': 0,
|
||||
'relay_state': 0,
|
||||
'rssi': -70,
|
||||
'sw_ver': '1.5.2 Build 171201 Rel.084625',
|
||||
'type': 'IOT.SMARTPLUGSWITCH',
|
||||
'updating': 0}
|
||||
},
|
||||
'emeter': {'voltage_mv': 246520, 'power_mw': 258401, 'current_ma': 3104, 'total_wh': 387}}
|
||||
|
||||
sysinfo_hs200 = {'system': {'get_sysinfo': {'active_mode': 'schedule',
|
||||
'alias': 'Christmas Tree Switch',
|
||||
'dev_name': 'Wi-Fi Smart Light Switch',
|
||||
'deviceId': '8006E0D62C90698C6A3EF72944F56DDC17D0DB80',
|
||||
'err_code': 0,
|
||||
'feature': 'TIM',
|
||||
'fwId': 'DB4F3246CD85AA59CAE738A63E7B9C34',
|
||||
'hwId': 'A0E3CC8F5C1166B27A16D56BE262A6D3',
|
||||
'hw_ver': '1.0',
|
||||
'icon_hash': '',
|
||||
'latitude': 12.2,
|
||||
'led_off': 0,
|
||||
'longitude': -12.2,
|
||||
'mac': 'AA:BB:CC:11:22:33',
|
||||
'mic_type': 'IOT.SMARTPLUGSWITCH',
|
||||
'model': 'HS200(US)',
|
||||
'oemId': '4AFE44A41F868FD2340E6D1308D8551D',
|
||||
'on_time': 9586,
|
||||
'relay_state': 1,
|
||||
'rssi': -53,
|
||||
'sw_ver': '1.1.0 Build 160521 Rel.085826',
|
||||
'updating': 0}}
|
||||
}
|
||||
|
||||
sysinfo_hs220 = {
|
||||
"system": {
|
||||
"get_sysinfo": {
|
||||
"sw_ver": "1.4.8 Build 180109 Rel.171240",
|
||||
"hw_ver": "1.0",
|
||||
"mic_type": "IOT.SMARTPLUGSWITCH",
|
||||
"model": "HS220(US)",
|
||||
"mac": "B0:4E:26:11:22:33",
|
||||
"dev_name": "Smart Wi-Fi Dimmer",
|
||||
"alias": "Chandelier",
|
||||
"relay_state": 0,
|
||||
"brightness": 25,
|
||||
"on_time": 0,
|
||||
"active_mode": "none",
|
||||
"feature": "TIM",
|
||||
"updating": 0,
|
||||
"icon_hash": "",
|
||||
"rssi": -53,
|
||||
"led_off": 0,
|
||||
"longitude_i": -12.2,
|
||||
"latitude_i": 12.2,
|
||||
"hwId": "84DCCF37225C9E55319617F7D5C095BD",
|
||||
"fwId": "00000000000000000000000000000000",
|
||||
"deviceId": "800695154E6B882428E30F850473F34019A9E999",
|
||||
"oemId": "3B13224B2807E0D48A9DD06EBD344CD6",
|
||||
"preferred_state":
|
||||
[
|
||||
{"index": 0, "brightness": 100},
|
||||
{"index": 1, "brightness": 75},
|
||||
{"index": 2, "brightness": 50},
|
||||
{"index": 3, "brightness": 25}
|
||||
],
|
||||
"next_action": {"type": -1},
|
||||
"err_code": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sysinfo_lb130 = {'system': {'get_sysinfo':
|
||||
{'active_mode': 'none',
|
||||
'alias': 'Living Room Side Table',
|
||||
'ctrl_protocols': {'name': 'Linkie', 'version': '1.0'},
|
||||
'description': 'Smart Wi-Fi LED Bulb with Color Changing',
|
||||
'dev_state': 'normal',
|
||||
'deviceId': '80123C4640E9FC33A9019A0F3FD8BF5C17B7D9A8',
|
||||
'disco_ver': '1.0',
|
||||
'heapsize': 347000,
|
||||
'hwId': '111E35908497A05512E259BB76801E10',
|
||||
'hw_ver': '1.0',
|
||||
'is_color': 1,
|
||||
'is_dimmable': 1,
|
||||
'is_factory': False,
|
||||
'is_variable_color_temp': 1,
|
||||
'light_state': {'brightness': 100,
|
||||
'color_temp': 3700,
|
||||
'hue': 0,
|
||||
'mode': 'normal',
|
||||
'on_off': 1,
|
||||
'saturation': 0},
|
||||
'mic_mac': '50C7BF104865',
|
||||
'mic_type': 'IOT.SMARTBULB',
|
||||
'model': 'LB130(US)',
|
||||
'oemId': '05BF7B3BE1675C5A6867B7A7E4C9F6F7',
|
||||
'preferred_state': [{'brightness': 50,
|
||||
'color_temp': 2700,
|
||||
'hue': 0,
|
||||
'index': 0,
|
||||
'saturation': 0},
|
||||
{'brightness': 100,
|
||||
'color_temp': 0,
|
||||
'hue': 0,
|
||||
'index': 1,
|
||||
'saturation': 75},
|
||||
{'brightness': 100,
|
||||
'color_temp': 0,
|
||||
'hue': 120,
|
||||
'index': 2,
|
||||
'saturation': 75},
|
||||
{'brightness': 100,
|
||||
'color_temp': 0,
|
||||
'hue': 240,
|
||||
'index': 3,
|
||||
'saturation': 75}],
|
||||
'rssi': -55,
|
||||
'sw_ver': '1.1.2 Build 160927 Rel.111100'}},
|
||||
'smartlife.iot.smartbulb.lightingservice': {'get_light_state':
|
||||
{'on_off':1,
|
||||
'mode':'normal',
|
||||
'hue': 0,
|
||||
'saturation': 0,
|
||||
'color_temp': 3700,
|
||||
'brightness': 100,
|
||||
'err_code': 0}},
|
||||
'smartlife.iot.common.emeter': emeter_units_support,
|
||||
}
|
||||
|
||||
sysinfo_lb100 = {'system': {
|
||||
'sys_info': {
|
||||
'emeter': {
|
||||
'err_code': -2001,
|
||||
'err_msg': 'Module not support'
|
||||
},
|
||||
'system': {
|
||||
'get_sysinfo': {
|
||||
'active_mode': 'none',
|
||||
'alias': 'New Light',
|
||||
'ctrl_protocols': {
|
||||
'name': 'Linkie',
|
||||
'version': '1.0'
|
||||
},
|
||||
'description': 'Smart Wi-Fi LED Bulb with Dimmable Light',
|
||||
'dev_state': 'normal',
|
||||
'deviceId': '8012996ED1F8DA43EFFD58B62BEC5ADE18192F88',
|
||||
'disco_ver': '1.0',
|
||||
'err_code': 0,
|
||||
'heapsize': 340808,
|
||||
'hwId': '111E35908497A05512E259BB76801E10',
|
||||
'hw_ver': '1.0',
|
||||
'is_color': 0,
|
||||
'is_dimmable': 1,
|
||||
'is_factory': False,
|
||||
'is_variable_color_temp': 0,
|
||||
'light_state': {
|
||||
'dft_on_state': {
|
||||
'brightness': 50,
|
||||
'color_temp': 2700,
|
||||
'hue': 0,
|
||||
'mode': 'normal',
|
||||
'saturation': 0
|
||||
},
|
||||
'on_off': 0
|
||||
},
|
||||
'mic_mac': '50C7BF3393F1',
|
||||
'mic_type': 'IOT.SMARTBULB',
|
||||
'model': 'LB100(US)',
|
||||
'oemId': '264E4E97B2D2B086F289AC1F00B90679',
|
||||
'preferred_state': [
|
||||
{
|
||||
'brightness': 100,
|
||||
'color_temp': 2700,
|
||||
'hue': 0,
|
||||
'index': 0,
|
||||
'saturation': 0
|
||||
},
|
||||
{
|
||||
'brightness': 75,
|
||||
'color_temp': 2700,
|
||||
'hue': 0,
|
||||
'index': 1,
|
||||
'saturation': 0
|
||||
},
|
||||
{
|
||||
'brightness': 25,
|
||||
'color_temp': 2700,
|
||||
'hue': 0,
|
||||
'index': 2,
|
||||
'saturation': 0
|
||||
},
|
||||
{
|
||||
'brightness': 1,
|
||||
'color_temp': 2700,
|
||||
'hue': 0,
|
||||
'index': 3,
|
||||
'saturation': 0
|
||||
}
|
||||
],
|
||||
'rssi': -54,
|
||||
'sw_ver': '1.2.3 Build 170123 Rel.100146'
|
||||
}
|
||||
}
|
||||
}
|
||||
}}
|
||||
|
||||
sysinfo_lb110 = {'system': {
|
||||
'sys_info':
|
||||
{'emeter':
|
||||
{'err_code': -2001,
|
||||
'err_msg': 'Module not support'},
|
||||
'system':
|
||||
{'get_sysinfo':
|
||||
{'active_mode': 'schedule',
|
||||
'alias': 'Downstairs Light',
|
||||
'ctrl_protocols':
|
||||
{'name': 'Linkie',
|
||||
'version': '1.0'},
|
||||
'description': 'Smart Wi-Fi LED Bulb '
|
||||
'with Dimmable Light',
|
||||
'dev_state': 'normal',
|
||||
'deviceId':
|
||||
'80120B3D03E0B639CDF33E3CB1466490187FEF32',
|
||||
'disco_ver': '1.0',
|
||||
'err_code': 0,
|
||||
'heapsize': 309908,
|
||||
'hwId': '111E35908497A05512E259BB76801E10',
|
||||
'hw_ver': '1.0',
|
||||
'is_color': 0,
|
||||
'is_dimmable': 1,
|
||||
'is_factory': False,
|
||||
'is_variable_color_temp': 0,
|
||||
'light_state':
|
||||
{'dft_on_state':
|
||||
{'brightness': 92,
|
||||
'color_temp': 2700,
|
||||
'hue': 0,
|
||||
'mode': 'normal',
|
||||
'saturation': 0},
|
||||
'on_off': 0},
|
||||
'mic_mac': '50C7BF7BE306',
|
||||
'mic_type': 'IOT.SMARTBULB',
|
||||
'model': 'LB110(EU)',
|
||||
'oemId':
|
||||
'A68E15472071CB761E5CCFB388A1D8AE',
|
||||
'preferred_state': [{'brightness': 100,
|
||||
'color_temp': 2700,
|
||||
'hue': 0,
|
||||
'index': 0,
|
||||
'saturation': 0},
|
||||
{'brightness': 58,
|
||||
'color_temp': 2700,
|
||||
'hue': 0,
|
||||
'index': 1,
|
||||
'saturation': 0},
|
||||
{'brightness': 25,
|
||||
'color_temp': 2700,
|
||||
'hue': 0,
|
||||
'index': 2,
|
||||
'saturation': 0},
|
||||
{'brightness': 1,
|
||||
'color_temp': 2700,
|
||||
'hue': 0,
|
||||
'index': 3,
|
||||
'saturation': 0}],
|
||||
'rssi': -61,
|
||||
'sw_ver': '1.5.5 Build 170623 '
|
||||
'Rel.090105'
|
||||
}
|
||||
}
|
||||
}
|
||||
}}
|
||||
|
||||
sysinfo_lb120 = {'system':
|
||||
{'sys_info':
|
||||
{'system':
|
||||
{'get_sysinfo':
|
||||
{'active_mode': 'none',
|
||||
'alias': 'LB1202',
|
||||
'ctrl_protocols': {'name': 'Linkie', 'version': '1.0'},
|
||||
'description': 'Smart Wi-Fi LED Bulb with Tunable White Light',
|
||||
'dev_state': 'normal',
|
||||
'deviceId': 'foo',
|
||||
'disco_ver': '1.0',
|
||||
'heapsize': 329032,
|
||||
'hwId': 'foo',
|
||||
'hw_ver': '1.0',
|
||||
'is_color': 0,
|
||||
'is_dimmable': 1,
|
||||
'is_factory': False,
|
||||
'is_variable_color_temp': 1,
|
||||
'light_state': {'dft_on_state': {'brightness': 31,
|
||||
'color_temp': 4100,
|
||||
'hue': 0,
|
||||
'mode': 'normal',
|
||||
'saturation': 0},
|
||||
'on_off': 0},
|
||||
'mic_mac': '50C7BF33937C',
|
||||
'mic_type': 'IOT.SMARTBULB',
|
||||
'model': 'LB120(US)',
|
||||
'oemId': 'foo',
|
||||
'preferred_state': [{'brightness': 100,
|
||||
'color_temp': 3500,
|
||||
'hue': 0,
|
||||
'index': 0,
|
||||
'saturation': 0},
|
||||
{'brightness': 50,
|
||||
'color_temp': 6500,
|
||||
'hue': 0,
|
||||
'index': 1,
|
||||
'saturation': 0},
|
||||
{'brightness': 50,
|
||||
'color_temp': 2700,
|
||||
'hue': 0,
|
||||
'index': 2,
|
||||
'saturation': 0},
|
||||
{'brightness': 1,
|
||||
'color_temp': 2700,
|
||||
'hue': 0,
|
||||
'index': 3,
|
||||
'saturation': 0}],
|
||||
'rssi': -47,
|
||||
'sw_ver': '1.4.3 Build 170504 Rel.144921'}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def error(target, cmd="no-command", msg="default msg"):
|
||||
return {target: {cmd: {"err_code": -1323, "msg": msg}}}
|
||||
|
||||
|
||||
def success(target, cmd, res):
|
||||
if res:
|
||||
res.update({"err_code": 0})
|
||||
else:
|
||||
res = {"err_code": 0}
|
||||
return {target: {cmd: res}}
|
||||
|
||||
|
||||
class FakeTransportProtocol(TPLinkSmartHomeProtocol):
|
||||
def __init__(self, sysinfo, invalid=False):
|
||||
""" invalid is set only for testing
|
||||
to force query() to throw the exception for non-connected """
|
||||
proto = FakeTransportProtocol.baseproto
|
||||
for target in sysinfo:
|
||||
for cmd in sysinfo[target]:
|
||||
proto[target][cmd] = sysinfo[target][cmd]
|
||||
self.proto = proto
|
||||
self.invalid = invalid
|
||||
|
||||
def set_alias(self, x, child_ids=[]):
|
||||
_LOGGER.debug("Setting alias to %s", x["alias"])
|
||||
if child_ids:
|
||||
for child in self.proto["system"]["get_sysinfo"]["children"]:
|
||||
if child["id"] in child_ids:
|
||||
child["alias"] = x["alias"]
|
||||
else:
|
||||
self.proto["system"]["get_sysinfo"]["alias"] = x["alias"]
|
||||
|
||||
def set_relay_state(self, x, child_ids=[]):
|
||||
_LOGGER.debug("Setting relay state to %s", x["state"])
|
||||
|
||||
if not child_ids and "children" in self.proto["system"]["get_sysinfo"]:
|
||||
for child in self.proto["system"]["get_sysinfo"]["children"]:
|
||||
child_ids.append(child["id"])
|
||||
|
||||
if child_ids:
|
||||
for child in self.proto["system"]["get_sysinfo"]["children"]:
|
||||
if child["id"] in child_ids:
|
||||
child["state"] = x["state"]
|
||||
else:
|
||||
self.proto["system"]["get_sysinfo"]["relay_state"] = x["state"]
|
||||
|
||||
def set_led_off(self, x):
|
||||
_LOGGER.debug("Setting led off to %s", x)
|
||||
self.proto["system"]["get_sysinfo"]["led_off"] = x["off"]
|
||||
|
||||
def set_mac(self, x):
|
||||
_LOGGER.debug("Setting mac to %s", x)
|
||||
self.proto["system"]["get_sysinfo"]["mac"] = x
|
||||
|
||||
def set_hs220_brightness(self, x):
|
||||
_LOGGER.debug("Setting brightness to %s", x)
|
||||
self.proto["system"]["get_sysinfo"]["brightness"] = x["brightness"]
|
||||
|
||||
def transition_light_state(self, x):
|
||||
_LOGGER.debug("Setting light state to %s", x)
|
||||
for key in x:
|
||||
self.proto["smartlife.iot.smartbulb.lightingservice"]["get_light_state"][key]=x[key]
|
||||
|
||||
baseproto = {
|
||||
"system": { "set_relay_state": set_relay_state,
|
||||
"set_dev_alias": set_alias,
|
||||
"set_led_off": set_led_off,
|
||||
"get_dev_icon": {"icon": None, "hash": None},
|
||||
"set_mac_addr": set_mac,
|
||||
"get_sysinfo": None,
|
||||
"context": None,
|
||||
},
|
||||
"emeter": { "get_realtime": None,
|
||||
"get_daystat": None,
|
||||
"get_monthstat": None,
|
||||
"erase_emeter_state": None
|
||||
},
|
||||
"smartlife.iot.common.emeter": { "get_realtime": None,
|
||||
"get_daystat": None,
|
||||
"get_monthstat": None,
|
||||
"erase_emeter_state": None
|
||||
},
|
||||
"smartlife.iot.smartbulb.lightingservice": { "get_light_state": None,
|
||||
"transition_light_state": transition_light_state,
|
||||
},
|
||||
"time": { "get_time": { "year": 2017, "month": 1, "mday": 2, "hour": 3, "min": 4, "sec": 5 },
|
||||
"get_timezone": {'zone_str': "test", 'dst_offset': -1, 'index': 12, 'tz_str': "test2" },
|
||||
"set_timezone": None,
|
||||
},
|
||||
# HS220 brightness, different setter and getter
|
||||
"smartlife.iot.dimmer": { "set_brightness": set_hs220_brightness,
|
||||
},
|
||||
"context": {"child_ids": None},
|
||||
}
|
||||
|
||||
def query(self, host, request, port=9999):
|
||||
if self.invalid:
|
||||
raise SmartDeviceException("Invalid connection, can't query!")
|
||||
|
||||
_LOGGER.debug("Requesting {} from {}:{}".format(request, host, port))
|
||||
|
||||
proto = self.proto
|
||||
|
||||
# collect child ids from context
|
||||
try:
|
||||
child_ids = request["context"]["child_ids"]
|
||||
request.pop("context", None)
|
||||
except KeyError:
|
||||
child_ids = []
|
||||
|
||||
target = next(iter(request))
|
||||
if target not in proto.keys():
|
||||
return error(target, msg="target not found")
|
||||
|
||||
cmd = next(iter(request[target]))
|
||||
if cmd not in proto[target].keys():
|
||||
return error(target, cmd, msg="command not found")
|
||||
|
||||
params = request[target][cmd]
|
||||
_LOGGER.debug("Going to execute {}.{} (params: {}).. ".format(target, cmd, params))
|
||||
|
||||
if callable(proto[target][cmd]):
|
||||
if child_ids:
|
||||
res = proto[target][cmd](self, params, child_ids)
|
||||
else:
|
||||
res = proto[target][cmd](self, params)
|
||||
# verify that change didn't break schema, requires refactoring..
|
||||
#TestSmartPlug.sysinfo_schema(self.proto["system"]["get_sysinfo"])
|
||||
return success(target, cmd, res)
|
||||
elif isinstance(proto[target][cmd], dict):
|
||||
return success(target, cmd, proto[target][cmd])
|
||||
else:
|
||||
raise NotImplementedError("target {} cmd {}".format(target, cmd))
|
47
pyHS100/tests/fixtures/HS100(US)_1.0.json
vendored
Normal file
47
pyHS100/tests/fixtures/HS100(US)_1.0.json
vendored
Normal file
@ -0,0 +1,47 @@
|
||||
{
|
||||
"emeter": {
|
||||
"get_realtime": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
}
|
||||
},
|
||||
"smartlife.iot.common.emeter": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.dimmer": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.smartbulb.lightingservice": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"system": {
|
||||
"get_sysinfo": {
|
||||
"active_mode": "schedule",
|
||||
"alias": "Mock hs100",
|
||||
"dev_name": "Wi-Fi Smart Plug",
|
||||
"deviceId": "048F069965D3230FD1382F0B78EAE68D42CAA2DE",
|
||||
"err_code": 0,
|
||||
"feature": "TIM",
|
||||
"hwId": "92688D028799C60F926049D1C9EFD9E8",
|
||||
"hw_ver": "1.0",
|
||||
"icon_hash": "",
|
||||
"latitude": 63.5442,
|
||||
"latitude_i": 63.5442,
|
||||
"led_off": 0,
|
||||
"longitude": -148.2817,
|
||||
"longitude_i": -148.2817,
|
||||
"mac": "50:c7:bf:a3:71:c0",
|
||||
"model": "HS100(US)",
|
||||
"oemId": "149C8A24AA3A1445DE84F00DFB210D60",
|
||||
"on_time": 0,
|
||||
"relay_state": 0,
|
||||
"rssi": -65,
|
||||
"sw_ver": "1.2.5 Build 171129 Rel.174814",
|
||||
"type": "IOT.SMARTPLUGSWITCH",
|
||||
"updating": 0
|
||||
}
|
||||
}
|
||||
}
|
47
pyHS100/tests/fixtures/HS105(US)_1.0.json
vendored
Normal file
47
pyHS100/tests/fixtures/HS105(US)_1.0.json
vendored
Normal file
@ -0,0 +1,47 @@
|
||||
{
|
||||
"emeter": {
|
||||
"get_realtime": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
}
|
||||
},
|
||||
"smartlife.iot.common.emeter": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.dimmer": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.smartbulb.lightingservice": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"system": {
|
||||
"get_sysinfo": {
|
||||
"active_mode": "schedule",
|
||||
"alias": "Mock hs105",
|
||||
"dev_name": "Smart Wi-Fi Plug Mini",
|
||||
"deviceId": "F0723FAFC1FA27FC755B9F228A2297D921FEBCD1",
|
||||
"err_code": 0,
|
||||
"feature": "TIM",
|
||||
"hwId": "51E17031929D5FEF9147091AD67B954A",
|
||||
"hw_ver": "1.0",
|
||||
"icon_hash": "",
|
||||
"INVALIDlatitude": 79.7779,
|
||||
"latitude_i": 79.7779,
|
||||
"led_off": 0,
|
||||
"INVALIDlongitude": 90.8844,
|
||||
"longitude_i": 90.8844,
|
||||
"mac": "50:c7:bf:ac:c0:6a",
|
||||
"model": "HS105(US)",
|
||||
"oemId": "990ADB7AEDE871C41D1B7613D1FE7A76",
|
||||
"on_time": 0,
|
||||
"relay_state": 0,
|
||||
"rssi": -65,
|
||||
"sw_ver": "1.2.9 Build 170808 Rel.145916",
|
||||
"type": "IOT.SMARTPLUGSWITCH",
|
||||
"updating": 0
|
||||
}
|
||||
}
|
||||
}
|
49
pyHS100/tests/fixtures/HS110(EU)_1.0_real.json
vendored
Normal file
49
pyHS100/tests/fixtures/HS110(EU)_1.0_real.json
vendored
Normal file
@ -0,0 +1,49 @@
|
||||
{
|
||||
"emeter": {
|
||||
"get_realtime": {
|
||||
"current": 0.015342,
|
||||
"err_code": 0,
|
||||
"power": 0.983971,
|
||||
"total": 32.448,
|
||||
"voltage": 235.595234
|
||||
}
|
||||
},
|
||||
"smartlife.iot.common.emeter": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.dimmer": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.smartbulb.lightingservice": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"system": {
|
||||
"get_sysinfo": {
|
||||
"active_mode": "schedule",
|
||||
"alias": "Kitchen",
|
||||
"dev_name": "Wi-Fi Smart Plug With Energy Monitoring",
|
||||
"deviceId": "8006588E50AD389303FF31AB6302907A17442F16",
|
||||
"err_code": 0,
|
||||
"feature": "TIM:ENE",
|
||||
"fwId": "00000000000000000000000000000000",
|
||||
"hwId": "45E29DA8382494D2E82688B52A0B2EB5",
|
||||
"hw_ver": "1.0",
|
||||
"icon_hash": "",
|
||||
"latitude": 51.476938,
|
||||
"led_off": 1,
|
||||
"longitude": 7.216849,
|
||||
"mac": "50:C7:BF:01:F8:CD",
|
||||
"model": "HS110(EU)",
|
||||
"oemId": "3D341ECE302C0642C99E31CE2430544B",
|
||||
"on_time": 512874,
|
||||
"relay_state": 1,
|
||||
"rssi": -71,
|
||||
"sw_ver": "1.2.5 Build 171213 Rel.101523",
|
||||
"type": "IOT.SMARTPLUGSWITCH",
|
||||
"updating": 0
|
||||
}
|
||||
}
|
||||
}
|
50
pyHS100/tests/fixtures/HS110(EU)_2.0.json
vendored
Normal file
50
pyHS100/tests/fixtures/HS110(EU)_2.0.json
vendored
Normal file
@ -0,0 +1,50 @@
|
||||
{
|
||||
"emeter": {
|
||||
"get_realtime": {
|
||||
"current_ma": 125,
|
||||
"err_code": 0,
|
||||
"power_mw": 3140,
|
||||
"total_wh": 51493,
|
||||
"voltage_mv": 122049
|
||||
}
|
||||
},
|
||||
"smartlife.iot.common.emeter": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.dimmer": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.smartbulb.lightingservice": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"system": {
|
||||
"get_sysinfo": {
|
||||
"active_mode": "schedule",
|
||||
"alias": "Mock hs110v2",
|
||||
"dev_name": "Smart Wi-Fi Plug With Energy Monitoring",
|
||||
"deviceId": "A466BCDB5026318939145B7CC7EF18D8C1D3A954",
|
||||
"err_code": 0,
|
||||
"feature": "TIM:ENE",
|
||||
"hwId": "1F7FABB46373CA51E3AFDE5930ECBB36",
|
||||
"hw_ver": "2.0",
|
||||
"icon_hash": "",
|
||||
"INVALIDlatitude": -60.4599,
|
||||
"latitude_i": -60.4599,
|
||||
"led_off": 0,
|
||||
"INVALIDlongitude": 76.1249,
|
||||
"longitude_i": 76.1249,
|
||||
"mac": "50:c7:bf:b9:40:08",
|
||||
"model": "HS110(EU)",
|
||||
"oemId": "BB668B949FA4559655F1187DD56622BD",
|
||||
"on_time": 0,
|
||||
"relay_state": 0,
|
||||
"rssi": -65,
|
||||
"sw_ver": "1.5.2 Build 180130 Rel.085820",
|
||||
"type": "IOT.SMARTPLUGSWITCH",
|
||||
"updating": 0
|
||||
}
|
||||
}
|
||||
}
|
50
pyHS100/tests/fixtures/HS110(US)_1.0.json
vendored
Normal file
50
pyHS100/tests/fixtures/HS110(US)_1.0.json
vendored
Normal file
@ -0,0 +1,50 @@
|
||||
{
|
||||
"emeter": {
|
||||
"get_realtime": {
|
||||
"current": 0.1256,
|
||||
"err_code": 0,
|
||||
"power": 3.14,
|
||||
"total": 51.493,
|
||||
"voltage": 122.049119
|
||||
}
|
||||
},
|
||||
"smartlife.iot.common.emeter": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.dimmer": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.smartbulb.lightingservice": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"system": {
|
||||
"get_sysinfo": {
|
||||
"active_mode": "schedule",
|
||||
"alias": "Mock hs110",
|
||||
"dev_name": "Wi-Fi Smart Plug With Energy Monitoring",
|
||||
"deviceId": "11A5FD4A0FA1FCE5468F55D23CE77D1753A93E11",
|
||||
"err_code": 0,
|
||||
"feature": "TIM:ENE",
|
||||
"hwId": "6C56A17315351DD0EDE0BDB1D9EBBD66",
|
||||
"hw_ver": "1.0",
|
||||
"icon_hash": "",
|
||||
"latitude": 82.2866,
|
||||
"latitude_i": 82.2866,
|
||||
"led_off": 0,
|
||||
"longitude": 10.0036,
|
||||
"longitude_i": 10.0036,
|
||||
"mac": "50:c7:bf:66:29:29",
|
||||
"model": "HS110(US)",
|
||||
"oemId": "F7DFC14D43DA806B55DB66D21F212B60",
|
||||
"on_time": 0,
|
||||
"relay_state": 0,
|
||||
"rssi": -65,
|
||||
"sw_ver": "1.0.8 Build 151113 Rel.24658",
|
||||
"type": "IOT.SMARTPLUGSWITCH",
|
||||
"updating": 0
|
||||
}
|
||||
}
|
||||
}
|
47
pyHS100/tests/fixtures/HS200(US)_1.0.json
vendored
Normal file
47
pyHS100/tests/fixtures/HS200(US)_1.0.json
vendored
Normal file
@ -0,0 +1,47 @@
|
||||
{
|
||||
"emeter": {
|
||||
"get_realtime": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
}
|
||||
},
|
||||
"smartlife.iot.common.emeter": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.dimmer": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.smartbulb.lightingservice": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"system": {
|
||||
"get_sysinfo": {
|
||||
"active_mode": "schedule",
|
||||
"alias": "Mock hs200",
|
||||
"dev_name": "Wi-Fi Smart Light Switch",
|
||||
"deviceId": "EC565185337CF59A4C9A73442AAD5F11C6E91716",
|
||||
"err_code": 0,
|
||||
"feature": "TIM",
|
||||
"hwId": "4B5DB5E42F13728107D075EF5C3ECFA1",
|
||||
"hw_ver": "1.0",
|
||||
"icon_hash": "",
|
||||
"latitude": 58.7882,
|
||||
"latitude_i": 58.7882,
|
||||
"led_off": 0,
|
||||
"longitude": 107.7225,
|
||||
"longitude_i": 107.7225,
|
||||
"mac": "50:c7:bf:95:4b:45",
|
||||
"model": "HS200(US)",
|
||||
"oemId": "D2A5D690B25980755216FD684AF8CD88",
|
||||
"on_time": 0,
|
||||
"relay_state": 0,
|
||||
"rssi": -65,
|
||||
"sw_ver": "1.1.0 Build 160521 Rel.085826",
|
||||
"type": "IOT.SMARTPLUGSWITCH",
|
||||
"updating": 0
|
||||
}
|
||||
}
|
||||
}
|
75
pyHS100/tests/fixtures/HS220(US)_1.0.json
vendored
Normal file
75
pyHS100/tests/fixtures/HS220(US)_1.0.json
vendored
Normal file
@ -0,0 +1,75 @@
|
||||
{
|
||||
"emeter": {
|
||||
"get_realtime": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
}
|
||||
},
|
||||
"smartlife.iot.common.emeter": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.dimmer": {
|
||||
"get_dimmer_parameters": {
|
||||
"bulb_type": 1,
|
||||
"err_code": 0,
|
||||
"fadeOffTime": 3000,
|
||||
"fadeOnTime": 3000,
|
||||
"gentleOffTime": 510000,
|
||||
"gentleOnTime": 3000,
|
||||
"minThreshold": 0,
|
||||
"rampRate": 30
|
||||
}
|
||||
},
|
||||
"smartlife.iot.smartbulb.lightingservice": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"system": {
|
||||
"get_sysinfo": {
|
||||
"active_mode": "count_down",
|
||||
"alias": "Mock hs220",
|
||||
"brightness": 50,
|
||||
"dev_name": "Smart Wi-Fi Dimmer",
|
||||
"deviceId": "98E16F2D5ED204F3094CF472260237133DC0D547",
|
||||
"err_code": 0,
|
||||
"feature": "TIM",
|
||||
"hwId": "231004CCCDB6C0B8FC7A3260C3470257",
|
||||
"hw_ver": "1.0",
|
||||
"icon_hash": "",
|
||||
"INVALIDlatitude": 11.6210,
|
||||
"latitude_i": 11.6210,
|
||||
"led_off": 0,
|
||||
"INVALIDlongitude": 42.2074,
|
||||
"longitude_i": 42.2074,
|
||||
"mac": "50:c7:bf:af:75:5d",
|
||||
"mic_type": "IOT.SMARTPLUGSWITCH",
|
||||
"model": "HS220(US)",
|
||||
"oemId": "8FBD0F3CCF7E82836DC7996C524EF772",
|
||||
"on_time": 0,
|
||||
"preferred_state": [
|
||||
{
|
||||
"brightness": 100,
|
||||
"index": 0
|
||||
},
|
||||
{
|
||||
"brightness": 75,
|
||||
"index": 1
|
||||
},
|
||||
{
|
||||
"brightness": 50,
|
||||
"index": 2
|
||||
},
|
||||
{
|
||||
"brightness": 25,
|
||||
"index": 3
|
||||
}
|
||||
],
|
||||
"relay_state": 0,
|
||||
"rssi": -65,
|
||||
"sw_ver": "1.5.7 Build 180912 Rel.104837",
|
||||
"type": "IOT.SMARTPLUGSWITCH",
|
||||
"updating": 0
|
||||
}
|
||||
}
|
||||
}
|
76
pyHS100/tests/fixtures/HS220(US)_1.0_real.json
vendored
Normal file
76
pyHS100/tests/fixtures/HS220(US)_1.0_real.json
vendored
Normal file
@ -0,0 +1,76 @@
|
||||
{
|
||||
"emeter": {
|
||||
"get_realtime": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
}
|
||||
},
|
||||
"smartlife.iot.common.emeter": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.dimmer": {
|
||||
"get_dimmer_parameters": {
|
||||
"bulb_type": 1,
|
||||
"err_code": 0,
|
||||
"fadeOffTime": 1000,
|
||||
"fadeOnTime": 1000,
|
||||
"gentleOffTime": 10000,
|
||||
"gentleOnTime": 3000,
|
||||
"minThreshold": 0,
|
||||
"rampRate": 30
|
||||
}
|
||||
},
|
||||
"smartlife.iot.smartbulb.lightingservice": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"system": {
|
||||
"get_sysinfo": {
|
||||
"active_mode": "none",
|
||||
"alias": "Living room left dimmer",
|
||||
"brightness": 25,
|
||||
"dev_name": "Smart Wi-Fi Dimmer",
|
||||
"deviceId": "000000000000000000000000000000000000000",
|
||||
"err_code": 0,
|
||||
"feature": "TIM",
|
||||
"fwId": "00000000000000000000000000000000",
|
||||
"hwId": "00000000000000000000000000000000",
|
||||
"hw_ver": "1.0",
|
||||
"icon_hash": "",
|
||||
"latitude_i": 11.6210,
|
||||
"led_off": 0,
|
||||
"longitude_i": 42.2074,
|
||||
"mac": "00:00:00:00:00:00",
|
||||
"mic_type": "IOT.SMARTPLUGSWITCH",
|
||||
"model": "HS220(US)",
|
||||
"next_action": {
|
||||
"type": -1
|
||||
},
|
||||
"oemId": "00000000000000000000000000000000",
|
||||
"on_time": 0,
|
||||
"preferred_state": [
|
||||
{
|
||||
"brightness": 100,
|
||||
"index": 0
|
||||
},
|
||||
{
|
||||
"brightness": 75,
|
||||
"index": 1
|
||||
},
|
||||
{
|
||||
"brightness": 50,
|
||||
"index": 2
|
||||
},
|
||||
{
|
||||
"brightness": 25,
|
||||
"index": 3
|
||||
}
|
||||
],
|
||||
"relay_state": 0,
|
||||
"rssi": -35,
|
||||
"sw_ver": "1.5.7 Build 180912 Rel.104837",
|
||||
"updating": 0
|
||||
}
|
||||
}
|
||||
}
|
102
pyHS100/tests/fixtures/HS300(US)_1.0.json
vendored
Normal file
102
pyHS100/tests/fixtures/HS300(US)_1.0.json
vendored
Normal file
@ -0,0 +1,102 @@
|
||||
{
|
||||
"emeter": {
|
||||
"get_realtime": {
|
||||
"current_ma": 125,
|
||||
"err_code": 0,
|
||||
"power_mw": 3140,
|
||||
"total_wh": 51493,
|
||||
"voltage_mv": 122049
|
||||
}
|
||||
},
|
||||
"smartlife.iot.common.emeter": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.dimmer": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.smartbulb.lightingservice": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"system": {
|
||||
"get_sysinfo": {
|
||||
"alias": "Mock hs300",
|
||||
"child_num": 6,
|
||||
"children": [
|
||||
{
|
||||
"alias": "Mock One",
|
||||
"id": "00",
|
||||
"next_action": {
|
||||
"type": -1
|
||||
},
|
||||
"on_time": 123,
|
||||
"state": 1
|
||||
},
|
||||
{
|
||||
"alias": "Mock Two",
|
||||
"id": "01",
|
||||
"next_action": {
|
||||
"type": -1
|
||||
},
|
||||
"on_time": 333,
|
||||
"state": 1
|
||||
},
|
||||
{
|
||||
"alias": "Mock Three",
|
||||
"id": "02",
|
||||
"next_action": {
|
||||
"type": -1
|
||||
},
|
||||
"on_time": 0,
|
||||
"state": 0
|
||||
},
|
||||
{
|
||||
"alias": "Mock Four",
|
||||
"id": "03",
|
||||
"next_action": {
|
||||
"type": -1
|
||||
},
|
||||
"on_time": 0,
|
||||
"state": 0
|
||||
},
|
||||
{
|
||||
"alias": "Mock Five",
|
||||
"id": "04",
|
||||
"next_action": {
|
||||
"type": -1
|
||||
},
|
||||
"on_time": 0,
|
||||
"state": 0
|
||||
},
|
||||
{
|
||||
"alias": "Mock Six",
|
||||
"id": "05",
|
||||
"next_action": {
|
||||
"type": -1
|
||||
},
|
||||
"on_time": 0,
|
||||
"state": 0
|
||||
}
|
||||
],
|
||||
"deviceId": "4BFC2F2C8678FE623700FD3737EC4E245196F3CF",
|
||||
"err_code": 0,
|
||||
"feature": "TIM:ENE",
|
||||
"hwId": "1B63E5DF21B5AFB52F364DE66BFAAF8A",
|
||||
"hw_ver": "1.0",
|
||||
"latitude": -68.9980,
|
||||
"latitude_i": -68.9980,
|
||||
"led_off": 0,
|
||||
"longitude": -109.4400,
|
||||
"longitude_i": -109.4400,
|
||||
"mac": "50:c7:bf:c2:75:88",
|
||||
"mic_type": "IOT.SMARTPLUGSWITCH",
|
||||
"model": "HS300(US)",
|
||||
"oemId": "FC71DAAB004326F9369EDEF4353E4FE1",
|
||||
"rssi": -68,
|
||||
"sw_ver": "1.0.6 Build 180627 Rel.081000",
|
||||
"updating": 0
|
||||
}
|
||||
}
|
||||
}
|
93
pyHS100/tests/fixtures/KL120(US)_1.0_real.json
vendored
Normal file
93
pyHS100/tests/fixtures/KL120(US)_1.0_real.json
vendored
Normal file
@ -0,0 +1,93 @@
|
||||
{
|
||||
"emeter": {
|
||||
"err_code": -2001,
|
||||
"err_msg": "Module not support"
|
||||
},
|
||||
"smartlife.iot.common.emeter": {
|
||||
"get_realtime": {
|
||||
"err_code": 0,
|
||||
"power_mw": 1800
|
||||
}
|
||||
},
|
||||
"smartlife.iot.dimmer": {
|
||||
"err_code": -2001,
|
||||
"err_msg": "Module not support"
|
||||
},
|
||||
"smartlife.iot.smartbulb.lightingservice": {
|
||||
"get_light_state": {
|
||||
"brightness": 10,
|
||||
"color_temp": 2700,
|
||||
"err_code": 0,
|
||||
"hue": 0,
|
||||
"mode": "normal",
|
||||
"on_off": 1,
|
||||
"saturation": 0
|
||||
}
|
||||
},
|
||||
"system": {
|
||||
"get_sysinfo": {
|
||||
"active_mode": "none",
|
||||
"alias": "",
|
||||
"ctrl_protocols": {
|
||||
"name": "Linkie",
|
||||
"version": "1.0"
|
||||
},
|
||||
"description": "Smart Wi-Fi LED Bulb with Tunable White Light",
|
||||
"dev_state": "normal",
|
||||
"deviceId": "801200814AD69370AC59DE5501319C051AF409C3",
|
||||
"disco_ver": "1.0",
|
||||
"err_code": 0,
|
||||
"heapsize": 290784,
|
||||
"hwId": "111E35908497A05512E259BB76801E10",
|
||||
"hw_ver": "1.0",
|
||||
"is_color": 0,
|
||||
"is_dimmable": 1,
|
||||
"is_factory": false,
|
||||
"is_variable_color_temp": 1,
|
||||
"light_state": {
|
||||
"brightness": 10,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"mode": "normal",
|
||||
"on_off": 1,
|
||||
"saturation": 0
|
||||
},
|
||||
"mic_mac": "D80D17150474",
|
||||
"mic_type": "IOT.SMARTBULB",
|
||||
"model": "KL120(US)",
|
||||
"oemId": "1210657CD7FBDC72895644388EEFAE8B",
|
||||
"preferred_state": [
|
||||
{
|
||||
"brightness": 100,
|
||||
"color_temp": 3500,
|
||||
"hue": 0,
|
||||
"index": 0,
|
||||
"saturation": 0
|
||||
},
|
||||
{
|
||||
"brightness": 50,
|
||||
"color_temp": 5000,
|
||||
"hue": 0,
|
||||
"index": 1,
|
||||
"saturation": 0
|
||||
},
|
||||
{
|
||||
"brightness": 50,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"index": 2,
|
||||
"saturation": 0
|
||||
},
|
||||
{
|
||||
"brightness": 1,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"index": 3,
|
||||
"saturation": 0
|
||||
}
|
||||
],
|
||||
"rssi": -52,
|
||||
"sw_ver": "1.8.6 Build 180809 Rel.091659"
|
||||
}
|
||||
}
|
||||
}
|
103
pyHS100/tests/fixtures/LB100(US)_1.0.json
vendored
Normal file
103
pyHS100/tests/fixtures/LB100(US)_1.0.json
vendored
Normal file
@ -0,0 +1,103 @@
|
||||
{
|
||||
"emeter": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.common.emeter": {
|
||||
"get_realtime": {
|
||||
"err_code": 0,
|
||||
"power_mw": 10800
|
||||
}
|
||||
},
|
||||
"smartlife.iot.dimmer": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.smartbulb.lightingservice": {
|
||||
"get_light_state": {
|
||||
"dft_on_state": {
|
||||
"brightness": 100,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"mode": "normal",
|
||||
"saturation": 0
|
||||
},
|
||||
"err_code": 0,
|
||||
"on_off": 0
|
||||
}
|
||||
},
|
||||
"system": {
|
||||
"get_sysinfo": {
|
||||
"active_mode": "none",
|
||||
"alias": "Mock lb100",
|
||||
"ctrl_protocols": {
|
||||
"name": "Linkie",
|
||||
"version": "1.0"
|
||||
},
|
||||
"description": "Smart Wi-Fi LED Bulb with Dimmable Light",
|
||||
"dev_state": "normal",
|
||||
"deviceId": "15BD5A6C4B729A7C0D4D46ADDFA7E2600793C56A",
|
||||
"disco_ver": "1.0",
|
||||
"err_code": 0,
|
||||
"heapsize": 302452,
|
||||
"hwId": "1B0DF0A2EFE6251DBE726D1D2167C78F",
|
||||
"hw_ver": "1.0",
|
||||
"is_color": 0,
|
||||
"is_dimmable": 1,
|
||||
"is_factory": false,
|
||||
"is_variable_color_temp": 0,
|
||||
"latitude": -51.8361,
|
||||
"latitude_i": -51.8361,
|
||||
"light_state": {
|
||||
"dft_on_state": {
|
||||
"brightness": 100,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"mode": "normal",
|
||||
"saturation": 0
|
||||
},
|
||||
"err_code": 0,
|
||||
"on_off": 0
|
||||
},
|
||||
"longitude": -34.0697,
|
||||
"longitude_i": -34.0697,
|
||||
"mac": "50:c7:bf:51:10:65",
|
||||
"mic_type": "IOT.SMARTBULB",
|
||||
"model": "LB100(US)",
|
||||
"oemId": "C9CF655C9A5AA101E66EBA5B382E40CC",
|
||||
"on_time": 0,
|
||||
"preferred_state": [
|
||||
{
|
||||
"brightness": 100,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"index": 0,
|
||||
"saturation": 0
|
||||
},
|
||||
{
|
||||
"brightness": 75,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"index": 1,
|
||||
"saturation": 0
|
||||
},
|
||||
{
|
||||
"brightness": 25,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"index": 2,
|
||||
"saturation": 0
|
||||
},
|
||||
{
|
||||
"brightness": 1,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"index": 3,
|
||||
"saturation": 0
|
||||
}
|
||||
],
|
||||
"rssi": -65,
|
||||
"sw_ver": "1.4.3 Build 170504 Rel.144921"
|
||||
}
|
||||
}
|
||||
}
|
103
pyHS100/tests/fixtures/LB120(US)_1.0.json
vendored
Normal file
103
pyHS100/tests/fixtures/LB120(US)_1.0.json
vendored
Normal file
@ -0,0 +1,103 @@
|
||||
{
|
||||
"emeter": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.common.emeter": {
|
||||
"get_realtime": {
|
||||
"err_code": 0,
|
||||
"power_mw": 10800
|
||||
}
|
||||
},
|
||||
"smartlife.iot.dimmer": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.smartbulb.lightingservice": {
|
||||
"get_light_state": {
|
||||
"dft_on_state": {
|
||||
"brightness": 100,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"mode": "normal",
|
||||
"saturation": 0
|
||||
},
|
||||
"err_code": 0,
|
||||
"on_off": 0
|
||||
}
|
||||
},
|
||||
"system": {
|
||||
"get_sysinfo": {
|
||||
"active_mode": "none",
|
||||
"alias": "Mock lb120",
|
||||
"ctrl_protocols": {
|
||||
"name": "Linkie",
|
||||
"version": "1.0"
|
||||
},
|
||||
"description": "Smart Wi-Fi LED Bulb with Tunable White Light",
|
||||
"dev_state": "normal",
|
||||
"deviceId": "62FD818E5B66A509D571D07D0F00FA4DD6468494",
|
||||
"disco_ver": "1.0",
|
||||
"err_code": 0,
|
||||
"heapsize": 302452,
|
||||
"hwId": "CC0588817E251DF996F1848ED331F543",
|
||||
"hw_ver": "1.0",
|
||||
"is_color": 0,
|
||||
"is_dimmable": 1,
|
||||
"is_factory": false,
|
||||
"is_variable_color_temp": 1,
|
||||
"latitude": -76.9197,
|
||||
"latitude_i": -76.9197,
|
||||
"light_state": {
|
||||
"dft_on_state": {
|
||||
"brightness": 100,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"mode": "normal",
|
||||
"saturation": 0
|
||||
},
|
||||
"err_code": 0,
|
||||
"on_off": 0
|
||||
},
|
||||
"longitude": 164.7293,
|
||||
"longitude_i": 164.7293,
|
||||
"mac": "50:c7:bf:dc:62:13",
|
||||
"mic_type": "IOT.SMARTBULB",
|
||||
"model": "LB120(US)",
|
||||
"oemId": "05D0D97951F565579A7F5A70A57AED0B",
|
||||
"on_time": 0,
|
||||
"preferred_state": [
|
||||
{
|
||||
"brightness": 100,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"index": 0,
|
||||
"saturation": 0
|
||||
},
|
||||
{
|
||||
"brightness": 75,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"index": 1,
|
||||
"saturation": 0
|
||||
},
|
||||
{
|
||||
"brightness": 25,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"index": 2,
|
||||
"saturation": 0
|
||||
},
|
||||
{
|
||||
"brightness": 1,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"index": 3,
|
||||
"saturation": 0
|
||||
}
|
||||
],
|
||||
"rssi": -65,
|
||||
"sw_ver": "1.1.0 Build 160630 Rel.085319"
|
||||
}
|
||||
}
|
||||
}
|
104
pyHS100/tests/fixtures/LB130(US)_1.0.json
vendored
Normal file
104
pyHS100/tests/fixtures/LB130(US)_1.0.json
vendored
Normal file
@ -0,0 +1,104 @@
|
||||
{
|
||||
"emeter": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.common.emeter": {
|
||||
"get_realtime": {
|
||||
"err_code": 0,
|
||||
"power_mw": 10800
|
||||
}
|
||||
},
|
||||
"smartlife.iot.dimmer": {
|
||||
"err_code": -1,
|
||||
"err_msg": "module not support"
|
||||
},
|
||||
"smartlife.iot.smartbulb.lightingservice": {
|
||||
"get_light_state": {
|
||||
"dft_on_state": {
|
||||
"brightness": 100,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"mode": "normal",
|
||||
"saturation": 0
|
||||
},
|
||||
"err_code": 0,
|
||||
"on_off": 0
|
||||
}
|
||||
},
|
||||
"system": {
|
||||
"get_sysinfo": {
|
||||
"active_mode": "none",
|
||||
"alias": "Mock lb130",
|
||||
"ctrl_protocols": {
|
||||
"name": "Linkie",
|
||||
"version": "1.0"
|
||||
},
|
||||
"description": "Smart Wi-Fi LED Bulb with Color Changing",
|
||||
"dev_state": "normal",
|
||||
"deviceId": "50BE9E7B6F26CA75D495C13EAA459C491768F143",
|
||||
"disco_ver": "1.0",
|
||||
"err_code": 0,
|
||||
"heapsize": 302452,
|
||||
"hwId": "C8AD962B53417C2845CC10CE25C00BB1",
|
||||
"hw_ver": "1.0",
|
||||
"is_color": 1,
|
||||
"is_dimmable": 1,
|
||||
"is_factory": false,
|
||||
"is_variable_color_temp": 1,
|
||||
"latitude": 76.8649,
|
||||
"latitude_i": 76.8649,
|
||||
"light_state": {
|
||||
"dft_on_state": {
|
||||
"brightness": 100,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"mode": "normal",
|
||||
"saturation": 0
|
||||
},
|
||||
"err_code": 0,
|
||||
"on_off": 0
|
||||
},
|
||||
"longitude": -40.7284,
|
||||
"longitude_i": -40.7284,
|
||||
"INVALIDmac": "50:c7:bf:ac:f6:19",
|
||||
"mic_mac": "50C7BFACF619",
|
||||
"mic_type": "IOT.SMARTBULB",
|
||||
"model": "LB130(US)",
|
||||
"oemId": "CF78964560AAB75A43F15D2E468B63EF",
|
||||
"on_time": 0,
|
||||
"preferred_state": [
|
||||
{
|
||||
"brightness": 100,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"index": 0,
|
||||
"saturation": 0
|
||||
},
|
||||
{
|
||||
"brightness": 75,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"index": 1,
|
||||
"saturation": 0
|
||||
},
|
||||
{
|
||||
"brightness": 25,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"index": 2,
|
||||
"saturation": 0
|
||||
},
|
||||
{
|
||||
"brightness": 1,
|
||||
"color_temp": 2700,
|
||||
"hue": 0,
|
||||
"index": 3,
|
||||
"saturation": 0
|
||||
}
|
||||
],
|
||||
"rssi": -65,
|
||||
"sw_ver": "1.6.0 Build 170703 Rel.141938"
|
||||
}
|
||||
}
|
||||
}
|
434
pyHS100/tests/newfakes.py
Normal file
434
pyHS100/tests/newfakes.py
Normal file
@ -0,0 +1,434 @@
|
||||
from ..protocol import TPLinkSmartHomeProtocol
|
||||
from .. import SmartDeviceException
|
||||
import logging
|
||||
import re
|
||||
from voluptuous import Schema, Range, All, Any, Coerce, Invalid, Optional, REMOVE_EXTRA
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def check_int_bool(x):
|
||||
if x != 0 and x != 1:
|
||||
raise Invalid(x)
|
||||
return x
|
||||
|
||||
|
||||
def check_mac(x):
|
||||
if re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", x.lower()):
|
||||
return x
|
||||
raise Invalid(x)
|
||||
|
||||
|
||||
def check_mode(x):
|
||||
if x in ["schedule", "none", "count_down"]:
|
||||
return x
|
||||
|
||||
raise Invalid("invalid mode {}".format(x))
|
||||
|
||||
|
||||
def lb_dev_state(x):
|
||||
if x in ["normal"]:
|
||||
return x
|
||||
|
||||
raise Invalid("Invalid dev_state {}".format(x))
|
||||
|
||||
|
||||
TZ_SCHEMA = Schema(
|
||||
{"zone_str": str, "dst_offset": int, "index": All(int, Range(min=0)), "tz_str": str}
|
||||
)
|
||||
|
||||
CURRENT_CONSUMPTION_SCHEMA = Schema(
|
||||
Any(
|
||||
{
|
||||
"voltage": Any(All(float, Range(min=0, max=300)), None),
|
||||
"power": Any(Coerce(float, Range(min=0)), None),
|
||||
"total": Any(Coerce(float, Range(min=0)), None),
|
||||
"current": Any(All(float, Range(min=0)), None),
|
||||
"voltage_mv": Any(
|
||||
All(float, Range(min=0, max=300000)), int, None
|
||||
), # TODO can this be int?
|
||||
"power_mw": Any(Coerce(float, Range(min=0)), None),
|
||||
"total_wh": Any(Coerce(float, Range(min=0)), None),
|
||||
"current_ma": Any(
|
||||
All(float, Range(min=0)), int, None
|
||||
), # TODO can this be int?
|
||||
},
|
||||
None,
|
||||
)
|
||||
)
|
||||
|
||||
# these schemas should go to the mainlib as
|
||||
# they can be useful when adding support for new features/devices
|
||||
# as well as to check that faked devices are operating properly.
|
||||
PLUG_SCHEMA = Schema(
|
||||
{
|
||||
"active_mode": check_mode,
|
||||
"alias": str,
|
||||
"dev_name": str,
|
||||
"deviceId": str,
|
||||
"feature": str,
|
||||
"fwId": str,
|
||||
"hwId": str,
|
||||
"hw_ver": str,
|
||||
"icon_hash": str,
|
||||
"led_off": check_int_bool,
|
||||
"latitude": Any(All(float, Range(min=-90, max=90)), None),
|
||||
"latitude_i": Any(All(float, Range(min=-90, max=90)), None),
|
||||
"longitude": Any(All(float, Range(min=-180, max=180)), None),
|
||||
"longitude_i": Any(All(float, Range(min=-180, max=180)), None),
|
||||
"mac": check_mac,
|
||||
"model": str,
|
||||
"oemId": str,
|
||||
"on_time": int,
|
||||
"relay_state": int,
|
||||
"rssi": Any(int, None), # rssi can also be positive, see #54
|
||||
"sw_ver": str,
|
||||
"type": str,
|
||||
"mic_type": str,
|
||||
"updating": check_int_bool,
|
||||
# these are available on hs220
|
||||
"brightness": int,
|
||||
"preferred_state": [
|
||||
{"brightness": All(int, Range(min=0, max=100)), "index": int}
|
||||
],
|
||||
"next_action": {"type": int},
|
||||
"child_num": Optional(Any(None, int)), # TODO fix hs300 checks
|
||||
"children": Optional(list), # TODO fix hs300
|
||||
# TODO some tplink simulator entries contain invalid (mic_mac, _i variants for lat/lon)
|
||||
# Therefore we add REMOVE_EXTRA..
|
||||
# "INVALIDmac": Optional,
|
||||
# "INVALIDlatitude": Optional,
|
||||
# "INVALIDlongitude": Optional,
|
||||
},
|
||||
extra=REMOVE_EXTRA,
|
||||
)
|
||||
|
||||
BULB_SCHEMA = PLUG_SCHEMA.extend(
|
||||
{
|
||||
"ctrl_protocols": Optional(dict),
|
||||
"description": Optional(str), # TODO: LBxxx similar to dev_name
|
||||
"dev_state": lb_dev_state,
|
||||
"disco_ver": str,
|
||||
"heapsize": int,
|
||||
"is_color": check_int_bool,
|
||||
"is_dimmable": check_int_bool,
|
||||
"is_factory": bool,
|
||||
"is_variable_color_temp": check_int_bool,
|
||||
"light_state": {
|
||||
"brightness": All(int, Range(min=0, max=100)),
|
||||
"color_temp": int,
|
||||
"hue": All(int, Range(min=0, max=255)),
|
||||
"mode": str,
|
||||
"on_off": check_int_bool,
|
||||
"saturation": All(int, Range(min=0, max=255)),
|
||||
"dft_on_state": Optional(
|
||||
{
|
||||
"brightness": All(int, Range(min=0, max=100)),
|
||||
"color_temp": All(int, Range(min=2700, max=9000)),
|
||||
"hue": All(int, Range(min=0, max=255)),
|
||||
"mode": str,
|
||||
"saturation": All(int, Range(min=0, max=255)),
|
||||
}
|
||||
),
|
||||
"err_code": int,
|
||||
},
|
||||
"preferred_state": [
|
||||
{
|
||||
"brightness": All(int, Range(min=0, max=100)),
|
||||
"color_temp": int,
|
||||
"hue": All(int, Range(min=0, max=255)),
|
||||
"index": int,
|
||||
"saturation": All(int, Range(min=0, max=255)),
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def get_realtime(obj, x, *args):
|
||||
return {
|
||||
"current": 0.268587,
|
||||
"voltage": 125.836131,
|
||||
"power": 33.495623,
|
||||
"total": 0.199000,
|
||||
}
|
||||
|
||||
|
||||
def get_monthstat(obj, x, *args):
|
||||
if x["year"] < 2016:
|
||||
return {"month_list": []}
|
||||
|
||||
return {
|
||||
"month_list": [
|
||||
{"year": 2016, "month": 11, "energy": 1.089000},
|
||||
{"year": 2016, "month": 12, "energy": 1.582000},
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def get_daystat(obj, x, *args):
|
||||
if x["year"] < 2016:
|
||||
return {"day_list": []}
|
||||
|
||||
return {
|
||||
"day_list": [
|
||||
{"year": 2016, "month": 11, "day": 24, "energy": 0.026000},
|
||||
{"year": 2016, "month": 11, "day": 25, "energy": 0.109000},
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
emeter_support = {
|
||||
"get_realtime": get_realtime,
|
||||
"get_monthstat": get_monthstat,
|
||||
"get_daystat": get_daystat,
|
||||
}
|
||||
|
||||
|
||||
def get_realtime_units(obj, x, *args):
|
||||
return {"power_mw": 10800}
|
||||
|
||||
|
||||
def get_monthstat_units(obj, x, *args):
|
||||
if x["year"] < 2016:
|
||||
return {"month_list": []}
|
||||
|
||||
return {
|
||||
"month_list": [
|
||||
{"year": 2016, "month": 11, "energy_wh": 32},
|
||||
{"year": 2016, "month": 12, "energy_wh": 16},
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def get_daystat_units(obj, x, *args):
|
||||
if x["year"] < 2016:
|
||||
return {"day_list": []}
|
||||
|
||||
return {
|
||||
"day_list": [
|
||||
{"year": 2016, "month": 11, "day": 24, "energy_wh": 20},
|
||||
{"year": 2016, "month": 11, "day": 25, "energy_wh": 32},
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
emeter_units_support = {
|
||||
"get_realtime": get_realtime_units,
|
||||
"get_monthstat": get_monthstat_units,
|
||||
"get_daystat": get_daystat_units,
|
||||
}
|
||||
|
||||
|
||||
emeter_commands = {
|
||||
"emeter": emeter_support,
|
||||
"smartlife.iot.common.emeter": emeter_units_support,
|
||||
}
|
||||
|
||||
|
||||
def error(target, cmd="no-command", msg="default msg"):
|
||||
return {target: {cmd: {"err_code": -1323, "msg": msg}}}
|
||||
|
||||
|
||||
def success(target, cmd, res):
|
||||
if res:
|
||||
res.update({"err_code": 0})
|
||||
else:
|
||||
res = {"err_code": 0}
|
||||
return {target: {cmd: res}}
|
||||
|
||||
|
||||
class FakeTransportProtocol(TPLinkSmartHomeProtocol):
|
||||
def __init__(self, info, invalid=False):
|
||||
# TODO remove invalid when removing the old tests.
|
||||
proto = FakeTransportProtocol.baseproto
|
||||
for target in info:
|
||||
# print("target %s" % target)
|
||||
for cmd in info[target]:
|
||||
# print("initializing tgt %s cmd %s" % (target, cmd))
|
||||
proto[target][cmd] = info[target][cmd]
|
||||
# if we have emeter support, check for it
|
||||
for module in ["emeter", "smartlife.iot.common.emeter"]:
|
||||
if module not in info:
|
||||
# TODO required for old tests
|
||||
continue
|
||||
if "get_realtime" in info[module]:
|
||||
get_realtime_res = info[module]["get_realtime"]
|
||||
# TODO remove when removing old tests
|
||||
if callable(get_realtime_res):
|
||||
get_realtime_res = get_realtime_res()
|
||||
if (
|
||||
"err_code" not in get_realtime_res
|
||||
or not get_realtime_res["err_code"]
|
||||
):
|
||||
proto[module] = emeter_commands[module]
|
||||
self.proto = proto
|
||||
|
||||
def set_alias(self, x, child_ids=[]):
|
||||
_LOGGER.debug("Setting alias to %s, child_ids: %s", x["alias"], child_ids)
|
||||
if child_ids:
|
||||
for child in self.proto["system"]["get_sysinfo"]["children"]:
|
||||
if child["id"] in child_ids:
|
||||
child["alias"] = x["alias"]
|
||||
else:
|
||||
self.proto["system"]["get_sysinfo"]["alias"] = x["alias"]
|
||||
|
||||
def set_relay_state(self, x, child_ids=[]):
|
||||
_LOGGER.debug("Setting relay state to %s", x["state"])
|
||||
|
||||
if not child_ids and "children" in self.proto["system"]["get_sysinfo"]:
|
||||
for child in self.proto["system"]["get_sysinfo"]["children"]:
|
||||
child_ids.append(child["id"])
|
||||
|
||||
_LOGGER.info("child_ids: %s", child_ids)
|
||||
if child_ids:
|
||||
for child in self.proto["system"]["get_sysinfo"]["children"]:
|
||||
if child["id"] in child_ids:
|
||||
_LOGGER.info("Found %s, turning to %s", child, x["state"])
|
||||
child["state"] = x["state"]
|
||||
else:
|
||||
self.proto["system"]["get_sysinfo"]["relay_state"] = x["state"]
|
||||
|
||||
def set_alias_old(self, x):
|
||||
_LOGGER.debug("Setting alias to %s", x["alias"])
|
||||
self.proto["system"]["get_sysinfo"]["alias"] = x["alias"]
|
||||
|
||||
def set_relay_state_old(self, x):
|
||||
_LOGGER.debug("Setting relay state to %s", x)
|
||||
self.proto["system"]["get_sysinfo"]["relay_state"] = x["state"]
|
||||
|
||||
def set_led_off(self, x, *args):
|
||||
_LOGGER.debug("Setting led off to %s", x)
|
||||
self.proto["system"]["get_sysinfo"]["led_off"] = x["off"]
|
||||
|
||||
def set_mac(self, x, *args):
|
||||
_LOGGER.debug("Setting mac to %s", x)
|
||||
self.proto["system"]["get_sysinfo"]["mac"] = x
|
||||
|
||||
def set_hs220_brightness(self, x, *args):
|
||||
_LOGGER.debug("Setting brightness to %s", x)
|
||||
self.proto["system"]["get_sysinfo"]["brightness"] = x["brightness"]
|
||||
|
||||
def transition_light_state(self, x, *args):
|
||||
_LOGGER.debug("Setting light state to %s", x)
|
||||
light_state = self.proto["smartlife.iot.smartbulb.lightingservice"][
|
||||
"get_light_state"
|
||||
]
|
||||
# The required change depends on the light state,
|
||||
# exception being turning the bulb on and off
|
||||
|
||||
if "on_off" in x:
|
||||
if x["on_off"] and not light_state["on_off"]: # turning on
|
||||
new_state = light_state["dft_on_state"]
|
||||
new_state["on_off"] = 1
|
||||
self.proto["smartlife.iot.smartbulb.lightingservice"][
|
||||
"get_light_state"
|
||||
] = new_state
|
||||
elif not x["on_off"] and light_state["on_off"]:
|
||||
new_state = {"dft_on_state": light_state, "on_off": 0}
|
||||
|
||||
self.proto["smartlife.iot.smartbulb.lightingservice"][
|
||||
"get_light_state"
|
||||
] = new_state
|
||||
|
||||
return
|
||||
|
||||
if not light_state["on_off"] and "on_off" not in x:
|
||||
light_state = light_state["dft_on_state"]
|
||||
|
||||
_LOGGER.debug("Current state: %s", light_state)
|
||||
for key in x:
|
||||
light_state[key] = x[key]
|
||||
|
||||
def light_state(self, x, *args):
|
||||
light_state = self.proto["smartlife.iot.smartbulb.lightingservice"][
|
||||
"get_light_state"
|
||||
]
|
||||
# Our tests have light state off, so we simply return the dft_on_state when device is on.
|
||||
_LOGGER.info("reporting light state: %s", light_state)
|
||||
if light_state["on_off"]:
|
||||
return light_state["dft_on_state"]
|
||||
else:
|
||||
return light_state
|
||||
|
||||
baseproto = {
|
||||
"system": {
|
||||
"set_relay_state": set_relay_state,
|
||||
"set_dev_alias": set_alias,
|
||||
"set_led_off": set_led_off,
|
||||
"get_dev_icon": {"icon": None, "hash": None},
|
||||
"set_mac_addr": set_mac,
|
||||
"get_sysinfo": None,
|
||||
},
|
||||
"emeter": {
|
||||
"get_realtime": None,
|
||||
"get_daystat": None,
|
||||
"get_monthstat": None,
|
||||
"erase_emeter_state": None,
|
||||
},
|
||||
"smartlife.iot.common.emeter": {
|
||||
"get_realtime": None,
|
||||
"get_daystat": None,
|
||||
"get_monthstat": None,
|
||||
"erase_emeter_state": None,
|
||||
},
|
||||
"smartlife.iot.smartbulb.lightingservice": {
|
||||
"get_light_state": light_state,
|
||||
"transition_light_state": transition_light_state,
|
||||
},
|
||||
"time": {
|
||||
"get_time": {
|
||||
"year": 2017,
|
||||
"month": 1,
|
||||
"mday": 2,
|
||||
"hour": 3,
|
||||
"min": 4,
|
||||
"sec": 5,
|
||||
},
|
||||
"get_timezone": {
|
||||
"zone_str": "test",
|
||||
"dst_offset": -1,
|
||||
"index": 12,
|
||||
"tz_str": "test2",
|
||||
},
|
||||
"set_timezone": None,
|
||||
},
|
||||
# HS220 brightness, different setter and getter
|
||||
"smartlife.iot.dimmer": {"set_brightness": set_hs220_brightness},
|
||||
}
|
||||
|
||||
def query(self, host, request, port=9999):
|
||||
proto = self.proto
|
||||
|
||||
# collect child ids from context
|
||||
try:
|
||||
child_ids = request["context"]["child_ids"]
|
||||
request.pop("context", None)
|
||||
except KeyError:
|
||||
child_ids = []
|
||||
|
||||
target = next(iter(request))
|
||||
if target not in proto.keys():
|
||||
return error(target, msg="target not found")
|
||||
|
||||
cmd = next(iter(request[target]))
|
||||
if cmd not in proto[target].keys():
|
||||
return error(target, cmd, msg="command not found")
|
||||
|
||||
params = request[target][cmd]
|
||||
_LOGGER.debug(
|
||||
"Going to execute {}.{} (params: {}).. ".format(target, cmd, params)
|
||||
)
|
||||
|
||||
if callable(proto[target][cmd]):
|
||||
res = proto[target][cmd](self, params, child_ids)
|
||||
_LOGGER.debug("[callable] %s.%s: %s", target, cmd, res)
|
||||
# verify that change didn't break schema, requires refactoring..
|
||||
# TestSmartPlug.sysinfo_schema(self.proto["system"]["get_sysinfo"])
|
||||
return success(target, cmd, res)
|
||||
elif isinstance(proto[target][cmd], dict):
|
||||
res = proto[target][cmd]
|
||||
_LOGGER.debug("[static] %s.%s: %s", target, cmd, res)
|
||||
return success(target, cmd, res)
|
||||
else:
|
||||
raise NotImplementedError("target {} cmd {}".format(target, cmd))
|
@ -1,241 +0,0 @@
|
||||
from unittest import TestCase, skip, skipIf
|
||||
from voluptuous import Schema, Invalid, All, Range
|
||||
from functools import partial
|
||||
from typing import Any, Dict # noqa: F401
|
||||
|
||||
from .. import SmartBulb, SmartDeviceException
|
||||
from .fakes import (FakeTransportProtocol,
|
||||
sysinfo_lb100, sysinfo_lb110,
|
||||
sysinfo_lb120, sysinfo_lb130)
|
||||
|
||||
BULB_IP = '192.168.250.186'
|
||||
SKIP_STATE_TESTS = False
|
||||
|
||||
|
||||
def check_int_bool(x):
|
||||
if x != 0 and x != 1:
|
||||
raise Invalid(x)
|
||||
return x
|
||||
|
||||
|
||||
def check_mode(x):
|
||||
if x in ['schedule', 'none']:
|
||||
return x
|
||||
|
||||
raise Invalid("invalid mode {}".format(x))
|
||||
|
||||
|
||||
class TestSmartBulb(TestCase):
|
||||
SYSINFO = sysinfo_lb130 # type: Dict[str, Any]
|
||||
# these schemas should go to the mainlib as
|
||||
# they can be useful when adding support for new features/devices
|
||||
# as well as to check that faked devices are operating properly.
|
||||
sysinfo_schema = Schema({
|
||||
'active_mode': check_mode,
|
||||
'alias': str,
|
||||
'ctrl_protocols': {
|
||||
'name': str,
|
||||
'version': str,
|
||||
},
|
||||
'description': str,
|
||||
'dev_state': str,
|
||||
'deviceId': str,
|
||||
'disco_ver': str,
|
||||
'heapsize': int,
|
||||
'hwId': str,
|
||||
'hw_ver': str,
|
||||
'is_color': check_int_bool,
|
||||
'is_dimmable': check_int_bool,
|
||||
'is_factory': bool,
|
||||
'is_variable_color_temp': check_int_bool,
|
||||
'light_state': {
|
||||
'brightness': All(int, Range(min=0, max=100)),
|
||||
'color_temp': int,
|
||||
'hue': All(int, Range(min=0, max=360)),
|
||||
'mode': str,
|
||||
'on_off': check_int_bool,
|
||||
'saturation': All(int, Range(min=0, max=255)),
|
||||
},
|
||||
'mic_mac': str,
|
||||
'mic_type': str,
|
||||
'model': str,
|
||||
'oemId': str,
|
||||
'preferred_state': [{
|
||||
'brightness': All(int, Range(min=0, max=100)),
|
||||
'color_temp': int,
|
||||
'hue': All(int, Range(min=0, max=360)),
|
||||
'index': int,
|
||||
'saturation': All(int, Range(min=0, max=255)),
|
||||
}],
|
||||
'rssi': All(int, Range(max=0)),
|
||||
'sw_ver': str,
|
||||
})
|
||||
|
||||
current_consumption_schema = Schema({
|
||||
'power_mw': int,
|
||||
})
|
||||
|
||||
tz_schema = Schema({
|
||||
'zone_str': str,
|
||||
'dst_offset': int,
|
||||
'index': All(int, Range(min=0)),
|
||||
'tz_str': str,
|
||||
})
|
||||
|
||||
def setUp(self):
|
||||
self.bulb = SmartBulb(BULB_IP,
|
||||
protocol=FakeTransportProtocol(self.SYSINFO))
|
||||
|
||||
def tearDown(self):
|
||||
self.bulb = None
|
||||
|
||||
def test_initialize(self):
|
||||
self.assertIsNotNone(self.bulb.sys_info)
|
||||
self.sysinfo_schema(self.bulb.sys_info)
|
||||
|
||||
def test_initialize_invalid_connection(self):
|
||||
bulb = SmartBulb('127.0.0.1',
|
||||
protocol=FakeTransportProtocol(self.SYSINFO,
|
||||
invalid=True))
|
||||
with self.assertRaises(SmartDeviceException):
|
||||
bulb.sys_info['model']
|
||||
|
||||
def test_query_helper(self):
|
||||
with self.assertRaises(SmartDeviceException):
|
||||
self.bulb._query_helper("test", "testcmd", {})
|
||||
# TODO check for unwrapping?
|
||||
|
||||
@skipIf(SKIP_STATE_TESTS, "SKIP_STATE_TESTS is True, skipping")
|
||||
def test_state(self):
|
||||
def set_invalid(x):
|
||||
self.bulb.state = x
|
||||
|
||||
set_invalid_int = partial(set_invalid, 1234)
|
||||
self.assertRaises(ValueError, set_invalid_int)
|
||||
|
||||
set_invalid_str = partial(set_invalid, "1234")
|
||||
self.assertRaises(ValueError, set_invalid_str)
|
||||
|
||||
set_invalid_bool = partial(set_invalid, True)
|
||||
self.assertRaises(ValueError, set_invalid_bool)
|
||||
|
||||
orig_state = self.bulb.state
|
||||
if orig_state == SmartBulb.BULB_STATE_OFF:
|
||||
self.bulb.state = SmartBulb.BULB_STATE_ON
|
||||
self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_ON)
|
||||
self.bulb.state = SmartBulb.BULB_STATE_OFF
|
||||
self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_OFF)
|
||||
elif orig_state == SmartBulb.BULB_STATE_ON:
|
||||
self.bulb.state = SmartBulb.BULB_STATE_OFF
|
||||
self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_OFF)
|
||||
self.bulb.state = SmartBulb.BULB_STATE_ON
|
||||
self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_ON)
|
||||
|
||||
def test_get_sysinfo(self):
|
||||
# initialize checks for this already, but just to be sure
|
||||
self.sysinfo_schema(self.bulb.get_sysinfo())
|
||||
|
||||
@skipIf(SKIP_STATE_TESTS, "SKIP_STATE_TESTS is True, skipping")
|
||||
def test_turns_and_isses(self):
|
||||
orig_state = self.bulb.state
|
||||
|
||||
if orig_state == SmartBulb.BULB_STATE_ON:
|
||||
self.bulb.state = SmartBulb.BULB_STATE_OFF
|
||||
self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_OFF)
|
||||
self.bulb.state = SmartBulb.BULB_STATE_ON
|
||||
self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_ON)
|
||||
else:
|
||||
self.bulb.state = SmartBulb.BULB_STATE_ON
|
||||
self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_ON)
|
||||
self.bulb.state = SmartBulb.BULB_STATE_OFF
|
||||
self.assertTrue(self.bulb.state == SmartBulb.BULB_STATE_OFF)
|
||||
|
||||
def test_get_emeter_realtime(self):
|
||||
self.current_consumption_schema((self.bulb.get_emeter_realtime()))
|
||||
|
||||
def test_get_emeter_daily(self):
|
||||
self.assertEqual(self.bulb.get_emeter_daily(year=1900, month=1), {})
|
||||
|
||||
k, v = self.bulb.get_emeter_daily(kwh=False).popitem()
|
||||
self.assertTrue(isinstance(k, int))
|
||||
self.assertTrue(isinstance(v, int))
|
||||
|
||||
k, v = self.bulb.get_emeter_daily(kwh=True).popitem()
|
||||
self.assertTrue(isinstance(k, int))
|
||||
self.assertTrue(isinstance(v, float))
|
||||
|
||||
def test_get_emeter_monthly(self):
|
||||
self.assertEqual(self.bulb.get_emeter_monthly(year=1900), {})
|
||||
|
||||
d = self.bulb.get_emeter_monthly(kwh=False)
|
||||
k, v = d.popitem()
|
||||
self.assertTrue(isinstance(k, int))
|
||||
self.assertTrue(isinstance(v, int))
|
||||
|
||||
d = self.bulb.get_emeter_monthly(kwh=True)
|
||||
k, v = d.popitem()
|
||||
self.assertTrue(isinstance(k, int))
|
||||
self.assertTrue(isinstance(v, float))
|
||||
|
||||
@skip("not clearing your stats..")
|
||||
def test_erase_emeter_stats(self):
|
||||
self.fail()
|
||||
|
||||
def test_current_consumption(self):
|
||||
x = self.bulb.current_consumption()
|
||||
self.assertTrue(isinstance(x, float))
|
||||
self.assertTrue(x >= 0.0)
|
||||
|
||||
def test_alias(self):
|
||||
test_alias = "TEST1234"
|
||||
original = self.bulb.alias
|
||||
self.assertTrue(isinstance(original, str))
|
||||
self.bulb.alias = test_alias
|
||||
self.assertEqual(self.bulb.alias, test_alias)
|
||||
self.bulb.alias = original
|
||||
self.assertEqual(self.bulb.alias, original)
|
||||
|
||||
def test_icon(self):
|
||||
self.assertEqual(set(self.bulb.icon.keys()), {'icon', 'hash'})
|
||||
|
||||
def test_rssi(self):
|
||||
self.sysinfo_schema({'rssi': self.bulb.rssi}) # wrapping for vol
|
||||
|
||||
def test_temperature_range(self):
|
||||
self.assertEqual(self.bulb.valid_temperature_range, (2500, 9000))
|
||||
with self.assertRaises(ValueError):
|
||||
self.bulb.color_temp = 1000
|
||||
with self.assertRaises(ValueError):
|
||||
self.bulb.color_temp = 10000
|
||||
|
||||
def test_hsv(self):
|
||||
hue, saturation, brightness = self.bulb.hsv
|
||||
self.assertTrue(0 <= hue <= 360)
|
||||
self.assertTrue(0 <= saturation <= 100)
|
||||
self.assertTrue(0 <= brightness <= 100)
|
||||
for invalid_hue in [-1, 361, 0.5]:
|
||||
with self.assertRaises(SmartDeviceException):
|
||||
self.bulb.hsv = (invalid_hue, 0, 0)
|
||||
|
||||
for invalid_saturation in [-1, 101, 0.5]:
|
||||
with self.assertRaises(SmartDeviceException):
|
||||
self.bulb.hsv = (0, invalid_saturation, 0)
|
||||
|
||||
for invalid_brightness in [-1, 101, 0.5]:
|
||||
with self.assertRaises(SmartDeviceException):
|
||||
self.bulb.hsv = (0, 0, invalid_brightness)
|
||||
|
||||
def test_repr(self):
|
||||
repr(self.bulb)
|
||||
|
||||
|
||||
class TestSmartBulbLB100(TestSmartBulb):
|
||||
SYSINFO = sysinfo_lb100
|
||||
|
||||
|
||||
class TestSmartBulbLB110(TestSmartBulb):
|
||||
SYSINFO = sysinfo_lb110
|
||||
|
||||
|
||||
class TestSmartBulbLB120(TestSmartBulb):
|
||||
SYSINFO = sysinfo_lb120
|
656
pyHS100/tests/test_fixtures.py
Normal file
656
pyHS100/tests/test_fixtures.py
Normal file
@ -0,0 +1,656 @@
|
||||
import datetime
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from pyHS100 import DeviceType, SmartStripException, SmartDeviceException
|
||||
from .newfakes import (
|
||||
BULB_SCHEMA,
|
||||
PLUG_SCHEMA,
|
||||
FakeTransportProtocol,
|
||||
CURRENT_CONSUMPTION_SCHEMA,
|
||||
TZ_SCHEMA,
|
||||
)
|
||||
from .conftest import (
|
||||
turn_on,
|
||||
handle_turn_on,
|
||||
plug,
|
||||
strip,
|
||||
bulb,
|
||||
color_bulb,
|
||||
non_color_bulb,
|
||||
has_emeter,
|
||||
no_emeter,
|
||||
dimmable,
|
||||
non_dimmable,
|
||||
variable_temp,
|
||||
non_variable_temp,
|
||||
)
|
||||
|
||||
|
||||
@plug
|
||||
def test_plug_sysinfo(dev):
|
||||
assert dev.sys_info is not None
|
||||
PLUG_SCHEMA(dev.sys_info)
|
||||
|
||||
assert dev.model is not None
|
||||
|
||||
assert dev.device_type == DeviceType.Plug or dev.device_type == DeviceType.Strip
|
||||
assert dev.is_plug or dev.is_strip
|
||||
|
||||
|
||||
@bulb
|
||||
def test_bulb_sysinfo(dev):
|
||||
assert dev.sys_info is not None
|
||||
BULB_SCHEMA(dev.sys_info)
|
||||
|
||||
assert dev.model is not None
|
||||
|
||||
assert dev.device_type == DeviceType.Bulb
|
||||
assert dev.is_bulb
|
||||
|
||||
|
||||
def test_state_info(dev):
|
||||
assert isinstance(dev.state_information, dict)
|
||||
|
||||
|
||||
def test_invalid_connection(dev):
|
||||
with patch.object(FakeTransportProtocol, "query", side_effect=SmartDeviceException):
|
||||
with pytest.raises(SmartDeviceException):
|
||||
dev.is_on
|
||||
|
||||
|
||||
def test_query_helper(dev):
|
||||
with pytest.raises(SmartDeviceException):
|
||||
dev._query_helper("test", "testcmd", {})
|
||||
# TODO check for unwrapping?
|
||||
|
||||
|
||||
def test_deprecated_state(dev):
|
||||
with pytest.deprecated_call():
|
||||
dev.state = "OFF"
|
||||
assert dev.state == "OFF"
|
||||
assert not dev.is_on
|
||||
|
||||
with pytest.deprecated_call():
|
||||
dev.state = "ON"
|
||||
assert dev.state == "ON"
|
||||
assert dev.is_on
|
||||
|
||||
with pytest.deprecated_call():
|
||||
with pytest.raises(ValueError):
|
||||
dev.state = "foo"
|
||||
|
||||
with pytest.deprecated_call():
|
||||
with pytest.raises(ValueError):
|
||||
dev.state = 1234
|
||||
|
||||
|
||||
def test_deprecated_alias(dev):
|
||||
with pytest.deprecated_call():
|
||||
dev.alias = "foo"
|
||||
|
||||
|
||||
def test_deprecated_mac(dev):
|
||||
with pytest.deprecated_call():
|
||||
dev.mac = 123123123123
|
||||
|
||||
|
||||
@plug
|
||||
def test_deprecated_led(dev):
|
||||
with pytest.deprecated_call():
|
||||
dev.led = True
|
||||
|
||||
|
||||
@turn_on
|
||||
def test_state(dev, turn_on):
|
||||
handle_turn_on(dev, turn_on)
|
||||
orig_state = dev.is_on
|
||||
if orig_state:
|
||||
dev.turn_off()
|
||||
assert not dev.is_on
|
||||
assert dev.is_off
|
||||
dev.turn_on()
|
||||
assert dev.is_on
|
||||
assert not dev.is_off
|
||||
else:
|
||||
dev.turn_on()
|
||||
assert dev.is_on
|
||||
assert not dev.is_off
|
||||
dev.turn_off()
|
||||
assert not dev.is_on
|
||||
assert dev.is_off
|
||||
|
||||
|
||||
@no_emeter
|
||||
def test_no_emeter(dev):
|
||||
assert not dev.has_emeter
|
||||
|
||||
with pytest.raises(SmartDeviceException):
|
||||
dev.get_emeter_realtime()
|
||||
with pytest.raises(SmartDeviceException):
|
||||
dev.get_emeter_daily()
|
||||
with pytest.raises(SmartDeviceException):
|
||||
dev.get_emeter_monthly()
|
||||
with pytest.raises(SmartDeviceException):
|
||||
dev.erase_emeter_stats()
|
||||
|
||||
|
||||
@has_emeter
|
||||
def test_get_emeter_realtime(dev):
|
||||
if dev.is_strip:
|
||||
pytest.skip("Disabled for HS300 temporarily")
|
||||
|
||||
assert dev.has_emeter
|
||||
|
||||
current_emeter = dev.get_emeter_realtime()
|
||||
CURRENT_CONSUMPTION_SCHEMA(current_emeter)
|
||||
|
||||
|
||||
@has_emeter
|
||||
def test_get_emeter_daily(dev):
|
||||
if dev.is_strip:
|
||||
pytest.skip("Disabled for HS300 temporarily")
|
||||
|
||||
assert dev.has_emeter
|
||||
|
||||
assert dev.get_emeter_daily(year=1900, month=1) == {}
|
||||
|
||||
d = dev.get_emeter_daily()
|
||||
assert len(d) > 0
|
||||
|
||||
k, v = d.popitem()
|
||||
assert isinstance(k, int)
|
||||
assert isinstance(v, float)
|
||||
|
||||
# Test kwh (energy, energy_wh)
|
||||
d = dev.get_emeter_daily(kwh=False)
|
||||
k2, v2 = d.popitem()
|
||||
assert v * 1000 == v2
|
||||
|
||||
|
||||
@has_emeter
|
||||
def test_get_emeter_monthly(dev):
|
||||
if dev.is_strip:
|
||||
pytest.skip("Disabled for HS300 temporarily")
|
||||
|
||||
assert dev.has_emeter
|
||||
|
||||
assert dev.get_emeter_monthly(year=1900) == {}
|
||||
|
||||
d = dev.get_emeter_monthly()
|
||||
assert len(d) > 0
|
||||
|
||||
k, v = d.popitem()
|
||||
assert isinstance(k, int)
|
||||
assert isinstance(v, float)
|
||||
|
||||
# Test kwh (energy, energy_wh)
|
||||
d = dev.get_emeter_monthly(kwh=False)
|
||||
k2, v2 = d.popitem()
|
||||
assert v * 1000 == v2
|
||||
|
||||
|
||||
@has_emeter
|
||||
def test_emeter_status(dev):
|
||||
if dev.is_strip:
|
||||
pytest.skip("Disabled for HS300 temporarily")
|
||||
|
||||
assert dev.has_emeter
|
||||
|
||||
d = dev.get_emeter_realtime()
|
||||
|
||||
with pytest.raises(KeyError):
|
||||
assert d["foo"]
|
||||
|
||||
assert d["power_mw"] == d["power"] * 1000
|
||||
# bulbs have only power according to tplink simulator.
|
||||
if not dev.is_bulb:
|
||||
assert d["voltage_mv"] == d["voltage"] * 1000
|
||||
|
||||
assert d["current_ma"] == d["current"] * 1000
|
||||
assert d["total_wh"] == d["total"] * 1000
|
||||
|
||||
|
||||
@pytest.mark.skip("not clearing your stats..")
|
||||
@has_emeter
|
||||
def test_erase_emeter_stats(dev):
|
||||
assert dev.has_emeter
|
||||
|
||||
dev.erase_emeter()
|
||||
|
||||
|
||||
@has_emeter
|
||||
def test_current_consumption(dev):
|
||||
if dev.is_strip:
|
||||
pytest.skip("Disabled for HS300 temporarily")
|
||||
|
||||
if dev.has_emeter:
|
||||
x = dev.current_consumption()
|
||||
assert isinstance(x, float)
|
||||
assert x >= 0.0
|
||||
else:
|
||||
assert dev.current_consumption() is None
|
||||
|
||||
|
||||
def test_alias(dev):
|
||||
test_alias = "TEST1234"
|
||||
original = dev.alias
|
||||
assert isinstance(original, str)
|
||||
|
||||
dev.set_alias(test_alias)
|
||||
assert dev.alias == test_alias
|
||||
|
||||
dev.set_alias(original)
|
||||
assert dev.alias == original
|
||||
|
||||
|
||||
@plug
|
||||
def test_led(dev):
|
||||
original = dev.led
|
||||
|
||||
dev.set_led(False)
|
||||
assert not dev.led
|
||||
dev.set_led(True)
|
||||
|
||||
assert dev.led
|
||||
|
||||
dev.set_led(original)
|
||||
|
||||
|
||||
@plug
|
||||
def test_on_since(dev):
|
||||
assert isinstance(dev.on_since, datetime.datetime)
|
||||
|
||||
|
||||
def test_icon(dev):
|
||||
assert set(dev.icon.keys()), {"icon", "hash"}
|
||||
|
||||
|
||||
def test_time(dev):
|
||||
assert isinstance(dev.time, datetime.datetime)
|
||||
# TODO check setting?
|
||||
|
||||
|
||||
def test_timezone(dev):
|
||||
TZ_SCHEMA(dev.timezone)
|
||||
|
||||
|
||||
def test_hw_info(dev):
|
||||
PLUG_SCHEMA(dev.hw_info)
|
||||
|
||||
|
||||
def test_location(dev):
|
||||
PLUG_SCHEMA(dev.location)
|
||||
|
||||
|
||||
def test_rssi(dev):
|
||||
PLUG_SCHEMA({"rssi": dev.rssi}) # wrapping for vol
|
||||
|
||||
|
||||
def test_mac(dev):
|
||||
PLUG_SCHEMA({"mac": dev.mac}) # wrapping for val
|
||||
# TODO check setting?
|
||||
|
||||
|
||||
@non_variable_temp
|
||||
def test_temperature_on_nonsupporting(dev):
|
||||
assert dev.valid_temperature_range == (0, 0)
|
||||
|
||||
# TODO test when device does not support temperature range
|
||||
with pytest.raises(SmartDeviceException):
|
||||
dev.set_color_temp(2700)
|
||||
with pytest.raises(SmartDeviceException):
|
||||
print(dev.color_temp)
|
||||
|
||||
|
||||
@variable_temp
|
||||
def test_out_of_range_temperature(dev):
|
||||
with pytest.raises(ValueError):
|
||||
dev.set_color_temp(1000)
|
||||
with pytest.raises(ValueError):
|
||||
dev.set_color_temp(10000)
|
||||
|
||||
|
||||
@non_dimmable
|
||||
def test_non_dimmable(dev):
|
||||
assert not dev.is_dimmable
|
||||
|
||||
with pytest.raises(SmartDeviceException):
|
||||
assert dev.brightness == 0
|
||||
with pytest.raises(SmartDeviceException):
|
||||
dev.set_brightness(100)
|
||||
|
||||
|
||||
@dimmable
|
||||
@turn_on
|
||||
def test_dimmable_brightness(dev, turn_on):
|
||||
handle_turn_on(dev, turn_on)
|
||||
assert dev.is_dimmable
|
||||
|
||||
dev.set_brightness(50)
|
||||
assert dev.brightness == 50
|
||||
|
||||
dev.set_brightness(10)
|
||||
assert dev.brightness == 10
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
dev.set_brightness("foo")
|
||||
|
||||
|
||||
@dimmable
|
||||
def test_invalid_brightness(dev):
|
||||
assert dev.is_dimmable
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
dev.set_brightness(110)
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
dev.set_brightness(-100)
|
||||
|
||||
|
||||
@color_bulb
|
||||
@turn_on
|
||||
def test_hsv(dev, turn_on):
|
||||
handle_turn_on(dev, turn_on)
|
||||
assert dev.is_color
|
||||
|
||||
hue, saturation, brightness = dev.hsv
|
||||
assert 0 <= hue <= 255
|
||||
assert 0 <= saturation <= 100
|
||||
assert 0 <= brightness <= 100
|
||||
|
||||
dev.set_hsv(hue=1, saturation=1, value=1)
|
||||
|
||||
hue, saturation, brightness = dev.hsv
|
||||
assert hue == 1
|
||||
assert saturation == 1
|
||||
assert brightness == 1
|
||||
|
||||
|
||||
@color_bulb
|
||||
@turn_on
|
||||
def test_invalid_hsv(dev, turn_on):
|
||||
handle_turn_on(dev, turn_on)
|
||||
|
||||
assert dev.is_color
|
||||
|
||||
for invalid_hue in [-1, 361, 0.5]:
|
||||
with pytest.raises(ValueError):
|
||||
dev.set_hsv(invalid_hue, 0, 0)
|
||||
|
||||
for invalid_saturation in [-1, 101, 0.5]:
|
||||
with pytest.raises(ValueError):
|
||||
dev.set_hsv(0, invalid_saturation, 0)
|
||||
|
||||
for invalid_brightness in [-1, 101, 0.5]:
|
||||
with pytest.raises(ValueError):
|
||||
dev.set_hsv(0, 0, invalid_brightness)
|
||||
|
||||
|
||||
@non_color_bulb
|
||||
def test_hsv_on_non_color(dev):
|
||||
assert not dev.is_color
|
||||
|
||||
with pytest.raises(SmartDeviceException):
|
||||
dev.set_hsv(0, 0, 0)
|
||||
with pytest.raises(SmartDeviceException):
|
||||
print(dev.hsv)
|
||||
|
||||
|
||||
@variable_temp
|
||||
@turn_on
|
||||
def test_try_set_colortemp(dev, turn_on):
|
||||
handle_turn_on(dev, turn_on)
|
||||
|
||||
dev.set_color_temp(2700)
|
||||
assert dev.color_temp == 2700
|
||||
|
||||
|
||||
@variable_temp
|
||||
@turn_on
|
||||
def test_deprecated_colortemp(dev, turn_on):
|
||||
handle_turn_on(dev, turn_on)
|
||||
with pytest.deprecated_call():
|
||||
dev.color_temp = 2700
|
||||
|
||||
|
||||
@dimmable
|
||||
def test_deprecated_brightness(dev):
|
||||
with pytest.deprecated_call():
|
||||
dev.brightness = 10
|
||||
|
||||
|
||||
@non_variable_temp
|
||||
def test_non_variable_temp(dev):
|
||||
with pytest.raises(SmartDeviceException):
|
||||
dev.set_color_temp(2700)
|
||||
|
||||
|
||||
@color_bulb
|
||||
@turn_on
|
||||
def test_deprecated_hsv(dev, turn_on):
|
||||
handle_turn_on(dev, turn_on)
|
||||
with pytest.deprecated_call():
|
||||
dev.hsv = (1, 1, 1)
|
||||
|
||||
|
||||
@strip
|
||||
def test_children_is_on(dev):
|
||||
is_on = dev.get_is_on()
|
||||
for i in range(dev.num_children):
|
||||
assert is_on[i] == dev.get_is_on(index=i)
|
||||
|
||||
|
||||
@strip
|
||||
@turn_on
|
||||
def test_children_change_state(dev, turn_on):
|
||||
handle_turn_on(dev, turn_on)
|
||||
for i in range(dev.num_children):
|
||||
orig_state = dev.get_is_on(index=i)
|
||||
if orig_state:
|
||||
dev.turn_off(index=i)
|
||||
assert not dev.get_is_on(index=i)
|
||||
assert dev.get_is_off(index=i)
|
||||
|
||||
dev.turn_on(index=i)
|
||||
assert dev.get_is_on(index=i)
|
||||
assert not dev.get_is_off(index=i)
|
||||
else:
|
||||
dev.turn_on(index=i)
|
||||
assert dev.get_is_on(index=i)
|
||||
assert not dev.get_is_off(index=i)
|
||||
dev.turn_off(index=i)
|
||||
assert not dev.get_is_on(index=i)
|
||||
assert dev.get_is_off(index=i)
|
||||
|
||||
|
||||
@strip
|
||||
def test_children_bounds(dev):
|
||||
out_of_bounds = dev.num_children + 100
|
||||
|
||||
with pytest.raises(SmartDeviceException):
|
||||
dev.turn_off(index=out_of_bounds)
|
||||
with pytest.raises(SmartDeviceException):
|
||||
dev.turn_on(index=out_of_bounds)
|
||||
with pytest.raises(SmartDeviceException):
|
||||
dev.get_is_on(index=out_of_bounds)
|
||||
with pytest.raises(SmartDeviceException):
|
||||
dev.get_alias(index=out_of_bounds)
|
||||
with pytest.raises(SmartDeviceException):
|
||||
dev.get_on_since(index=out_of_bounds)
|
||||
|
||||
|
||||
@strip
|
||||
def test_children_alias(dev):
|
||||
original = dev.get_alias()
|
||||
test_alias = "TEST1234"
|
||||
for idx in range(dev.num_children):
|
||||
dev.set_alias(alias=test_alias, index=idx)
|
||||
assert dev.get_alias(index=idx) == test_alias
|
||||
dev.set_alias(alias=original[idx], index=idx)
|
||||
assert dev.get_alias(index=idx) == original[idx]
|
||||
|
||||
|
||||
@strip
|
||||
def test_children_on_since(dev):
|
||||
for idx in range(dev.num_children):
|
||||
assert dev.get_on_since(index=idx)
|
||||
|
||||
|
||||
@pytest.mark.skip("this test will wear out your relays")
|
||||
def test_all_binary_states(dev):
|
||||
# test every binary state
|
||||
for state in range(2 ** dev.num_children):
|
||||
# create binary state map
|
||||
state_map = {}
|
||||
for plug_index in range(dev.num_children):
|
||||
state_map[plug_index] = bool((state >> plug_index) & 1)
|
||||
|
||||
if state_map[plug_index]:
|
||||
dev.turn_on(index=plug_index)
|
||||
else:
|
||||
dev.turn_off(index=plug_index)
|
||||
|
||||
# check state map applied
|
||||
for index, state in dev.get_is_on().items():
|
||||
assert state_map[index] == state
|
||||
|
||||
# toggle each outlet with state map applied
|
||||
for plug_index in range(dev.num_children):
|
||||
|
||||
# toggle state
|
||||
if state_map[plug_index]:
|
||||
dev.turn_off(index=plug_index)
|
||||
else:
|
||||
dev.turn_on(index=plug_index)
|
||||
|
||||
# only target outlet should have state changed
|
||||
for index, state in dev.get_is_on().items():
|
||||
if index == plug_index:
|
||||
assert state != state_map[index]
|
||||
else:
|
||||
assert state == state_map[index]
|
||||
|
||||
# reset state
|
||||
if state_map[plug_index]:
|
||||
dev.turn_on(index=plug_index)
|
||||
else:
|
||||
dev.turn_off(index=plug_index)
|
||||
|
||||
# original state map should be restored
|
||||
for index, state in dev.get_is_on().items():
|
||||
assert state == state_map[index]
|
||||
|
||||
|
||||
@strip
|
||||
def test_children_get_emeter_realtime(dev):
|
||||
assert dev.has_emeter
|
||||
# test with index
|
||||
for plug_index in range(dev.num_children):
|
||||
emeter = dev.get_emeter_realtime(index=plug_index)
|
||||
CURRENT_CONSUMPTION_SCHEMA(emeter)
|
||||
|
||||
# test without index
|
||||
for index, emeter in dev.get_emeter_realtime().items():
|
||||
CURRENT_CONSUMPTION_SCHEMA(emeter)
|
||||
|
||||
# out of bounds
|
||||
with pytest.raises(SmartStripException):
|
||||
dev.get_emeter_realtime(index=dev.num_children + 100)
|
||||
|
||||
|
||||
@strip
|
||||
def test_children_get_emeter_daily(dev):
|
||||
assert dev.has_emeter
|
||||
# test with index
|
||||
for plug_index in range(dev.num_children):
|
||||
emeter = dev.get_emeter_daily(year=1900, month=1, index=plug_index)
|
||||
assert emeter == {}
|
||||
|
||||
emeter = dev.get_emeter_daily(index=plug_index)
|
||||
assert len(emeter) > 0
|
||||
|
||||
k, v = emeter.popitem()
|
||||
assert isinstance(k, int)
|
||||
assert isinstance(v, float)
|
||||
|
||||
# test without index
|
||||
all_emeter = dev.get_emeter_daily(year=1900, month=1)
|
||||
for plug_index, emeter in all_emeter.items():
|
||||
assert emeter == {}
|
||||
|
||||
emeter = dev.get_emeter_daily(index=plug_index)
|
||||
|
||||
k, v = emeter.popitem()
|
||||
assert isinstance(k, int)
|
||||
assert isinstance(v, float)
|
||||
|
||||
# out of bounds
|
||||
with pytest.raises(SmartStripException):
|
||||
dev.get_emeter_daily(year=1900, month=1, index=dev.num_children + 100)
|
||||
|
||||
|
||||
@strip
|
||||
def test_children_get_emeter_monthly(dev):
|
||||
assert dev.has_emeter
|
||||
# test with index
|
||||
for plug_index in range(dev.num_children):
|
||||
emeter = dev.get_emeter_monthly(year=1900, index=plug_index)
|
||||
assert emeter == {}
|
||||
|
||||
emeter = dev.get_emeter_monthly()
|
||||
assert len(emeter) > 0
|
||||
|
||||
k, v = emeter.popitem()
|
||||
assert isinstance(k, int)
|
||||
assert isinstance(v, float)
|
||||
|
||||
# test without index
|
||||
all_emeter = dev.get_emeter_monthly(year=1900)
|
||||
for index, emeter in all_emeter.items():
|
||||
assert emeter == {}
|
||||
assert len(emeter) > 0
|
||||
|
||||
k, v = emeter.popitem()
|
||||
assert isinstance(k, int)
|
||||
assert isinstance(v, float)
|
||||
|
||||
# out of bounds
|
||||
with pytest.raises(SmartStripException):
|
||||
dev.get_emeter_monthly(year=1900, index=dev.num_children + 100)
|
||||
|
||||
|
||||
def test_cache(dev):
|
||||
from datetime import timedelta
|
||||
|
||||
dev.cache_ttl = timedelta(seconds=3)
|
||||
with patch.object(
|
||||
FakeTransportProtocol, "query", wraps=dev.protocol.query
|
||||
) as query_mock:
|
||||
CHECK_COUNT = 1
|
||||
# Smartstrip calls sysinfo in its __init__ to request children, so
|
||||
# the even first get call here will get its results from the cache.
|
||||
if dev.is_strip:
|
||||
CHECK_COUNT = 0
|
||||
|
||||
dev.get_sysinfo()
|
||||
assert query_mock.call_count == CHECK_COUNT
|
||||
dev.get_sysinfo()
|
||||
assert query_mock.call_count == CHECK_COUNT
|
||||
|
||||
|
||||
def test_cache_invalidates(dev):
|
||||
from datetime import timedelta
|
||||
|
||||
dev.cache_ttl = timedelta(seconds=0)
|
||||
|
||||
with patch.object(
|
||||
FakeTransportProtocol, "query", wraps=dev.protocol.query
|
||||
) as query_mock:
|
||||
dev.get_sysinfo()
|
||||
assert query_mock.call_count == 1
|
||||
dev.get_sysinfo()
|
||||
assert query_mock.call_count == 2
|
||||
# assert query_mock.called_once()
|
@ -5,7 +5,7 @@ import json
|
||||
|
||||
class TestTPLinkSmartHomeProtocol(TestCase):
|
||||
def test_encrypt(self):
|
||||
d = json.dumps({'foo': 1, 'bar': 2})
|
||||
d = json.dumps({"foo": 1, "bar": 2})
|
||||
encrypted = TPLinkSmartHomeProtocol.encrypt(d)
|
||||
# encrypt adds a 4 byte header
|
||||
encrypted = encrypted[4:]
|
||||
@ -14,8 +14,28 @@ class TestTPLinkSmartHomeProtocol(TestCase):
|
||||
def test_encrypt_unicode(self):
|
||||
d = "{'snowman': '\u2603'}"
|
||||
|
||||
e = bytes([208, 247, 132, 234, 133, 242, 159, 254, 144, 183,
|
||||
141, 173, 138, 104, 240, 115, 84, 41])
|
||||
e = bytes(
|
||||
[
|
||||
208,
|
||||
247,
|
||||
132,
|
||||
234,
|
||||
133,
|
||||
242,
|
||||
159,
|
||||
254,
|
||||
144,
|
||||
183,
|
||||
141,
|
||||
173,
|
||||
138,
|
||||
104,
|
||||
240,
|
||||
115,
|
||||
84,
|
||||
41,
|
||||
]
|
||||
)
|
||||
|
||||
encrypted = TPLinkSmartHomeProtocol.encrypt(d)
|
||||
# encrypt adds a 4 byte header
|
||||
@ -24,8 +44,28 @@ class TestTPLinkSmartHomeProtocol(TestCase):
|
||||
self.assertEqual(e, encrypted)
|
||||
|
||||
def test_decrypt_unicode(self):
|
||||
e = bytes([208, 247, 132, 234, 133, 242, 159, 254, 144, 183,
|
||||
141, 173, 138, 104, 240, 115, 84, 41])
|
||||
e = bytes(
|
||||
[
|
||||
208,
|
||||
247,
|
||||
132,
|
||||
234,
|
||||
133,
|
||||
242,
|
||||
159,
|
||||
254,
|
||||
144,
|
||||
183,
|
||||
141,
|
||||
173,
|
||||
138,
|
||||
104,
|
||||
240,
|
||||
115,
|
||||
84,
|
||||
41,
|
||||
]
|
||||
)
|
||||
|
||||
d = "{'snowman': '\u2603'}"
|
||||
|
||||
|
@ -1,373 +0,0 @@
|
||||
from unittest import TestCase, skip
|
||||
from voluptuous import Schema, Invalid, All, Any, Range, Coerce
|
||||
from functools import partial
|
||||
import datetime
|
||||
import re
|
||||
from typing import Dict # noqa: F401
|
||||
|
||||
from .. import SmartPlug, SmartDeviceException
|
||||
from .fakes import (FakeTransportProtocol,
|
||||
sysinfo_hs100,
|
||||
sysinfo_hs105,
|
||||
sysinfo_hs110,
|
||||
sysinfo_hs110_au_v2,
|
||||
sysinfo_hs200,
|
||||
sysinfo_hs220,
|
||||
)
|
||||
|
||||
# Set IP instead of None if you want to run tests on a device.
|
||||
PLUG_IP = None
|
||||
|
||||
|
||||
def check_int_bool(x):
|
||||
if x != 0 and x != 1:
|
||||
raise Invalid(x)
|
||||
return x
|
||||
|
||||
|
||||
def check_mac(x):
|
||||
if re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", x.lower()):
|
||||
return x
|
||||
raise Invalid(x)
|
||||
|
||||
|
||||
def check_mode(x):
|
||||
if x in ['schedule', 'none']:
|
||||
return x
|
||||
|
||||
raise Invalid("invalid mode {}".format(x))
|
||||
|
||||
|
||||
class TestSmartPlugHS100(TestCase):
|
||||
SYSINFO = sysinfo_hs100 # type: Dict
|
||||
# these schemas should go to the mainlib as
|
||||
# they can be useful when adding support for new features/devices
|
||||
# as well as to check that faked devices are operating properly.
|
||||
sysinfo_schema = Schema({
|
||||
'active_mode': check_mode,
|
||||
'alias': str,
|
||||
'dev_name': str,
|
||||
'deviceId': str,
|
||||
'feature': str,
|
||||
'fwId': str,
|
||||
'hwId': str,
|
||||
'hw_ver': str,
|
||||
'icon_hash': str,
|
||||
'led_off': check_int_bool,
|
||||
'latitude': Any(All(float, Range(min=-90, max=90)), None),
|
||||
'latitude_i': Any(All(float, Range(min=-90, max=90)), None),
|
||||
'longitude': Any(All(float, Range(min=-180, max=180)), None),
|
||||
'longitude_i': Any(All(float, Range(min=-180, max=180)), None),
|
||||
'mac': check_mac,
|
||||
'model': str,
|
||||
'oemId': str,
|
||||
'on_time': int,
|
||||
'relay_state': int,
|
||||
'rssi': Any(int, None), # rssi can also be positive, see #54
|
||||
'sw_ver': str,
|
||||
'type': str,
|
||||
'mic_type': str,
|
||||
'updating': check_int_bool,
|
||||
# these are available on hs220
|
||||
'brightness': int,
|
||||
'preferred_state': [{
|
||||
'brightness': All(int, Range(min=0, max=100)),
|
||||
'index': int,
|
||||
}],
|
||||
"next_action": {"type": int},
|
||||
|
||||
})
|
||||
|
||||
current_consumption_schema = Schema(Any({
|
||||
'voltage': Any(All(float, Range(min=0, max=300)), None),
|
||||
'power': Any(Coerce(float, Range(min=0)), None),
|
||||
'total': Any(Coerce(float, Range(min=0)), None),
|
||||
'current': Any(All(float, Range(min=0)), None),
|
||||
|
||||
'voltage_mv': Any(All(float, Range(min=0, max=300000)), None),
|
||||
'power_mw': Any(Coerce(float, Range(min=0)), None),
|
||||
'total_wh': Any(Coerce(float, Range(min=0)), None),
|
||||
'current_ma': Any(All(float, Range(min=0)), None),
|
||||
}, None))
|
||||
|
||||
tz_schema = Schema({
|
||||
'zone_str': str,
|
||||
'dst_offset': int,
|
||||
'index': All(int, Range(min=0)),
|
||||
'tz_str': str,
|
||||
})
|
||||
|
||||
def setUp(self):
|
||||
if PLUG_IP is not None:
|
||||
self.plug = SmartPlug(PLUG_IP)
|
||||
else:
|
||||
self.plug = SmartPlug("127.0.0.1",
|
||||
protocol=FakeTransportProtocol(self.SYSINFO))
|
||||
|
||||
def tearDown(self):
|
||||
self.plug = None
|
||||
|
||||
def test_initialize(self):
|
||||
self.assertIsNotNone(self.plug.sys_info)
|
||||
self.sysinfo_schema(self.plug.sys_info)
|
||||
|
||||
def test_initialize_invalid_connection(self):
|
||||
plug = SmartPlug('127.0.0.1',
|
||||
protocol=FakeTransportProtocol(self.SYSINFO,
|
||||
invalid=True))
|
||||
with self.assertRaises(SmartDeviceException):
|
||||
plug.sys_info['model']
|
||||
|
||||
def test_query_helper(self):
|
||||
with self.assertRaises(SmartDeviceException):
|
||||
self.plug._query_helper("test", "testcmd", {})
|
||||
# TODO check for unwrapping?
|
||||
|
||||
def test_state(self):
|
||||
def set_invalid(x):
|
||||
self.plug.state = x
|
||||
|
||||
set_invalid_int = partial(set_invalid, 1234)
|
||||
self.assertRaises(ValueError, set_invalid_int)
|
||||
|
||||
set_invalid_str = partial(set_invalid, "1234")
|
||||
self.assertRaises(ValueError, set_invalid_str)
|
||||
|
||||
set_invalid_bool = partial(set_invalid, True)
|
||||
self.assertRaises(ValueError, set_invalid_bool)
|
||||
|
||||
orig_state = self.plug.state
|
||||
if orig_state == SmartPlug.SWITCH_STATE_OFF:
|
||||
self.plug.state = "ON"
|
||||
self.assertTrue(self.plug.state == SmartPlug.SWITCH_STATE_ON)
|
||||
self.plug.state = "OFF"
|
||||
self.assertTrue(self.plug.state == SmartPlug.SWITCH_STATE_OFF)
|
||||
elif orig_state == SmartPlug.SWITCH_STATE_ON:
|
||||
self.plug.state = "OFF"
|
||||
self.assertTrue(self.plug.state == SmartPlug.SWITCH_STATE_OFF)
|
||||
self.plug.state = "ON"
|
||||
self.assertTrue(self.plug.state == SmartPlug.SWITCH_STATE_ON)
|
||||
elif orig_state == SmartPlug.SWITCH_STATE_UNKNOWN:
|
||||
self.fail("can't test for unknown state")
|
||||
|
||||
def test_get_sysinfo(self):
|
||||
# initialize checks for this already, but just to be sure
|
||||
self.sysinfo_schema(self.plug.get_sysinfo())
|
||||
|
||||
def test_turns_and_isses(self):
|
||||
orig_state = self.plug.is_on
|
||||
|
||||
if orig_state:
|
||||
self.plug.turn_off()
|
||||
self.assertFalse(self.plug.is_on)
|
||||
self.assertTrue(self.plug.is_off)
|
||||
self.plug.turn_on()
|
||||
self.assertTrue(self.plug.is_on)
|
||||
else:
|
||||
self.plug.turn_on()
|
||||
self.assertFalse(self.plug.is_off)
|
||||
self.assertTrue(self.plug.is_on)
|
||||
self.plug.turn_off()
|
||||
self.assertTrue(self.plug.is_off)
|
||||
|
||||
def test_has_emeter(self):
|
||||
# a not so nice way for checking for emeter availability..
|
||||
if "110" in self.plug.sys_info["model"]:
|
||||
self.assertTrue(self.plug.has_emeter)
|
||||
else:
|
||||
self.assertFalse(self.plug.has_emeter)
|
||||
|
||||
def test_get_emeter_realtime(self):
|
||||
if self.plug.has_emeter:
|
||||
current_emeter = self.plug.get_emeter_realtime()
|
||||
self.current_consumption_schema(current_emeter)
|
||||
else:
|
||||
self.assertEqual(self.plug.get_emeter_realtime(), None)
|
||||
|
||||
def test_get_emeter_daily(self):
|
||||
if self.plug.has_emeter:
|
||||
self.assertEqual(self.plug.get_emeter_daily(year=1900, month=1),
|
||||
{})
|
||||
|
||||
d = self.plug.get_emeter_daily()
|
||||
if len(d) < 1:
|
||||
print("no emeter daily information, skipping..")
|
||||
return
|
||||
k, v = d.popitem()
|
||||
self.assertTrue(isinstance(k, int))
|
||||
self.assertTrue(isinstance(v, float))
|
||||
else:
|
||||
self.assertEqual(self.plug.get_emeter_daily(year=1900, month=1),
|
||||
None)
|
||||
|
||||
def test_get_emeter_monthly(self):
|
||||
if self.plug.has_emeter:
|
||||
self.assertEqual(self.plug.get_emeter_monthly(year=1900), {})
|
||||
|
||||
d = self.plug.get_emeter_monthly()
|
||||
if len(d) < 1:
|
||||
print("no emeter monthly information, skipping..")
|
||||
return
|
||||
k, v = d.popitem()
|
||||
self.assertTrue(isinstance(k, int))
|
||||
self.assertTrue(isinstance(v, float))
|
||||
else:
|
||||
self.assertEqual(self.plug.get_emeter_monthly(year=1900), None)
|
||||
|
||||
@skip("not clearing your stats..")
|
||||
def test_erase_emeter_stats(self):
|
||||
self.fail()
|
||||
|
||||
def test_current_consumption(self):
|
||||
if self.plug.has_emeter:
|
||||
x = self.plug.current_consumption()
|
||||
self.assertTrue(isinstance(x, float))
|
||||
self.assertTrue(x >= 0.0)
|
||||
else:
|
||||
self.assertEqual(self.plug.current_consumption(), None)
|
||||
|
||||
def test_alias(self):
|
||||
test_alias = "TEST1234"
|
||||
original = self.plug.alias
|
||||
self.assertTrue(isinstance(original, str))
|
||||
self.plug.alias = test_alias
|
||||
self.assertEqual(self.plug.alias, test_alias)
|
||||
self.plug.alias = original
|
||||
self.assertEqual(self.plug.alias, original)
|
||||
|
||||
def test_led(self):
|
||||
original = self.plug.led
|
||||
|
||||
self.plug.led = False
|
||||
self.assertFalse(self.plug.led)
|
||||
self.plug.led = True
|
||||
self.assertTrue(self.plug.led)
|
||||
|
||||
self.plug.led = original
|
||||
|
||||
def test_icon(self):
|
||||
self.assertEqual(set(self.plug.icon.keys()), {'icon', 'hash'})
|
||||
|
||||
def test_time(self):
|
||||
self.assertTrue(isinstance(self.plug.time, datetime.datetime))
|
||||
# TODO check setting?
|
||||
|
||||
def test_timezone(self):
|
||||
self.tz_schema(self.plug.timezone)
|
||||
|
||||
def test_hw_info(self):
|
||||
self.sysinfo_schema(self.plug.hw_info)
|
||||
|
||||
def test_on_since(self):
|
||||
self.assertTrue(isinstance(self.plug.on_since, datetime.datetime))
|
||||
|
||||
def test_location(self):
|
||||
self.sysinfo_schema(self.plug.location)
|
||||
|
||||
def test_rssi(self):
|
||||
self.sysinfo_schema({'rssi': self.plug.rssi}) # wrapping for vol
|
||||
|
||||
def test_mac(self):
|
||||
self.sysinfo_schema({'mac': self.plug.mac}) # wrapping for val
|
||||
# TODO check setting?
|
||||
|
||||
def test_repr(self):
|
||||
repr(self.plug)
|
||||
|
||||
|
||||
class TestSmartPlugHS110(TestSmartPlugHS100):
|
||||
SYSINFO = sysinfo_hs110
|
||||
|
||||
def test_emeter_upcast(self):
|
||||
emeter = self.plug.get_emeter_realtime()
|
||||
self.assertAlmostEqual(emeter["power"] * 10**3, emeter["power_mw"])
|
||||
self.assertAlmostEqual(emeter["voltage"] * 10**3, emeter["voltage_mv"])
|
||||
self.assertAlmostEqual(emeter["current"] * 10**3, emeter["current_ma"])
|
||||
self.assertAlmostEqual(emeter["total"] * 10**3, emeter["total_wh"])
|
||||
|
||||
def test_emeter_daily_upcast(self):
|
||||
emeter = self.plug.get_emeter_daily()
|
||||
_, v = emeter.popitem()
|
||||
|
||||
emeter = self.plug.get_emeter_daily(kwh=False)
|
||||
_, v2 = emeter.popitem()
|
||||
|
||||
self.assertAlmostEqual(v * 10**3, v2)
|
||||
|
||||
def test_get_emeter_monthly_upcast(self):
|
||||
emeter = self.plug.get_emeter_monthly()
|
||||
_, v = emeter.popitem()
|
||||
|
||||
emeter = self.plug.get_emeter_monthly(kwh=False)
|
||||
_, v2 = emeter.popitem()
|
||||
|
||||
self.assertAlmostEqual(v * 10**3, v2)
|
||||
|
||||
|
||||
class TestSmartPlugHS110_HW2(TestSmartPlugHS100):
|
||||
SYSINFO = sysinfo_hs110_au_v2
|
||||
|
||||
def test_emeter_downcast(self):
|
||||
emeter = self.plug.get_emeter_realtime()
|
||||
self.assertAlmostEqual(emeter["power"], emeter["power_mw"] / 10**3)
|
||||
self.assertAlmostEqual(emeter["voltage"], emeter["voltage_mv"] / 10**3)
|
||||
self.assertAlmostEqual(emeter["current"], emeter["current_ma"] / 10**3)
|
||||
self.assertAlmostEqual(emeter["total"], emeter["total_wh"] / 10**3)
|
||||
|
||||
def test_emeter_daily_downcast(self):
|
||||
emeter = self.plug.get_emeter_daily()
|
||||
_, v = emeter.popitem()
|
||||
|
||||
emeter = self.plug.get_emeter_daily(kwh=False)
|
||||
_, v2 = emeter.popitem()
|
||||
|
||||
self.assertAlmostEqual(v * 10**3, v2)
|
||||
|
||||
def test_get_emeter_monthly_downcast(self):
|
||||
emeter = self.plug.get_emeter_monthly()
|
||||
_, v = emeter.popitem()
|
||||
|
||||
emeter = self.plug.get_emeter_monthly(kwh=False)
|
||||
_, v2 = emeter.popitem()
|
||||
|
||||
self.assertAlmostEqual(v * 10**3, v2)
|
||||
|
||||
|
||||
class TestSmartPlugHS200(TestSmartPlugHS100):
|
||||
SYSINFO = sysinfo_hs200
|
||||
|
||||
|
||||
class TestSmartPlugHS105(TestSmartPlugHS100):
|
||||
SYSINFO = sysinfo_hs105
|
||||
|
||||
def test_location_i(self):
|
||||
if PLUG_IP is not None:
|
||||
plug_i = SmartPlug(PLUG_IP)
|
||||
else:
|
||||
plug_i = SmartPlug("127.0.0.1",
|
||||
protocol=FakeTransportProtocol(self.SYSINFO))
|
||||
|
||||
self.sysinfo_schema(plug_i.location)
|
||||
|
||||
|
||||
class TestSmartPlugHS220(TestSmartPlugHS105):
|
||||
"""HS220 with dimming functionality. Sysinfo looks similar to HS105."""
|
||||
SYSINFO = sysinfo_hs220
|
||||
|
||||
def test_dimmable(self):
|
||||
assert self.plug.is_dimmable
|
||||
assert self.plug.brightness == 25
|
||||
self.plug.brightness = 100
|
||||
assert self.plug.brightness == 100
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
self.plug.brightness = 110
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
self.plug.brightness = -1
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
self.plug.brightness = "foo"
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
self.plug.brightness = 11.1
|
@ -1,441 +0,0 @@
|
||||
from unittest import TestCase, skip
|
||||
from voluptuous import Schema, All, Any, Range, Coerce
|
||||
import datetime
|
||||
|
||||
from .. import SmartStrip, SmartPlug, SmartStripException, SmartDeviceException
|
||||
from .fakes import FakeTransportProtocol, sysinfo_hs300
|
||||
from .test_pyHS100 import check_mac, check_int_bool
|
||||
|
||||
# Set IP instead of None if you want to run tests on a device.
|
||||
STRIP_IP = None
|
||||
|
||||
|
||||
class TestSmartStripHS300(TestCase):
|
||||
SYSINFO = sysinfo_hs300 # type: Dict
|
||||
# these schemas should go to the mainlib as
|
||||
# they can be useful when adding support for new features/devices
|
||||
# as well as to check that faked devices are operating properly.
|
||||
sysinfo_schema = Schema({
|
||||
"sw_ver": str,
|
||||
"hw_ver": str,
|
||||
"model": str,
|
||||
"deviceId": str,
|
||||
"oemId": str,
|
||||
"hwId": str,
|
||||
"rssi": Any(int, None), # rssi can also be positive, see #54
|
||||
"longitude": Any(All(int, Range(min=-1800000, max=1800000)), None),
|
||||
"latitude": Any(All(int, Range(min=-900000, max=900000)), None),
|
||||
"longitude_i": Any(All(int, Range(min=-1800000, max=1800000)), None),
|
||||
"latitude_i": Any(All(int, Range(min=-900000, max=900000)), None),
|
||||
"alias": str,
|
||||
"mic_type": str,
|
||||
"feature": str,
|
||||
"mac": check_mac,
|
||||
"updating": check_int_bool,
|
||||
"led_off": check_int_bool,
|
||||
"children": [{
|
||||
"id": str,
|
||||
"state": int,
|
||||
"alias": str,
|
||||
"on_time": int,
|
||||
"next_action": {"type": int},
|
||||
}],
|
||||
"child_num": int,
|
||||
"err_code": int,
|
||||
})
|
||||
|
||||
current_consumption_schema = Schema(
|
||||
Any(
|
||||
{
|
||||
"voltage": Any(All(float, Range(min=0, max=300)), None),
|
||||
"power": Any(Coerce(float, Range(min=0)), None),
|
||||
"total": Any(Coerce(float, Range(min=0)), None),
|
||||
"current": Any(All(float, Range(min=0)), None),
|
||||
|
||||
"voltage_mv": Any(All(int, Range(min=0, max=300000)), None),
|
||||
"power_mw": Any(Coerce(int, Range(min=0)), None),
|
||||
"total_wh": Any(Coerce(int, Range(min=0)), None),
|
||||
"current_ma": Any(All(int, Range(min=0)), None),
|
||||
},
|
||||
None
|
||||
)
|
||||
)
|
||||
|
||||
tz_schema = Schema({
|
||||
"zone_str": str,
|
||||
"dst_offset": int,
|
||||
"index": All(int, Range(min=0)),
|
||||
"tz_str": str,
|
||||
})
|
||||
|
||||
def setUp(self):
|
||||
if STRIP_IP is not None:
|
||||
self.strip = SmartStrip(STRIP_IP)
|
||||
else:
|
||||
self.strip = SmartStrip(
|
||||
host="127.0.0.1",
|
||||
protocol=FakeTransportProtocol(self.SYSINFO)
|
||||
)
|
||||
|
||||
def tearDown(self):
|
||||
self.strip = None
|
||||
|
||||
def test_initialize(self):
|
||||
self.assertIsNotNone(self.strip.sys_info)
|
||||
self.assertTrue(self.strip.num_children)
|
||||
self.sysinfo_schema(self.strip.sys_info)
|
||||
|
||||
def test_initialize_invalid_connection(self):
|
||||
with self.assertRaises(SmartDeviceException):
|
||||
SmartStrip(
|
||||
host="127.0.0.1",
|
||||
protocol=FakeTransportProtocol(self.SYSINFO, invalid=True))
|
||||
|
||||
def test_query_helper(self):
|
||||
with self.assertRaises(SmartDeviceException):
|
||||
self.strip._query_helper("test", "testcmd", {})
|
||||
|
||||
def test_raise_for_index(self):
|
||||
with self.assertRaises(SmartStripException):
|
||||
self.strip.raise_for_index(index=self.strip.num_children + 100)
|
||||
|
||||
def test_state_strip(self):
|
||||
with self.assertRaises(ValueError):
|
||||
self.strip.state = 1234
|
||||
with self.assertRaises(ValueError):
|
||||
self.strip.state = "1234"
|
||||
with self.assertRaises(ValueError):
|
||||
self.strip.state = True
|
||||
|
||||
orig_state = self.strip.state
|
||||
if orig_state == SmartPlug.SWITCH_STATE_OFF:
|
||||
self.strip.state = "ON"
|
||||
self.assertTrue(self.strip.state == SmartPlug.SWITCH_STATE_ON)
|
||||
self.strip.state = "OFF"
|
||||
self.assertTrue(self.strip.state == SmartPlug.SWITCH_STATE_OFF)
|
||||
elif orig_state == SmartPlug.SWITCH_STATE_ON:
|
||||
self.strip.state = "OFF"
|
||||
self.assertTrue(self.strip.state == SmartPlug.SWITCH_STATE_OFF)
|
||||
self.strip.state = "ON"
|
||||
self.assertTrue(self.strip.state == SmartPlug.SWITCH_STATE_ON)
|
||||
elif orig_state == SmartPlug.SWITCH_STATE_UNKNOWN:
|
||||
self.fail("can't test for unknown state")
|
||||
|
||||
def test_state_plugs(self):
|
||||
# value errors
|
||||
for plug_index in range(self.strip.num_children):
|
||||
with self.assertRaises(ValueError):
|
||||
self.strip.set_state(value=1234, index=plug_index)
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
self.strip.set_state(value="1234", index=plug_index)
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
self.strip.set_state(value=True, index=plug_index)
|
||||
|
||||
# out of bounds error
|
||||
with self.assertRaises(SmartStripException):
|
||||
self.strip.set_state(
|
||||
value=SmartPlug.SWITCH_STATE_ON,
|
||||
index=self.strip.num_children + 100
|
||||
)
|
||||
|
||||
# on off
|
||||
for plug_index in range(self.strip.num_children):
|
||||
orig_state = self.strip.state[plug_index]
|
||||
if orig_state == SmartPlug.SWITCH_STATE_OFF:
|
||||
self.strip.set_state(value="ON", index=plug_index)
|
||||
self.assertTrue(
|
||||
self.strip.state[plug_index] == SmartPlug.SWITCH_STATE_ON)
|
||||
self.strip.set_state(value="OFF", index=plug_index)
|
||||
self.assertTrue(
|
||||
self.strip.state[plug_index] == SmartPlug.SWITCH_STATE_OFF)
|
||||
elif orig_state == SmartPlug.SWITCH_STATE_ON:
|
||||
self.strip.set_state(value="OFF", index=plug_index)
|
||||
self.assertTrue(
|
||||
self.strip.state[plug_index] == SmartPlug.SWITCH_STATE_OFF)
|
||||
self.strip.set_state(value="ON", index=plug_index)
|
||||
self.assertTrue(
|
||||
self.strip.state[plug_index] == SmartPlug.SWITCH_STATE_ON)
|
||||
elif orig_state == SmartPlug.SWITCH_STATE_UNKNOWN:
|
||||
self.fail("can't test for unknown state")
|
||||
|
||||
def test_turns_and_isses(self):
|
||||
# all on
|
||||
self.strip.turn_on()
|
||||
for index, state in self.strip.is_on().items():
|
||||
self.assertTrue(state)
|
||||
self.assertTrue(self.strip.is_on(index=index) == state)
|
||||
|
||||
# all off
|
||||
self.strip.turn_off()
|
||||
for index, state in self.strip.is_on().items():
|
||||
self.assertFalse(state)
|
||||
self.assertTrue(self.strip.is_on(index=index) == state)
|
||||
|
||||
# individual on
|
||||
for plug_index in range(self.strip.num_children):
|
||||
original_states = self.strip.is_on()
|
||||
self.strip.turn_on(index=plug_index)
|
||||
|
||||
# only target outlet should have state changed
|
||||
for index, state in self.strip.is_on().items():
|
||||
if index == plug_index:
|
||||
self.assertTrue(state != original_states[index])
|
||||
else:
|
||||
self.assertTrue(state == original_states[index])
|
||||
|
||||
# individual off
|
||||
for plug_index in range(self.strip.num_children):
|
||||
original_states = self.strip.is_on()
|
||||
self.strip.turn_off(index=plug_index)
|
||||
|
||||
# only target outlet should have state changed
|
||||
for index, state in self.strip.is_on().items():
|
||||
if index == plug_index:
|
||||
self.assertTrue(state != original_states[index])
|
||||
else:
|
||||
self.assertTrue(state == original_states[index])
|
||||
|
||||
# out of bounds
|
||||
with self.assertRaises(SmartStripException):
|
||||
self.strip.turn_off(index=self.strip.num_children + 100)
|
||||
with self.assertRaises(SmartStripException):
|
||||
self.strip.turn_on(index=self.strip.num_children + 100)
|
||||
with self.assertRaises(SmartStripException):
|
||||
self.strip.is_on(index=self.strip.num_children + 100)
|
||||
|
||||
@skip("this test will wear out your relays")
|
||||
def test_all_binary_states(self):
|
||||
# test every binary state
|
||||
for state in range(2 ** self.strip.num_children):
|
||||
|
||||
# create binary state map
|
||||
state_map = {}
|
||||
for plug_index in range(self.strip.num_children):
|
||||
state_map[plug_index] = bool((state >> plug_index) & 1)
|
||||
|
||||
if state_map[plug_index]:
|
||||
self.strip.turn_on(index=plug_index)
|
||||
else:
|
||||
self.strip.turn_off(index=plug_index)
|
||||
|
||||
# check state map applied
|
||||
for index, state in self.strip.is_on().items():
|
||||
self.assertTrue(state_map[index] == state)
|
||||
|
||||
# toggle each outlet with state map applied
|
||||
for plug_index in range(self.strip.num_children):
|
||||
|
||||
# toggle state
|
||||
if state_map[plug_index]:
|
||||
self.strip.turn_off(index=plug_index)
|
||||
else:
|
||||
self.strip.turn_on(index=plug_index)
|
||||
|
||||
# only target outlet should have state changed
|
||||
for index, state in self.strip.is_on().items():
|
||||
if index == plug_index:
|
||||
self.assertTrue(state != state_map[index])
|
||||
else:
|
||||
self.assertTrue(state == state_map[index])
|
||||
|
||||
# reset state
|
||||
if state_map[plug_index]:
|
||||
self.strip.turn_on(index=plug_index)
|
||||
else:
|
||||
self.strip.turn_off(index=plug_index)
|
||||
|
||||
# original state map should be restored
|
||||
for index, state in self.strip.is_on().items():
|
||||
self.assertTrue(state == state_map[index])
|
||||
|
||||
def test_has_emeter(self):
|
||||
# a not so nice way for checking for emeter availability..
|
||||
if "HS300" in self.strip.sys_info["model"]:
|
||||
self.assertTrue(self.strip.has_emeter)
|
||||
else:
|
||||
self.assertFalse(self.strip.has_emeter)
|
||||
|
||||
def test_get_emeter_realtime(self):
|
||||
if self.strip.has_emeter:
|
||||
# test with index
|
||||
for plug_index in range(self.strip.num_children):
|
||||
emeter = self.strip.get_emeter_realtime(index=plug_index)
|
||||
self.current_consumption_schema(emeter)
|
||||
|
||||
# test without index
|
||||
for index, emeter in self.strip.get_emeter_realtime().items():
|
||||
self.current_consumption_schema(emeter)
|
||||
|
||||
# out of bounds
|
||||
with self.assertRaises(SmartStripException):
|
||||
self.strip.get_emeter_realtime(
|
||||
index=self.strip.num_children + 100
|
||||
)
|
||||
else:
|
||||
self.assertEqual(self.strip.get_emeter_realtime(), None)
|
||||
|
||||
def test_get_emeter_daily(self):
|
||||
if self.strip.has_emeter:
|
||||
# test with index
|
||||
for plug_index in range(self.strip.num_children):
|
||||
emeter = self.strip.get_emeter_daily(year=1900, month=1,
|
||||
index=plug_index)
|
||||
self.assertEqual(emeter, {})
|
||||
if len(emeter) < 1:
|
||||
print("no emeter daily information, skipping..")
|
||||
return
|
||||
k, v = emeter.popitem()
|
||||
self.assertTrue(isinstance(k, int))
|
||||
self.assertTrue(isinstance(v, float))
|
||||
|
||||
# test without index
|
||||
all_emeter = self.strip.get_emeter_daily(year=1900, month=1)
|
||||
for index, emeter in all_emeter.items():
|
||||
self.assertEqual(emeter, {})
|
||||
if len(emeter) < 1:
|
||||
print("no emeter daily information, skipping..")
|
||||
return
|
||||
k, v = emeter.popitem()
|
||||
self.assertTrue(isinstance(k, int))
|
||||
self.assertTrue(isinstance(v, float))
|
||||
|
||||
# out of bounds
|
||||
with self.assertRaises(SmartStripException):
|
||||
self.strip.get_emeter_daily(
|
||||
year=1900,
|
||||
month=1,
|
||||
index=self.strip.num_children + 100
|
||||
)
|
||||
else:
|
||||
self.assertEqual(
|
||||
self.strip.get_emeter_daily(year=1900, month=1), None)
|
||||
|
||||
def test_get_emeter_monthly(self):
|
||||
if self.strip.has_emeter:
|
||||
# test with index
|
||||
for plug_index in range(self.strip.num_children):
|
||||
emeter = self.strip.get_emeter_monthly(year=1900,
|
||||
index=plug_index)
|
||||
self.assertEqual(emeter, {})
|
||||
if len(emeter) < 1:
|
||||
print("no emeter daily information, skipping..")
|
||||
return
|
||||
k, v = emeter.popitem()
|
||||
self.assertTrue(isinstance(k, int))
|
||||
self.assertTrue(isinstance(v, float))
|
||||
|
||||
# test without index
|
||||
all_emeter = self.strip.get_emeter_monthly(year=1900)
|
||||
for index, emeter in all_emeter.items():
|
||||
self.assertEqual(emeter, {})
|
||||
if len(emeter) < 1:
|
||||
print("no emeter daily information, skipping..")
|
||||
return
|
||||
k, v = emeter.popitem()
|
||||
self.assertTrue(isinstance(k, int))
|
||||
self.assertTrue(isinstance(v, float))
|
||||
|
||||
# out of bounds
|
||||
with self.assertRaises(SmartStripException):
|
||||
self.strip.get_emeter_monthly(
|
||||
year=1900,
|
||||
index=self.strip.num_children + 100
|
||||
)
|
||||
else:
|
||||
self.assertEqual(self.strip.get_emeter_monthly(year=1900), None)
|
||||
|
||||
@skip("not clearing your stats..")
|
||||
def test_erase_emeter_stats(self):
|
||||
self.fail()
|
||||
|
||||
def test_current_consumption(self):
|
||||
if self.strip.has_emeter:
|
||||
# test with index
|
||||
for plug_index in range(self.strip.num_children):
|
||||
emeter = self.strip.current_consumption(index=plug_index)
|
||||
self.assertTrue(isinstance(emeter, float))
|
||||
self.assertTrue(emeter >= 0.0)
|
||||
|
||||
# test without index
|
||||
for index, emeter in self.strip.current_consumption().items():
|
||||
self.assertTrue(isinstance(emeter, float))
|
||||
self.assertTrue(emeter >= 0.0)
|
||||
|
||||
# out of bounds
|
||||
with self.assertRaises(SmartStripException):
|
||||
self.strip.current_consumption(
|
||||
index=self.strip.num_children + 100
|
||||
)
|
||||
else:
|
||||
self.assertEqual(self.strip.current_consumption(), None)
|
||||
|
||||
def test_alias(self):
|
||||
test_alias = "TEST1234"
|
||||
|
||||
# strip alias
|
||||
original = self.strip.alias
|
||||
self.assertTrue(isinstance(original, str))
|
||||
self.strip.alias = test_alias
|
||||
self.assertEqual(self.strip.alias, test_alias)
|
||||
self.strip.alias = original
|
||||
self.assertEqual(self.strip.alias, original)
|
||||
|
||||
# plug alias
|
||||
original = self.strip.get_alias()
|
||||
for plug in range(self.strip.num_children):
|
||||
self.strip.set_alias(alias=test_alias, index=plug)
|
||||
self.assertEqual(self.strip.get_alias(index=plug), test_alias)
|
||||
self.strip.set_alias(alias=original[plug], index=plug)
|
||||
self.assertEqual(self.strip.get_alias(index=plug), original[plug])
|
||||
|
||||
def test_led(self):
|
||||
original = self.strip.led
|
||||
|
||||
self.strip.led = False
|
||||
self.assertFalse(self.strip.led)
|
||||
self.strip.led = True
|
||||
self.assertTrue(self.strip.led)
|
||||
self.strip.led = original
|
||||
|
||||
def test_icon(self):
|
||||
with self.assertRaises(NotImplementedError):
|
||||
self.strip.icon
|
||||
|
||||
def test_time(self):
|
||||
self.assertTrue(isinstance(self.strip.time, datetime.datetime))
|
||||
# TODO check setting?
|
||||
|
||||
def test_timezone(self):
|
||||
self.tz_schema(self.strip.timezone)
|
||||
|
||||
def test_hw_info(self):
|
||||
self.sysinfo_schema(self.strip.hw_info)
|
||||
|
||||
def test_on_since(self):
|
||||
# out of bounds
|
||||
with self.assertRaises(SmartStripException):
|
||||
self.strip.on_since(index=self.strip.num_children + 1)
|
||||
|
||||
# individual on_since
|
||||
for plug_index in range(self.strip.num_children):
|
||||
self.assertTrue(isinstance(
|
||||
self.strip.on_since(index=plug_index), datetime.datetime))
|
||||
|
||||
# all on_since
|
||||
for index, plug_on_since in self.strip.on_since().items():
|
||||
self.assertTrue(isinstance(plug_on_since, datetime.datetime))
|
||||
|
||||
def test_location(self):
|
||||
print(self.strip.location)
|
||||
self.sysinfo_schema(self.strip.location)
|
||||
|
||||
def test_rssi(self):
|
||||
self.sysinfo_schema({'rssi': self.strip.rssi}) # wrapping for vol
|
||||
|
||||
def test_mac(self):
|
||||
self.sysinfo_schema({'mac': self.strip.mac}) # wrapping for vol
|
||||
|
||||
def test_repr(self):
|
||||
repr(self.strip)
|
@ -1,2 +1,3 @@
|
||||
click
|
||||
click-datetime
|
||||
pre-commit
|
||||
|
4
setup.py
4
setup.py
@ -8,8 +8,8 @@ setup(name='pyHS100',
|
||||
author_email='sean@gadgetreactor.com',
|
||||
license='GPLv3',
|
||||
packages=['pyHS100'],
|
||||
install_requires=['click', 'click-datetime', 'typing'],
|
||||
python_requires='>=3.4',
|
||||
install_requires=['click', 'typing', 'deprecation'],
|
||||
python_requires='>=3.5',
|
||||
entry_points={
|
||||
'console_scripts': [
|
||||
'pyhs100=pyHS100.cli:cli',
|
||||
|
Loading…
Reference in New Issue
Block a user