python-kasa 0.6.2.1__py3-none-any.whl → 0.7.0.dev0__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 (164) hide show
  1. kasa/__init__.py +88 -27
  2. kasa/aestransport.py +51 -34
  3. kasa/cli.py +326 -130
  4. kasa/device.py +406 -0
  5. kasa/device_factory.py +83 -44
  6. kasa/device_type.py +7 -3
  7. kasa/deviceconfig.py +16 -9
  8. kasa/discover.py +100 -81
  9. kasa/emeterstatus.py +7 -5
  10. kasa/exceptions.py +41 -26
  11. kasa/feature.py +201 -0
  12. kasa/httpclient.py +21 -14
  13. kasa/interfaces/__init__.py +16 -0
  14. kasa/interfaces/fan.py +20 -0
  15. kasa/interfaces/led.py +38 -0
  16. kasa/interfaces/light.py +133 -0
  17. kasa/interfaces/lighteffect.py +80 -0
  18. kasa/interfaces/lightpreset.py +76 -0
  19. kasa/iot/__init__.py +18 -0
  20. kasa/{effects.py → iot/effects.py} +4 -2
  21. kasa/{smartbulb.py → iot/iotbulb.py} +100 -147
  22. kasa/{smartdevice.py → iot/iotdevice.py} +157 -286
  23. kasa/{smartdimmer.py → iot/iotdimmer.py} +42 -33
  24. kasa/iot/iotlightstrip.py +71 -0
  25. kasa/{modules/module.py → iot/iotmodule.py} +22 -42
  26. kasa/iot/iotplug.py +94 -0
  27. kasa/{smartstrip.py → iot/iotstrip.py} +57 -75
  28. kasa/{modules → iot/modules}/__init__.py +10 -2
  29. kasa/{modules → iot/modules}/ambientlight.py +31 -3
  30. kasa/{modules → iot/modules}/antitheft.py +1 -0
  31. kasa/{modules → iot/modules}/cloud.py +25 -6
  32. kasa/{modules → iot/modules}/countdown.py +1 -0
  33. kasa/iot/modules/emeter.py +210 -0
  34. kasa/iot/modules/led.py +32 -0
  35. kasa/iot/modules/light.py +221 -0
  36. kasa/iot/modules/lighteffect.py +122 -0
  37. kasa/iot/modules/lightpreset.py +151 -0
  38. kasa/{modules → iot/modules}/motion.py +8 -8
  39. kasa/{modules → iot/modules}/rulemodule.py +11 -12
  40. kasa/{modules → iot/modules}/schedule.py +1 -0
  41. kasa/{modules → iot/modules}/time.py +5 -4
  42. kasa/{modules → iot/modules}/usage.py +10 -8
  43. kasa/iotprotocol.py +22 -20
  44. kasa/klaptransport.py +25 -15
  45. kasa/module.py +136 -0
  46. kasa/modulemapping.py +25 -0
  47. kasa/modulemapping.pyi +96 -0
  48. kasa/protocol.py +6 -4
  49. kasa/smart/__init__.py +6 -0
  50. kasa/smart/effects.py +429 -0
  51. kasa/smart/modules/__init__.py +57 -0
  52. kasa/smart/modules/alarm.py +142 -0
  53. kasa/smart/modules/autooff.py +96 -0
  54. kasa/smart/modules/batterysensor.py +54 -0
  55. kasa/smart/modules/brightness.py +66 -0
  56. kasa/smart/modules/childdevice.py +10 -0
  57. kasa/smart/modules/cloud.py +42 -0
  58. kasa/smart/modules/color.py +96 -0
  59. kasa/smart/modules/colortemperature.py +78 -0
  60. kasa/smart/modules/contactsensor.py +42 -0
  61. kasa/smart/modules/devicemodule.py +22 -0
  62. kasa/smart/modules/energy.py +101 -0
  63. kasa/smart/modules/fan.py +80 -0
  64. kasa/smart/modules/firmware.py +216 -0
  65. kasa/smart/modules/frostprotection.py +59 -0
  66. kasa/smart/modules/humiditysensor.py +55 -0
  67. kasa/smart/modules/led.py +49 -0
  68. kasa/smart/modules/light.py +139 -0
  69. kasa/smart/modules/lighteffect.py +115 -0
  70. kasa/smart/modules/lightpreset.py +142 -0
  71. kasa/smart/modules/lightstripeffect.py +135 -0
  72. kasa/smart/modules/lighttransition.py +183 -0
  73. kasa/smart/modules/reportmode.py +36 -0
  74. kasa/smart/modules/temperaturecontrol.py +177 -0
  75. kasa/smart/modules/temperaturesensor.py +77 -0
  76. kasa/smart/modules/time.py +57 -0
  77. kasa/smart/modules/waterleaksensor.py +66 -0
  78. kasa/smart/smartchilddevice.py +65 -0
  79. kasa/smart/smartdevice.py +653 -0
  80. kasa/smart/smartmodule.py +112 -0
  81. kasa/smartprotocol.py +107 -41
  82. kasa/tests/conftest.py +27 -562
  83. kasa/tests/device_fixtures.py +427 -0
  84. kasa/tests/discovery_fixtures.py +197 -0
  85. kasa/tests/fakeprotocol_iot.py +64 -6
  86. kasa/tests/fakeprotocol_smart.py +215 -22
  87. kasa/tests/fixtureinfo.py +154 -0
  88. kasa/tests/fixtures/smart/H100(EU)_1.0_1.2.3.json +221 -0
  89. kasa/tests/fixtures/smart/H100(EU)_1.0_1.5.10.json +547 -0
  90. kasa/tests/fixtures/smart/H100(EU)_1.0_1.5.5.json +391 -0
  91. kasa/tests/fixtures/smart/KH100(UK)_1.0_1.5.6.json +1557 -0
  92. kasa/tests/fixtures/smart/KS240(US)_1.0_1.0.4.json +899 -0
  93. kasa/tests/fixtures/smart/KS240(US)_1.0_1.0.5.json +479 -0
  94. kasa/tests/fixtures/smart/L530E(EU)_3.0_1.1.6.json +449 -0
  95. kasa/tests/fixtures/smart/P100_1.0.0_1.1.3.json +173 -0
  96. kasa/tests/fixtures/smart/P100_1.0.0_1.4.0.json +204 -0
  97. kasa/tests/fixtures/smart/P110(EU)_1.0_1.0.7.json +566 -0
  98. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.4.0.json +170 -0
  99. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.8.0.json +171 -0
  100. kasa/tests/fixtures/smart/child/KE100(UK)_1.0_2.8.0.json +171 -0
  101. kasa/tests/fixtures/smart/child/T110(EU)_1.0_1.8.0.json +526 -0
  102. kasa/tests/fixtures/smart/child/T300(EU)_1.0_1.7.0.json +533 -0
  103. kasa/tests/fixtures/smart/child/T310(EU)_1.0_1.5.0.json +530 -0
  104. kasa/tests/fixtures/smart/child/T315(EU)_1.0_1.7.0.json +537 -0
  105. kasa/tests/smart/__init__.py +0 -0
  106. kasa/tests/smart/features/__init__.py +0 -0
  107. kasa/tests/smart/features/test_brightness.py +55 -0
  108. kasa/tests/smart/features/test_colortemp.py +30 -0
  109. kasa/tests/smart/modules/__init__.py +0 -0
  110. kasa/tests/smart/modules/test_contact.py +28 -0
  111. kasa/tests/smart/modules/test_fan.py +79 -0
  112. kasa/tests/smart/modules/test_firmware.py +108 -0
  113. kasa/tests/smart/modules/test_humidity.py +28 -0
  114. kasa/tests/smart/modules/test_light_effect.py +41 -0
  115. kasa/tests/smart/modules/test_temperature.py +47 -0
  116. kasa/tests/smart/modules/test_temperaturecontrol.py +137 -0
  117. kasa/tests/smart/modules/test_waterleak.py +42 -0
  118. kasa/tests/test_aestransport.py +115 -23
  119. kasa/tests/test_bulb.py +115 -85
  120. kasa/tests/test_childdevice.py +19 -7
  121. kasa/tests/test_cli.py +453 -99
  122. kasa/tests/test_common_modules.py +216 -0
  123. kasa/tests/test_device.py +268 -0
  124. kasa/tests/test_device_factory.py +61 -35
  125. kasa/tests/test_device_type.py +1 -1
  126. kasa/tests/test_deviceconfig.py +2 -2
  127. kasa/tests/test_dimmer.py +33 -24
  128. kasa/tests/test_discovery.py +112 -63
  129. kasa/tests/test_emeter.py +14 -10
  130. kasa/tests/test_feature.py +205 -0
  131. kasa/tests/test_httpclient.py +9 -9
  132. kasa/tests/test_iotdevice.py +286 -0
  133. kasa/tests/test_klapprotocol.py +94 -37
  134. kasa/tests/test_lightstrip.py +24 -19
  135. kasa/tests/test_plug.py +46 -8
  136. kasa/tests/test_protocol.py +8 -10
  137. kasa/tests/test_readme_examples.py +87 -26
  138. kasa/tests/test_smartdevice.py +203 -311
  139. kasa/tests/test_smartprotocol.py +130 -25
  140. kasa/tests/test_strip.py +15 -6
  141. kasa/tests/test_usage.py +1 -1
  142. kasa/xortransport.py +15 -12
  143. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/METADATA +45 -143
  144. python_kasa-0.7.0.dev0.dist-info/RECORD +239 -0
  145. kasa/modules/emeter.py +0 -111
  146. kasa/smartlightstrip.py +0 -143
  147. kasa/smartplug.py +0 -91
  148. kasa/tapo/__init__.py +0 -7
  149. kasa/tapo/childdevice.py +0 -41
  150. kasa/tapo/tapobulb.py +0 -262
  151. kasa/tapo/tapodevice.py +0 -409
  152. kasa/tapo/tapoplug.py +0 -45
  153. kasa/tests/fixtures/HS105(US)_1.0_mocked.json +0 -47
  154. kasa/tests/fixtures/HS110(EU)_2.0_mocked.json +0 -50
  155. kasa/tests/fixtures/HS110(US)_1.0_mocked.json +0 -50
  156. kasa/tests/fixtures/HS200(US)_1.0_mocked.json +0 -47
  157. kasa/tests/fixtures/HS220(US)_1.0_mocked.json +0 -75
  158. kasa/tests/fixtures/LB100(US)_1.0_mocked.json +0 -103
  159. kasa/tests/fixtures/LB120(US)_1.0_mocked.json +0 -103
  160. kasa/tests/fixtures/LB130(US)_1.0_mocked.json +0 -104
  161. python_kasa-0.6.2.1.dist-info/RECORD +0 -167
  162. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/LICENSE +0 -0
  163. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/WHEEL +0 -0
  164. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/entry_points.txt +0 -0
