python-kasa 0.9.0__py3-none-any.whl → 0.10.0__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 (77) hide show
  1. kasa/cli/common.py +31 -2
  2. kasa/cli/device.py +3 -0
  3. kasa/cli/discover.py +63 -20
  4. kasa/cli/feature.py +17 -5
  5. kasa/cli/hub.py +95 -0
  6. kasa/cli/lazygroup.py +1 -2
  7. kasa/cli/main.py +14 -5
  8. kasa/cli/vacuum.py +84 -0
  9. kasa/device.py +42 -6
  10. kasa/device_factory.py +32 -12
  11. kasa/device_type.py +2 -0
  12. kasa/deviceconfig.py +13 -4
  13. kasa/discover.py +66 -49
  14. kasa/exceptions.py +3 -0
  15. kasa/feature.py +29 -7
  16. kasa/interfaces/__init__.py +4 -0
  17. kasa/interfaces/alarm.py +75 -0
  18. kasa/interfaces/childsetup.py +70 -0
  19. kasa/interfaces/light.py +44 -29
  20. kasa/iot/iotdimmer.py +1 -3
  21. kasa/iot/iotstrip.py +8 -2
  22. kasa/iot/modules/light.py +4 -40
  23. kasa/iot/modules/lightpreset.py +1 -1
  24. kasa/iot/modules/motion.py +324 -18
  25. kasa/module.py +26 -5
  26. kasa/protocols/iotprotocol.py +15 -1
  27. kasa/protocols/smartcamprotocol.py +16 -7
  28. kasa/protocols/smartprotocol.py +43 -9
  29. kasa/smart/modules/__init__.py +18 -0
  30. kasa/smart/modules/alarm.py +132 -15
  31. kasa/smart/modules/batterysensor.py +28 -14
  32. kasa/smart/modules/childdevice.py +8 -0
  33. kasa/smart/modules/childlock.py +37 -0
  34. kasa/smart/modules/childsetup.py +112 -0
  35. kasa/smart/modules/clean.py +411 -0
  36. kasa/smart/modules/cleanrecords.py +205 -0
  37. kasa/smart/modules/consumables.py +170 -0
  38. kasa/smart/modules/devicemodule.py +4 -1
  39. kasa/smart/modules/dustbin.py +117 -0
  40. kasa/smart/modules/energy.py +6 -4
  41. kasa/smart/modules/light.py +3 -34
  42. kasa/smart/modules/mop.py +90 -0
  43. kasa/smart/modules/powerprotection.py +124 -0
  44. kasa/smart/modules/speaker.py +67 -0
  45. kasa/smart/smartchilddevice.py +19 -2
  46. kasa/smart/smartdevice.py +127 -40
  47. kasa/smart/smartmodule.py +16 -3
  48. kasa/smartcam/__init__.py +2 -1
  49. kasa/smartcam/modules/__init__.py +6 -0
  50. kasa/smartcam/modules/alarm.py +61 -18
  51. kasa/smartcam/modules/babycrydetection.py +3 -1
  52. kasa/smartcam/modules/battery.py +113 -0
  53. kasa/smartcam/modules/camera.py +8 -5
  54. kasa/smartcam/modules/childdevice.py +4 -1
  55. kasa/smartcam/modules/childsetup.py +112 -0
  56. kasa/smartcam/modules/device.py +8 -3
  57. kasa/smartcam/modules/led.py +2 -0
  58. kasa/smartcam/modules/lensmask.py +2 -0
  59. kasa/smartcam/modules/motiondetection.py +3 -1
  60. kasa/smartcam/modules/persondetection.py +3 -1
  61. kasa/smartcam/modules/petdetection.py +49 -0
  62. kasa/smartcam/modules/tamperdetection.py +3 -1
  63. kasa/smartcam/modules/time.py +2 -0
  64. kasa/smartcam/smartcamchild.py +118 -0
  65. kasa/smartcam/smartcamdevice.py +74 -56
  66. kasa/smartcam/smartcammodule.py +7 -16
  67. kasa/transports/aestransport.py +2 -0
  68. kasa/transports/klaptransport.py +53 -7
  69. kasa/transports/linkietransport.py +2 -0
  70. kasa/transports/sslaestransport.py +151 -15
  71. kasa/transports/ssltransport.py +3 -1
  72. kasa/transports/xortransport.py +16 -5
  73. {python_kasa-0.9.0.dist-info → python_kasa-0.10.0.dist-info}/METADATA +5 -3
  74. {python_kasa-0.9.0.dist-info → python_kasa-0.10.0.dist-info}/RECORD +77 -60
  75. {python_kasa-0.9.0.dist-info → python_kasa-0.10.0.dist-info}/WHEEL +0 -0
  76. {python_kasa-0.9.0.dist-info → python_kasa-0.10.0.dist-info}/entry_points.txt +0 -0
  77. {python_kasa-0.9.0.dist-info → python_kasa-0.10.0.dist-info}/licenses/LICENSE +0 -0
