2021-05-10 00:19:00 +00:00
|
|
|
"""This script generates devinfo files for the test suite.
|
|
|
|
|
2023-10-29 22:15:42 +00:00
|
|
|
If you have new, yet unsupported device or a device with no devinfo file under
|
|
|
|
kasa/tests/fixtures, feel free to run this script and create a PR to add the file
|
|
|
|
to the repository.
|
2021-05-10 00:19:00 +00:00
|
|
|
|
|
|
|
Executing this script will several modules and methods one by one,
|
|
|
|
and finally execute a query to query all of them at once.
|
|
|
|
"""
|
2023-12-02 16:33:35 +00:00
|
|
|
import base64
|
2021-05-10 00:19:00 +00:00
|
|
|
import collections.abc
|
|
|
|
import json
|
|
|
|
import logging
|
|
|
|
import re
|
|
|
|
from collections import defaultdict, namedtuple
|
|
|
|
from pprint import pprint
|
|
|
|
|
2023-11-29 19:01:20 +00:00
|
|
|
import asyncclick as click
|
2021-05-10 00:19:00 +00:00
|
|
|
|
2023-12-02 16:33:35 +00:00
|
|
|
from kasa import Credentials, Discover, SmartDevice
|
2023-11-29 19:01:20 +00:00
|
|
|
from kasa.discover import DiscoveryResult
|
2023-12-02 16:33:35 +00:00
|
|
|
from kasa.tapo.tapodevice import TapoDevice
|
2021-05-10 00:19:00 +00:00
|
|
|
|
|
|
|
Call = namedtuple("Call", "module method")
|
|
|
|
|
|
|
|
|
|
|
|
def scrub(res):
|
|
|
|
"""Remove identifiers from the given dict."""
|
|
|
|
keys_to_scrub = [
|
|
|
|
"deviceId",
|
|
|
|
"fwId",
|
|
|
|
"hwId",
|
|
|
|
"oemId",
|
|
|
|
"mac",
|
|
|
|
"mic_mac",
|
|
|
|
"latitude_i",
|
|
|
|
"longitude_i",
|
|
|
|
"latitude",
|
|
|
|
"longitude",
|
2023-11-29 19:01:20 +00:00
|
|
|
"owner",
|
|
|
|
"device_id",
|
|
|
|
"ip",
|
|
|
|
"ssid",
|
|
|
|
"hw_id",
|
|
|
|
"fw_id",
|
|
|
|
"oem_id",
|
2023-12-08 13:29:07 +00:00
|
|
|
"nickname",
|
|
|
|
"alias",
|
2021-05-10 00:19:00 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
for k, v in res.items():
|
|
|
|
if isinstance(v, collections.abc.Mapping):
|
|
|
|
res[k] = scrub(res.get(k))
|
|
|
|
else:
|
|
|
|
if k in keys_to_scrub:
|
2021-06-19 19:46:36 +00:00
|
|
|
if k in ["latitude", "latitude_i", "longitude", "longitude_i"]:
|
2021-05-10 00:19:00 +00:00
|
|
|
v = 0
|
2023-11-29 19:01:20 +00:00
|
|
|
elif k in ["ip"]:
|
|
|
|
v = "127.0.0.123"
|
2023-12-02 16:33:35 +00:00
|
|
|
elif k in ["ssid"]:
|
|
|
|
# Need a valid base64 value here
|
2023-12-08 13:29:07 +00:00
|
|
|
v = base64.b64encode(b"#MASKED_SSID#").decode()
|
|
|
|
elif k in ["nickname"]:
|
|
|
|
v = base64.b64encode(b"#MASKED_NAME#").decode()
|
|
|
|
elif k in ["alias"]:
|
|
|
|
v = "#MASKED_NAME#"
|
2021-05-10 00:19:00 +00:00
|
|
|
else:
|
|
|
|
v = re.sub(r"\w", "0", v)
|
|
|
|
|
|
|
|
res[k] = v
|
|
|
|
return res
|
|
|
|
|
|
|
|
|
|
|
|
def default_to_regular(d):
|
|
|
|
"""Convert nested defaultdicts to regular ones.
|
|
|
|
|
|
|
|
From https://stackoverflow.com/a/26496899
|
|
|
|
"""
|
|
|
|
if isinstance(d, defaultdict):
|
|
|
|
d = {k: default_to_regular(v) for k, v in d.items()}
|
|
|
|
return d
|
|
|
|
|
|
|
|
|
|
|
|
@click.command()
|
|
|
|
@click.argument("host")
|
2023-11-29 19:01:20 +00:00
|
|
|
@click.option(
|
|
|
|
"--username",
|
|
|
|
default=None,
|
|
|
|
required=False,
|
|
|
|
envvar="TPLINK_CLOUD_USERNAME",
|
|
|
|
help="Username/email address to authenticate to device.",
|
|
|
|
)
|
|
|
|
@click.option(
|
|
|
|
"--password",
|
|
|
|
default=None,
|
|
|
|
required=False,
|
|
|
|
envvar="TPLINK_CLOUD_PASSWORD",
|
|
|
|
help="Password to use to authenticate to device.",
|
|
|
|
)
|
2021-06-19 19:46:36 +00:00
|
|
|
@click.option("-d", "--debug", is_flag=True)
|
2023-11-29 19:01:20 +00:00
|
|
|
async def cli(host, debug, username, password):
|
2021-05-10 00:19:00 +00:00
|
|
|
"""Generate devinfo file for given device."""
|
|
|
|
if debug:
|
|
|
|
logging.basicConfig(level=logging.DEBUG)
|
|
|
|
|
2023-12-02 16:33:35 +00:00
|
|
|
credentials = Credentials(username=username, password=password)
|
|
|
|
device = await Discover.discover_single(host, credentials=credentials)
|
|
|
|
|
|
|
|
if isinstance(device, TapoDevice):
|
2023-12-05 15:45:09 +00:00
|
|
|
save_filename, copy_folder, final = await get_smart_fixture(device)
|
2023-12-02 16:33:35 +00:00
|
|
|
else:
|
2023-12-05 15:45:09 +00:00
|
|
|
save_filename, copy_folder, final = await get_legacy_fixture(device)
|
2023-12-02 16:33:35 +00:00
|
|
|
|
|
|
|
pprint(scrub(final))
|
2023-12-05 15:45:09 +00:00
|
|
|
save = click.prompt(
|
|
|
|
f"Do you want to save the above content to {save_filename} (y/n)"
|
|
|
|
)
|
2023-12-02 16:33:35 +00:00
|
|
|
if save == "y":
|
2023-12-05 15:45:09 +00:00
|
|
|
click.echo(f"Saving info to {save_filename}")
|
2023-12-02 16:33:35 +00:00
|
|
|
|
2023-12-05 15:45:09 +00:00
|
|
|
with open(save_filename, "w") as f:
|
2023-12-02 16:33:35 +00:00
|
|
|
json.dump(final, f, sort_keys=True, indent=4)
|
|
|
|
f.write("\n")
|
2023-12-05 15:45:09 +00:00
|
|
|
|
|
|
|
click.echo(
|
|
|
|
f"Saved. Copy/Move {save_filename} to "
|
|
|
|
+ f"{copy_folder} to add it to the test suite"
|
|
|
|
)
|
2023-12-02 16:33:35 +00:00
|
|
|
else:
|
|
|
|
click.echo("Not saving.")
|
|
|
|
|
|
|
|
|
|
|
|
async def get_legacy_fixture(device):
|
|
|
|
"""Get fixture for legacy IOT style protocol."""
|
2021-05-10 00:19:00 +00:00
|
|
|
items = [
|
|
|
|
Call(module="system", method="get_sysinfo"),
|
|
|
|
Call(module="emeter", method="get_realtime"),
|
|
|
|
Call(module="smartlife.iot.dimmer", method="get_dimmer_parameters"),
|
|
|
|
Call(module="smartlife.iot.common.emeter", method="get_realtime"),
|
|
|
|
Call(
|
|
|
|
module="smartlife.iot.smartbulb.lightingservice", method="get_light_state"
|
|
|
|
),
|
2022-01-29 17:28:14 +00:00
|
|
|
Call(module="smartlife.iot.LAS", method="get_config"),
|
|
|
|
Call(module="smartlife.iot.PIR", method="get_config"),
|
2021-05-10 00:19:00 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
successes = []
|
|
|
|
|
2023-11-29 19:01:20 +00:00
|
|
|
for test_call in items:
|
2021-05-10 00:19:00 +00:00
|
|
|
try:
|
|
|
|
click.echo(f"Testing {test_call}..", nl=False)
|
2023-11-29 19:01:20 +00:00
|
|
|
info = await device.protocol.query(
|
|
|
|
{test_call.module: {test_call.method: None}}
|
|
|
|
)
|
2021-05-10 00:19:00 +00:00
|
|
|
resp = info[test_call.module]
|
|
|
|
except Exception as ex:
|
|
|
|
click.echo(click.style(f"FAIL {ex}", fg="red"))
|
|
|
|
else:
|
|
|
|
if "err_msg" in resp:
|
|
|
|
click.echo(click.style(f"FAIL {resp['err_msg']}", fg="red"))
|
|
|
|
else:
|
|
|
|
click.echo(click.style("OK", fg="green"))
|
|
|
|
successes.append((test_call, info))
|
|
|
|
|
|
|
|
final_query = defaultdict(defaultdict)
|
|
|
|
final = defaultdict(defaultdict)
|
|
|
|
for succ, resp in successes:
|
|
|
|
final_query[succ.module][succ.method] = None
|
|
|
|
final[succ.module][succ.method] = resp
|
|
|
|
|
|
|
|
final = default_to_regular(final)
|
|
|
|
|
|
|
|
try:
|
2023-11-29 19:01:20 +00:00
|
|
|
final = await device.protocol.query(final_query)
|
2021-05-10 00:19:00 +00:00
|
|
|
except Exception as ex:
|
|
|
|
click.echo(
|
|
|
|
click.style(
|
|
|
|
f"Unable to query all successes at once: {ex}", bold=True, fg="red"
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
2023-11-29 19:01:20 +00:00
|
|
|
if device._discovery_info:
|
|
|
|
# Need to recreate a DiscoverResult here because we don't want the aliases
|
|
|
|
# in the fixture, we want the actual field names as returned by the device.
|
|
|
|
dr = DiscoveryResult(**device._discovery_info)
|
|
|
|
final["discovery_result"] = dr.dict(
|
|
|
|
by_alias=False, exclude_unset=True, exclude_none=True, exclude_defaults=True
|
|
|
|
)
|
|
|
|
|
2021-05-10 00:19:00 +00:00
|
|
|
click.echo("Got %s successes" % len(successes))
|
|
|
|
click.echo(click.style("## device info file ##", bold=True))
|
|
|
|
|
|
|
|
sysinfo = final["system"]["get_sysinfo"]
|
|
|
|
model = sysinfo["model"]
|
|
|
|
hw_version = sysinfo["hw_ver"]
|
|
|
|
sw_version = sysinfo["sw_ver"]
|
|
|
|
sw_version = sw_version.split(" ", maxsplit=1)[0]
|
2023-12-05 15:45:09 +00:00
|
|
|
save_filename = f"{model}_{hw_version}_{sw_version}.json"
|
|
|
|
copy_folder = "kasa/tests/fixtures/"
|
|
|
|
return save_filename, copy_folder, final
|
2021-05-10 00:19:00 +00:00
|
|
|
|
2023-12-02 16:33:35 +00:00
|
|
|
|
|
|
|
async def get_smart_fixture(device: SmartDevice):
|
|
|
|
"""Get fixture for new TAPO style protocol."""
|
|
|
|
items = [
|
|
|
|
Call(module="component_nego", method="component_nego"),
|
|
|
|
Call(module="device_info", method="get_device_info"),
|
|
|
|
Call(module="device_usage", method="get_device_usage"),
|
|
|
|
Call(module="device_time", method="get_device_time"),
|
|
|
|
Call(module="energy_usage", method="get_energy_usage"),
|
|
|
|
Call(module="current_power", method="get_current_power"),
|
2023-12-08 13:29:07 +00:00
|
|
|
Call(module="temp_humidity_records", method="get_temp_humidity_records"),
|
|
|
|
Call(module="child_device_list", method="get_child_device_list"),
|
|
|
|
Call(
|
|
|
|
module="trigger_logs",
|
|
|
|
method={"get_trigger_logs": {"page_size": 5, "start_id": 0}},
|
|
|
|
),
|
2023-12-02 16:33:35 +00:00
|
|
|
Call(
|
|
|
|
module="child_device_component_list",
|
|
|
|
method="get_child_device_component_list",
|
|
|
|
),
|
|
|
|
]
|
|
|
|
|
|
|
|
successes = []
|
|
|
|
|
|
|
|
for test_call in items:
|
|
|
|
try:
|
|
|
|
click.echo(f"Testing {test_call}..", nl=False)
|
|
|
|
response = await device.protocol.query(test_call.method)
|
|
|
|
except Exception as ex:
|
|
|
|
click.echo(click.style(f"FAIL {ex}", fg="red"))
|
|
|
|
else:
|
|
|
|
if not response:
|
|
|
|
click.echo(click.style("FAIL not suported", fg="red"))
|
|
|
|
else:
|
|
|
|
click.echo(click.style("OK", fg="green"))
|
|
|
|
successes.append(test_call)
|
|
|
|
|
|
|
|
requests = []
|
|
|
|
for succ in successes:
|
|
|
|
requests.append({"method": succ.method})
|
|
|
|
|
|
|
|
final_query = {"multipleRequest": {"requests": requests}}
|
|
|
|
|
|
|
|
try:
|
|
|
|
responses = await device.protocol.query(final_query)
|
|
|
|
except Exception as ex:
|
|
|
|
click.echo(
|
|
|
|
click.style(
|
|
|
|
f"Unable to query all successes at once: {ex}", bold=True, fg="red"
|
|
|
|
)
|
|
|
|
)
|
|
|
|
final = {}
|
|
|
|
for response in responses["responses"]:
|
|
|
|
final[response["method"]] = response["result"]
|
|
|
|
|
2023-12-05 15:45:09 +00:00
|
|
|
# Need to recreate a DiscoverResult here because we don't want the aliases
|
|
|
|
# in the fixture, we want the actual field names as returned by the device.
|
|
|
|
dr = DiscoveryResult(**device._discovery_info) # type: ignore
|
|
|
|
final["discovery_result"] = dr.dict(
|
|
|
|
by_alias=False, exclude_unset=True, exclude_none=True, exclude_defaults=True
|
|
|
|
)
|
2023-12-02 16:33:35 +00:00
|
|
|
|
|
|
|
click.echo("Got %s successes" % len(successes))
|
|
|
|
click.echo(click.style("## device info file ##", bold=True))
|
|
|
|
|
|
|
|
hw_version = final["get_device_info"]["hw_ver"]
|
|
|
|
sw_version = final["get_device_info"]["fw_ver"]
|
2023-12-05 15:45:09 +00:00
|
|
|
model = final["discovery_result"]["device_model"]
|
2023-12-02 16:33:35 +00:00
|
|
|
sw_version = sw_version.split(" ", maxsplit=1)[0]
|
|
|
|
|
2023-12-05 15:45:09 +00:00
|
|
|
save_filename = f"{model}_{hw_version}_{sw_version}.json"
|
|
|
|
copy_folder = "kasa/tests/fixtures/smart/"
|
|
|
|
return save_filename, copy_folder, final
|
2021-05-10 00:19:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
cli()
|