kasa/cli.py CHANGED
@@ -1,38 +1,47 @@
1
1
  """python-kasa cli tool."""
2
+
3
+ from __future__ import annotations
4
+
2
5
  import ast
3
6
  import asyncio
4
7
  import json
5
8
  import logging
6
9
  import re
7
10
  import sys
11
+ from contextlib import asynccontextmanager
8
12
  from functools import singledispatch, wraps
9
13
  from pprint import pformat as pf
10
- from typing import Any, Dict, cast
14
+ from typing import Any, cast
11
15
 
12
16
  import asyncclick as click
17
+ from pydantic.v1 import ValidationError
13
18
 
14
19
  from kasa import (
15
- AuthenticationException,
20
+ AuthenticationError,
16
21
  ConnectionType,
17
22
  Credentials,
23
+ Device,
18
24
  DeviceConfig,
19
25
  DeviceFamilyType,
20
26
  Discover,
21
27
  EncryptType,
22
- SmartBulb,
23
- SmartDevice,
24
- SmartDimmer,
25
- SmartLightStrip,
26
- SmartPlug,
27
- SmartStrip,
28
- UnsupportedDeviceException,
28
+ Feature,
29
+ KasaException,
30
+ Module,
31
+ UnsupportedDeviceError,
29
32
  )