kasa/cli/common.py CHANGED
@@ -10,7 +10,7 @@ from collections.abc import Callable
10
10
  from contextlib import contextmanager
11
11
  from functools import singledispatch, update_wrapper, wraps
12
12
  from gettext import gettext
13
- from typing import TYPE_CHECKING, Any, Final
13
+ from typing import TYPE_CHECKING, Any, Final, NoReturn
14
14
 
15
15
  import asyncclick as click
16
16
 
@@ -57,7 +57,7 @@ def echo(*args, **kwargs) -> None:
57
57
  _echo(*args, **kwargs)
58
58
 
59
59
 
60
- def error(msg: str) -> None:
60
+ def error(msg: str) -> NoReturn:
61
61
  """Print an error and exit."""
62
62
  echo(f"[bold red]{msg}[/bold red]")
63
63
  sys.exit(1)
@@ -68,6 +68,16 @@ def json_formatter_cb(result: Any, **kwargs) -> None:
68
68
  if not kwargs.get("json"):
69
69
  return
70
70
 
71
+ # Calling the discover command directly always returns a DeviceDict so if host
72
+ # was specified just format the device json
73
+ if (
74
+ (host := kwargs.get("host"))
75
+ and isinstance(result, dict)
76
+ and (dev := result.get(host))
77
+ and isinstance(dev, Device)
78
+ ):
79
+ result = dev
80
+
71
81
  @singledispatch
72
82
  def to_serializable(val):
