python-kasa 0.7.4__py3-none-any.whl → 0.7.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. kasa/aestransport.py +55 -31
  2. kasa/cachedzoneinfo.py +28 -0
  3. kasa/cli/common.py +2 -0
  4. kasa/cli/device.py +1 -1
  5. kasa/cli/discover.py +134 -34
  6. kasa/cli/main.py +50 -12
  7. kasa/cli/time.py +114 -9
  8. kasa/device.py +8 -4
  9. kasa/device_factory.py +30 -15
  10. kasa/device_type.py +1 -0
  11. kasa/deviceconfig.py +13 -5
  12. kasa/discover.py +197 -13
  13. kasa/exceptions.py +51 -0
  14. kasa/experimental/__init__.py +28 -0
  15. kasa/experimental/modules/__init__.py +13 -0
  16. kasa/experimental/modules/camera.py +71 -0
  17. kasa/experimental/modules/childdevice.py +25 -0
  18. kasa/experimental/modules/device.py +40 -0
  19. kasa/experimental/modules/time.py +91 -0
  20. kasa/experimental/smartcamera.py +197 -0
  21. kasa/experimental/smartcameramodule.py +100 -0
  22. kasa/experimental/smartcameraprotocol.py +251 -0
  23. kasa/experimental/sslaestransport.py +473 -0
  24. kasa/httpclient.py +4 -1
  25. kasa/interfaces/__init__.py +2 -0
  26. kasa/interfaces/time.py +26 -0
  27. kasa/iot/iotbulb.py +4 -2
  28. kasa/iot/iotdevice.py +29 -20
  29. kasa/iot/iotplug.py +1 -1
  30. kasa/iot/iotstrip.py +13 -6
  31. kasa/iot/iottimezone.py +186 -0
  32. kasa/iot/modules/ambientlight.py +3 -3
  33. kasa/iot/modules/cloud.py +3 -3
  34. kasa/iot/modules/emeter.py +1 -1
  35. kasa/iot/modules/light.py +1 -1
  36. kasa/iot/modules/lightpreset.py +1 -1
  37. kasa/iot/modules/time.py +44 -6
  38. kasa/klaptransport.py +0 -1
  39. kasa/module.py +6 -3
  40. kasa/protocol.py +4 -1
  41. kasa/smart/modules/cloud.py +3 -9
  42. kasa/smart/modules/color.py +6 -9
  43. kasa/smart/modules/contactsensor.py +3 -8
  44. kasa/smart/modules/devicemodule.py +3 -2
  45. kasa/smart/modules/energy.py +11 -0
  46. kasa/smart/modules/fan.py +4 -10
  47. kasa/smart/modules/humiditysensor.py +4 -9
  48. kasa/smart/modules/light.py +1 -1
  49. kasa/smart/modules/lighteffect.py +1 -1
  50. kasa/smart/modules/lightpreset.py +1 -1
  51. kasa/smart/modules/lighttransition.py +1 -1
  52. kasa/smart/modules/reportmode.py +3 -8
  53. kasa/smart/modules/temperaturesensor.py +7 -10
  54. kasa/smart/modules/time.py +58 -28
  55. kasa/smart/modules/waterleaksensor.py +29 -9
  56. kasa/smart/smartchilddevice.py +47 -19
  57. kasa/smart/smartdevice.py +51 -25
  58. kasa/smart/smartmodule.py +13 -7
  59. kasa/smartprotocol.py +11 -2
  60. {python_kasa-0.7.4.dist-info → python_kasa-0.7.6.dist-info}/METADATA +7 -3
  61. python_kasa-0.7.6.dist-info/RECORD +117 -0
  62. python_kasa-0.7.4.dist-info/RECORD +0 -104
  63. {python_kasa-0.7.4.dist-info → python_kasa-0.7.6.dist-info}/WHEEL +0 -0
  64. {python_kasa-0.7.4.dist-info → python_kasa-0.7.6.dist-info}/entry_points.txt +0 -0
  65. {python_kasa-0.7.4.dist-info → python_kasa-0.7.6.dist-info}/licenses/LICENSE +0 -0
kasa/aestransport.py CHANGED
@@ -14,7 +14,7 @@ from collections.abc import AsyncGenerator
14
14
  from enum import Enum, auto
