python-kasa 0.7.0.dev5__py3-none-any.whl → 0.7.0.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 (48) hide show
  1. kasa/aestransport.py +6 -2
  2. kasa/cli.py +60 -45
  3. kasa/device.py +105 -2
  4. kasa/discover.py +2 -1
  5. kasa/feature.py +85 -10
  6. kasa/httpclient.py +1 -1
  7. kasa/interfaces/energy.py +6 -0
  8. kasa/interfaces/light.py +61 -1
  9. kasa/interfaces/lighteffect.py +41 -1
  10. kasa/interfaces/lightpreset.py +70 -2
  11. kasa/iot/iotdevice.py +6 -1
  12. kasa/iot/iotstrip.py +14 -3
  13. kasa/iot/modules/lightpreset.py +2 -1
  14. kasa/module.py +39 -1
  15. kasa/smart/modules/alarm.py +1 -0
  16. kasa/smart/modules/autooff.py +3 -1
  17. kasa/smart/modules/childdevice.py +39 -1
  18. kasa/smart/modules/firmware.py +4 -1
  19. kasa/smart/modules/frostprotection.py +0 -22
  20. kasa/smart/modules/humiditysensor.py +1 -0
  21. kasa/smart/modules/led.py +1 -1
  22. kasa/smart/modules/lightpreset.py +2 -1
  23. kasa/smart/modules/lighttransition.py +5 -7
  24. kasa/smart/modules/reportmode.py +2 -0
  25. kasa/smart/modules/temperaturecontrol.py +3 -2
  26. kasa/smart/modules/temperaturesensor.py +3 -2
  27. kasa/smart/modules/time.py +3 -2
  28. kasa/smart/modules/waterleaksensor.py +2 -0
  29. kasa/smart/smartdevice.py +10 -5
  30. kasa/tests/device_fixtures.py +1 -1
  31. kasa/tests/discovery_fixtures.py +3 -1
  32. kasa/tests/fakeprotocol_smart.py +2 -2
  33. kasa/tests/smart/modules/test_firmware.py +12 -1
  34. kasa/tests/test_cli.py +18 -3
  35. kasa/tests/test_device.py +2 -1
  36. kasa/tests/test_emeter.py +8 -8
  37. kasa/tests/test_feature.py +6 -2
  38. kasa/tests/test_httpclient.py +2 -2
  39. kasa/tests/test_iotdevice.py +5 -4
  40. kasa/tests/test_readme_examples.py +59 -0
  41. kasa/tests/test_smartdevice.py +4 -3
  42. kasa/tests/test_strip.py +15 -2
  43. kasa/xortransport.py +3 -3
  44. {python_kasa-0.7.0.dev5.dist-info → python_kasa-0.7.0.1.dist-info}/METADATA +102 -129
  45. {python_kasa-0.7.0.dev5.dist-info → python_kasa-0.7.0.1.dist-info}/RECORD +48 -48
  46. {python_kasa-0.7.0.dev5.dist-info → python_kasa-0.7.0.1.dist-info}/LICENSE +0 -0
  47. {python_kasa-0.7.0.dev5.dist-info → python_kasa-0.7.0.1.dist-info}/WHEEL +0 -0
  48. {python_kasa-0.7.0.dev5.dist-info → python_kasa-0.7.0.1.dist-info}/entry_points.txt +0 -0
kasa/aestransport.py CHANGED
@@ -10,8 +10,9 @@ import base64
10
10
  import hashlib
11
11
  import logging
12
12
  import time
13
+ from collections.abc import AsyncGenerator
13
14
  from enum import Enum, auto
14
- from typing import TYPE_CHECKING, Any, AsyncGenerator, Dict, cast
15
+ from typing import TYPE_CHECKING, Any, Dict, cast
15
16
 
16
17
  from cryptography.hazmat.primitives import padding, serialization
17
18
  from cryptography.hazmat.primitives.asymmetric import padding as asymmetric_padding
@@ -371,7 +372,10 @@ class AesEncyptionSession:
371
372
  handshake_key_bytes: bytes = base64.b64decode(handshake_key.encode("UTF-8"))
372
373
  private_key_data = base64.b64decode(keypair.get_private_key().encode("UTF-8"))
373
374
 
