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:
Teemu R
2019-06-16 17:05:00 -04:00
committed by GitHub
parent e82746da24
commit 2d60467bea
36 changed files with 2980 additions and 2367 deletions

113
pyHS100/tests/conftest.py Normal file
View 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"))

View File

@@ -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))

View 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
}
}
}

View 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
}
}
}

View 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
}
}
}

View 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
}
}
}

View 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
}
}
}

View 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
}
}
}

View 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
}
}
}

View 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
}
}
}

View 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
}
}
}

View 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"
}
}
}

View 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"
}
}
}

View 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"
}
}
}

View 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
View 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))

View File

@@ -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

View 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()

View File

@@ -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'}"

View File

@@ -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

View File

@@ -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)