15
15
  from typing import TYPE_CHECKING, Any, Dict, cast
16
16
 
17
- from cryptography.hazmat.primitives import padding, serialization
17
+ from cryptography.hazmat.primitives import hashes, padding, serialization
18
18
  from cryptography.hazmat.primitives.asymmetric import padding as asymmetric_padding
19
19
  from cryptography.hazmat.primitives.asymmetric import rsa
20
20
  from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
@@ -108,7 +108,9 @@ class AesTransport(BaseTransport):
108
108
  self._key_pair: KeyPair | None = None
109
109
  if config.aes_keys:
110
110
  aes_keys = config.aes_keys
111
- self._key_pair = KeyPair(aes_keys["private"], aes_keys["public"])
111
+ self._key_pair = KeyPair.create_from_der_keys(
112
+ aes_keys["private"], aes_keys["public"]
113
+ )
112
114
  self._app_url = URL(f"http://{self._host}:{self._port}/app")
113
115
  self._token_url: URL | None = None
114
116
 
@@ -277,14 +279,14 @@ class AesTransport(BaseTransport):
277
279
  if not self._key_pair:
278
280
  kp = KeyPair.create_key_pair()
279
281
  self._config.aes_keys = {
280
- "private": kp.get_private_key(),
281
- "public": kp.get_public_key(),
282
+ "private": kp.private_key_der_b64,
283
+ "public": kp.public_key_der_b64,
282
284
  }
283
285
  self._key_pair = kp
284
286
 
285
287
  pub_key = (
286
288
  "-----BEGIN PUBLIC KEY-----\n"
287
- + self._key_pair.get_public_key() # type: ignore[union-attr]
289
+ + self._key_pair.public_key_der_b64 # type: ignore[union-attr]
288
290
  + "\n-----END PUBLIC KEY-----\n"
289
291
  )
290
292
  handshake_params = {"key": pub_key}
@@ -392,18 +394,11 @@ class AesEncyptionSession:
392
394
  """Class for an AES encryption session."""
393
395
 
394
396
  @staticmethod
395
- def create_from_keypair(handshake_key: str, keypair):
397
+ def create_from_keypair(handshake_key: str, keypair: KeyPair):
396
398
  """Create the encryption session."""
397
- handshake_key_bytes: bytes = base64.b64decode(handshake_key.encode("UTF-8"))
398
- private_key_data = base64.b64decode(keypair.get_private_key().encode("UTF-8"))
399
+ handshake_key_bytes: bytes = base64.b64decode(handshake_key.encode())
399
400
 
400
- private_key = cast(
401
- rsa.RSAPrivateKey,
402
- serialization.load_der_private_key(private_key_data, None, None),
403
- )
404
- key_and_iv = private_key.decrypt(
405
- handshake_key_bytes, asymmetric_padding.PKCS1v15()
406
- )
401
+ key_and_iv = keypair.decrypt_handshake_key(handshake_key_bytes)
407
402
  if key_and_iv is None:
408
403
  raise ValueError("Decryption failed!")
409
404
 
@@ -438,30 +433,59 @@ class KeyPair:
438
433
  """Create a key pair."""
439
434
  private_key = rsa.generate_private_key(public_exponent=65537, key_size=key_size)
440
435
  public_key = private_key.public_key()
436
+ return KeyPair(private_key, public_key)
437
+
438
+ @staticmethod
439
+ def create_from_der_keys(private_key_der_b64: str, public_key_der_b64: str):
440
+ """Create a key pair."""
441
+ key_bytes = base64.b64decode(private_key_der_b64.encode())
442
+ private_key = cast(
443
+ rsa.RSAPrivateKey, serialization.load_der_private_key(key_bytes, None)
444
+ )
445
+ key_bytes = base64.b64decode(public_key_der_b64.encode())
446
+ public_key = cast(
447
+ rsa.RSAPublicKey, serialization.load_der_public_key(key_bytes, None)
448
+ )
441
449
 