374
- private_key = serialization.load_der_private_key(private_key_data, None, None)
375
+ private_key = cast(
376
+ rsa.RSAPrivateKey,
377
+ serialization.load_der_private_key(private_key_data, None, None),
378
+ )
375
379
  key_and_iv = private_key.decrypt(
376
380
  handshake_key_bytes, asymmetric_padding.PKCS1v15()
377
381
  )
kasa/cli.py CHANGED
@@ -101,9 +101,7 @@ DEVICE_FAMILY_TYPES = [device_family_type.value for device_family_type in Device
101
101
  # Block list of commands which require no update
102
102
  SKIP_UPDATE_COMMANDS = ["raw-command", "command"]
103
103
 
104
- click.anyio_backend = "asyncio"
105
-
106
- pass_dev = click.make_pass_decorator(Device)
104
+ pass_dev = click.make_pass_decorator(Device) # type: ignore[type-abstract]
107
105
 
108
106
 
109
107
  def CatchAllExceptions(cls):
@@ -379,6 +377,7 @@ async def cli(
379
377
  echo("No host name given, trying discovery..")
380
378
  return await ctx.invoke(discover)
381
379
 
380
+ device_updated = False
382
381
  if type is not None:
383
382
  dev = TYPE_TO_CLASS[type](host)
384
383
  elif device_family and encrypt_type:
@@ -396,11 +395,14 @@ async def cli(
396
395
  connection_type=ctype,
397
396
  )
398
397
  dev = await Device.connect(config=config)
398
+ device_updated = True
399
399
  else:
400
- echo(
401
- "No --type or --device-family and --encrypt-type defined, "
402
- + f"discovering for {discovery_timeout} seconds.."
403
- )
400
+ if device_family or encrypt_type:
401
+ echo(
402
+ "--device-family and --encrypt-type options must both be "
403
+ "provided or they are ignored\n"
404
+ f"discovering for {discovery_timeout} seconds.."
405
+ )
404
406
  dev = await Discover.discover_single(
405
407
  host,
406
408
  port=port,
@@ -411,7 +413,7 @@ async def cli(
411
413
 
412
414
  # Skip update on specific commands, or if device factory,
413
415
  # that performs an update was used for the device.
414
- if ctx.invoked_subcommand not in SKIP_UPDATE_COMMANDS and not device_family:
416
+ if ctx.invoked_subcommand not in SKIP_UPDATE_COMMANDS and not device_updated:
415
417
  await dev.update()
416
418
 
417
419
  @asynccontextmanager
@@ -606,9 +608,7 @@ def _echo_features(
606
608
  id_: feat for id_, feat in features.items() if feat.category == category
607
609
  }
608
610
 
609
- if not features:
610
- return
611
- echo(f"[bold]{title}[/bold]")
611
+ echo(f"{indent}[bold]{title}[/bold]")
612
612
  for _, feat in features.items():
613
613
  try:
614
614
  echo(f"{indent}{feat}")
@@ -620,33 +620,40 @@ def _echo_features(
620
620
  echo(f"{indent}{feat.name} ({feat.id}): [red]got exception ({ex})[/red]")
621
621
 
622
622
 
623
- def _echo_all_features(features, *, verbose=False, title_prefix=None):
623
+ def _echo_all_features(features, *, verbose=False, title_prefix=None, indent=""):
624
624
  """Print out all features by category."""
625
625
  if title_prefix is not None:
626
- echo(f"[bold]\n\t == {title_prefix} ==[/bold]")
626
+ echo(f"[bold]\n{indent}== {title_prefix} ==[/bold]")
627
627
  _echo_features(
628
628
  features,
629
- title="\n\t== Primary features ==",
629
+ title="== Primary features ==",
630
630
  category=Feature.Category.Primary,
631
631
  verbose=verbose,
632
+ indent=indent,
632
633
  )
634
+ echo()
633
635
  _echo_features(
634
636
  features,
635
- title="\n\t== Information ==",
637
+ title="== Information ==",
636
638
  category=Feature.Category.Info,
637
639
  verbose=verbose,
640
+ indent=indent,
638
641
  )
642
+ echo()
639
643
  _echo_features(
640
644
  features,
641
- title="\n\t== Configuration ==",
645
+ title="== Configuration ==",
642
646
  category=Feature.Category.Config,
643
647
  verbose=verbose,
648
+ indent=indent,
644
649
  )
650
+ echo()
645
651
  _echo_features(
646
652
  features,
647
- title="\n\t== Debug ==",
653
+ title="== Debug ==",
648
654
  category=Feature.Category.Debug,
649
655
  verbose=verbose,
656
+ indent=indent,
650
657
  )
651
658
 
652
659
 
@@ -658,38 +665,42 @@ async def state(ctx, dev: Device):
658
665
  verbose = ctx.parent.params.get("verbose", False) if ctx.parent else False
659
666
 
660
667
  echo(f"[bold]== {dev.alias} - {dev.model} ==[/bold]")
661
- echo(f"\tHost: {dev.host}")
662
- echo(f"\tPort: {dev.port}")
663
- echo(f"\tDevice state: {dev.is_on}")
668
+ echo(f"Host: {dev.host}")
669
+ echo(f"Port: {dev.port}")
670
+ echo(f"Device state: {dev.is_on}")
671
+
672
+ echo(f"Time: {dev.time} (tz: {dev.timezone}")
673
+ echo(f"Hardware: {dev.hw_info['hw_ver']}")
674
+ echo(f"Software: {dev.hw_info['sw_ver']}")
675
+ echo(f"MAC (rssi): {dev.mac} ({dev.rssi})")
676
+ if verbose:
677
+ echo(f"Location: {dev.location}")
678
+
679
+ _echo_all_features(dev.features, verbose=verbose)
680
+ echo()
681
+
664
682
  if dev.children:
665
- echo("\t== Children ==")
683
+ echo("[bold]== Children ==[/bold]")
666
684
  for child in dev.children:
667
685
  _echo_all_features(
668
686
  child.features,
669
- title_prefix=f"{child.alias} ({child.model}, {child.device_type})",
687
+ title_prefix=f"{child.alias} ({child.model})",
670
688
  verbose=verbose,
689
+ indent="\t",
671
690
  )
672
691
 
673
692
  echo()
674
693
 
675
- echo("\t[bold]== Generic information ==[/bold]")
676
- echo(f"\tTime: {dev.time} (tz: {dev.timezone}")
677
- echo(f"\tHardware: {dev.hw_info['hw_ver']}")
678
- echo(f"\tSoftware: {dev.hw_info['sw_ver']}")
679
- echo(f"\tMAC (rssi): {dev.mac} ({dev.rssi})")
680
- echo(f"\tLocation: {dev.location}")
681
-
682
- _echo_all_features(dev.features, verbose=verbose)
683
-
684
- echo("\n\t[bold]== Modules ==[/bold]")
685
- for module in dev.modules.values():
686
- echo(f"\t[green]+ {module}[/green]")
687
-
688
694
  if verbose:
695
+ echo("\n\t[bold]== Modules ==[/bold]")
696
+ for module in dev.modules.values():
697
+ echo(f"\t[green]+ {module}[/green]")
698
+
689
699
  echo("\n\t[bold]== Protocol information ==[/bold]")
690
700
  echo(f"\tCredentials hash: {dev.credentials_hash}")
691
701
  echo()
692
702
  _echo_discovery_info(dev._discovery_info)
703
+
693
704
  return dev.internal_state
694
705
 
695
706
 
@@ -996,7 +1007,7 @@ async def time_get(dev: Device):
996
1007
 
997
1008
  @time.command(name="sync")
998
1009
  @pass_dev
999
- async def time_sync(dev: SmartDevice):
1010
+ async def time_sync(dev: Device):
1000
1011
  """Set the device time to current time."""
1001
1012
  if not isinstance(dev, SmartDevice):
1002
1013
  raise NotImplementedError("setting time currently only implemented on smart")
@@ -1134,7 +1145,7 @@ async def presets(ctx):
1134
1145
 
1135
1146
  @presets.command(name="list")
1136
1147
  @pass_dev
1137
- def presets_list(dev: IotBulb):
1148
+ def presets_list(dev: Device):
1138
1149
  """List presets."""
1139
1150
  if not dev.is_bulb or not isinstance(dev, IotBulb):
1140
1151
  error("Presets only supported on iot bulbs")
@@ -1153,7 +1164,7 @@ def presets_list(dev: IotBulb):
1153
1164
  @click.option("--saturation", type=int)
1154
1165
  @click.option("--temperature", type=int)
1155
1166
  @pass_dev
1156
- async def presets_modify(dev: IotBulb, index, brightness, hue, saturation, temperature):
1167
+ async def presets_modify(dev: Device, index, brightness, hue, saturation, temperature):
1157
1168
  """Modify a preset."""
1158
1169
  for preset in dev.presets:
1159
1170
  if preset.index == index:
@@ -1181,7 +1192,7 @@ async def presets_modify(dev: IotBulb, index, brightness, hue, saturation, tempe
1181
1192
  @click.option("--type", type=click.Choice(["soft", "hard"], case_sensitive=False))
1182
1193
  @click.option("--last", is_flag=True)
1183
1194
  @click.option("--preset", type=int)
1184
- async def turn_on_behavior(dev: IotBulb, type, last, preset):
1195
+ async def turn_on_behavior(dev: Device, type, last, preset):
1185
1196
  """Modify bulb turn-on behavior."""
1186
1197
  if not dev.is_bulb or not isinstance(dev, IotBulb):
1187
1198
  error("Presets only supported on iot bulbs")
@@ -1239,7 +1250,7 @@ async def shell(dev: Device):
1239
1250
  logging.getLogger("asyncio").setLevel(logging.WARNING)
1240
1251
  loop = asyncio.get_event_loop()
1241
1252
  try:
1242
- await embed(
1253
+ await embed( # type: ignore[func-returns-value]
1243
1254
  globals=globals(),
1244
1255
  locals=locals(),
1245
1256
  return_asyncio_coroutine=True,
@@ -1254,25 +1265,29 @@ async def shell(dev: Device):
1254
1265
  @click.argument("value", required=False)
1255
1266
  @click.option("--child", required=False)
1256
1267
  @pass_dev
1257
- async def feature(dev: Device, child: str, name: str, value):
1268
+ @click.pass_context
1269
+ async def feature(ctx: click.Context, dev: Device, child: str, name: str, value):
1258
1270
  """Access and modify features.
1259
1271
 
1260
1272
  If no *name* is given, lists available features and their values.
1261
1273
  If only *name* is given, the value of named feature is returned.
1262
1274
  If both *name* and *value* are set, the described setting is changed.
1263
1275
  """
1276
+ verbose = ctx.parent.params.get("verbose", False) if ctx.parent else False
1277
+
1264
1278
  if child is not None:
1265
1279
  echo(f"Targeting child device {child}")
1266
1280
  dev = dev.get_child_device(child)
1267
1281
  if not name:
1268
- _echo_features(dev.features, "\n[bold]== Features ==[/bold]\n", indent="")
1282
+ _echo_all_features(dev.features, verbose=verbose, indent="")
1269
1283
 
1270
1284
  if dev.children:
1271
1285
  for child_dev in dev.children:
1272
- _echo_features(
1286
+ _echo_all_features(
1273
1287
  child_dev.features,
1274
- f"\n[bold]== Child {child_dev.alias} ==\n",
1275
- indent="",
1288
+ verbose=verbose,
1289
+ title_prefix=f"Child {child_dev.alias}",
1290
+ indent="\t",
1276
1291
  )
1277
1292
 
1278
1293
  return
kasa/device.py CHANGED
@@ -1,12 +1,115 @@
1
- """Module for Device base class."""
1
+ """Interact with TPLink Smart Home devices.
2
+
3
+ Once you have a device via :ref:`Discovery <discover_target>` or
4
+ :ref:`Connect <connect_target>` you can start interacting with a device.
5
+
6
+ >>> from kasa import Discover
7
+ >>>
8
+ >>> dev = await Discover.discover_single(
9
+ >>> "127.0.0.2",
10
+ >>> username="user@example.com",
11
+ >>> password="great_password"
12
+ >>> )
13
+ >>>
14
+
15
+ Most devices can be turned on and off
16
+
17
+ >>> await dev.turn_on()
18
+ >>> await dev.update()
19
+ >>> print(dev.is_on)
20
+ True
21
+
22
+ >>> await dev.turn_off()
23
+ >>> await dev.update()
24
+ >>> print(dev.is_on)
25
+ False
26
+
27
+ All devices provide several informational properties:
28
+
29
+ >>> dev.alias
30
+ Bedroom Lamp Plug
31
+ >>> dev.model
32
+ HS110(EU)
33
+ >>> dev.rssi
34
+ -71
35
+ >>> dev.mac
36
+ 50:C7:BF:00:00:00
37
+
38
+ Some information can also be changed programmatically:
39
+
40
+ >>> await dev.set_alias("new alias")
41
+ >>> await dev.update()
42
+ >>> dev.alias
43
+ new alias
44
+
45
+ Devices support different functionality that are exposed via
46
+ :ref:`modules <module_target>` that you can access via :attr:`~kasa.Device.modules`:
47
+
48
+ >>> for module_name in dev.modules:
49
+ >>> print(module_name)
50
+ Energy
51
+ schedule
52
+ usage
53
+ anti_theft
54
+ time
55
+ cloud
56
+ Led
57
+
58
+ >>> led_module = dev.modules["Led"]
59
+ >>> print(led_module.led)
60
+ False
61
+ >>> await led_module.set_led(True)
62
+ >>> await dev.update()
63
+ >>> print(led_module.led)
64
+ True
65
+
66
+ Individual pieces of functionality are also exposed via :ref:`features <feature_target>`
67
+ which you can access via :attr:`~kasa.Device.features` and will only be present if
68
+ they are supported.
69
+
70
+ Features are similar to modules in that they provide functionality that may or may
71
+ not be present.
72
+
73
+ Whereas modules group functionality into a common interface, features expose a single
74
+ function that may or may not be part of a module.
75
+
76
+ The advantage of features is that they have a simple common interface of `id`, `name`,
77
+ `value` and `set_value` so no need to learn the module API.
78
+
79
+ They are useful if you want write code that dynamically adapts as new features are
80
+ added to the API.
81
+
82
+ >>> for feature_name in dev.features:
83
+ >>> print(feature_name)
84
+ state
85
+ rssi
86
+ on_since
87
+ current_consumption
88
+ consumption_today
89
+ consumption_this_month
90
+ consumption_total
91
+ voltage
92
+ current
93
+ cloud_connection
94
+ led
95
+
96
+ >>> led_feature = dev.features["led"]
97
+ >>> print(led_feature.value)
98
+ True
99
+ >>> await led_feature.set_value(False)
100
+ >>> await dev.update()
101
+ >>> print(led_feature.value)
102
+ False
103
+ """
2
104
 
3
105
  from __future__ import annotations
4
106
 
5
107
  import logging
6
108
  from abc import ABC, abstractmethod
109
+ from collections.abc import Mapping, Sequence
7
110
  from dataclasses import dataclass
8
111
  from datetime import datetime
9
- from typing import TYPE_CHECKING, Any, Mapping, Sequence
112
+ from typing import TYPE_CHECKING, Any
10
113
  from warnings import warn
11
114
 
12
115
  from typing_extensions import TypeAlias
kasa/discover.py CHANGED
@@ -86,7 +86,8 @@ import binascii
86
86
  import ipaddress
87
87
  import logging
88
88
  import socket
89
- from typing import Awaitable, Callable, Dict, Optional, Type, cast
89
+ from collections.abc import Awaitable
90
+ from typing import Callable, Dict, Optional, Type, cast
90
91
 
91
92
  # When support for cpython older than 3.11 is dropped
92
93
  # async_timeout can be replaced with asyncio.timeout
kasa/feature.py CHANGED
@@ -1,4 +1,67 @@
1
- """Generic interface for defining device features."""
1
+ """Interact with feature.
2
+
3
+ Features are implemented by devices to represent individual pieces of functionality like
4
+ state, time, firmware.
5
+
6
+ >>> from kasa import Discover, Module
7
+ >>>
8
+ >>> dev = await Discover.discover_single(
9
+ >>> "127.0.0.3",
10
+ >>> username="user@example.com",
11
+ >>> password="great_password"
12
+ >>> )
13
+ >>> await dev.update()
14
+ >>> print(dev.alias)
15
+ Living Room Bulb
16
+
17
+ Features allow for instrospection and can be interacted with as new features are added
18
+ to the API:
19
+
20
+ >>> for feature_id, feature in dev.features.items():
21
+ >>> print(f"{feature.name} ({feature_id}): {feature.value}")
22
+ Device ID (device_id): 0000000000000000000000000000000000000000
23
+ State (state): True
24
+ Signal Level (signal_level): 2
25
+ RSSI (rssi): -52
26
+ SSID (ssid): #MASKED_SSID#
27
+ Overheated (overheated): False
28
+ Brightness (brightness): 100
29
+ Cloud connection (cloud_connection): True
30
+ HSV (hsv): HSV(hue=0, saturation=100, value=100)
31
+ Color temperature (color_temperature): 2700
32
+ Auto update enabled (auto_update_enabled): False
33
+ Update available (update_available): False
34
+ Current firmware version (current_firmware_version): 1.1.6 Build 240130 Rel.173828
35
+ Available firmware version (available_firmware_version): 1.1.6 Build 240130 Rel.173828
36
+ Light effect (light_effect): Off
37
+ Light preset (light_preset): Not set
38
+ Smooth transition on (smooth_transition_on): 2
39
+ Smooth transition off (smooth_transition_off): 2
40
+ Device time (device_time): 2024-02-23 02:40:15+01:00
41
+
42
+ To see whether a device supports a feature, check for the existence of it:
43
+
44
+ >>> if feature := dev.features.get("brightness"):
45
+ >>> print(feature.value)
46
+ 100
47
+
48
+ You can update the value of a feature
49
+
50
+ >>> await feature.set_value(50)
51
+ >>> await dev.update()
52
+ >>> print(feature.value)
53
+ 50
54
+
55
+ Features have types that can be used for introspection:
56
+
57
+ >>> feature = dev.features["light_preset"]
58
+ >>> print(feature.type)
59
+ Type.Choice
60
+
61
+ >>> print(feature.choices)
62
+ ['Not set', 'Light preset 1', 'Light preset 2', 'Light preset 3',\
63
+ 'Light preset 4', 'Light preset 5', 'Light preset 6', 'Light preset 7']
64
+ """
2
65
 
3
66
  from __future__ import annotations
4
67
 
@@ -36,7 +99,7 @@ class Feature:
36
99
  Choice = auto()
37
100
  Unknown = -1
38
101
 
39
- # TODO: unsure if this is a great idea..
102
+ # Aliases for easy access
40
103
  Sensor = Type.Sensor
41
104
  BinarySensor = Type.BinarySensor
42
105
  Switch = Type.Switch
@@ -66,6 +129,8 @@ class Feature:
66
129
  id: str
67
130
  #: User-friendly short description
68
131
  name: str
132
+ #: Type of the feature
133
+ type: Feature.Type
69
134
  #: Name of the property that allows accessing the value
70
135
  attribute_getter: str | Callable | None = None
71
136
  #: Name of the method that allows changing the value
@@ -76,10 +141,11 @@ class Feature:
76
141
  icon: str | None = None
77
142
  #: Unit, if applicable
78
143
  unit: str | None = None
144
+ #: Attribute containing the name of the unit getter property.
145
+ #: If set, this property will be used to set *unit*.
146
+ unit_getter: str | None = None
79
147
  #: Category hint for downstreams
80
148
  category: Feature.Category = Category.Unset
81
- #: Type of the feature
82
- type: Feature.Type = Type.Sensor
83
149
 
84
150
  # Display hints offer a way suggest how the value should be shown to users
85
151
  #: Hint to help rounding the sensor values to given after-comma digits
@@ -114,6 +180,10 @@ class Feature:
114
180
  if self.choices_getter is not None:
115
181
  self.choices = getattr(container, self.choices_getter)
116
182
 
183
+ # Populate unit, if unit_getter is given
184
+ if self.unit_getter is not None:
185
+ self.unit = getattr(container, self.unit_getter)
186
+
117
187
  # Set the category, if unset
118
188
  if self.category is Feature.Category.Unset:
119
189
  if self.attribute_setter:
@@ -121,14 +191,19 @@ class Feature:
121
191
  else:
122
192
  self.category = Feature.Category.Info
123
193
 
124
- if self.category == Feature.Category.Config and self.type in [
194
+ if self.type in (
125
195
  Feature.Type.Sensor,
126
196
  Feature.Type.BinarySensor,
127
- ]:
128
- raise ValueError(
129
- f"Invalid type for configurable feature: {self.name} ({self.id}):"
130
- f" {self.type}"
131
- )
197
+ ):
198
+ if self.category == Feature.Category.Config:
199
+ raise ValueError(
200
+ f"Invalid type for configurable feature: {self.name} ({self.id}):"
201
+ f" {self.type}"
202
+ )
203
+ elif self.attribute_setter is not None:
204
+ raise ValueError(
205
+ f"Read-only feat defines attribute_setter: {self.name} ({self.id}):"
206
+ )
132
207
 
133
208
  @property
134
209
  def value(self):
kasa/httpclient.py CHANGED
@@ -36,7 +36,7 @@ class HttpClient:
36
36
 
37
37
  def __init__(self, config: DeviceConfig) -> None:
38
38
  self._config = config
39
- self._client_session: aiohttp.ClientSession = None
39
+ self._client_session: aiohttp.ClientSession | None = None
40
40
  self._jar = aiohttp.CookieJar(unsafe=True, quote_cookie=False)
41
41
  self._last_url = URL(f"http://{self._config.host}/")
42
42
 
kasa/interfaces/energy.py CHANGED
@@ -44,6 +44,7 @@ class Energy(Module, ABC):
44
44
  id="current_consumption",
45
45
  precision_hint=1,
46
46
  category=Feature.Category.Primary,
47
+ type=Feature.Type.Sensor,
47
48
  )
48
49
  )
49
50
  self._add_feature(
@@ -56,6 +57,7 @@ class Energy(Module, ABC):
56
57
  id="consumption_today",
57
58
  precision_hint=3,
58
59
  category=Feature.Category.Info,
60
+ type=Feature.Type.Sensor,
59
61
  )
60
62
  )
61
63
  self._add_feature(
@@ -68,6 +70,7 @@ class Energy(Module, ABC):
68
70
  unit="kWh",
69
71
  precision_hint=3,
70
72
  category=Feature.Category.Info,
73
+ type=Feature.Type.Sensor,
71
74
  )
72
75
  )
73
76
  if self.supports(self.ModuleFeature.CONSUMPTION_TOTAL):
@@ -81,6 +84,7 @@ class Energy(Module, ABC):
81
84
  id="consumption_total",
82
85
  precision_hint=3,
83
86
  category=Feature.Category.Info,
87
+ type=Feature.Type.Sensor,
84
88
  )
85
89
  )
86
90
  if self.supports(self.ModuleFeature.VOLTAGE_CURRENT):
@@ -94,6 +98,7 @@ class Energy(Module, ABC):
94
98
  id="voltage",
95
99
  precision_hint=1,
96
100
  category=Feature.Category.Primary,
101
+ type=Feature.Type.Sensor,
97
102
  )
98
103
  )
99
104
  self._add_feature(
@@ -106,6 +111,7 @@ class Energy(Module, ABC):
106
111
  id="current",
107
112
  precision_hint=2,
108
113
  category=Feature.Category.Primary,
114
+ type=Feature.Type.Sensor,
109
115
  )
110
116
  )