30
33
  from kasa.discover import DiscoveryResult
31
-
32
- try:
33
- from pydantic.v1 import ValidationError
34
- except ImportError:
35
- from pydantic import ValidationError
34
+ from kasa.iot import (
35
+ IotBulb,
36
+ IotDevice,
37
+ IotDimmer,
38
+ IotLightStrip,
39
+ IotPlug,
40
+ IotStrip,
41
+ IotWallSwitch,
42
+ )
43
+ from kasa.iot.modules import Usage
44
+ from kasa.smart import SmartDevice
36
45
 
37
46
  try:
38
47
  from rich import print as _do_echo
@@ -62,11 +71,20 @@ echo = _do_echo
62
71
 
63
72
 
64
73
  TYPE_TO_CLASS = {
65
- "plug": SmartPlug,
66
- "bulb": SmartBulb,
67
- "dimmer": SmartDimmer,
68
- "strip": SmartStrip,
69
- "lightstrip": SmartLightStrip,
74
+ "plug": IotPlug,
75
+ "switch": IotWallSwitch,
76
+ "bulb": IotBulb,
77
+ "dimmer": IotDimmer,
78
+ "strip": IotStrip,
79
+ "lightstrip": IotLightStrip,
80
+ "iot.plug": IotPlug,
81
+ "iot.switch": IotWallSwitch,
82
+ "iot.bulb": IotBulb,
83
+ "iot.dimmer": IotDimmer,
84
+ "iot.strip": IotStrip,
85
+ "iot.lightstrip": IotLightStrip,
86
+ "smart.plug": SmartDevice,
87
+ "smart.bulb": SmartDevice,
70
88
  }
71
89
 
72
90
  ENCRYPT_TYPES = [encrypt_type.value for encrypt_type in EncryptType]
@@ -80,21 +98,46 @@ SKIP_UPDATE_COMMANDS = ["wifi", "raw-command", "command"]
80
98
 
81
99
  click.anyio_backend = "asyncio"
82
100
 
83
- pass_dev = click.make_pass_decorator(SmartDevice)
101
+ pass_dev = click.make_pass_decorator(Device)
84
102
 
85
103
 
86
- class ExceptionHandlerGroup(click.Group):
87
- """Group to capture all exceptions and print them nicely.
104
+ def CatchAllExceptions(cls):
105
+ """Capture all exceptions and prints them nicely.
88
106
 
89
- Idea from https://stackoverflow.com/a/44347763
107
+ Idea from https://stackoverflow.com/a/44347763 and
108
+ https://stackoverflow.com/questions/52213375
90
109
  """
91
110
 
92
- def __call__(self, *args, **kwargs):
93
- """Run the coroutine in the event loop and print any exceptions."""
94
- try:
95
- asyncio.get_event_loop().run_until_complete(self.main(*args, **kwargs))
96
- except Exception as ex:
97
- echo(f"Got error: {ex!r}")
111
+ def _handle_exception(debug, exc):
112
+ if isinstance(exc, click.ClickException):
113
+ raise
114
+ echo(f"Raised error: {exc}")
115
+ if debug:
116
+ raise
117
+ echo("Run with --debug enabled to see stacktrace")
118
+ sys.exit(1)
119
+
120
+ class _CommandCls(cls):
121
+ _debug = False
122
+
123
+ async def make_context(self, info_name, args, parent=None, **extra):
124
+ self._debug = any(
125
+ [arg for arg in args if arg in ["--debug", "-d", "--verbose", "-v"]]
126
+ )
127
+ try:
128
+ return await super().make_context(
129
+ info_name, args, parent=parent, **extra
130
+ )
131
+ except Exception as exc:
132
+ _handle_exception(self._debug, exc)
133
+
134
+ async def invoke(self, ctx):
135
+ try:
136
+ return await super().invoke(ctx)
137
+ except Exception as exc:
138
+ _handle_exception(self._debug, exc)
139
+
140
+ return _CommandCls
98
141
 
99
142
 
100
143
  def json_formatter_cb(result, **kwargs):
@@ -110,8 +153,8 @@ def json_formatter_cb(result, **kwargs):
110
153
  """
111
154
  return str(val)
112
155
 
113
- @to_serializable.register(SmartDevice)
114
- def _device_to_serializable(val: SmartDevice):
156
+ @to_serializable.register(Device)
157
+ def _device_to_serializable(val: Device):
115
158
  """Serialize smart device data, just using the last update raw payload."""
116
159
  return val.internal_state
117
160
 
@@ -121,7 +164,7 @@ def json_formatter_cb(result, **kwargs):
121
164
 
122
165
  @click.group(
123
166
  invoke_without_command=True,
124
- cls=ExceptionHandlerGroup,
167
+ cls=CatchAllExceptions(click.Group),
125
168
  result_callback=json_formatter_cb,
126
169
  )