73
83
  """Regular obj-to-string for json serialization.
@@ -85,6 +95,25 @@ def json_formatter_cb(result: Any, **kwargs) -> None:
85
95
  print(json_content)
86
96
 
87
97
 
98
+ async def invoke_subcommand(
99
+ command: click.BaseCommand,
100
+ ctx: click.Context,
101
+ args: list[str] | None = None,
102
+ **extra: Any,
103
+ ) -> Any:
104
+ """Invoke a click subcommand.
105
+
106
+ Calling ctx.Invoke() treats the command like a simple callback and doesn't
107
+ process any result_callbacks so we use this pattern from the click docs
108
+ https://click.palletsprojects.com/en/stable/exceptions/#what-if-i-don-t-want-that.
109
+ """
110
+ if args is None:
111
+ args = []
112
+ sub_ctx = await command.make_context(command.name, args, parent=ctx, **extra)
113
+ async with sub_ctx:
114
+ return await command.invoke(sub_ctx)
115
+
116
+
88
117
  def pass_dev_or_child(wrapped_function: Callable) -> Callable:
89
118
  """Pass the device or child to the click command based on the child options."""
90
119
  child_help = (
kasa/cli/device.py CHANGED
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from pprint import pformat as pf
6
+ from typing import TYPE_CHECKING
6
7
 
7
8
  import asyncclick as click
8
9
 
@@ -82,6 +83,8 @@ async def state(ctx, dev: Device):
82
83
  echo()
83
84
  from .discover import _echo_discovery_info
84
85
 
86
+ if TYPE_CHECKING:
87
+ assert dev._discovery_info
85
88
  _echo_discovery_info(dev._discovery_info)
86
89
 
87
90
  return dev.internal_state
kasa/cli/discover.py CHANGED
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import asyncio
6
6
  from pprint import pformat as pf
7
+ from typing import TYPE_CHECKING, cast
7
8
 
8
9
  import asyncclick as click
9
10
 
@@ -17,8 +18,12 @@ from kasa import (
17
18
  from kasa.discover import (
18
19
  NEW_DISCOVERY_REDACTORS,
19
20
  ConnectAttempt,
21
+ DeviceDict,
20
22
  DiscoveredRaw,
21
23
  DiscoveryResult,
24
+ OnDiscoveredCallable,
25
+ OnDiscoveredRawCallable,
26
+ OnUnsupportedCallable,
22
27
  )
23
28
  from kasa.iot.iotdevice import _extract_sys_info
24
29
  from kasa.protocols.iotprotocol import REDACTORS as IOT_REDACTORS
@@ -30,15 +35,33 @@ from .common import echo, error
30
35
 
31
36
  @click.group(invoke_without_command=True)
32
37
  @click.pass_context
33
- async def discover(ctx):
38
+ async def discover(ctx: click.Context):
34
39
  """Discover devices in the network."""
35
40
  if ctx.invoked_subcommand is None:
36
41
  return await ctx.invoke(detail)
37
42
 
38
43
 
44
+ @discover.result_callback()
45
+ @click.pass_context
46
+ async def _close_protocols(ctx: click.Context, discovered: DeviceDict):
47
+ """Close all the device protocols if discover was invoked directly by the user."""
48
+ if _discover_is_root_cmd(ctx):
49
+ for dev in discovered.values():
50
+ await dev.disconnect()
51
+ return discovered
52
+
53
+
54
+ def _discover_is_root_cmd(ctx: click.Context) -> bool:
55
+ """Will return true if discover was invoked directly by the user."""
56
+ root_ctx = ctx.find_root()
57
+ return (
58
+ root_ctx.invoked_subcommand is None or root_ctx.invoked_subcommand == "discover"
59
+ )
60
+
61
+
39
62
  @discover.command()
40
63
  @click.pass_context
41
- async def detail(ctx):
64
+ async def detail(ctx: click.Context) -> DeviceDict:
42
65
  """Discover devices in the network using udp broadcasts."""
43
66
  unsupported = []
44
67
  auth_failed = []
@@ -59,10 +82,14 @@ async def detail(ctx):
59
82
  from .device import state
60
83
 
61
84
  async def print_discovered(dev: Device) -> None:
85
+ if TYPE_CHECKING:
86
+ assert ctx.parent
62
87
  async with sem:
63
88
  try:
64
89
  await dev.update()
65
90
  except AuthenticationError:
91
+ if TYPE_CHECKING:
92
+ assert dev._discovery_info
66
93
  auth_failed.append(dev._discovery_info)
67
94
  echo("== Authentication failed for device ==")
68
95
  _echo_discovery_info(dev._discovery_info)
@@ -73,9 +100,11 @@ async def detail(ctx):
73
100
  echo()
74
101
 
75
102
  discovered = await _discover(
76
- ctx, print_discovered=print_discovered, print_unsupported=print_unsupported
103
+ ctx,
104
+ print_discovered=print_discovered if _discover_is_root_cmd(ctx) else None,
105
+ print_unsupported=print_unsupported,
77
106
  )
78
- if ctx.parent.parent.params["host"]:
107
+ if ctx.find_root().params["host"]:
79
108
  return discovered
80
109
 
81
110
  echo(f"Found {len(discovered)} devices")
@@ -96,7 +125,7 @@ async def detail(ctx):
96
125
  help="Set flag to redact sensitive data from raw output.",
97
126
  )
98
127
  @click.pass_context
99
- async def raw(ctx, redact: bool):
128
+ async def raw(ctx: click.Context, redact: bool) -> DeviceDict:
100
129
  """Return raw discovery data returned from devices."""
101
130
 
102
131
  def print_raw(discovered: DiscoveredRaw):
@@ -116,7 +145,7 @@ async def raw(ctx, redact: bool):
116
145
 
117
146
  @discover.command()
118
147
  @click.pass_context
119
- async def list(ctx):
148
+ async def list(ctx: click.Context) -> DeviceDict:
120
149
  """List devices in the network in a table using udp broadcasts."""
121
150
  sem = asyncio.Semaphore()
122
151
 
@@ -147,18 +176,24 @@ async def list(ctx):
147
176
  f"{'HOST':<15} {'MODEL':<9} {'DEVICE FAMILY':<20} {'ENCRYPT':<7} "
148
177
  f"{'HTTPS':<5} {'LV':<3} {'ALIAS'}"
149
178
  )
150
- return await _discover(
179
+ discovered = await _discover(
151
180
  ctx,
152
181
  print_discovered=print_discovered,
153
182
  print_unsupported=print_unsupported,
154
183
  do_echo=False,
155
184
  )
185
+ return discovered
156
186
 
157
187
 
158
188
  async def _discover(
159
- ctx, *, print_discovered=None, print_unsupported=None, print_raw=None, do_echo=True
160
- ):
161
- params = ctx.parent.parent.params
189
+ ctx: click.Context,
190
+ *,
191
+ print_discovered: OnDiscoveredCallable | None = None,
192
+ print_unsupported: OnUnsupportedCallable | None = None,
193
+ print_raw: OnDiscoveredRawCallable | None = None,
194
+ do_echo=True,
195
+ ) -> DeviceDict:
196
+ params = ctx.find_root().params
162
197
  target = params["target"]
163
198
  username = params["username"]
164
199
  password = params["password"]
@@ -170,8 +205,9 @@ async def _discover(
170
205
  credentials = Credentials(username, password) if username and password else None
171
206
 
172
207
  if host:
208
+ host = cast(str, host)
173
209
  echo(f"Discovering device {host} for {discovery_timeout} seconds")
174
- return await Discover.discover_single(
210
+ dev = await Discover.discover_single(
175
211
  host,
176
212
  port=port,
177
213
  credentials=credentials,
@@ -180,6 +216,12 @@ async def _discover(
180
216
  on_unsupported=print_unsupported,
181
217
  on_discovered_raw=print_raw,
182
218
  )
219
+ if dev:
220
+ if print_discovered:
221
+ await print_discovered(dev)
222
+ return {host: dev}
223
+ else:
224
+ return {}
183
225
  if do_echo:
184
226
  echo(f"Discovering devices on {target} for {discovery_timeout} seconds")
185
227
  discovered_devices = await Discover.discover(
@@ -193,21 +235,18 @@ async def _discover(
193
235
  on_discovered_raw=print_raw,
194
236
  )
195
237
 
196
- for device in discovered_devices.values():
197
- await device.protocol.close()
198
-
199
238
  return discovered_devices
200
239
 
201
240
 
202
241
  @discover.command()
203
242
  @click.pass_context
204
- async def config(ctx):
243
+ async def config(ctx: click.Context) -> DeviceDict:
205
244
  """Bypass udp discovery and try to show connection config for a device.