111
117
 
kasa/interfaces/light.py CHANGED
@@ -1,4 +1,64 @@
1
- """Module for Device base class."""
1
+ """Interact with a TPLink Light.
2
+
3
+ >>> from kasa import Discover, Module
4
+ >>>
5
+ >>> dev = await Discover.discover_single(
6
+ >>> "127.0.0.3",
7
+ >>> username="user@example.com",
8
+ >>> password="great_password"
9
+ >>> )
10
+ >>> await dev.update()
11
+ >>> print(dev.alias)
12
+ Living Room Bulb
13
+
14
+ Lights, like any other supported devices, can be turned on and off:
15
+
16
+ >>> print(dev.is_on)
17
+ >>> await dev.turn_on()
18
+ >>> await dev.update()
19
+ >>> print(dev.is_on)
20
+ True
21
+
22
+ Get the light module to interact:
23
+
24
+ >>> light = dev.modules[Module.Light]
25
+
26
+ You can use the ``is_``-prefixed properties to check for supported features:
27
+
28
+ >>> light.is_dimmable
29
+ True
30
+ >>> light.is_color
31
+ True
32
+ >>> light.is_variable_color_temp
33
+ True
34
+
35
+ All known bulbs support changing the brightness:
36
+
37
+ >>> light.brightness
38
+ 100
39
+ >>> await light.set_brightness(50)
40
+ >>> await dev.update()
41
+ >>> light.brightness
42
+ 50
43
+
44
+ Bulbs supporting color temperature can be queried for the supported range:
45
+
46
+ >>> light.valid_temperature_range
47
+ ColorTempRange(min=2500, max=6500)
48
+ >>> await light.set_color_temp(3000)
49
+ >>> await dev.update()
50
+ >>> light.color_temp
51
+ 3000
52
+
53
+ Color bulbs can be adjusted by passing hue, saturation and value:
54
+
55
+ >>> await light.set_hsv(180, 100, 80)
56
+ >>> await dev.update()
57
+ >>> light.hsv
58
+ HSV(hue=180, saturation=100, value=80)
59
+
60
+
61
+ """
2
62
 
3
63
  from __future__ import annotations
4
64