442
- private_key_bytes = private_key.private_bytes(
450
+ return KeyPair(private_key, public_key)
451
+
452
+ def __init__(self, private_key: rsa.RSAPrivateKey, public_key: rsa.RSAPublicKey):
453
+ self.private_key = private_key
454
+ self.public_key = public_key
455
+ self.private_key_der_bytes = self.private_key.private_bytes(
443
456
  encoding=serialization.Encoding.DER,
444
457
  format=serialization.PrivateFormat.PKCS8,
445
458
  encryption_algorithm=serialization.NoEncryption(),
446
459
  )
447
- public_key_bytes = public_key.public_bytes(
460
+ self.public_key_der_bytes = self.public_key.public_bytes(
448
461
  encoding=serialization.Encoding.DER,
449
462
  format=serialization.PublicFormat.SubjectPublicKeyInfo,
450
463
  )
464
+ self.private_key_der_b64 = base64.b64encode(self.private_key_der_bytes).decode()
465
+ self.public_key_der_b64 = base64.b64encode(self.public_key_der_bytes).decode()
451
466
 
452
- return KeyPair(
453
- private_key=base64.b64encode(private_key_bytes).decode("UTF-8"),
454
- public_key=base64.b64encode(public_key_bytes).decode("UTF-8"),
467
+ def get_public_pem(self) -> bytes:
468
+ """Get public key in PEM encoding."""
469
+ return self.public_key.public_bytes(
470
+ encoding=serialization.Encoding.PEM,
471
+ format=serialization.PublicFormat.SubjectPublicKeyInfo,
455
472
  )
456
473
 
457
- def __init__(self, private_key: str, public_key: str):
458
- self.private_key = private_key
459
- self.public_key = public_key
460
-
461
- def get_private_key(self) -> str:
462
- """Get the private key."""
463
- return self.private_key
464
-
465
- def get_public_key(self) -> str:
466
- """Get the public key."""
467
- return self.public_key
474
+ def decrypt_handshake_key(self, encrypted_key: bytes) -> bytes:
475
+ """Decrypt an aes handshake key."""
476
+ decrypted = self.private_key.decrypt(
477
+ encrypted_key, asymmetric_padding.PKCS1v15()
478
+ )
479
+ return decrypted
480
+
481
+ def decrypt_discovery_key(self, encrypted_key: bytes) -> bytes:
482
+ """Decrypt an aes discovery key."""
483
+ decrypted = self.private_key.decrypt(
484
+ encrypted_key,
485
+ asymmetric_padding.OAEP(
486
+ mgf=asymmetric_padding.MGF1(algorithm=hashes.SHA1()), # noqa: S303
487
+ algorithm=hashes.SHA1(), # noqa: S303
488
+ label=None,
489
+ ),
490
+ )
491
+ return decrypted
kasa/cachedzoneinfo.py ADDED
@@ -0,0 +1,28 @@
1
+ """Module for caching ZoneInfos."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+
7
+ from zoneinfo import ZoneInfo
8
+
9
+
10
+ class CachedZoneInfo(ZoneInfo):
11
+ """Cache ZoneInfo objects."""
12
+
13
+ _cache: dict[str, ZoneInfo] = {}
14
+
15
+ @classmethod
16
+ async def get_cached_zone_info(cls, time_zone_str: str) -> ZoneInfo:
17
+ """Get a cached zone info object."""
18
+ if cached := cls._cache.get(time_zone_str):
19
+ return cached
20
+ loop = asyncio.get_running_loop()
21
+ zinfo = await loop.run_in_executor(None, _get_zone_info, time_zone_str)
22
+ cls._cache[time_zone_str] = zinfo
23
+ return zinfo
24
+
25
+
26
+ def _get_zone_info(time_zone_str: str) -> ZoneInfo:
27
+ """Get a time zone object for the given time zone string."""
28
+ return ZoneInfo(time_zone_str)
kasa/cli/common.py CHANGED
@@ -201,6 +201,8 @@ def CatchAllExceptions(cls):
201
201
  # Handle exit request from click.
202
202
  if isinstance(exc, click.exceptions.Exit):
203
203
  sys.exit(exc.exit_code)
204
+ if isinstance(exc, click.exceptions.Abort):
205
+ sys.exit(0)
204
206
 
205
207
  echo(f"Raised error: {exc}")
206
208
  if debug:
kasa/cli/device.py CHANGED
@@ -40,7 +40,7 @@ async def state(ctx, dev: Device):
40
40
  echo(f"Port: {dev.port}")
41
41
  echo(f"Device state: {dev.is_on}")
42
42
 
43
- echo(f"Time: {dev.time} (tz: {dev.timezone}")
43
+ echo(f"Time: {dev.time} (tz: {dev.timezone})")
44
44
  echo(f"Hardware: {dev.hw_info['hw_ver']}")
45
45
  echo(f"Software: {dev.hw_info['sw_ver']}")
46
46
  echo(f"MAC (rssi): {dev.mac} ({dev.rssi})")
kasa/cli/discover.py CHANGED
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import asyncio
6
+ from pprint import pformat as pf
6
7
 
7
8
  import asyncclick as click
8
9
  from pydantic.v1 import ValidationError
@@ -16,26 +17,24 @@ from kasa import (
16
17
  )
17
18
  from kasa.discover import DiscoveryResult
18
19
 
19
- from .common import echo
20
+ from .common import echo, error
20
21
 
21
22
 
22
- @click.command()
23
+ @click.group(invoke_without_command=True)
23
24
  @click.pass_context
24
25
  async def discover(ctx):
25
26
  """Discover devices in the network."""
26
- target = ctx.parent.params["target"]
27
- username = ctx.parent.params["username"]
28
- password = ctx.parent.params["password"]
29
- discovery_timeout = ctx.parent.params["discovery_timeout"]
30
- timeout = ctx.parent.params["timeout"]
31
- port = ctx.parent.params["port"]
27
+ if ctx.invoked_subcommand is None:
28
+ return await ctx.invoke(detail)
32
29
 
33
- credentials = Credentials(username, password) if username and password else None
34
30
 
35
- sem = asyncio.Semaphore()
36
- discovered = dict()
31
+ @discover.command()
32
+ @click.pass_context
33
+ async def detail(ctx):
34
+ """Discover devices in the network using udp broadcasts."""
37
35
  unsupported = []
38
36
  auth_failed = []
37
+ sem = asyncio.Semaphore()
39
38
 
40
39
  async def print_unsupported(unsupported_exception: UnsupportedDeviceError):
41
40
  unsupported.append(unsupported_exception)
@@ -49,8 +48,6 @@ async def discover(ctx):
49
48
  echo(f"\t{unsupported_exception}")
50
49
  echo()
51
50
 
52
- echo(f"Discovering devices on {target} for {discovery_timeout} seconds")
53
-
54
51
  from .device import state
55
52
 
56
53
  async def print_discovered(dev: Device):
@@ -65,9 +62,73 @@ async def discover(ctx):
65
62
  else:
66
63
  ctx.parent.obj = dev
67
64
  await ctx.parent.invoke(state)
68
- discovered[dev.host] = dev.internal_state
69
65
  echo()
70
66
 
67
+ discovered = await _discover(ctx, print_discovered, print_unsupported)
68
+ if ctx.parent.parent.params["host"]:
69
+ return discovered
70
+
71
+ echo(f"Found {len(discovered)} devices")
72
+ if unsupported:
73
+ echo(f"Found {len(unsupported)} unsupported devices")
74
+ if auth_failed:
75
+ echo(f"Found {len(auth_failed)} devices that failed to authenticate")
76
+
77
+ return discovered
78
+
79
+
80
+ @discover.command()
81
+ @click.pass_context
82
+ async def list(ctx):
83
+ """List devices in the network in a table using udp broadcasts."""
84
+ sem = asyncio.Semaphore()
85
+
86
+ async def print_discovered(dev: Device):
87
+ cparams = dev.config.connection_type
88
+ infostr = (
89
+ f"{dev.host:<15} {cparams.device_family.value:<20} "
90
+ f"{cparams.encryption_type.value:<7}"
91
+ )
92
+ async with sem:
93
+ try:
94
+ await dev.update()
95
+ except AuthenticationError:
96
+ echo(f"{infostr} - Authentication failed")
97
+ else:
98
+ echo(f"{infostr} {dev.alias}")
99
+
100
+ async def print_unsupported(unsupported_exception: UnsupportedDeviceError):
101
+ if host := unsupported_exception.host:
102
+ echo(f"{host:<15} UNSUPPORTED DEVICE")
103
+
104
+ echo(f"{'HOST':<15} {'DEVICE FAMILY':<20} {'ENCRYPT':<7} {'ALIAS'}")
105
+ return await _discover(ctx, print_discovered, print_unsupported, do_echo=False)
106
+
107
+
108
+ async def _discover(ctx, print_discovered, print_unsupported, *, do_echo=True):
109
+ params = ctx.parent.parent.params
110
+ target = params["target"]
111
+ username = params["username"]
112
+ password = params["password"]
113
+ discovery_timeout = params["discovery_timeout"]
114
+ timeout = params["timeout"]
115
+ host = params["host"]
116
+ port = params["port"]
117
+
118
+ credentials = Credentials(username, password) if username and password else None
119
+
120
+ if host:
121
+ echo(f"Discovering device {host} for {discovery_timeout} seconds")
122
+ return await Discover.discover_single(
123
+ host,
124
+ port=port,
125
+ credentials=credentials,
126
+ timeout=timeout,
127
+ discovery_timeout=discovery_timeout,
128
+ on_unsupported=print_unsupported,
129
+ )
130
+ if do_echo:
131
+ echo(f"Discovering devices on {target} for {discovery_timeout} seconds")
71
132
  discovered_devices = await Discover.discover(
72
133
  target=target,
73
134
  discovery_timeout=discovery_timeout,
@@ -81,13 +142,42 @@ async def discover(ctx):
81
142
  for device in discovered_devices.values():
82
143
  await device.protocol.close()
83
144
 
84
- echo(f"Found {len(discovered)} devices")
85
- if unsupported:
86
- echo(f"Found {len(unsupported)} unsupported devices")
87
- if auth_failed:
88
- echo(f"Found {len(auth_failed)} devices that failed to authenticate")
145
+ return discovered_devices
89
146
 
90
- return discovered
147
+
148
+ @discover.command()
149
+ @click.pass_context
150
+ async def config(ctx):
151
+ """Bypass udp discovery and try to show connection config for a device.
152
+
153
+ Bypasses udp discovery and shows the parameters required to connect
154
+ directly to the device.
155
+ """
156
+ params = ctx.parent.parent.params
157
+ username = params["username"]
158
+ password = params["password"]
159
+ timeout = params["timeout"]
160
+ host = params["host"]
161
+ port = params["port"]
162
+
163
+ if not host:
164
+ error("--host option must be supplied to discover config")
165
+
166
+ credentials = Credentials(username, password) if username and password else None
167
+
168
+ dev = await Discover.try_connect_all(
169
+ host, credentials=credentials, timeout=timeout, port=port
170
+ )
171
+ if dev:
172
+ cparams = dev.config.connection_type
173
+ echo("Managed to connect, cli options to connect are:")
174
+ echo(
175
+ f"--device-family {cparams.device_family.value} "
176
+ f"--encrypt-type {cparams.encryption_type.value} "
177
+ f"{'--https' if cparams.https else '--no-https'}"
178
+ )
179
+ else:
180
+ error(f"Unable to connect to {host}")
91
181
 
92
182
 
93
183
  def _echo_dictionary(discovery_info: dict):
@@ -113,21 +203,31 @@ def _echo_discovery_info(discovery_info):
113
203
  _echo_dictionary(discovery_info)
114
204
  return
115
205
 
206
+ def _conditional_echo(label, value):
207
+ if value:
208
+ ws = " " * (19 - len(label))
209
+ echo(f"\t{label}:{ws}{value}")
210
+
116
211
  echo("\t[bold]== Discovery Result ==[/bold]")
117
- echo(f"\tDevice Type: {dr.device_type}")
118
- echo(f"\tDevice Model: {dr.device_model}")
119
- echo(f"\tIP: {dr.ip}")
120
- echo(f"\tMAC: {dr.mac}")
121
- echo(f"\tDevice Id (hash): {dr.device_id}")
122
- echo(f"\tOwner (hash): {dr.owner}")
123
- echo(f"\tHW Ver: {dr.hw_ver}")
124
- echo(f"\tSupports IOT Cloud: {dr.is_support_iot_cloud}")
125
- echo(f"\tOBD Src: {dr.obd_src}")
126
- echo(f"\tFactory Default: {dr.factory_default}")
127
- echo(f"\tEncrypt Type: {dr.mgt_encrypt_schm.encrypt_type}")
128
- echo(f"\tSupports HTTPS: {dr.mgt_encrypt_schm.is_support_https}")
129
- echo(f"\tHTTP Port: {dr.mgt_encrypt_schm.http_port}")
130
- echo(f"\tLV (Login Level): {dr.mgt_encrypt_schm.lv}")
212
+ _conditional_echo("Device Type", dr.device_type)
213
+ _conditional_echo("Device Model", dr.device_model)
214
+ _conditional_echo("Device Name", dr.device_name)
215
+ _conditional_echo("IP", dr.ip)
216
+ _conditional_echo("MAC", dr.mac)
217
+ _conditional_echo("Device Id (hash)", dr.device_id)
218
+ _conditional_echo("Owner (hash)", dr.owner)
219
+ _conditional_echo("FW Ver", dr.firmware_version)
220
+ _conditional_echo("HW Ver", dr.hw_ver)
221
+ _conditional_echo("HW Ver", dr.hardware_version)
222
+ _conditional_echo("Supports IOT Cloud", dr.is_support_iot_cloud)
223
+ _conditional_echo("OBD Src", dr.owner)
224
+ _conditional_echo("Factory Default", dr.factory_default)
225
+ _conditional_echo("Encrypt Type", dr.mgt_encrypt_schm.encrypt_type)
226
+ _conditional_echo("Encrypt Type", dr.encrypt_type)
227
+ _conditional_echo("Supports HTTPS", dr.mgt_encrypt_schm.is_support_https)
228
+ _conditional_echo("HTTP Port", dr.mgt_encrypt_schm.http_port)
229
+ _conditional_echo("Encrypt info", pf(dr.encrypt_info) if dr.encrypt_info else None)
230
+ _conditional_echo("Decrypted", pf(dr.decrypted_data) if dr.decrypted_data else None)
131
231
 
132
232
 
133
233
  async def find_host_from_alias(alias, target="255.255.255.255", timeout=1, attempts=3):
kasa/cli/main.py CHANGED
@@ -16,6 +16,7 @@ if TYPE_CHECKING:
16
16
  from kasa import Device
17
17
 
18
18
  from kasa.deviceconfig import DeviceEncryptionType
19
+ from kasa.experimental import Experimental
19
20
 
20
21
  from .common import (
21
22
  SKIP_UPDATE_COMMANDS,
@@ -35,9 +36,11 @@ TYPES = [
35
36
  "strip",
36
37
  "lightstrip",
37
38
  "smart",
39
+ "camera",
38
40
  ]
39
41
 
40
42
  ENCRYPT_TYPES = [encrypt_type.value for encrypt_type in DeviceEncryptionType]
43
+ DEFAULT_TARGET = "255.255.255.255"
41
44
 
42
45
 
43
46
  def _legacy_type_to_class(_type):
@@ -114,7 +117,7 @@ def _legacy_type_to_class(_type):
114
117
  @click.option(
115
118
  "--target",
116
119
  envvar="KASA_TARGET",
117
- default="255.255.255.255",
120
+ default=DEFAULT_TARGET,
118
121
  required=False,
119
122
  show_default=True,
120
123
  help="The broadcast address to be used for discovery.",
@@ -158,6 +161,7 @@ def _legacy_type_to_class(_type):
158
161
  type=click.Choice(ENCRYPT_TYPES, case_sensitive=False),
159
162
  )
160
163
  @click.option(
164
+ "-df",
161
165
  "--device-family",
162
166
  envvar="KASA_DEVICE_FAMILY",
163
167
  default="SMART.TAPOPLUG",
@@ -171,6 +175,14 @@ def _legacy_type_to_class(_type):
171
175
  type=int,
172
176
  help="The login version for device authentication. Defaults to 2",
173
177
  )
178
+ @click.option(
179
+ "--https/--no-https",
180
+ envvar="KASA_HTTPS",
181
+ default=False,
182
+ is_flag=True,
183
+ type=bool,
184
+ help="Set flag if the device encryption uses https.",
185
+ )
174
186
  @click.option(
175
187
  "--timeout",
176
188
  envvar="KASA_TIMEOUT",
@@ -182,7 +194,7 @@ def _legacy_type_to_class(_type):
182
194
  @click.option(
183
195
  "--discovery-timeout",
184
196
  envvar="KASA_DISCOVERY_TIMEOUT",
185
- default=5,
197
+ default=10,
186
198
  required=False,
187
199
  show_default=True,
188
200
  help="Timeout for discovery.",
@@ -208,6 +220,14 @@ def _legacy_type_to_class(_type):
208
220
  envvar="KASA_CREDENTIALS_HASH",
209
221
  help="Hashed credentials used to authenticate to the device.",
210
222
  )
223
+ @click.option(
224
+ "--experimental/--no-experimental",
225
+ default=None,
226
+ is_flag=True,
227
+ type=bool,
228
+ envvar=Experimental.ENV_VAR,
229
+ help="Enable experimental mode for devices not yet fully supported.",
230
+ )
211
231
  @click.version_option(package_name="python-kasa")
212
232
  @click.pass_context
213
233
  async def cli(
@@ -220,6 +240,7 @@ async def cli(
220
240
  debug,
221
241
  type,
222
242
  encrypt_type,
243
+ https,
223
244
  device_family,
224
245
  login_version,
225
246
  json,
@@ -228,6 +249,7 @@ async def cli(
228
249
  username,
229
250
  password,
230
251
  credentials_hash,
252
+ experimental,
231
253
  ):
232
254
  """A tool for controlling TP-Link smart home devices.""" # noqa
233
255
  # no need to perform any checks if we are just displaying the help
@@ -236,6 +258,15 @@ async def cli(
236
258
  ctx.obj = object()
237
259
  return
238
260
 
261
+ if target != DEFAULT_TARGET and host:
262
+ error("--target is not a valid option for single host discovery")
263
+
264
+ if experimental is not None:
265
+ Experimental.set_enabled(experimental)
266
+
267
+ if Experimental.enabled():
268
+ echo("Experimental support is enabled")
269
+
239
270
  logging_config: dict[str, Any] = {
240
271
  "level": logging.DEBUG if debug > 0 else logging.INFO
241
272
  }
@@ -294,12 +325,21 @@ async def cli(
294
325
  return await ctx.invoke(discover)
295
326
 
296
327
  device_updated = False
297
- if type is not None and type != "smart":
328
+ if type is not None and type not in {"smart", "camera"}:
298
329
  from kasa.deviceconfig import DeviceConfig
299
330
 
300
331
  config = DeviceConfig(host=host, port_override=port, timeout=timeout)
301
332
  dev = _legacy_type_to_class(type)(host, config=config)
302
- elif type == "smart" or (device_family and encrypt_type):
333
+ elif type in {"smart", "camera"} or (device_family and encrypt_type):
334
+ if type == "camera":
335
+ if not experimental:
336
+ error(
337
+ "Camera is an experimental type, please enable with --experimental"
338
+ )
339
+ encrypt_type = "AES"
340
+ https = True
341
+ device_family = "SMART.IPCAMERA"
342
+
303
343
  from kasa.device import Device
304
344
  from kasa.deviceconfig import (
305
345
  DeviceConfig,
@@ -310,10 +350,12 @@ async def cli(
310
350
 
311
351
  if not encrypt_type:
312
352
  encrypt_type = "KLAP"
353
+
313
354
  ctype = DeviceConnectionParameters(
314
355
  DeviceFamily(device_family),
315
356
  DeviceEncryptionType(encrypt_type),
316
357
  login_version,
358
+ https,
317
359
  )
318
360
  config = DeviceConfig(
319
361
  host=host,
@@ -326,15 +368,11 @@ async def cli(
326
368
  dev = await Device.connect(config=config)
327
369
  device_updated = True
328
370
  else:
329
- from kasa.discover import Discover
371
+ from .discover import discover
330
372
 
331
- dev = await Discover.discover_single(
332
- host,
333
- port=port,
334
- credentials=credentials,
335
- timeout=timeout,
336
- discovery_timeout=discovery_timeout,
337
- )
373
+ dev = await ctx.invoke(discover)
374
+ if not dev:
375
+ error(f"Unable to create device for {host}")
338
376
 
339
377
  # Skip update on specific commands, or if device factory,
340
378
  # that performs an update was used for the device.