python-kasa 0.7.7__py3-none-any.whl → 0.8.1__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 (115) hide show
  1. kasa/__init__.py +30 -29
  2. kasa/cachedzoneinfo.py +0 -1
  3. kasa/cli/common.py +16 -8
  4. kasa/cli/device.py +1 -1
  5. kasa/cli/discover.py +50 -16
  6. kasa/cli/feature.py +10 -2
  7. kasa/cli/lazygroup.py +5 -3
  8. kasa/cli/light.py +37 -20
  9. kasa/cli/main.py +19 -36
  10. kasa/cli/schedule.py +1 -1
  11. kasa/cli/time.py +2 -2
  12. kasa/cli/usage.py +21 -42
  13. kasa/cli/wifi.py +1 -1
  14. kasa/credentials.py +17 -0
  15. kasa/device.py +83 -54
  16. kasa/device_factory.py +22 -50
  17. kasa/deviceconfig.py +58 -104
  18. kasa/discover.py +115 -83
  19. kasa/emeterstatus.py +2 -2
  20. kasa/exceptions.py +6 -6
  21. kasa/feature.py +20 -14
  22. kasa/httpclient.py +5 -4
  23. kasa/interfaces/__init__.py +3 -0
  24. kasa/interfaces/energy.py +18 -11
  25. kasa/interfaces/fan.py +6 -3
  26. kasa/interfaces/led.py +2 -2
  27. kasa/interfaces/light.py +9 -9
  28. kasa/interfaces/lighteffect.py +4 -3
  29. kasa/interfaces/lightpreset.py +3 -3
  30. kasa/interfaces/thermostat.py +65 -0
  31. kasa/iot/iotbulb.py +35 -33
  32. kasa/iot/iotdevice.py +117 -27
  33. kasa/iot/iotdimmer.py +17 -13
  34. kasa/iot/iotlightstrip.py +2 -2
  35. kasa/iot/iotmodule.py +13 -5
  36. kasa/iot/iotplug.py +5 -4
  37. kasa/iot/iotstrip.py +34 -21
  38. kasa/iot/iottimezone.py +0 -1
  39. kasa/iot/modules/ambientlight.py +5 -5
  40. kasa/iot/modules/cloud.py +23 -18
  41. kasa/iot/modules/emeter.py +7 -3
  42. kasa/iot/modules/led.py +2 -2
  43. kasa/iot/modules/light.py +4 -2
  44. kasa/iot/modules/lighteffect.py +5 -5
  45. kasa/iot/modules/lightpreset.py +30 -20
  46. kasa/iot/modules/motion.py +5 -5
  47. kasa/iot/modules/rulemodule.py +20 -19
  48. kasa/iot/modules/time.py +6 -6
  49. kasa/iot/modules/usage.py +18 -14
  50. kasa/json.py +17 -2
  51. kasa/module.py +101 -12
  52. kasa/modulemapping.pyi +1 -3
  53. kasa/protocols/__init__.py +12 -0
  54. kasa/{iotprotocol.py → protocols/iotprotocol.py} +10 -6
  55. kasa/{protocol.py → protocols/protocol.py} +9 -65
  56. kasa/{experimental/smartcameraprotocol.py → protocols/smartcamprotocol.py} +12 -10
  57. kasa/{smartprotocol.py → protocols/smartprotocol.py} +18 -11
  58. kasa/smart/effects.py +3 -1
  59. kasa/smart/modules/__init__.py +2 -0
  60. kasa/smart/modules/alarm.py +3 -3
  61. kasa/smart/modules/autooff.py +4 -4
  62. kasa/smart/modules/batterysensor.py +3 -3
  63. kasa/smart/modules/brightness.py +6 -4
  64. kasa/smart/modules/childprotection.py +1 -1
  65. kasa/smart/modules/cloud.py +2 -2
  66. kasa/smart/modules/color.py +2 -2
  67. kasa/smart/modules/colortemperature.py +3 -3
  68. kasa/smart/modules/contactsensor.py +2 -2
  69. kasa/smart/modules/devicemodule.py +1 -1
  70. kasa/smart/modules/energy.py +44 -19
  71. kasa/smart/modules/fan.py +11 -6
  72. kasa/smart/modules/firmware.py +34 -34
  73. kasa/smart/modules/frostprotection.py +1 -1
  74. kasa/smart/modules/humiditysensor.py +2 -2
  75. kasa/smart/modules/led.py +4 -4
  76. kasa/smart/modules/light.py +22 -8
  77. kasa/smart/modules/lighteffect.py +5 -5
  78. kasa/smart/modules/lightpreset.py +10 -8
  79. kasa/smart/modules/lightstripeffect.py +9 -8
  80. kasa/smart/modules/lighttransition.py +28 -11
  81. kasa/smart/modules/motionsensor.py +2 -2
  82. kasa/smart/modules/reportmode.py +2 -2
  83. kasa/smart/modules/temperaturecontrol.py +5 -17
  84. kasa/smart/modules/temperaturesensor.py +5 -3
  85. kasa/smart/modules/thermostat.py +74 -0
  86. kasa/smart/modules/time.py +5 -6
  87. kasa/smart/modules/triggerlogs.py +9 -6
  88. kasa/smart/modules/waterleaksensor.py +1 -1
  89. kasa/smart/smartchilddevice.py +25 -15
  90. kasa/smart/smartdevice.py +127 -36
  91. kasa/smart/smartmodule.py +12 -14
  92. kasa/smartcam/__init__.py +5 -0
  93. kasa/{experimental → smartcam}/modules/__init__.py +7 -1
  94. kasa/smartcam/modules/alarm.py +166 -0
  95. kasa/{experimental → smartcam}/modules/camera.py +30 -3
  96. kasa/{experimental → smartcam}/modules/childdevice.py +3 -2
  97. kasa/{experimental → smartcam}/modules/device.py +2 -2
  98. kasa/smartcam/modules/led.py +28 -0
  99. kasa/smartcam/modules/pantilt.py +107 -0
  100. kasa/{experimental → smartcam}/modules/time.py +4 -5
  101. kasa/{experimental/smartcamera.py → smartcam/smartcamdevice.py} +95 -31
  102. kasa/{experimental/smartcameramodule.py → smartcam/smartcammodule.py} +16 -13
  103. kasa/transports/__init__.py +16 -0
  104. kasa/{aestransport.py → transports/aestransport.py} +32 -25
  105. kasa/transports/basetransport.py +55 -0
  106. kasa/{klaptransport.py → transports/klaptransport.py} +38 -27
  107. kasa/{experimental → transports}/sslaestransport.py +16 -11
  108. kasa/{xortransport.py → transports/xortransport.py} +6 -8
  109. {python_kasa-0.7.7.dist-info → python_kasa-0.8.1.dist-info}/METADATA +19 -23
  110. python_kasa-0.8.1.dist-info/RECORD +127 -0
  111. {python_kasa-0.7.7.dist-info → python_kasa-0.8.1.dist-info}/WHEEL +1 -1
  112. kasa/experimental/__init__.py +0 -28
  113. python_kasa-0.7.7.dist-info/RECORD +0 -119
  114. {python_kasa-0.7.7.dist-info → python_kasa-0.8.1.dist-info}/entry_points.txt +0 -0
  115. {python_kasa-0.7.7.dist-info → python_kasa-0.8.1.dist-info}/licenses/LICENSE +0 -0
