Add try_connect_all to allow initialisation without udp broadcast (#1171)

- Try all valid combinations of protocol/transport/device class and attempt to connect. 
- Add cli command `discover config` to return the connection options after connecting via `try_connect_all`.
- The cli command does not return the actual device for processing as this is not a recommended way to regularly connect to devices.
This commit is contained in:
Steven B.
2024-10-22 14:33:46 +01:00
committed by GitHub
parent 852116795c
commit 3c865b5fb6
5 changed files with 231 additions and 3 deletions

View File

@@ -17,7 +17,7 @@ from kasa import (
)
from kasa.discover import DiscoveryResult
from .common import echo
from .common import echo, error
@click.group(invoke_without_command=True)
@@ -145,6 +145,41 @@ async def _discover(ctx, print_discovered, print_unsupported, *, do_echo=True):
return discovered_devices
@discover.command()
@click.pass_context
async def config(ctx):
"""Bypass udp discovery and try to show connection config for a device.
Bypasses udp discovery and shows the parameters required to connect
directly to the device.
"""
params = ctx.parent.parent.params
username = params["username"]
password = params["password"]
timeout = params["timeout"]
host = params["host"]
port = params["port"]
if not host:
error("--host option must be supplied to discover config")
credentials = Credentials(username, password) if username and password else None
dev = await Discover.try_connect_all(
host, credentials=credentials, timeout=timeout, port=port
)
if dev:
cparams = dev.config.connection_type
echo("Managed to connect, cli options to connect are:")
echo(
f"--device-family {cparams.device_family.value} "
f"--encrypt-type {cparams.encryption_type.value} "
f"{'--https' if cparams.https else '--no-https'}"
)
else:
error(f"Unable to connect to {host}")
def _echo_dictionary(discovery_info: dict):
echo("\t[bold]== Discovery information ==[/bold]")
for key, value in discovery_info.items():

View File

@@ -39,6 +39,7 @@ TYPES = [
]
ENCRYPT_TYPES = [encrypt_type.value for encrypt_type in DeviceEncryptionType]
DEFAULT_TARGET = "255.255.255.255"
def _legacy_type_to_class(_type):
@@ -115,7 +116,7 @@ def _legacy_type_to_class(_type):
@click.option(
"--target",
envvar="KASA_TARGET",
default="255.255.255.255",
default=DEFAULT_TARGET,
required=False,
show_default=True,
help="The broadcast address to be used for discovery.",
@@ -256,6 +257,9 @@ async def cli(
ctx.obj = object()
return
if target != DEFAULT_TARGET and host:
error("--target is not a valid option for single host discovery")
if experimental:
from kasa.experimental.enabled import Enabled