206
245
 
207
246
  Bypasses udp discovery and shows the parameters required to connect
208
247
  directly to the device.
209
248
  """
210
- params = ctx.parent.parent.params
249
+ params = ctx.find_root().params
211
250
  username = params["username"]
212
251
  password = params["password"]
213
252
  timeout = params["timeout"]
@@ -222,8 +261,11 @@ async def config(ctx):
222
261
  host_port = host + (f":{port}" if port else "")
223
262
 
224
263
  def on_attempt(connect_attempt: ConnectAttempt, success: bool) -> None:
225
- prot, tran, dev = connect_attempt
226
- key_str = f"{prot.__name__} + {tran.__name__} + {dev.__name__}"
264
+ prot, tran, dev, https = connect_attempt
265
+ key_str = (
266
+ f"{prot.__name__} + {tran.__name__} + {dev.__name__}"
267
+ f" + {'https' if https else 'http'}"
268
+ )
227
269
  result = "succeeded" if success else "failed"
228
270
  msg = f"Attempt to connect to {host_port} with {key_str} {result}"
229
271
  echo(msg)
@@ -239,6 +281,7 @@ async def config(ctx):
239
281
  f"--encrypt-type {cparams.encryption_type.value} "
240
282
  f"{'--https' if cparams.https else '--no-https'}"
241
283
  )
284
+ return {host: dev}
242
285
  else:
243
286
  error(f"Unable to connect to {host}")
244
287
 
@@ -251,7 +294,7 @@ def _echo_dictionary(discovery_info: dict) -> None:
251
294
  echo(f"\t{key_name_and_spaces}{value}")
252
295
 
253
296
 
254
- def _echo_discovery_info(discovery_info) -> None:
297
+ def _echo_discovery_info(discovery_info: dict) -> None:
255
298
  # We don't have discovery info when all connection params are passed manually
256
299
  if discovery_info is None:
257
300
  return
@@ -283,7 +326,7 @@ def _echo_discovery_info(discovery_info) -> None:
283
326
  _conditional_echo("HW Ver", dr.hw_ver)
284
327
  _conditional_echo("HW Ver", dr.hardware_version)
285
328
  _conditional_echo("Supports IOT Cloud", dr.is_support_iot_cloud)
286
- _conditional_echo("OBD Src", dr.owner)
329
+ _conditional_echo("OBD Src", dr.obd_src)
287
330
  _conditional_echo("Factory Default", dr.factory_default)
288
331
  _conditional_echo("Encrypt Type", dr.encrypt_type)
289
332
  if mgt_encrypt_schm := dr.mgt_encrypt_schm:
kasa/cli/feature.py CHANGED
@@ -6,10 +6,7 @@ import ast
6
6
 
7
7
  import asyncclick as click
8
8
 
9
- from kasa import (
10
- Device,
11
- Feature,
12
- )
9
+ from kasa import Device, Feature
13
10
 
14
11
  from .common import (
15
12
  echo,
@@ -133,7 +130,22 @@ async def feature(
133
130
  echo(f"{feat.name} ({name}): {feat.value}{unit}")
134
131
  return feat.value
135
132
 
136
- value = ast.literal_eval(value)
133
+ try:
134
+ # Attempt to parse as python literal.
135
+ value = ast.literal_eval(value)
136
+ except ValueError:
137
+ # The value is probably an unquoted string, so we'll raise an error,
138
+ # and tell the user to quote the string.
139
+ raise click.exceptions.BadParameter(
140
+ f'{repr(value)} for {name} (Perhaps you forgot to "quote" the value?)'
141
+ ) from SyntaxError
142
+ except SyntaxError:
143
+ # There are likely miss-matched quotes or odd characters in the input,
144
+ # so abort and complain to the user.
145
+ raise click.exceptions.BadParameter(
146
+ f"{repr(value)} for {name}"
147
+ ) from SyntaxError
148
+
137
149
  echo(f"Changing {name} from {feat.value} to {value}")
138
150
  response = await dev.features[name].set_value(value)
139
151
  await dev.update()
kasa/cli/hub.py ADDED
@@ -0,0 +1,95 @@
1
+ """Hub-specific commands."""
2
+
3
+ import asyncio
4
+
5
+ import asyncclick as click
6
+
7
+ from kasa import DeviceType, Module, SmartDevice
8
+ from kasa.smart import SmartChildDevice
9
+
10
+ from .common import (
11
+ echo,
12
+ error,
13
+ pass_dev,
14
+ )
15
+
16
+
17
+ def pretty_category(cat: str):
18
+ """Return pretty category for paired devices."""
19
+ return SmartChildDevice.CHILD_DEVICE_TYPE_MAP.get(cat)
20
+
21
+
22
+ @click.group()
23
+ @pass_dev
24
+ async def hub(dev: SmartDevice):
25
+ """Commands controlling hub child device pairing."""
26
+ if dev.device_type is not DeviceType.Hub:
27
+ error(f"{dev} is not a hub.")
28
+
29
+ if dev.modules.get(Module.ChildSetup) is None:
30
+ error(f"{dev} does not have child setup module.")
31
+
32
+
33
+ @hub.command(name="list")
34
+ @pass_dev
35
+ async def hub_list(dev: SmartDevice):
36
+ """List hub paired child devices."""
37
+ for c in dev.children:
38
+ echo(f"{c.device_id}: {c}")
39
+
40
+
41
+ @hub.command(name="supported")
42
+ @pass_dev
43
+ async def hub_supported(dev: SmartDevice):
44
+ """List supported hub child device categories."""
45
+ cs = dev.modules[Module.ChildSetup]
46
+
47
+ for cat in cs.supported_categories:
48
+ echo(f"Supports: {cat}")
49
+
50
+
51
+ @hub.command(name="pair")
52
+ @click.option("--timeout", default=10)
53
+ @pass_dev
54
+ async def hub_pair(dev: SmartDevice, timeout: int):
55
+ """Pair all pairable device.
56
+
57
+ This will pair any child devices currently in pairing mode.
58
+ """
59
+ cs = dev.modules[Module.ChildSetup]
60
+
61
+ echo(f"Finding new devices for {timeout} seconds...")
62
+
63
+ pair_res = await cs.pair(timeout=timeout)
64
+ if not pair_res:
65
+ echo("No devices found.")
66
+
67
+ for child in pair_res:
68
+ echo(
69
+ f"Paired {child['name']} ({child['device_model']}, "
70
+ f"{pretty_category(child['category'])}) with id {child['device_id']}"
71
+ )
72
+
73
+
74
+ @hub.command(name="unpair")
75
+ @click.argument("device_id")
76
+ @pass_dev
77
+ async def hub_unpair(dev, device_id: str):
78
+ """Unpair given device."""
79
+ cs = dev.modules[Module.ChildSetup]
80
+
81
+ # Accessing private here, as the property exposes only values
82
+ if device_id not in dev._children:
83
+ error(f"{dev} does not have children with identifier {device_id}")
84
+
85
+ res = await cs.unpair(device_id=device_id)
86
+ # Give the device some time to update its internal state, just in case.
87
+ await asyncio.sleep(1)
88
+ await dev.update()
89
+
90
+ if device_id not in dev._children:
91
+ echo(f"Unpaired {device_id}")
92
+ else:
93
+ error(f"Failed to unpair {device_id}")
94
+
95
+ return res
kasa/cli/lazygroup.py CHANGED
@@ -66,7 +66,6 @@ class LazyGroup(click.Group):
66
66
  # check the result to make debugging easier
67
67
  if not isinstance(cmd_object, click.BaseCommand):
68
68
  raise ValueError(
69
- f"Lazy loading of {cmd_name} failed by returning "
70
- "a non-command object"
69
+ f"Lazy loading of {cmd_name} failed by returning a non-command object"
71
70
  )
72
71
  return cmd_object
kasa/cli/main.py CHANGED
@@ -22,6 +22,7 @@ from .common import (
22
22
  CatchAllExceptions,
23
23
  echo,
24
24
  error,
25
+ invoke_subcommand,
25
26
  json_formatter_cb,
26
27
  pass_dev_or_child,
27
28
  )
@@ -92,6 +93,8 @@ def _legacy_type_to_class(_type: str) -> Any:
92
93
  "hsv": "light",
93
94
  "temperature": "light",
94
95
  "effect": "light",
96
+ "vacuum": "vacuum",
97
+ "hub": "hub",
95
98
  },
96
99
  result_callback=json_formatter_cb,
97
100
  )
@@ -295,9 +298,10 @@ async def cli(
295
298
  echo("No host name given, trying discovery..")
296
299
  from .discover import discover
297
300
 
298
- return await ctx.invoke(discover)
301
+ return await invoke_subcommand(discover, ctx)
299
302
 
300
303
  device_updated = False
304
+ device_discovered = False
301
305
 
302
306
  if type is not None and type not in {"smart", "camera"}:
303
307
  from kasa.deviceconfig import DeviceConfig
@@ -351,12 +355,14 @@ async def cli(
351
355
  return
352
356
  echo(f"Found hostname by alias: {dev.host}")
353
357
  device_updated = True
354
- else:
358
+ else: # host will be set
355
359
  from .discover import discover
356
360
 
357
- dev = await ctx.invoke(discover)
358
- if not dev:
361
+ discovered = await invoke_subcommand(discover, ctx)
362
+ if not discovered:
359
363
  error(f"Unable to create device for {host}")
364
+ dev = discovered[host]
365
+ device_discovered = True
360
366
 
361
367
  # Skip update on specific commands, or if device factory,
362
368
  # that performs an update was used for the device.
@@ -372,11 +378,14 @@ async def cli(
372
378
 
373
379
  ctx.obj = await ctx.with_async_resource(async_wrapped_device(dev))
374
380
 
375
- if ctx.invoked_subcommand is None:
381
+ # discover command has already invoked state
382
+ if ctx.invoked_subcommand is None and not device_discovered:
376
383
  from .device import state
377
384
 
378
385
  return await ctx.invoke(state)
379
386
 
387
+ return dev
388
+
380
389
 
381
390
  @cli.command()
382
391
  @pass_dev_or_child
kasa/cli/vacuum.py ADDED
@@ -0,0 +1,84 @@
1
+ """Module for cli vacuum commands.."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncclick as click
6
+
7
+ from kasa import (
8
+ Device,
9
+ Module,
10
+ )
11
+
12
+ from .common import (
13
+ error,
14
+ pass_dev_or_child,
15
+ )
16
+
17
+
18
+ @click.group(invoke_without_command=False)
19
+ @click.pass_context
20
+ async def vacuum(ctx: click.Context) -> None:
21
+ """Vacuum commands."""
22
+
23
+
24
+ @vacuum.group(invoke_without_command=True, name="records")
25
+ @pass_dev_or_child
26
+ async def records_group(dev: Device) -> None:
27
+ """Access cleaning records."""
28
+ if not (rec := dev.modules.get(Module.CleanRecords)):
29
+ error("This device does not support records.")
30
+
31
+ data = rec.parsed_data
32
+ latest = data.last_clean
33
+ click.echo(
34
+ f"Totals: {rec.total_clean_area} {rec.area_unit} in {rec.total_clean_time} "
35
+ f"(cleaned {rec.total_clean_count} times)"
36
+ )
37
+ click.echo(f"Last clean: {latest.clean_area} {rec.area_unit} @ {latest.clean_time}")
38
+ click.echo("Execute `kasa vacuum records list` to list all records.")
39
+
40
+
41
+ @records_group.command(name="list")
42
+ @pass_dev_or_child
43
+ async def records_list(dev: Device) -> None:
44
+ """List all cleaning records."""
45
+ if not (rec := dev.modules.get(Module.CleanRecords)):
46
+ error("This device does not support records.")
47
+
48
+ data = rec.parsed_data
49
+ for record in data.records:
50
+ click.echo(
51
+ f"* {record.timestamp}: cleaned {record.clean_area} {rec.area_unit}"
52
+ f" in {record.clean_time}"
53
+ )
54
+
55
+
56
+ @vacuum.group(invoke_without_command=True, name="consumables")
57
+ @pass_dev_or_child
58
+ @click.pass_context
59
+ async def consumables(ctx: click.Context, dev: Device) -> None:
60
+ """List device consumables."""
61
+ if not (cons := dev.modules.get(Module.Consumables)):
62
+ error("This device does not support consumables.")
63
+
64
+ if not ctx.invoked_subcommand:
65
+ for c in cons.consumables.values():
66
+ click.echo(f"{c.name} ({c.id}): {c.used} used, {c.remaining} remaining")
67
+
68
+
69
+ @consumables.command(name="reset")
70
+ @click.argument("consumable_id", required=True)
71
+ @pass_dev_or_child
72
+ async def reset_consumable(dev: Device, consumable_id: str) -> None:
73
+ """Reset the consumable used/remaining time."""
74
+ cons = dev.modules[Module.Consumables]
75
+
76
+ if consumable_id not in cons.consumables:
77
+ error(
78
+ f"Consumable {consumable_id} not found in "
79
+ f"device consumables: {', '.join(cons.consumables.keys())}."
80
+ )
81
+
82
+ await cons.reset_consumable(consumable_id)
83
+
84
+ click.echo(f"Consumable {consumable_id} reset")
kasa/device.py CHANGED
@@ -107,7 +107,7 @@ from __future__ import annotations
107
107
 