kasa/__init__.py CHANGED
@@ -13,7 +13,7 @@ to be handled by the user of the library.
13
13
  """
14
14
 
15
15
  from importlib.metadata import version
16
- from typing import TYPE_CHECKING
16
+ from typing import TYPE_CHECKING, Any
17
17
  from warnings import warn
18
18
 
19
19
  from kasa.credentials import Credentials
@@ -36,13 +36,11 @@ from kasa.exceptions import (
36
36
  )
37
37
  from kasa.feature import Feature
38
38
  from kasa.interfaces.light import HSV, ColorTempRange, Light, LightState
39
- from kasa.iotprotocol import (
40
- IotProtocol,
41
- _deprecated_TPLinkSmartHomeProtocol, # noqa: F401
42
- )
39
+ from kasa.interfaces.thermostat import Thermostat, ThermostatState
43
40
  from kasa.module import Module
44
- from kasa.protocol import BaseProtocol, BaseTransport
45
- from kasa.smartprotocol import SmartProtocol
41
+ from kasa.protocols import BaseProtocol, IotProtocol, SmartProtocol
42
+ from kasa.protocols.iotprotocol import _deprecated_TPLinkSmartHomeProtocol # noqa: F401
43
+ from kasa.transports import BaseTransport
46
44
 
47
45
  __version__ = version("python-kasa")
48
46
 
@@ -75,6 +73,8 @@ __all__ = [
75
73
  "DeviceConnectionParameters",
76
74
  "DeviceEncryptionType",
77
75
  "DeviceFamily",
76
+ "ThermostatState",
77
+ "Thermostat",
78
78
  ]
79
79
 
80
80
  from . import iot
@@ -100,28 +100,29 @@ deprecated_classes = {
100
100
  "DeviceFamilyType": DeviceFamily,
101
101
  }
102
102
 
103
-
104
- def __getattr__(name):
105
- if name in deprecated_names:
106
- warn(f"{name} is deprecated", DeprecationWarning, stacklevel=2)
107
- return globals()[f"_deprecated_{name}"]
108
- if name in deprecated_smart_devices:
109
- new_class = deprecated_smart_devices[name]
110
- package_name = ".".join(new_class.__module__.split(".")[:-1])
111
- warn(
112
- f"{name} is deprecated, use {new_class.__name__} "
113
- + f"from package {package_name} instead or use Discover.discover_single()"
114
- + " and Device.connect() to support new protocols",
115
- DeprecationWarning,
116
- stacklevel=2,
117
- )
118
- return new_class
119
- if name in deprecated_classes:
120
- new_class = deprecated_classes[name]
121
- msg = f"{name} is deprecated, use {new_class.__name__} instead"
122
- warn(msg, DeprecationWarning, stacklevel=2)
123
- return new_class
124
- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
103
+ if not TYPE_CHECKING:
104
+
105
+ def __getattr__(name: str) -> Any:
106
+ if name in deprecated_names:
107
+ warn(f"{name} is deprecated", DeprecationWarning, stacklevel=2)
108
+ return globals()[f"_deprecated_{name}"]
109
+ if name in deprecated_smart_devices:
110
+ new_class = deprecated_smart_devices[name]
111
+ package_name = ".".join(new_class.__module__.split(".")[:-1])
112
+ warn(
113
+ f"{name} is deprecated, use {new_class.__name__} from "
114
+ + f"package {package_name} instead or use Discover.discover_single()"
115
+ + " and Device.connect() to support new protocols",
116
+ DeprecationWarning,
117
+ stacklevel=2,
118
+ )
119
+ return new_class
120
+ if name in deprecated_classes:
121
+ new_class = deprecated_classes[name] # type: ignore[assignment]
122
+ msg = f"{name} is deprecated, use {new_class.__name__} instead"
123
+ warn(msg, DeprecationWarning, stacklevel=2)
124
+ return new_class
125
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
125
126
 
126
127
 
127
128
  if TYPE_CHECKING:
kasa/cachedzoneinfo.py CHANGED
@@ -3,7 +3,6 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import asyncio
6
-
7
6
  from zoneinfo import ZoneInfo
8
7
 
9
8
 
kasa/cli/common.py CHANGED
@@ -5,9 +5,10 @@ from __future__ import annotations
5
5
  import json
6
6
  import re
7
7
  import sys
8
+ from collections.abc import Callable
8
9
  from contextlib import contextmanager
9
10
  from functools import singledispatch, update_wrapper, wraps
10
- from typing import Final
11
+ from typing import TYPE_CHECKING, Any, Final
11
12
 
12
13
  import asyncclick as click
13
14
 
@@ -37,7 +38,7 @@ except ImportError:
37
38
  """Strip rich formatting from messages."""
38
39
 
39
40
  @wraps(echo_func)
40
- def wrapper(message=None, *args, **kwargs):
41
+ def wrapper(message=None, *args, **kwargs) -> None:
41
42
  if message is not None:
42
43
  message = rich_formatting.sub("", message)
43
44
  echo_func(message, *args, **kwargs)
@@ -47,20 +48,20 @@ except ImportError:
47
48
  _echo = _strip_rich_formatting(click.echo)
48
49
 
49
50
 
50
- def echo(*args, **kwargs):
51
+ def echo(*args, **kwargs) -> None:
51
52
  """Print a message."""
52
53
  ctx = click.get_current_context().find_root()
53
54
  if "json" not in ctx.params or ctx.params["json"] is False:
54
55
  _echo(*args, **kwargs)
55
56
 
56
57
 
57
- def error(msg: str):
58
+ def error(msg: str) -> None:
58
59
  """Print an error and exit."""
59
60
  echo(f"[bold red]{msg}[/bold red]")
60
61
  sys.exit(1)
61
62
 
62
63
 
63
- def json_formatter_cb(result, **kwargs):
64
+ def json_formatter_cb(result: Any, **kwargs) -> None:
64
65
  """Format and output the result as JSON, if requested."""
65
66
  if not kwargs.get("json"):
66
67
  return
@@ -82,7 +83,7 @@ def json_formatter_cb(result, **kwargs):
82
83
  print(json_content)
83
84
 
84
85
 
85
- def pass_dev_or_child(wrapped_function):
86
+ def pass_dev_or_child(wrapped_function: Callable) -> Callable:
86
87
  """Pass the device or child to the click command based on the child options."""
87
88
  child_help = (
88
89
  "Child ID or alias for controlling sub-devices. "
@@ -133,7 +134,10 @@ def pass_dev_or_child(wrapped_function):
133
134
 
134
135
 
135
136
  async def _get_child_device(
136
- device: Device, child_option, child_index_option, info_command
137
+ device: Device,
138
+ child_option: str | None,
139
+ child_index_option: int | None,
140
+ info_command: str | None,
137
141
  ) -> Device | None:
138
142
  def _list_children():
139
143
  return "\n".join(
@@ -178,11 +182,15 @@ async def _get_child_device(
178
182
  f"{child_option} children are:\n{_list_children()}"
179
183
  )
180
184
 
185
+ if TYPE_CHECKING:
186
+ assert isinstance(child_index_option, int)
187
+
181
188
  if child_index_option + 1 > len(device.children) or child_index_option < 0:
182
189
  error(
183
190
  f"Invalid index {child_index_option}, "
184
191
  f"device has {len(device.children)} children"
185
192
  )
193
+
186
194
  child_by_index = device.children[child_index_option]
187
195
  echo(f"Targeting child device {child_by_index.alias}")
188
196
  return child_by_index
@@ -195,7 +203,7 @@ def CatchAllExceptions(cls):
195
203
  https://stackoverflow.com/questions/52213375
196
204
  """