127
170
  @click.option(
@@ -210,7 +253,7 @@ def json_formatter_cb(result, **kwargs):
210
253
  @click.option(
211
254
  "--discovery-timeout",
212
255
  envvar="KASA_DISCOVERY_TIMEOUT",
213
- default=3,
256
+ default=5,
214
257
  required=False,
215
258
  show_default=True,
216
259
  help="Timeout for discovery.",
@@ -259,9 +302,9 @@ async def cli(
259
302
  ):
260
303
  """A tool for controlling TP-Link smart home devices.""" # noqa
261
304
  # no need to perform any checks if we are just displaying the help
262
- if sys.argv[-1] == "--help":
305
+ if "--help" in sys.argv:
263
306
  # Context object is required to avoid crashing on sub-groups
264
- ctx.obj = SmartDevice(None)
307
+ ctx.obj = object()
265
308
  return
266
309
 
267
310
  # If JSON output is requested, disable echo
@@ -277,7 +320,7 @@ async def cli(
277
320
  global _do_echo
278
321
  echo = _do_echo
279
322
 
280
- logging_config: Dict[str, Any] = {
323
+ logging_config: dict[str, Any] = {
281
324
  "level": logging.DEBUG if debug > 0 else logging.INFO
282
325
  }
283
326
  try:
@@ -334,18 +377,24 @@ async def cli(
334
377
  )
335
378
  config = DeviceConfig(
336
379
  host=host,
380
+ port_override=port,
337
381
  credentials=credentials,
338
382
  credentials_hash=credentials_hash,
339
383
  timeout=timeout,
340
384
  connection_type=ctype,
341
385
  )
342
- dev = await SmartDevice.connect(config=config)
386
+ dev = await Device.connect(config=config)
343
387
  else:
344
- echo("No --type or --device-family and --encrypt-type defined, discovering..")
388
+ echo(
389
+ "No --type or --device-family and --encrypt-type defined, "
390
+ + f"discovering for {discovery_timeout} seconds.."
391
+ )
345
392
  dev = await Discover.discover_single(
346
393
  host,
347
394
  port=port,
348
395
  credentials=credentials,
396
+ timeout=timeout,
397
+ discovery_timeout=discovery_timeout,
349
398
  )
350
399
 
351
400
  # Skip update on specific commands, or if device factory,
@@ -353,7 +402,14 @@ async def cli(
353
402
  if ctx.invoked_subcommand not in SKIP_UPDATE_COMMANDS and not device_family:
354
403
  await dev.update()
355
404
 
356
- ctx.obj = dev
405
+ @asynccontextmanager
406
+ async def async_wrapped_device(device: Device):
407
+ try:
408
+ yield device
409
+ finally:
410
+ await device.disconnect()
411
+
412
+ ctx.obj = await ctx.with_async_resource(async_wrapped_device(dev))
357
413
 
358
414
  if ctx.invoked_subcommand is None:
359
415
  return await ctx.invoke(state)
@@ -383,7 +439,7 @@ async def scan(dev):
383
439
  @click.option("--keytype", prompt=True)
384
440
  @click.option("--password", prompt=True, hide_input=True)
385
441
  @pass_dev
386
- async def join(dev: SmartDevice, ssid: str, password: str, keytype: str):
442
+ async def join(dev: Device, ssid: str, password: str, keytype: str):
387
443
  """Join the given wifi network."""
388
444
  echo(f"Asking the device to connect to {ssid}..")
389
445
  res = await dev.wifi_join(ssid, password, keytype=keytype)
@@ -413,7 +469,7 @@ async def discover(ctx):
413
469
  unsupported = []
414
470
  auth_failed = []
415
471
 
416
- async def print_unsupported(unsupported_exception: UnsupportedDeviceException):
472
+ async def print_unsupported(unsupported_exception: UnsupportedDeviceError):
417
473
  unsupported.append(unsupported_exception)
418
474
  async with sem:
419
475
  if unsupported_exception.discovery_result:
@@ -427,22 +483,22 @@ async def discover(ctx):
427
483
 
428
484
  echo(f"Discovering devices on {target} for {discovery_timeout} seconds")
429
485
 
430
- async def print_discovered(dev: SmartDevice):
486
+ async def print_discovered(dev: Device):
431
487
  async with sem:
432
488
  try:
433
489
  await dev.update()
434
- except AuthenticationException:
490
+ except AuthenticationError:
435
491
  auth_failed.append(dev._discovery_info)
436
492
  echo("== Authentication failed for device ==")
437
493
  _echo_discovery_info(dev._discovery_info)
438
494
  echo()
439
495
  else:
440
- discovered[dev.host] = dev.internal_state
441
496
  ctx.parent.obj = dev
442
497
  await ctx.parent.invoke(state)
498
+ discovered[dev.host] = dev.internal_state
443
499
  echo()
444
500
 
445
- await Discover.discover(
501
+ discovered_devices = await Discover.discover(
446
502
  target=target,
447
503
  discovery_timeout=discovery_timeout,
448
504
  on_discovered=print_discovered,
@@ -452,6 +508,9 @@ async def discover(ctx):
452
508
  credentials=credentials,
453
509
  )
454
510
 
511
+ for device in discovered_devices.values():
512
+ await device.protocol.close()
513
+
455
514
  echo(f"Found {len(discovered)} devices")
456
515
  if unsupported:
457
516
  echo(f"Found {len(unsupported)} unsupported devices")
@@ -470,6 +529,10 @@ def _echo_dictionary(discovery_info: dict):
470
529
 
471
530
 
472
531
  def _echo_discovery_info(discovery_info):
532
+ # We don't have discovery info when all connection params are passed manually
533
+ if discovery_info is None:
534
+ return
535
+
473
536
  if "system" in discovery_info and "get_sysinfo" in discovery_info["system"]:
474
537
  _echo_dictionary(discovery_info["system"]["get_sysinfo"])
475
538
  return
@@ -518,10 +581,67 @@ async def sysinfo(dev):
518
581
  return dev.sys_info
519
582
 
520
583
 
584
+ def _echo_features(
585
+ features: dict[str, Feature],
586
+ title: str,
587
+ category: Feature.Category | None = None,
588
+ verbose: bool = False,
589
+ indent: str = "\t",
590
+ ):
591
+ """Print out a listing of features and their values."""
592
+ if category is not None:
593
+ features = {
594
+ id_: feat for id_, feat in features.items() if feat.category == category
595
+ }
596
+
597
+ if not features:
598
+ return
599
+ echo(f"[bold]{title}[/bold]")
600
+ for _, feat in features.items():
601
+ try:
602
+ echo(f"{indent}{feat}")
603
+ if verbose:
604
+ echo(f"{indent}\tType: {feat.type}")
605
+ echo(f"{indent}\tCategory: {feat.category}")
606
+ echo(f"{indent}\tIcon: {feat.icon}")
607
+ except Exception as ex:
608
+ echo(f"{indent}{feat.name} ({feat.id}): [red]got exception ({ex})[/red]")
609
+
610
+
611
+ def _echo_all_features(features, *, verbose=False, title_prefix=None):
612
+ """Print out all features by category."""
613
+ if title_prefix is not None:
614
+ echo(f"[bold]\n\t == {title_prefix} ==[/bold]")
615
+ _echo_features(
616
+ features,
617
+ title="\n\t== Primary features ==",
618
+ category=Feature.Category.Primary,
619
+ verbose=verbose,
620
+ )
621
+ _echo_features(
622
+ features,
623
+ title="\n\t== Information ==",
624
+ category=Feature.Category.Info,
625
+ verbose=verbose,
626
+ )
627
+ _echo_features(
628
+ features,
629
+ title="\n\t== Configuration ==",
630
+ category=Feature.Category.Config,
631
+ verbose=verbose,
632
+ )
633
+ _echo_features(
634
+ features,
635
+ title="\n\t== Debug ==",
636
+ category=Feature.Category.Debug,
637
+ verbose=verbose,
638
+ )
639
+
640
+
521
641
  @cli.command()
522
642
  @pass_dev
523
643
  @click.pass_context
524
- async def state(ctx, dev: SmartDevice):
644
+ async def state(ctx, dev: Device):
525
645
  """Print out device state and versions."""
526
646
  verbose = ctx.parent.params.get("verbose", False) if ctx.parent else False
527
647
 
@@ -529,10 +649,15 @@ async def state(ctx, dev: SmartDevice):
529
649
  echo(f"\tHost: {dev.host}")
530
650
  echo(f"\tPort: {dev.port}")
531
651
  echo(f"\tDevice state: {dev.is_on}")
532
- if dev.is_strip:
533
- echo("\t[bold]== Plugs ==[/bold]")
534
- for plug in dev.children: # type: ignore
535
- echo(f"\t* Socket '{plug.alias}' state: {plug.is_on} since {plug.on_since}")
652
+ if dev.children:
653
+ echo("\t== Children ==")
654
+ for child in dev.children:
655
+ _echo_all_features(
656
+ child.features,
657
+ title_prefix=f"{child.alias} ({child.model}, {child.device_type})",
658
+ verbose=verbose,
659
+ )
660
+
536
661
  echo()
537
662
 
538
663
  echo("\t[bold]== Generic information ==[/bold]")
@@ -542,33 +667,15 @@ async def state(ctx, dev: SmartDevice):
542
667
  echo(f"\tMAC (rssi): {dev.mac} ({dev.rssi})")
543
668
  echo(f"\tLocation: {dev.location}")
544
669
 
545
- echo("\n\t[bold]== Device specific information ==[/bold]")
546
- for info_name, info_data in dev.state_information.items():
547
- if isinstance(info_data, list):
548
- echo(f"\t{info_name}:")
549
- for item in info_data:
550
- echo(f"\t\t{item}")
551
- else:
552
- echo(f"\t{info_name}: {info_data}")
553
-
554
- if dev.has_emeter:
555
- echo("\n\t[bold]== Current State ==[/bold]")
556
- emeter_status = dev.emeter_realtime
557
- echo(f"\t{emeter_status}")
670
+ _echo_all_features(dev.features, verbose=verbose)
558
671
 
559
672
  echo("\n\t[bold]== Modules ==[/bold]")
560
673
  for module in dev.modules.values():
561
- if module.is_supported:
562
- echo(f"\t[green]+ {module}[/green]")
563
- else:
564
- echo(f"\t[red]- {module}[/red]")
674
+ echo(f"\t[green]+ {module}[/green]")
565
675
 
566
676
  if verbose:
567
- echo("\n\t[bold]== Verbose information ==[/bold]")
677
+ echo("\n\t[bold]== Protocol information ==[/bold]")
568
678
  echo(f"\tCredentials hash: {dev.credentials_hash}")
569
- echo(f"\tDevice ID: {dev.device_id}")
570
- for feature in dev.features:
571
- echo(f"\tFeature: {feature}")
572
679
  echo()
573
680
  _echo_discovery_info(dev._discovery_info)
574
681
  return dev.internal_state
@@ -584,7 +691,6 @@ async def alias(dev, new_alias, index):
584
691
  if not dev.is_strip:
585
692
  echo("Index can only used for power strips!")
586
693
  return
587
- dev = cast(SmartStrip, dev)
588
694
  dev = dev.get_plug_by_index(index)
589
695
 
590
696
  if new_alias is not None:
@@ -606,7 +712,7 @@ async def alias(dev, new_alias, index):
606
712
  @click.argument("module")
607
713
  @click.argument("command")
608
714
  @click.argument("parameters", default=None, required=False)
609
- async def raw_command(ctx, dev: SmartDevice, module, command, parameters):
715
+ async def raw_command(ctx, dev: Device, module, command, parameters):
610
716
  """Run a raw command on the device."""
611
717
  logging.warning("Deprecated, use 'kasa command --module %s %s'", module, command)
612
718
  return await ctx.forward(cmd_command)
@@ -615,14 +721,28 @@ async def raw_command(ctx, dev: SmartDevice, module, command, parameters):
615
721
  @cli.command(name="command")
616
722
  @pass_dev
617
723
  @click.option("--module", required=False, help="Module for IOT protocol.")
724
+ @click.option("--child", required=False, help="Child ID for controlling sub-devices")
618
725
  @click.argument("command")
619
726
  @click.argument("parameters", default=None, required=False)
620
- async def cmd_command(dev: SmartDevice, module, command, parameters):
727
+ async def cmd_command(dev: Device, module, child, command, parameters):
621
728
  """Run a raw command on the device."""
622
729
  if parameters is not None:
623
730
  parameters = ast.literal_eval(parameters)
624
731
 
625
- res = await dev._query_helper(module, command, parameters)
732
+ if child:
733
+ # The way child devices are accessed requires a ChildDevice to
734
+ # wrap the communications. Doing this properly would require creating
735
+ # a common interfaces for both IOT and SMART child devices.
736
+ # As a stop-gap solution, we perform an update instead.
737
+ await dev.update()
738
+ dev = dev.get_child_device(child)
739
+
740
+ if isinstance(dev, IotDevice):
741
+ res = await dev._query_helper(module, command, parameters)
742
+ elif isinstance(dev, SmartDevice):
743
+ res = await dev._query_helper(command, parameters)
744
+ else:
745
+ raise KasaException("Unexpected device type %s.", dev)
626
746
  echo(json.dumps(res))
627
747
  return res
628
748
 
@@ -634,7 +754,7 @@ async def cmd_command(dev: SmartDevice, module, command, parameters):
634
754
  @click.option("--year", type=click.DateTime(["%Y"]), default=None, required=False)
635
755
  @click.option("--month", type=click.DateTime(["%Y-%m"]), default=None, required=False)
636
756
  @click.option("--erase", is_flag=True)
637
- async def emeter(dev: SmartDevice, index: int, name: str, year, month, erase):
757
+ async def emeter(dev: Device, index: int, name: str, year, month, erase):
638
758
  """Query emeter for historical consumption.
639
759
 
640
760
  Daily and monthly data provided in CSV format.
@@ -644,7 +764,6 @@ async def emeter(dev: SmartDevice, index: int, name: str, year, month, erase):
644
764
  echo("Index and name are only for power strips!")
645
765
  return
646
766
 
647
- dev = cast(SmartStrip, dev)
648
767
  if index is not None:
649
768
  dev = dev.get_plug_by_index(index)
650
769
  elif name:
@@ -655,6 +774,12 @@ async def emeter(dev: SmartDevice, index: int, name: str, year, month, erase):
655
774
  echo("Device has no emeter")
656
775
  return
657
776
 
777
+ if (year or month or erase) and not isinstance(dev, IotDevice):
778
+ echo("Device has no historical statistics")
779
+ return
780
+ else:
781
+ dev = cast(IotDevice, dev)
782
+
658
783
  if erase:
659
784
  echo("Erasing emeter statistics..")
660
785
  return await dev.erase_emeter_stats()
@@ -696,13 +821,13 @@ async def emeter(dev: SmartDevice, index: int, name: str, year, month, erase):
696
821
  @click.option("--year", type=click.DateTime(["%Y"]), default=None, required=False)
697
822
  @click.option("--month", type=click.DateTime(["%Y-%m"]), default=None, required=False)
698
823
  @click.option("--erase", is_flag=True)
699
- async def usage(dev: SmartDevice, year, month, erase):
824
+ async def usage(dev: Device, year, month, erase):
700
825
  """Query usage for historical consumption.
701
826
 
702
827
  Daily and monthly data provided in CSV format.
703
828
  """
704
829
  echo("[bold]== Usage ==[/bold]")
705
- usage = dev.modules["usage"]
830
+ usage = cast(Usage, dev.modules["usage"])
706
831
 
707
832
  if erase:
708
833
  echo("Erasing usage statistics..")
@@ -734,18 +859,18 @@ async def usage(dev: SmartDevice, year, month, erase):
734
859
  @click.argument("brightness", type=click.IntRange(0, 100), default=None, required=False)
735
860
  @click.option("--transition", type=int, required=False)
736
861
  @pass_dev
737
- async def brightness(dev: SmartBulb, brightness: int, transition: int):
862
+ async def brightness(dev: Device, brightness: int, transition: int):
738
863
  """Get or set brightness."""
739
- if not dev.is_dimmable:
864
+ if not (light := dev.modules.get(Module.Light)) or not light.is_dimmable:
740
865
  echo("This device does not support brightness.")
741
866
  return
742
867
 
743
868
  if brightness is None:
744
- echo(f"Brightness: {dev.brightness}")
745
- return dev.brightness
869
+ echo(f"Brightness: {light.brightness}")
870
+ return light.brightness
746
871
  else:
747
872
  echo(f"Setting brightness to {brightness}")
748
- return await dev.set_brightness(brightness, transition=transition)
873
+ return await light.set_brightness(brightness, transition=transition)
749
874
 
750
875
 
751
876
  @cli.command()
@@ -754,15 +879,15 @@ async def brightness(dev: SmartBulb, brightness: int, transition: int):
754
879
  )
755
880
  @click.option("--transition", type=int, required=False)
756
881
  @pass_dev
757
- async def temperature(dev: SmartBulb, temperature: int, transition: int):
882
+ async def temperature(dev: Device, temperature: int, transition: int):
758
883
  """Get or set color temperature."""
759
- if not dev.is_variable_color_temp:
884
+ if not (light := dev.modules.get(Module.Light)) or not light.is_variable_color_temp:
760
885
  echo("Device does not support color temperature")
761
886
  return
762
887
 
763
888
  if temperature is None:
764
- echo(f"Color temperature: {dev.color_temp}")
765
- valid_temperature_range = dev.valid_temperature_range
889
+ echo(f"Color temperature: {light.color_temp}")
890
+ valid_temperature_range = light.valid_temperature_range
766
891
  if valid_temperature_range != (0, 0):
767
892
  echo("(min: {}, max: {})".format(*valid_temperature_range))
768
893
  else:
@@ -770,31 +895,35 @@ async def temperature(dev: SmartBulb, temperature: int, transition: int):
770
895
  "Temperature range unknown, please open a github issue"
771
896
  f" or a pull request for model '{dev.model}'"
772
897
  )
773
- return dev.valid_temperature_range
898
+ return light.valid_temperature_range
774
899
  else:
775
900
  echo(f"Setting color temperature to {temperature}")
776
- return await dev.set_color_temp(temperature, transition=transition)
901
+ return await light.set_color_temp(temperature, transition=transition)
777
902
 
778
903
 
779
904
  @cli.command()
780
905
  @click.argument("effect", type=click.STRING, default=None, required=False)
781
906
  @click.pass_context
782
907
  @pass_dev
783
- async def effect(dev, ctx, effect):
908
+ async def effect(dev: Device, ctx, effect):
784
909
  """Set an effect."""
785
- if not dev.has_effects:
910
+ if not (light_effect := dev.modules.get(Module.LightEffect)):
786
911
  echo("Device does not support effects")
787
912
  return
788
913
  if effect is None:
914
+ echo(
915
+ f"Light effect: {light_effect.effect}\n"
916
+ + f"Available Effects: {light_effect.effect_list}"
917
+ )
918
+ return light_effect.effect
919
+
920
+ if effect not in light_effect.effect_list:
789
921
  raise click.BadArgumentUsage(
790
- f"Setting an effect requires a named built-in effect: {dev.effect_list}",
791
- ctx,
922
+ f"Effect must be one of: {light_effect.effect_list}", ctx
792
923
  )
793
- if effect not in dev.effect_list:
794
- raise click.BadArgumentUsage(f"Effect must be one of: {dev.effect_list}", ctx)
795
924
 
796
925
  echo(f"Setting Effect: {effect}")
797
- return await dev.set_effect(effect)
926
+ return await light_effect.set_effect(effect)
798
927
 
799
928
 
800
929
  @cli.command()
@@ -804,33 +933,36 @@ async def effect(dev, ctx, effect):
804
933
  @click.option("--transition", type=int, required=False)
805
934
  @click.pass_context
806
935
  @pass_dev
807
- async def hsv(dev, ctx, h, s, v, transition):
936
+ async def hsv(dev: Device, ctx, h, s, v, transition):
808
937
  """Get or set color in HSV."""
809
- if not dev.is_color:
938
+ if not (light := dev.modules.get(Module.Light)) or not light.is_color:
810
939
  echo("Device does not support colors")
811
940
  return
812
941
 
813
- if h is None or s is None or v is None:
814
- echo(f"Current HSV: {dev.hsv}")
815
- return dev.hsv
942
+ if h is None and s is None and v is None:
943
+ echo(f"Current HSV: {light.hsv}")
944
+ return light.hsv
816
945
  elif s is None or v is None:
817
946
  raise click.BadArgumentUsage("Setting a color requires 3 values.", ctx)
818
947
  else:
819
948
  echo(f"Setting HSV: {h} {s} {v}")
820
- return await dev.set_hsv(h, s, v, transition=transition)
949
+ return await light.set_hsv(h, s, v, transition=transition)
821
950
 
822
951
 
823
952
  @cli.command()
824
953
  @click.argument("state", type=bool, required=False)
825
954
  @pass_dev
826
- async def led(dev, state):
955
+ async def led(dev: Device, state):
827
956
  """Get or set (Plug's) led state."""
957
+ if not (led := dev.modules.get(Module.Led)):
958
+ echo("Device does not support led.")
959
+ return
828
960
  if state is not None:
829
961
  echo(f"Turning led to {state}")
830
- return await dev.set_led(state)
962
+ return await led.set_led(state)
831
963
  else:
832
- echo(f"LED state: {dev.led}")
833
- return dev.led
964
+ echo(f"LED state: {led.led}")
965
+ return led.led
834
966
 
835
967
 
836
968
  @cli.command()
@@ -847,14 +979,13 @@ async def time(dev):
847
979
  @click.option("--name", type=str, required=False)
848
980
  @click.option("--transition", type=int, required=False)
849
981
  @pass_dev
850
- async def on(dev: SmartDevice, index: int, name: str, transition: int):
982
+ async def on(dev: Device, index: int, name: str, transition: int):
851
983
  """Turn the device on."""
852
984
  if index is not None or name is not None:
853
- if not dev.is_strip:
854
- echo("Index and name are only for power strips!")
985
+ if not dev.children:
986
+ echo("Index and name are only for devices with children.")
855
987
  return
856
988
 
857
- dev = cast(SmartStrip, dev)
858
989
  if index is not None:
859
990
  dev = dev.get_plug_by_index(index)
860
991
  elif name:
@@ -869,14 +1000,13 @@ async def on(dev: SmartDevice, index: int, name: str, transition: int):
869
1000
  @click.option("--name", type=str, required=False)
870
1001
  @click.option("--transition", type=int, required=False)
871
1002
  @pass_dev
872
- async def off(dev: SmartDevice, index: int, name: str, transition: int):
1003
+ async def off(dev: Device, index: int, name: str, transition: int):
873
1004
  """Turn the device off."""
874
1005
  if index is not None or name is not None:
875
- if not dev.is_strip:
876
- echo("Index and name are only for power strips!")
1006
+ if not dev.children:
1007
+ echo("Index and name are only for devices with children.")
877
1008
  return
878
1009
 
879
- dev = cast(SmartStrip, dev)
880
1010
  if index is not None:
881
1011
  dev = dev.get_plug_by_index(index)
882
1012
  elif name:
@@ -891,14 +1021,13 @@ async def off(dev: SmartDevice, index: int, name: str, transition: int):
891
1021
  @click.option("--name", type=str, required=False)
892
1022
  @click.option("--transition", type=int, required=False)
893
1023
  @pass_dev
894
- async def toggle(dev: SmartDevice, index: int, name: str, transition: int):
1024
+ async def toggle(dev: Device, index: int, name: str, transition: int):
895
1025
  """Toggle the device on/off."""
896
1026
  if index is not None or name is not None:
897
- if not dev.is_strip:
898
- echo("Index and name are only for power strips!")
1027
+ if not dev.children:
1028
+ echo("Index and name are only for devices with children.")
899
1029
  return
900
1030
 
901
- dev = cast(SmartStrip, dev)
902
1031
  if index is not None:
903
1032
  dev = dev.get_plug_by_index(index)
904
1033
  elif name:
@@ -965,10 +1094,10 @@ async def presets(ctx):
965
1094
 
966
1095
  @presets.command(name="list")
967
1096
  @pass_dev
968
- def presets_list(dev: SmartBulb):
1097
+ def presets_list(dev: IotBulb):
969
1098
  """List presets."""
970
- if not dev.is_bulb:
971
- echo("Presets only supported on bulbs")
1099
+ if not dev.is_bulb or not isinstance(dev, IotBulb):
1100
+ echo("Presets only supported on iot bulbs")
972
1101
  return
973
1102
 
974
1103
  for preset in dev.presets:
@@ -984,9 +1113,7 @@ def presets_list(dev: SmartBulb):
984
1113
  @click.option("--saturation", type=int)
985
1114
  @click.option("--temperature", type=int)
986
1115
  @pass_dev
987
- async def presets_modify(
988
- dev: SmartBulb, index, brightness, hue, saturation, temperature
989
- ):
1116
+ async def presets_modify(dev: IotBulb, index, brightness, hue, saturation, temperature):
990
1117
  """Modify a preset."""
991
1118
  for preset in dev.presets:
992
1119
  if preset.index == index:
@@ -1014,8 +1141,11 @@ async def presets_modify(
1014
1141
  @click.option("--type", type=click.Choice(["soft", "hard"], case_sensitive=False))
1015
1142
  @click.option("--last", is_flag=True)
1016
1143
  @click.option("--preset", type=int)
1017
- async def turn_on_behavior(dev: SmartBulb, type, last, preset):
1144
+ async def turn_on_behavior(dev: IotBulb, type, last, preset):
1018
1145
  """Modify bulb turn-on behavior."""
1146
+ if not dev.is_bulb or not isinstance(dev, IotBulb):
1147
+ echo("Presets only supported on iot bulbs")
1148
+ return
1019
1149
  settings = await dev.get_turn_on_behavior()
1020
1150
  echo(f"Current turn on behavior: {settings}")
1021
1151
 
@@ -1050,10 +1180,7 @@ async def turn_on_behavior(dev: SmartBulb, type, last, preset):
1050
1180
  )
1051
1181
  async def update_credentials(dev, username, password):
1052
1182
  """Update device credentials for authenticated devices."""
1053
- # Importing here as this is not really a public interface for now
1054
- from kasa.tapo import TapoDevice
1055
-
1056
- if not isinstance(dev, TapoDevice):
1183
+ if not isinstance(dev, SmartDevice):
1057
1184
  raise NotImplementedError(
1058
1185
  "Credentials can only be updated on authenticated devices."
1059
1186
  )
@@ -1063,5 +1190,74 @@ async def update_credentials(dev, username, password):
1063
1190
  return await dev.update_credentials(username, password)
1064
1191
 
1065
1192
 
1193
+ @cli.command()
1194
+ @pass_dev
1195
+ async def shell(dev: Device):
1196
+ """Open interactive shell."""
1197
+ echo("Opening shell for %s" % dev)
1198
+ from ptpython.repl import embed
1199
+
1200
+ logging.getLogger("parso").setLevel(logging.WARNING) # prompt parsing
1201
+ logging.getLogger("asyncio").setLevel(logging.WARNING)
1202
+ loop = asyncio.get_event_loop()
1203
+ try:
1204
+ await embed(
1205
+ globals=globals(),
1206
+ locals=locals(),
1207
+ return_asyncio_coroutine=True,
1208
+ patch_stdout=True,
1209
+ )
1210
+ except EOFError:
1211
+ loop.stop()
1212
+
1213
+
1214
+ @cli.command(name="feature")
1215
+ @click.argument("name", required=False)
1216
+ @click.argument("value", required=False)
1217
+ @click.option("--child", required=False)
1218
+ @pass_dev
1219
+ async def feature(dev: Device, child: str, name: str, value):
1220
+ """Access and modify features.
1221
+
1222
+ If no *name* is given, lists available features and their values.
1223
+ If only *name* is given, the value of named feature is returned.
1224
+ If both *name* and *value* are set, the described setting is changed.
1225
+ """
1226
+ if child is not None:
1227
+ echo(f"Targeting child device {child}")
1228
+ dev = dev.get_child_device(child)
1229
+ if not name:
1230
+ _echo_features(dev.features, "\n[bold]== Features ==[/bold]\n", indent="")
1231
+
1232
+ if dev.children:
1233
+ for child_dev in dev.children:
1234
+ _echo_features(
1235
+ child_dev.features,
1236
+ f"\n[bold]== Child {child_dev.alias} ==\n",
1237
+ indent="",
1238
+ )
1239
+
1240
+ return
1241
+
1242
+ if name not in dev.features:
1243
+ echo(f"No feature by name '{name}'")
1244
+ return
1245
+
1246
+ feat = dev.features[name]
1247
+
1248
+ if value is None:
1249
+ unit = f" {feat.unit}" if feat.unit else ""
1250
+ echo(f"{feat.name} ({name}): {feat.value}{unit}")
1251
+ return feat.value
1252
+
1253
+ value = ast.literal_eval(value)
1254
+ echo(f"Changing {name} from {feat.value} to {value}")
1255
+ response = await dev.features[name].set_value(value)
1256
+ await dev.update()
1257
+ echo(f"New state: {feat.value}")
1258
+
1259
+ return response
1260
+
1261
+
1066
1262
  if __name__ == "__main__":
1067
1263
  cli()