108
108
  import logging
109
109
  from abc import ABC, abstractmethod
110
- from collections.abc import Mapping, Sequence
110
+ from collections.abc import Callable, Mapping, Sequence
111
111
  from dataclasses import dataclass
112
112
  from datetime import datetime, tzinfo
113
113
  from typing import TYPE_CHECKING, Any, TypeAlias
@@ -537,19 +537,52 @@ class Device(ABC):
537
537
 
538
538
  return None
539
539
 
540
+ def _get_deprecated_callable_attribute(self, name: str) -> Any | None:
541
+ vals: dict[str, tuple[ModuleName, Callable[[Any], Any], str]] = {
542
+ "is_dimmable": (
543
+ Module.Light,
544
+ lambda c: c.has_feature("brightness"),
545
+ 'light_module.has_feature("brightness")',
546
+ ),
547
+ "is_color": (
548
+ Module.Light,
549
+ lambda c: c.has_feature("hsv"),
550
+ 'light_module.has_feature("hsv")',
551
+ ),
552
+ "is_variable_color_temp": (
553
+ Module.Light,
554
+ lambda c: c.has_feature("color_temp"),
555
+ 'light_module.has_feature("color_temp")',
556
+ ),
557
+ "valid_temperature_range": (
558
+ Module.Light,
559
+ lambda c: c._deprecated_valid_temperature_range(),
560
+ 'minimum and maximum value of get_feature("color_temp")',
561
+ ),
562
+ "has_effects": (
563
+ Module.Light,
564
+ lambda c: Module.LightEffect in c._device.modules,
565
+ "Module.LightEffect in device.modules",
566
+ ),
567
+ }
568
+ if mod_call_msg := vals.get(name):
569
+ mod, call, msg = mod_call_msg
570
+ msg = f"{name} is deprecated, use: {msg} instead"
571
+ warn(msg, DeprecationWarning, stacklevel=2)
572
+ if (module := self.modules.get(mod)) is None:
573
+ raise AttributeError(f"Device has no attribute {name!r}")
574
+ return call(module)
575
+
576
+ return None
577
+
540
578
  _deprecated_other_attributes = {
541
579
  # light attributes
542
- "is_color": (Module.Light, ["is_color"]),
543
- "is_dimmable": (Module.Light, ["is_dimmable"]),
544
- "is_variable_color_temp": (Module.Light, ["is_variable_color_temp"]),
545
580
  "brightness": (Module.Light, ["brightness"]),
546
581
  "set_brightness": (Module.Light, ["set_brightness"]),
547
582
  "hsv": (Module.Light, ["hsv"]),
548
583
  "set_hsv": (Module.Light, ["set_hsv"]),
549
584
  "color_temp": (Module.Light, ["color_temp"]),
550
585
  "set_color_temp": (Module.Light, ["set_color_temp"]),
551
- "valid_temperature_range": (Module.Light, ["valid_temperature_range"]),
552
- "has_effects": (Module.Light, ["has_effects"]),
553
586
  "_deprecated_set_light_state": (Module.Light, ["has_effects"]),
554
587
  # led attributes
555
588
  "led": (Module.Led, ["led"]),
@@ -588,6 +621,9 @@ class Device(ABC):
588
621
  msg = f"{name} is deprecated, use device_type property instead"
589
622
  warn(msg, DeprecationWarning, stacklevel=2)
590
623
  return self.device_type == dep_device_type_attr[1]
624
+ # callable
625
+ if (result := self._get_deprecated_callable_attribute(name)) is not None:
626
+ return result
591
627
  # Other deprecated attributes
592
628
  if (dep_attr := self._deprecated_other_attributes.get(name)) and (
593
629
  (replacing_attr := self._get_replacing_attr(dep_attr[0], *dep_attr[1]))