197
205
 
198
- def _handle_exception(debug, exc):
206
+ def _handle_exception(debug, exc) -> None:
199
207
  if isinstance(exc, click.ClickException):
200
208
  raise
201
209
  # Handle exit request from click.
kasa/cli/device.py CHANGED
@@ -22,7 +22,7 @@ from .common import (
22
22
 
23
23
  @click.group()
24
24
  @pass_dev_or_child
25
- def device(dev):
25
+ def device(dev) -> None:
26
26
  """Commands to control basic device settings."""
27
27
 
28
28
 
kasa/cli/discover.py CHANGED
@@ -6,7 +6,6 @@ import asyncio
6
6
  from pprint import pformat as pf
7
7
 
8
8
  import asyncclick as click
9
- from pydantic.v1 import ValidationError
10
9
 
11
10
  from kasa import (
12
11
  AuthenticationError,
@@ -36,7 +35,7 @@ async def detail(ctx):
36
35
  auth_failed = []
37
36
  sem = asyncio.Semaphore()
38
37
 
39
- async def print_unsupported(unsupported_exception: UnsupportedDeviceError):
38
+ async def print_unsupported(unsupported_exception: UnsupportedDeviceError) -> None:
40
39
  unsupported.append(unsupported_exception)
41
40
  async with sem:
42
41
  if unsupported_exception.discovery_result:
@@ -50,7 +49,7 @@ async def detail(ctx):
50
49
 
51
50
  from .device import state
52
51
 
53
- async def print_discovered(dev: Device):
52
+ async def print_discovered(dev: Device) -> None:
54
53
  async with sem:
55
54
  try:
56
55
  await dev.update()
@@ -189,7 +188,7 @@ async def config(ctx):
189
188
  error(f"Unable to connect to {host}")
190
189
 
191
190
 
192
- def _echo_dictionary(discovery_info: dict):
191
+ def _echo_dictionary(discovery_info: dict) -> None:
193
192
  echo("\t[bold]== Discovery information ==[/bold]")
194
193
  for key, value in discovery_info.items():
195
194
  key_name = " ".join(x.capitalize() or "_" for x in key.split("_"))
@@ -197,7 +196,7 @@ def _echo_dictionary(discovery_info: dict):
197
196
  echo(f"\t{key_name_and_spaces}{value}")
198
197
 
199
198
 
200
- def _echo_discovery_info(discovery_info):
199
+ def _echo_discovery_info(discovery_info) -> None:
201
200
  # We don't have discovery info when all connection params are passed manually
202
201
  if discovery_info is None:
203
202
  return
@@ -207,8 +206,8 @@ def _echo_discovery_info(discovery_info):
207
206
  return
208
207
 
209
208
  try:
210
- dr = DiscoveryResult(**discovery_info)
211
- except ValidationError:
209
+ dr = DiscoveryResult.from_dict(discovery_info)
210
+ except Exception:
212
211
  _echo_dictionary(discovery_info)
213
212
  return
214
213
 
@@ -239,13 +238,48 @@ def _echo_discovery_info(discovery_info):
239
238
  _conditional_echo("Decrypted", pf(dr.decrypted_data) if dr.decrypted_data else None)
240
239
 
241
240
 
242
- async def find_host_from_alias(alias, target="255.255.255.255", timeout=1, attempts=3):
241
+ async def find_dev_from_alias(
242
+ alias: str,
243
+ credentials: Credentials | None,
244
+ target: str = "255.255.255.255",
245
+ timeout: int = 5,
246
+ attempts: int = 3,
247
+ ) -> Device | None:
243
248
  """Discover a device identified by its alias."""
244
- for _attempt in range(1, attempts):
245
- found_devs = await Discover.discover(target=target, timeout=timeout)
246
- for _ip, dev in found_devs.items():
247
- if dev.alias.lower() == alias.lower():
248
- host = dev.host
249
- return host
250
-
251
- return None
249
+ found_event = asyncio.Event()
250
+ found_device = []
251
+ seen_hosts = set()
252
+
253
+ async def on_discovered(dev: Device):
254
+ if dev.host in seen_hosts:
255
+ return
256
+ seen_hosts.add(dev.host)
257
+ try:
258
+ await dev.update()
259
+ except Exception as ex:
260
+ echo(f"Error querying device {dev.host}: {ex}")
261
+ return
262
+ finally:
263
+ await dev.protocol.close()
264
+ if not dev.alias:
265
+ echo(f"Skipping device {dev.host} with no alias")
266
+ return
267
+ if dev.alias.lower() == alias.lower():
268
+ found_device.append(dev)
269
+ found_event.set()
270
+
271
+ async def do_discover():
272
+ for _ in range(1, attempts):
273
+ await Discover.discover(
274
+ target=target,
275
+ timeout=timeout,
276
+ credentials=credentials,
277
+ on_discovered=on_discovered,
278
+ )
279
+ if found_event.is_set():
280
+ break
281
+ found_event.set()
282
+
283
+ asyncio.create_task(do_discover())
284
+ await found_event.wait()
285
+ return found_device[0] if found_device else None
kasa/cli/feature.py CHANGED
@@ -24,7 +24,7 @@ def _echo_features(
24
24
  category: Feature.Category | None = None,
25
25
  verbose: bool = False,
26
26
  indent: str = "\t",
27
- ):
27
+ ) -> None:
28
28
  """Print out a listing of features and their values."""
29
29
  if category is not None:
30
30
  features = {
@@ -43,7 +43,9 @@ def _echo_features(
43
43
  echo(f"{indent}{feat.name} ({feat.id}): [red]got exception ({ex})[/red]")
44
44
 
45
45
 
46
- def _echo_all_features(features, *, verbose=False, title_prefix=None, indent=""):
46
+ def _echo_all_features(
47
+ features, *, verbose=False, title_prefix=None, indent=""
48
+ ) -> None:
47
49
  """Print out all features by category."""
48
50
  if title_prefix is not None:
49
51
  echo(f"[bold]\n{indent}== {title_prefix} ==[/bold]")
@@ -120,6 +122,12 @@ async def feature(
120
122
 
121
123
  feat = dev.features[name]
122
124
 
125
+ if value is None and feat.type is Feature.Type.Action:
126
+ echo(f"Executing action {name}")
127
+ response = await dev.features[name].set_value(value)
128
+ echo(response)
129
+ return response
130
+
123
131
  if value is None:
124
132
  unit = f" {feat.unit}" if feat.unit else ""
125
133
  echo(f"{feat.name} ({name}): {feat.value}{unit}")
kasa/cli/lazygroup.py CHANGED
@@ -3,6 +3,8 @@
3
3
  Taken from the click help files.
4
4
  """
5
5
 
6
+ from __future__ import annotations
7
+
6
8
  import importlib
7
9
 
8
10
  import asyncclick as click
@@ -11,7 +13,7 @@ import asyncclick as click
11
13
  class LazyGroup(click.Group):
12
14
  """Lazy group class."""
13
15
 
14
- def __init__(self, *args, lazy_subcommands=None, **kwargs):
16
+ def __init__(self, *args, lazy_subcommands=None, **kwargs) -> None:
15
17
  super().__init__(*args, **kwargs)
16
18
  # lazy_subcommands is a map of the form:
17
19
  #
@@ -31,9 +33,9 @@ class LazyGroup(click.Group):
31
33
  return self._lazy_load(cmd_name)
32
34
  return super().get_command(ctx, cmd_name)
33
35
 
34
- def format_commands(self, ctx, formatter):
36
+ def format_commands(self, ctx, formatter) -> None:
35
37
  """Format the top level help output."""
36
- sections = {}
38
+ sections: dict[str, list] = {}
37
39
  for cmd, parent in self.lazy_subcommands.items():
38
40
  sections.setdefault(parent, [])
39
41
  cmd_obj = self.get_command(ctx, cmd)
kasa/cli/light.py CHANGED
@@ -15,7 +15,7 @@ from .common import echo, error, pass_dev_or_child
15
15
 
16
16
  @click.group()
17
17
  @pass_dev_or_child
18
- def light(dev):
18
+ def light(dev) -> None:
19
19
  """Commands to control light settings."""
20
20
 
21
21
 
@@ -127,43 +127,60 @@ async def presets(ctx, dev):
127
127
  def presets_list(dev: Device):
128
128
  """List presets."""
129
129
  if not (light_preset := dev.modules.get(Module.LightPreset)):
130
- error("Presets not supported on device")
130
+ error("Device does not support light presets")
131
131
  return
132
132
 
133
- for preset in light_preset.preset_states_list:
134
- echo(preset)
133
+ for idx, preset in enumerate(light_preset.preset_states_list):
134
+ echo(
135
+ f"[{idx}] Hue: {preset.hue or '':3} "
136
+ f"Saturation: {preset.saturation or '':3} "
137
+ f"Brightness/Value: {preset.brightness or '':3} "
138
+ f"Temp: {preset.color_temp or '':4}"
139
+ )
135
140
 
136
141
  return light_preset.preset_states_list
137
142
 
138
143
 
139
144
  @presets.command(name="modify")
140
145
  @click.argument("index", type=int)
141
- @click.option("--brightness", type=int)
142
- @click.option("--hue", type=int)
143
- @click.option("--saturation", type=int)
144
- @click.option("--temperature", type=int)
146
+ @click.option("--brightness", type=int, required=False, default=None)
147
+ @click.option("--hue", type=int, required=False, default=None)
148
+ @click.option("--saturation", type=int, required=False, default=None)
149
+ @click.option("--temperature", type=int, required=False, default=None)
145
150
  @pass_dev_or_child
146
151
  async def presets_modify(dev: Device, index, brightness, hue, saturation, temperature):
147
152
  """Modify a preset."""
148
- for preset in dev.presets:
149
- if preset.index == index:
150
- break
151
- else:
152
- error(f"No preset found for index {index}")
153
+ if not (light_preset := dev.modules.get(Module.LightPreset)):
154
+ error("Device does not support light presets")
155
+ return
156
+
157
+ max_index = len(light_preset.preset_states_list) - 1
158
+ if index > len(light_preset.preset_states_list) - 1:
159
+ error(f"Invalid index, must be between 0 and {max_index}")
160
+ return
161
+
162
+ if all([val is None for val in {brightness, hue, saturation, temperature}]):
163
+ error("Need to supply at least one option to modify.")
153
164
  return
154
165
 
155
- if brightness is not None:
166
+ # Preset names have `Not set`` as the first value
167
+ preset_name = light_preset.preset_list[index + 1]
168
+ preset = light_preset.preset_states_list[index]
169
+
170
+ echo(f"Preset {preset_name} currently: {preset}")
171
+
172
+ if brightness is not None and preset.brightness is not None:
156
173
  preset.brightness = brightness
157
- if hue is not None:
174
+ if hue is not None and preset.hue is not None:
158
175
  preset.hue = hue
159
- if saturation is not None:
176
+ if saturation is not None and preset.saturation is not None:
160
177
  preset.saturation = saturation
161
- if temperature is not None:
178
+ if temperature is not None and preset.temperature is not None:
162
179
  preset.color_temp = temperature
163
180
 
164
- echo(f"Going to save preset: {preset}")
181
+ echo(f"Updating preset {preset_name} to: {preset}")
165
182
 
166
- return await dev.save_preset(preset)
183
+ return await light_preset.save_preset(preset_name, preset)
167
184
 
168
185
 
169
186
  @light.command()
@@ -173,7 +190,7 @@ async def presets_modify(dev: Device, index, brightness, hue, saturation, temper
173
190
  @click.option("--preset", type=int)
174
191
  async def turn_on_behavior(dev: Device, type, last, preset):
175
192
  """Modify bulb turn-on behavior."""
176
- if not dev.is_bulb or not isinstance(dev, IotBulb):
193
+ if dev.device_type is not Device.Type.Bulb or not isinstance(dev, IotBulb):
177
194
  error("Presets only supported on iot bulbs")
178
195
  return
179
196
  settings = await dev.get_turn_on_behavior()
kasa/cli/main.py CHANGED
@@ -16,7 +16,6 @@ if TYPE_CHECKING:
16
16
  from kasa import Device
17
17
 
18
18
  from kasa.deviceconfig import DeviceEncryptionType
19
- from kasa.experimental import Experimental
20
19
 
21
20
  from .common import (
22
21
  SKIP_UPDATE_COMMANDS,
@@ -43,7 +42,7 @@ ENCRYPT_TYPES = [encrypt_type.value for encrypt_type in DeviceEncryptionType]
43
42
  DEFAULT_TARGET = "255.255.255.255"
44
43
 
45
44
 
46
- def _legacy_type_to_class(_type):
45
+ def _legacy_type_to_class(_type: str) -> Any:
47
46
  from kasa.iot import (
48
47
  IotBulb,
49
48
  IotDimmer,
@@ -76,6 +75,7 @@ def _legacy_type_to_class(_type):
76
75
  "time": None,
77
76
  "schedule": None,
78
77
  "usage": None,
78
+ "energy": "usage",
79
79
  # device commands runnnable at top level
80
80
  "state": "device",
81
81
  "on": "device",
@@ -220,14 +220,6 @@ def _legacy_type_to_class(_type):
220
220
  envvar="KASA_CREDENTIALS_HASH",
221
221
  help="Hashed credentials used to authenticate to the device.",
222
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
- )
231
223
  @click.version_option(package_name="python-kasa")
232
224
  @click.pass_context
233
225
  async def cli(
@@ -249,7 +241,6 @@ async def cli(
249
241
  username,
250
242
  password,
251
243
  credentials_hash,
252
- experimental,
253
244
  ):
254
245
  """A tool for controlling TP-Link smart home devices.""" # noqa
255
246
  # no need to perform any checks if we are just displaying the help
@@ -261,12 +252,6 @@ async def cli(
261
252
  if target != DEFAULT_TARGET and host:
262
253
  error("--target is not a valid option for single host discovery")
263
254
 
264
- if experimental is not None:
265
- Experimental.set_enabled(experimental)
266
-
267
- if Experimental.enabled():
268
- echo("Experimental support is enabled")
269
-
270
255
  logging_config: dict[str, Any] = {
271
256
  "level": logging.DEBUG if debug > 0 else logging.INFO
272
257
  }
@@ -291,18 +276,6 @@ async def cli(
291
276
  if alias is not None and host is not None:
292
277
  raise click.BadOptionUsage("alias", "Use either --alias or --host, not both.")
293
278
 
294
- if alias is not None and host is None:
295
- echo(f"Alias is given, using discovery to find host {alias}")
296
-
297
- from .discover import find_host_from_alias
298
-
299
- host = await find_host_from_alias(alias=alias, target=target)
300
- if host:
301
- echo(f"Found hostname is {host}")
302
- else:
303
- echo(f"No device with name {alias} found")
304
- return
305
-
306
279
  if bool(password) != bool(username):
307
280
  raise click.BadOptionUsage(
308
281
  "username", "Using authentication requires both --username and --password"
@@ -315,7 +288,7 @@ async def cli(
315
288
  else:
316
289
  credentials = None
317
290
 
318
- if host is None:
291
+ if host is None and alias is None:
319
292
  if ctx.invoked_subcommand and ctx.invoked_subcommand != "discover":
320
293
  error("Only discover is available without --host or --alias")
321
294
 
@@ -325,6 +298,7 @@ async def cli(
325
298
  return await ctx.invoke(discover)
326
299
 
327
300
  device_updated = False
301
+
328
302
  if type is not None and type not in {"smart", "camera"}:
329
303
  from kasa.deviceconfig import DeviceConfig
330
304
 
@@ -332,10 +306,6 @@ async def cli(
332
306
  dev = _legacy_type_to_class(type)(host, config=config)
333
307
  elif type in {"smart", "camera"} or (device_family and encrypt_type):
334
308
  if type == "camera":
335
- if not experimental:
336
- error(
337
- "Camera is an experimental type, please enable with --experimental"
338
- )
339
309
  encrypt_type = "AES"
340
310
  https = True
341
311
  device_family = "SMART.IPCAMERA"
@@ -367,6 +337,19 @@ async def cli(
367
337
  )
368
338
  dev = await Device.connect(config=config)
369
339
  device_updated = True
340
+ elif alias:
341
+ echo(f"Alias is given, using discovery to find host {alias}")
342
+
343
+ from .discover import find_dev_from_alias
344
+
345
+ dev = await find_dev_from_alias(
346
+ alias=alias, target=target, credentials=credentials
347
+ )
348
+ if not dev:
349
+ echo(f"No device with name {alias} found")
350
+ return
351
+ echo(f"Found hostname by alias: {dev.host}")
352
+ device_updated = True
370
353
  else:
371
354
  from .discover import discover
372
355
 
@@ -396,9 +379,9 @@ async def cli(
396
379
 
397
380
  @cli.command()
398
381
  @pass_dev_or_child
399
- async def shell(dev: Device):
382
+ async def shell(dev: Device) -> None:
400
383
  """Open interactive shell."""
401
- echo("Opening shell for %s" % dev)
384
+ echo(f"Opening shell for {dev}")
402
385
  from ptpython.repl import embed
403
386
 
404
387
  logging.getLogger("parso").setLevel(logging.WARNING) # prompt parsing
kasa/cli/schedule.py CHANGED
@@ -14,7 +14,7 @@ from .common import (
14
14
 
15
15
  @click.group()
16
16
  @pass_dev
17
- async def schedule(dev):
17
+ async def schedule(dev) -> None:
18
18
  """Scheduling commands."""
19
19
 
20
20
 
kasa/cli/time.py CHANGED
@@ -2,10 +2,10 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import zoneinfo
5
6
  from datetime import datetime
6
7
 
7
8
  import asyncclick as click
8
- import zoneinfo
9
9
 
10
10
  from kasa import (
11
11
  Device,
@@ -23,7 +23,7 @@ from .common import (
23
23
 
24
24
  @click.group(invoke_without_command=True)
25
25
  @click.pass_context
26
- async def time(ctx: click.Context):
26
+ async def time(ctx: click.Context) -> None:
27
27
  """Get and set time."""
28
28
  if ctx.invoked_subcommand is None:
29
29
  await ctx.invoke(time_get)