Move connect_single to SmartDevice.connect (#538)

This refactors `Discover.connect_single` by moving device instance construction into a separate device factory module.
New `SmartDevice.connect(host, *, port, timeout, credentials, device_type)` class method replaces the functionality of `connect_single`,
and also now allows constructing device instances without relying on UDP discovery for type discovery if `device_type` parameter is set.

---------

Co-authored-by: Teemu R. <tpr@iki.fi>
This commit is contained in:
J. Nick Koston
2023-11-21 23:48:53 +01:00
committed by GitHub
parent 27c4799adc
commit e98252ff17
11 changed files with 361 additions and 144 deletions

View File

@@ -13,14 +13,13 @@ import asyncclick as click
from kasa import (
AuthenticationException,
Credentials,
DeviceType,
Discover,
SmartBulb,
SmartDevice,
SmartDimmer,
SmartLightStrip,
SmartPlug,
SmartStrip,
)
from kasa.device_factory import DEVICE_TYPE_TO_CLASS
try:
from rich import print as _do_echo
@@ -43,13 +42,11 @@ except ImportError:
# --json has set it to _nop_echo
echo = _do_echo
TYPE_TO_CLASS = {
"plug": SmartPlug,
"bulb": SmartBulb,
"dimmer": SmartDimmer,
"strip": SmartStrip,
"lightstrip": SmartLightStrip,
}
DEVICE_TYPES = [
device_type.value
for device_type in DeviceType
if device_type in DEVICE_TYPE_TO_CLASS
]
click.anyio_backend = "asyncio"
@@ -129,7 +126,7 @@ def json_formatter_cb(result, **kwargs):
"--type",
envvar="KASA_TYPE",
default=None,
type=click.Choice(list(TYPE_TO_CLASS), case_sensitive=False),
type=click.Choice(DEVICE_TYPES, case_sensitive=False),
)
@click.option(
"--json", default=False, is_flag=True, help="Output raw device response as JSON."
@@ -235,7 +232,10 @@ async def cli(
return await ctx.invoke(discover, timeout=discovery_timeout)
if type is not None:
dev = TYPE_TO_CLASS[type](host, credentials=credentials)
device_type = DeviceType.from_value(type)
dev = await SmartDevice.connect(
host, credentials=credentials, device_type=device_type
)
else:
echo("No --type defined, discovering..")
dev = await Discover.discover_single(
@@ -243,8 +243,8 @@ async def cli(
port=port,
credentials=credentials,
)
await dev.update()
await dev.update()
ctx.obj = dev
if ctx.invoked_subcommand is None: